@cosyte/cli 0.0.5 → 0.0.6

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/version.ts","../../src/core/exit-codes.ts","../../src/core/diagnostics.ts","../../src/core/format.ts","../../src/core/findings.ts","../../src/core/parsers.ts","../../src/core/input.ts","../../src/core/phi.ts","../../src/core/wrap.ts","../../src/commands/convert.ts","../../src/commands/inspect.ts","../../src/commands/parse.ts","../../src/commands/validate.ts","../../src/mcp/tools.ts","../../src/mcp/server.ts","../../src/bin/cosyte-mcp.ts"],"names":["ERROR_SEVERITIES","parseArgs","Server","ListToolsRequestSchema","CallToolRequestSchema","StdioServerTransport"],"mappings":";;;;;;;;;AAyBO,IAAM,OAAA,GAAkB,OAAA;;;ACYxB,IAAM,IAAA,GAAO;AAAA;AAAA,EAElB,EAAA,EAAI,CAAA;AAAA;AAAA;AAAA;AAAA,EAIJ,OAAA,EAAS,CAAA;AAAA;AAAA,EAET,KAAA,EAAO,CAAA;AAAA;AAAA,EAEP,OAAA,EAAS,EAAA;AAAA;AAAA,EAET,OAAA,EAAS,EAAA;AAAA;AAAA;AAAA,EAGT,WAAA,EAAa,EAAA;AAAA;AAAA,EAEb,QAAA,EAAU;AACZ,CAAA;;;AC3BO,IAAM,SAAA,GAAY;AAAA;AAAA,EAEvB,SAAA,EAAW,WAAA;AAAA;AAAA,EAEX,YAAA,EAAc,cAAA;AAAA;AAAA,EAEd,eAAA,EAAiB,iBAAA;AAAA;AAAA,EAEjB,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAEvB,oBAAA,EAAsB,sBAAA;AAAA;AAAA;AAAA,EAGtB,sBAAA,EAAwB,wBAAA;AAAA;AAAA;AAAA;AAAA,EAIxB,sBAAA,EAAwB,wBAAA;AAAA;AAAA,EAExB,gBAAA,EAAkB,kBAAA;AAAA,EAGD;AAAA;AAAA,EAGjB,mBAAA,EAAqB,qBA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AM,SAAA,EAAW,IAAA,KAAS,OAAA,CAAQ,MAAA;AAC1C,IAAA,MAAM,SAAS,MAAM,YAAA,CAAa,IAAA,EAAM,IAAA,IAAQ,EAAE,CAAA;AAClD,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,MAAO,EAAE,IAAA,EAAM,CAAA,CAAE,IAAA,EAAM,IAAA,EAAM,CAAA,CAAE,MAAK,CAAE,CAAA;AAAA,MACnE,SAAS,MAAA,CAAO,OAAA;AAAA,MAChB,iBAAA,EAAmB,EAAE,IAAA,EAAM,MAAA,CAAO,kBAAkB,IAAA,EAAM,EAAA,EAAI,MAAA,CAAO,iBAAA,CAAkB,EAAA;AAAG,KAC5F;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;AAgBA,eAAsB,gBAAA,GAAkC;AACtD,EAAA,MAAM,SAAS,eAAA,EAAgB;AAC/B,EAAA,MAAM,MAAA,CAAO,OAAA,CAAQ,IAAIC,6BAAA,EAAsB,CAAA;AACjD;;;AC3EA,gBAAA,EAAiB,CAAE,MAAM,MAAM;AAE7B,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,4DAA4D,CAAA;AACjF,EAAA,OAAA,CAAQ,QAAA,GAAW,EAAA;AACrB,CAAC,CAAA","file":"cosyte-mcp.cjs","sourcesContent":["/**\n * The CLI version string, synced with `package.json#version` on release by `scripts/sync-version.mjs`,\n * which the `version` script runs immediately after `changeset version`. Kept in its own module so\n * both the programmatic entry point and the dispatcher share one source of truth.\n *\n * The declaration below is rewritten by that script and is matched at column 0, annotation included.\n * Renaming it or reflowing it makes the script exit non-zero rather than silently no-op; the shape is\n * pinned by `test/sanity.test.ts`, and the value is compared against `package.json` there too.\n *\n * @packageDocumentation\n */\n\n/**\n * The `@cosyte/cli` version. On the uniform `v0.0.x-until-first-alpha` ladder.\n *\n * Read by `cosyte --version` and by the MCP server's advertised `SERVER_INFO`, so it is a\n * user-visible surface on both front doors, not merely an export.\n *\n * @example\n * ```ts\n * import { VERSION } from \"@cosyte/cli\";\n *\n * console.log(`cosyte ${VERSION}`);\n * ```\n */\nexport const VERSION: string = \"0.0.5\";\n","/**\n * The `cosyte` CLI **exit-code contract**: a designed, documented surface that CI pipelines and\n * shell scripts branch on. Grounded in the Unix `sysexits.h` conventions.\n *\n * The load-bearing rule: **the CLI never prints a reassuring line and exits `0` on input it could not\n * handle.** An undetectable format, an unreadable file, or a parser that throws each map to a\n * distinct, stable non-zero code, never a silent success.\n *\n * | Code | Name | Meaning |\n * |------|------------|----------------------------------------------------------------------|\n * | `0` | `OK` | success: the operation completed; `validate` found the input **valid** |\n * | `1` | `INVALID` | operation-level failure: `validate` found the input **invalid** (a real, expected CI signal: the message is bad, the tool worked) |\n * | `2` | `USAGE` | usage error: unknown command, bad flag, missing argument (EX_USAGE) |\n * | `65` | `DATAERR` | data error: input could not be parsed / format not detected (EX_DATAERR) |\n * | `66` | `NOINPUT` | no input: the file does not exist or is unreadable (EX_NOINPUT) |\n * | `69` | `UNAVAILABLE` | a required capability is not yet available: e.g. `redact` before `@cosyte/deid` is wired (EX_UNAVAILABLE) |\n * | `70` | `SOFTWARE` | internal error: an unexpected exception, i.e. a bug (EX_SOFTWARE) |\n *\n * The load-bearing `validate` rule: a **parseable-but-invalid** message is exit `1`, never exit `0`.\n * The CLI must never print a reassuring line and exit green on a bad message. Exit `65` is reserved\n * for input that could not be **parsed** at all (a distinct signal from \"parsed, but does not\n * conform\").\n *\n * @packageDocumentation\n */\n\n/**\n * The stable exit-code map. Adding a code is a documented, tested change to the CLI's contract;\n * renaming or repurposing one is a breaking change.\n *\n * @example\n * ```ts\n * import { EXIT } from \"@cosyte/cli\";\n *\n * process.exitCode = EXIT.OK; // => 0\n * ```\n */\nexport const EXIT = {\n /** Success: the operation completed; `validate` found the input **valid**. */\n OK: 0,\n /** Operation-level failure: `validate` found the input **invalid** (parseable but non-conformant):\n * a real, expected CI signal that the message is bad and the tool worked. Never emitted for\n * unparseable input (that is `DATAERR`). */\n INVALID: 1,\n /** Usage error: unknown command, bad flag, missing argument (`EX_USAGE`). */\n USAGE: 2,\n /** Data error: input could not be parsed or its format could not be detected (`EX_DATAERR`). */\n DATAERR: 65,\n /** No input: the named file does not exist or is unreadable (`EX_NOINPUT`). */\n NOINPUT: 66,\n /** Unavailable: a required capability is not yet wired (e.g. `redact` before `@cosyte/deid`), a\n * distinct non-zero signal that is never a fake success (`EX_UNAVAILABLE`). */\n UNAVAILABLE: 69,\n /** Internal error: an unexpected exception (a bug), distinct from a handled bad input (`EX_SOFTWARE`). */\n SOFTWARE: 70,\n} as const;\n\n/**\n * A value from {@link EXIT}: the exit code a CLI invocation resolves to.\n */\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n","/**\n * The CLI's **value-free diagnostic channel**. Every error the CLI raises on its own behalf carries a\n * stable `CLI_*` code, a fixed exit code, and a **PHI-safe** message built only from positional /\n * structural context: a segment or field index, a byte offset, a file path, a format name, a warning\n * code. **A diagnostic never echoes an input value** (a name, a DOB, an MRN, a result). This is the\n * parsers' \"warning = code + position, never a value\" rule applied at the CLI edge.\n *\n * @packageDocumentation\n */\n\nimport { EXIT, type ExitCode } from \"./exit-codes.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Stable **CLI diagnostic code** registry: errors the CLI owns (routing, I/O, argument handling),\n * distinct from the wrapped library's own warning/issue codes which are passed through unchanged.\n * Each code is its own value (`key === value`) so the set survives `Object.values(...)`; renaming or\n * removing one is a **breaking change** because scripts branch on the stderr text.\n *\n * @example\n * ```ts\n * import { CLI_CODES } from \"@cosyte/cli\";\n *\n * if (diagnostic.code === CLI_CODES.CLI_FORMAT_UNDETECTED) {\n * // ask the user for --format\n * }\n * ```\n */\nexport const CLI_CODES = {\n /** A required argument was missing or a flag was invalid. Exit `2`. */\n CLI_USAGE: \"CLI_USAGE\",\n /** The named file does not exist or could not be read. Exit `66`. */\n CLI_NO_INPUT: \"CLI_NO_INPUT\",\n /** The input was empty, no bytes to detect or parse. Exit `65`. */\n CLI_EMPTY_INPUT: \"CLI_EMPTY_INPUT\",\n /** No format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_UNDETECTED: \"CLI_FORMAT_UNDETECTED\",\n /** More than one format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_AMBIGUOUS: \"CLI_FORMAT_AMBIGUOUS\",\n /** A recognised format whose parser does not support the requested operation (e.g. `parse` on a\n * format wired only for `inspect`). Names the format + operation, never the bytes. Exit `65`. */\n CLI_FORMAT_UNSUPPORTED: \"CLI_FORMAT_UNSUPPORTED\",\n /** The optional parser package for a recognised format is not installed. The six breadth parsers\n * (dicom/x12/ccda/ncpdp/astm/mllp) are `optionalDependencies`: normally installed, but if\n * one is absent the CLI degrades to this value-free signal rather than crashing. Exit `69`. */\n CLI_PARSER_UNAVAILABLE: \"CLI_PARSER_UNAVAILABLE\",\n /** The wrapped parser rejected the input. Positional context only, never the offending bytes. Exit `65`. */\n CLI_PARSE_FAILED: \"CLI_PARSE_FAILED\",\n /** The BYO ConceptMap supplied to `map-codes` is not valid JSON or not a loadable FHIR ConceptMap.\n * Names the stable terminology-loader code, never the map's bytes. Exit `65`. */\n CLI_MAP_INVALID: \"CLI_MAP_INVALID\",\n /** A command whose ground-layer library is not yet wired (e.g. `redact` before `@cosyte/deid` is\n * wired). Never a fake success: a distinct, value-free \"unavailable\" signal. Exit `69`. */\n CLI_NOT_IMPLEMENTED: \"CLI_NOT_IMPLEMENTED\",\n /** An unexpected internal error (a bug). Exit `70`. */\n CLI_INTERNAL: \"CLI_INTERNAL\",\n} as const;\n\n/**\n * A value from {@link CLI_CODES}: the stable code carried by a {@link CliError}.\n */\nexport type CliCode = (typeof CLI_CODES)[keyof typeof CLI_CODES];\n\n/**\n * A typed, PHI-safe CLI error. Its {@link CliError.message | message} is **value-free by\n * construction**: callers must build it from codes, indices, offsets, format names, and file paths,\n * never from an input value. It carries the {@link ExitCode} the invocation resolves to.\n *\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT } from \"@cosyte/cli\";\n *\n * throw new CliError(CLI_CODES.CLI_NO_INPUT, EXIT.NOINPUT, \"cannot read the named file\");\n * ```\n */\nexport class CliError extends Error {\n /** The stable diagnostic code. */\n public readonly code: CliCode;\n /** The exit code this error resolves the invocation to. */\n public readonly exit: ExitCode;\n\n /**\n * @param code - A stable {@link CliCode}.\n * @param exit - The {@link ExitCode} to resolve to.\n * @param message - A **value-free** explanation (positional/structural context only, never PHI).\n */\n public constructor(code: CliCode, exit: ExitCode, message: string) {\n super(message);\n this.name = \"CliError\";\n this.code = code;\n this.exit = exit;\n }\n}\n\n/**\n * Render a {@link CliError} as a single value-free `stderr` line: `cosyte: <CODE>: <message>`. The\n * message is already value-free by the {@link CliError} contract; this only prefixes the tool name\n * and the code so scripts and humans can branch on a stable token.\n *\n * @param err - The CLI error to render.\n * @returns The stderr line (no trailing newline).\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, formatDiagnostic } from \"@cosyte/cli\";\n *\n * formatDiagnostic(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file> argument\"));\n * // => \"cosyte: CLI_USAGE: missing <file> argument\"\n * ```\n */\nexport function formatDiagnostic(err: CliError): string {\n return `cosyte: ${err.code}: ${err.message}`;\n}\n\n/**\n * Resolve a {@link CliError} into a value-free {@link RunResult}: empty `stdout` (nothing reaches the\n * data channel on an error), the rendered diagnostic on `stderr`, and the error's exit code. The\n * single place the CLI turns an owned error into a result, so every command and the dispatcher render\n * errors identically.\n *\n * @param err - The CLI error to resolve.\n * @returns The value-free {@link RunResult}.\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, errorResult } from \"@cosyte/cli\";\n *\n * errorResult(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file>\")).exit; // => 2\n * ```\n */\nexport function errorResult(err: CliError): RunResult {\n return { stdout: \"\", stderr: `${formatDiagnostic(err)}\\n`, exit: err.exit };\n}\n\n/**\n * Coerce an unknown thrown value into a {@link CliError}. A {@link CliError} passes through; anything\n * else becomes a `CLI_INTERNAL` / {@link EXIT.SOFTWARE} error whose message is a **fixed, value-free\n * string**: the original message is deliberately discarded so a parser exception that embedded input\n * bytes can never reach stderr.\n *\n * @param err - The caught value.\n * @returns A {@link CliError} safe to render to stderr.\n * @example\n * ```ts\n * import { toCliError } from \"@cosyte/cli\";\n *\n * toCliError(new Error(\"boom\")).code; // => \"CLI_INTERNAL\"\n * ```\n */\nexport function toCliError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n return new CliError(\n CLI_CODES.CLI_INTERNAL,\n EXIT.SOFTWARE,\n \"an unexpected internal error occurred (no input is echoed)\",\n );\n}\n","/**\n * **Content-based format autodetection**: the feature that makes `cosyte parse <file>` feel magic,\n * and the one that must **fail safe**. Detection sniffs the leading bytes' *content*, never the file\n * extension: a `.txt` full of `MSH|^~\\&…` is HL7; a `.json` with a `resourceType` is FHIR.\n *\n * The hazard is a wrong sniff routing bytes to the wrong parser and yielding confident garbage. So\n * detection is **conservative**: a single confident signature match parses; **zero or more than one**\n * match is *not* a guess. It is a typed `none`/`ambiguous` result the caller turns into a data-error\n * exit asking for `--format`. This is the parsers' \"never a confident wrong value\" rule at the\n * routing layer.\n *\n * All eight cosyte formats carry a signature: **hl7** (`MSH` + field separator), **mllp**\n * (a leading `0x0B` VT frame byte: an MLLP-framed stream, de-framed to its enclosed HL7), **fhir** (a\n * JSON object declaring `resourceType`), **x12** (a leading `ISA` interchange header), **astm** (a\n * leading `H` record whose second byte is the field delimiter), **ccda** (a `<ClinicalDocument>` root),\n * **ncpdp** (a `<Message>` root in the NCPDP SCRIPT namespace), and **dicom** (the `DICM` magic at byte\n * 128). The signatures are **conservative and, on realistic inputs, mutually exclusive**: the\n * distinctive-lead formats (`MSH`, `ISA`, `H`+delimiter, `<ClinicalDocument>`, `<Message>`+ncpdp, the\n * `DICM` magic, `0x0B` VT, `{…\"resourceType\"`) don't overlap on a real message of any one type. They\n * are **not** disjoint in the absolute sense: a pathological input could satisfy two (an MLLP frame\n * enclosing a `<ClinicalDocument>` payload matches both `mllp` and `ccda`; a text file whose byte 128\n * is `DICM` matches both), which is exactly why the **`ambiguous` branch is load-bearing, not dead\n * code**: any co-match is a *detected* ambiguity (a value-free data error asking for `--format`),\n * **never a silent mis-route**.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\n\n/** The set of formats the `cosyte` command names. */\nexport type CosyteFormat = \"hl7\" | \"fhir\" | \"dicom\" | \"x12\" | \"ccda\" | \"ncpdp\" | \"astm\" | \"mllp\";\n\n/**\n * How confident autodetection is:\n * - `certain`: exactly one signature matched (`format` names it);\n * - `ambiguous`: more than one matched (`format` is `null`; `candidates` names them);\n * - `none`: nothing matched (`format` is `null`; `candidates` is empty).\n *\n * `format` is `null` unless `confidence` is `certain`, so a non-certain result can never be mistaken\n * for a routable format.\n */\nexport interface DetectResult {\n /** The detected format, or `null` when `confidence` is not `certain`. */\n readonly format: CosyteFormat | null;\n /** The detection confidence. */\n readonly confidence: \"certain\" | \"ambiguous\" | \"none\";\n /** The matching candidate formats (0 for `none`, 1 for `certain`, ≥2 for `ambiguous`). Value-free. */\n readonly candidates: readonly CosyteFormat[];\n}\n\n/** A single format signature: a value-free predicate over the input's decoded prefix + raw bytes. */\ninterface Signature {\n readonly format: CosyteFormat;\n readonly match: (prefix: string, bytes: Uint8Array) => boolean;\n}\n\n/** How many leading bytes to decode for text sniffing. Small: signatures live in the first line. */\nconst SNIFF_BYTES = 512;\n\n/** Strip a leading UTF-8 BOM and any leading ASCII whitespace for a tolerant sniff. Deliberately does\n * **not** strip the MLLP `0x0B` VT frame byte (`\\v`): that byte is the mllp signature, so consuming it\n * here would collide the hl7 and mllp signatures on a framed message. */\nfunction leadingText(bytes: Uint8Array): string {\n const slice = bytes.subarray(0, SNIFF_BYTES);\n let text = new TextDecoder(\"utf-8\", { fatal: false }).decode(slice);\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\n return text;\n}\n\n/** Trim only regular leading whitespace (space/tab/CR/LF/FF), never the `0x0B` VT MLLP frame byte. */\nfunction trimLeading(prefix: string): string {\n return prefix.replace(/^[ \\t\\r\\n\\f]+/, \"\");\n}\n\n/** True iff `ch` is a single printable, non-alphanumeric byte usable as a wire delimiter (e.g. `|`, `*`). */\nfunction isDelimiter(ch: string | undefined): boolean {\n if (ch === undefined) return false;\n const code = ch.charCodeAt(0);\n return code > 0x20 && code < 0x7f && !/[A-Za-z0-9]/.test(ch);\n}\n\n/**\n * HL7 v2: the message begins with an `MSH` segment whose 4th character is the field separator\n * (conventionally `|`) followed by the encoding characters. Conservative: requires `MSH` + a\n * non-alphanumeric single-char field separator. An MLLP-framed message (leading `0x0B`) is **not**\n * claimed here (it is the `mllp` signature) because {@link trimLeading} preserves the VT byte.\n */\nfunction looksLikeHl7(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"MSH\") && isDelimiter(s[3]);\n}\n\n/**\n * MLLP: a Minimal Lower Layer Protocol frame opens with the `0x0B` VT byte. This is a **transport\n * framing**, not a document format: the CLI de-frames it and parses the enclosed HL7 v2 payload(s).\n * The check is on the **raw first byte**, so it is disjoint from every text signature.\n */\nfunction looksLikeMllp(_prefix: string, bytes: Uint8Array): boolean {\n return bytes[0] === 0x0b;\n}\n\n/**\n * FHIR: a JSON object whose first non-whitespace byte is `{` and which declares a string-valued\n * top-level `resourceType` member near the top. Conservative: both the object framing and the\n * `resourceType` key must be present, so a bare JSON object without it is not claimed as FHIR.\n */\nfunction looksLikeFhir(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"{\")) return false;\n return /\"resourceType\"\\s*:\\s*\"/.test(s);\n}\n\n/**\n * X12 EDI: an interchange opens with the fixed 3-byte `ISA` segment id immediately followed by the\n * element separator (a non-alphanumeric byte: `*` conventionally, but delimiter-agnostic).\n */\nfunction looksLikeX12(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"ISA\") && isDelimiter(s[3]);\n}\n\n/**\n * ASTM E1394/E1381 records: the first record is an `H` (header) whose second byte is the field\n * delimiter and whose next three bytes are the repeat / component / escape **delimiter declarations**\n * (all punctuation: classically `\\^&`). Requiring the full 4-delimiter block, not just `H` + one\n * delimiter, keeps a mundane `H:...`/`H!...` text line from being confidently mis-routed to ASTM (it\n * would instead be a value-free `CLI_FORMAT_UNDETECTED`). Distinct from HL7 (`MSH`) and X12 (`ISA`).\n */\nfunction looksLikeAstm(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"H\") || s.length < 5) return false;\n // s[1] = field delimiter; s[2..4] = the repeat/component/escape delimiter declarations.\n return isDelimiter(s[1]) && isDelimiter(s[2]) && isDelimiter(s[3]) && isDelimiter(s[4]);\n}\n\n/** C-CDA: an HL7 v3 CDA document rooted at `<ClinicalDocument>` (XML). */\nfunction looksLikeCcda(prefix: string): boolean {\n return /<ClinicalDocument[\\s>]/.test(prefix);\n}\n\n/**\n * NCPDP SCRIPT: an ePrescribing message rooted at `<Message>` in the NCPDP SCRIPT namespace.\n * Requires **both** the `<Message>` root and the `ncpdp` namespace marker so a generic `<Message>`\n * XML is not mis-claimed (conservative: disjoint from C-CDA's `<ClinicalDocument>`).\n */\nfunction looksLikeNcpdp(prefix: string): boolean {\n return /<Message[\\s>]/.test(prefix) && /ncpdp/i.test(prefix);\n}\n\n/** DICOM Part 10: the `DICM` magic sits at byte offset 128, after the 128-byte preamble. */\nfunction looksLikeDicom(_prefix: string, bytes: Uint8Array): boolean {\n if (bytes.length < 132) return false;\n return (\n bytes[128] === 0x44 && bytes[129] === 0x49 && bytes[130] === 0x43 && bytes[131] === 0x4d // \"DICM\"\n );\n}\n\n/** The signature registry: disjoint by construction across all eight cosyte formats. */\nconst SIGNATURES: readonly Signature[] = [\n { format: \"hl7\", match: (prefix) => looksLikeHl7(prefix) },\n { format: \"mllp\", match: (prefix, bytes) => looksLikeMllp(prefix, bytes) },\n { format: \"fhir\", match: (prefix) => looksLikeFhir(prefix) },\n { format: \"x12\", match: (prefix) => looksLikeX12(prefix) },\n { format: \"astm\", match: (prefix) => looksLikeAstm(prefix) },\n { format: \"ccda\", match: (prefix) => looksLikeCcda(prefix) },\n { format: \"ncpdp\", match: (prefix) => looksLikeNcpdp(prefix) },\n { format: \"dicom\", match: (prefix, bytes) => looksLikeDicom(prefix, bytes) },\n];\n\n/** The formats content-autodetection can recognise (every format now carries a signature). */\nexport const DETECTABLE_FORMATS: readonly CosyteFormat[] = SIGNATURES.map((s) => s.format);\n\n/**\n * Detect the healthcare format of `bytes` by content, conservatively.\n *\n * @param bytes - The input bytes (a whole file or a stdin buffer). Only the leading prefix is sniffed.\n * @returns A {@link DetectResult}: `certain` + a `format` on a single match, else `ambiguous`/`none`\n * with `format: null` and the value-free `candidates` list. **Never guesses.**\n * @example\n * ```ts\n * import { detectFormat } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * detectFormat(enc.encode(\"MSH|^~\\\\&|A|B\\r\")).format; // => \"hl7\"\n * detectFormat(enc.encode('{\"resourceType\":\"Patient\"}')).format; // => \"fhir\"\n * detectFormat(enc.encode(\"hello\")).confidence; // => \"none\"\n * ```\n */\nexport function detectFormat(bytes: Uint8Array): DetectResult {\n if (bytes.length === 0) return classifyCandidates([]);\n const prefix = leadingText(bytes);\n const candidates = SIGNATURES.filter((sig) => sig.match(prefix, bytes)).map((sig) => sig.format);\n return classifyCandidates(candidates);\n}\n\n/**\n * Classify a list of matched candidate formats into a {@link DetectResult}: exactly one → `certain`,\n * zero → `none`, two-or-more → `ambiguous` (all with `format` `null` unless certain). Split out and\n * exported so the **ambiguity** contract is directly testable. It is otherwise unreachable while\n * every signature is disjoint, and it must stay a *detected* ambiguity, never a mis-route.\n *\n * @param candidates - The formats whose signatures matched the input.\n * @returns The classified {@link DetectResult}.\n * @example\n * ```ts\n * import { classifyCandidates } from \"@cosyte/cli\";\n *\n * classifyCandidates([\"hl7\"]).confidence; // => \"certain\"\n * classifyCandidates([]).confidence; // => \"none\"\n * classifyCandidates([\"hl7\", \"fhir\"]).confidence; // => \"ambiguous\"\n * ```\n */\nexport function classifyCandidates(candidates: readonly CosyteFormat[]): DetectResult {\n const [first, second] = candidates;\n if (second !== undefined) return { format: null, confidence: \"ambiguous\", candidates };\n if (first !== undefined) return { format: first, confidence: \"certain\", candidates };\n return { format: null, confidence: \"none\", candidates: [] };\n}\n\n/**\n * Build the value-free {@link CliError} for a **non-certain** detection: the data error the caller\n * returns instead of guessing a parser. `ambiguous` names the matching candidates (a value-free code\n * list); `none` asks for `--format`. Both map to the data-error exit (`65`). Never echoes input bytes.\n *\n * @param detected - A {@link DetectResult} whose `format` is `null` (i.e. not `certain`).\n * @returns A value-free `CLI_FORMAT_AMBIGUOUS` or `CLI_FORMAT_UNDETECTED` error.\n * @example\n * ```ts\n * import { classifyCandidates, detectionError } from \"@cosyte/cli\";\n *\n * detectionError(classifyCandidates([])).code; // => \"CLI_FORMAT_UNDETECTED\"\n * detectionError(classifyCandidates([\"hl7\", \"fhir\"])).code; // => \"CLI_FORMAT_AMBIGUOUS\"\n * ```\n */\nexport function detectionError(detected: DetectResult): CliError {\n if (detected.confidence === \"ambiguous\") {\n return new CliError(\n CLI_CODES.CLI_FORMAT_AMBIGUOUS,\n EXIT.DATAERR,\n `input matched multiple formats (${detected.candidates.join(\", \")}); disambiguate with --format`,\n );\n }\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNDETECTED,\n EXIT.DATAERR,\n `could not detect the input format; re-run with --format (detectable: ${DETECTABLE_FORMATS.join(\", \")})`,\n );\n}\n\n/** The full set of format names `--format` accepts as syntactically valid (a bad value is a usage error). */\nexport const KNOWN_FORMATS: readonly CosyteFormat[] = [\n \"hl7\",\n \"fhir\",\n \"dicom\",\n \"x12\",\n \"ccda\",\n \"ncpdp\",\n \"astm\",\n \"mllp\",\n];\n\n/**\n * Narrow an arbitrary `--format` string to a {@link CosyteFormat}, or `null` if it is not a known\n * format name (which the caller turns into a usage error, exit `2`).\n *\n * @param value - The raw `--format` argument.\n * @returns The narrowed format, or `null`.\n * @example\n * ```ts\n * import { asCosyteFormat } from \"@cosyte/cli\";\n *\n * asCosyteFormat(\"hl7\"); // => \"hl7\"\n * asCosyteFormat(\"nope\"); // => null\n * ```\n */\nexport function asCosyteFormat(value: string): CosyteFormat | null {\n return (KNOWN_FORMATS as readonly string[]).includes(value) ? (value as CosyteFormat) : null;\n}\n","/**\n * The CLI's **value-free finding** shape and the positional locators that populate it. A finding says\n * *what kind* of thing was observed (a stable code + severity) and *where* (a positional locator),\n * **never** the offending value. Shared by `validate` (conformance findings) and\n * `inspect` (structural summary) so both render locations identically and value-free.\n *\n * @packageDocumentation\n */\n\n/**\n * A single value-free finding: a stable code, a severity, and a positional locator. Every field is\n * safe to print, log, or serialize. None carries a name, DOB, MRN, or field value.\n */\nexport interface Finding {\n /** The stable diagnostic/warning code (the wrapped library's or the CLI's). */\n readonly code: string;\n /** The R4-style severity (`fatal` | `error` | `warning` | `information`), or `warning` for HL7. */\n readonly severity: string;\n /** A value-free positional locator: a FHIRPath expression, or an HL7 segment/field index path. */\n readonly location: string;\n}\n\n/** The minimal, value-free positional shape shared by HL7 warnings (indices only, never a value). */\ninterface Hl7PositionLike {\n readonly segmentIndex: number;\n readonly fieldIndex?: number;\n readonly repetitionIndex?: number;\n readonly componentIndex?: number;\n readonly subcomponentIndex?: number;\n}\n\n/**\n * Render an HL7 warning position as a **value-free** locator string built only from its numeric\n * indices: e.g. `seg[3].field[5].comp[1]`. No segment content, no field value, ever appears; only the\n * structural coordinates the parser reported.\n *\n * @param pos - The HL7 position (segment/field/repetition/component/subcomponent indices).\n * @returns A value-free locator, e.g. `\"seg[3].field[5]\"`.\n * @example\n * ```ts\n * import { formatHl7Position } from \"@cosyte/cli\";\n *\n * formatHl7Position({ segmentIndex: 3, fieldIndex: 5 }); // => \"seg[3].field[5]\"\n * formatHl7Position({ segmentIndex: 0 }); // => \"seg[0]\"\n * ```\n */\nexport function formatHl7Position(pos: Hl7PositionLike): string {\n let out = `seg[${String(pos.segmentIndex)}]`;\n if (pos.fieldIndex !== undefined) out += `.field[${String(pos.fieldIndex)}]`;\n if (pos.repetitionIndex !== undefined) out += `.rep[${String(pos.repetitionIndex)}]`;\n if (pos.componentIndex !== undefined) out += `.comp[${String(pos.componentIndex)}]`;\n if (pos.subcomponentIndex !== undefined) out += `.sub[${String(pos.subcomponentIndex)}]`;\n return out;\n}\n","/**\n * The **per-format parser adapter registry**: the single place the CLI routes a resolved format to\n * its wrapped `@cosyte/*` parser, for each of the four wrapping operations (`parse` / `inspect` /\n * `fmt` / `validate`). One lazy, value-free registry, so the wrapper boundary lives in exactly one\n * file.\n *\n * **Capability is per (format, operation).** Not every parser faithfully supports every operation:\n * DICOM's model is binary (no faithful JSON `parse`, no text `fmt`), C-CDA's canonical form is XML (no\n * library-blessed JSON `parse`), MLLP is a transport container (de-framed to HL7, `parse`/`inspect`\n * only). {@link OP_SUPPORT} is the honest matrix; an unsupported (format, op) is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, **never** a faked result.\n *\n * **Lazy + optional.** Every parser is imported dynamically inside its branch, so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code. The six breadth parsers are `optionalDependencies`: if\n * one is absent the dynamic import is caught and degrades to a value-free `CLI_PARSER_UNAVAILABLE`\n * (exit `69`) rather than an unhandled crash: the CLI core still works with any of them missing.\n *\n * @packageDocumentation\n */\n\nimport type * as CosyteFhir from \"@cosyte/fhir\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport { formatHl7Position, type Finding } from \"./findings.js\";\nimport type { CosyteFormat } from \"./format.js\";\n\n/** The four wrapping operations a command can ask a format's adapter to perform. */\nexport type Op = \"parse\" | \"inspect\" | \"fmt\" | \"validate\";\n\n/** A value-free parse warning: a stable code plus the parser's positional (index-only) context. */\nexport type ParseWarning = { readonly code: string } & Readonly<Record<string, unknown>>;\n\n/** The result of wrapping a parser's `parse`: the library's parsed model + its value-free warnings. */\nexport interface ParseResult {\n /** The wrapped library's parsed model: emitted verbatim as JSON on the data channel. */\n readonly model: unknown;\n /** The parser's value-free warnings (code + position). */\n readonly warnings: readonly ParseWarning[];\n}\n\n/** The result of a canonical re-serialization (`fmt`): the spec-clean text + a value-free warning count. */\nexport interface FmtResult {\n /** The wrapped serializer's output text. */\n readonly output: string;\n /** How many parse warnings the round-trip surfaced (value-free count only). */\n readonly warningCount: number;\n}\n\n/** The verdict of running a format's validation surface: value-free findings + the validity boolean. */\nexport interface Verdict {\n /** The value-free findings (code + severity + positional locator). */\n readonly findings: readonly Finding[];\n /** `true` iff the input is valid (no error/fatal-severity finding). */\n readonly valid: boolean;\n}\n\n/* ── value-free structural summaries (one variant per format) ─────────────────────────────────── */\n\n/** Value-free structural summary of an HL7 v2 message. */\nexport interface Hl7Summary {\n readonly format: \"hl7\";\n readonly messageType: string | null;\n readonly version: string | null;\n readonly segmentCount: number;\n readonly segments: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a FHIR resource. */\nexport interface FhirSummary {\n readonly format: \"fhir\";\n readonly resourceType: string | null;\n readonly bundleType?: string | null;\n readonly entryCount?: number;\n readonly entryResourceTypes?: Readonly<Record<string, number>>;\n readonly issueCount: number;\n}\n\n/** Value-free structural summary of an X12 interchange (envelope counts + transaction-set ids). */\nexport interface X12Summary {\n readonly format: \"x12\";\n readonly groupCount: number;\n readonly transactionCount: number;\n /** Count of each transaction-set identifier code (ST-01), e.g. `{ \"834\": 1 }`: value-free codes. */\n readonly transactionSetIds: Readonly<Record<string, number>>;\n readonly segmentCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an ASTM record message. */\nexport interface AstmSummary {\n readonly format: \"astm\";\n /** The host-query classification kind (`results` | `orders` | `host-query` | `indeterminate`). */\n readonly messageKind: string;\n readonly recordCount: number;\n /** Count of each single-letter record type, e.g. `{ H: 1, P: 1, O: 2, R: 4, L: 1 }`. */\n readonly recordTypes: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a C-CDA document (document type + section LOINC codes). */\nexport interface CcdaSummary {\n readonly format: \"ccda\";\n readonly documentType: string | null;\n readonly sectionCount: number;\n /** The LOINC `code` of each top-level section (value-free classification codes). */\n readonly sectionCodes: readonly string[];\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a DICOM dataset (classification UIDs + element count). */\nexport interface DicomSummary {\n readonly format: \"dicom\";\n /** The SOP Class UID (a standard OID identifying the object type: value-free classification). */\n readonly sopClassUid: string | null;\n /** The Transfer Syntax UID (encoding classification: value-free). */\n readonly transferSyntaxUid: string | null;\n readonly elementCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an NCPDP SCRIPT message. */\nexport interface NcpdpSummary {\n readonly format: \"ncpdp\";\n readonly standard: \"SCRIPT\";\n /** The SCRIPT message type (e.g. `NewRx`, `CancelRx`: a value-free classification). */\n readonly messageType: string | null;\n /** The SCRIPT version (e.g. `2017071`: value-free). */\n readonly version: string | null;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an MLLP stream (frame count only; the payloads are HL7). */\nexport interface MllpSummary {\n readonly format: \"mllp\";\n readonly frameCount: number;\n readonly warningCount: number;\n}\n\n/** The discriminated value-free structural summary `inspect` renders. */\nexport type InspectSummary =\n | Hl7Summary\n | FhirSummary\n | X12Summary\n | AstmSummary\n | CcdaSummary\n | DicomSummary\n | NcpdpSummary\n | MllpSummary;\n\n/* ── the capability matrix ───────────────────────────────────────────────────────────────────── */\n\n/**\n * The honest per-format operation matrix. A (format, op) pair absent here is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, never a faked result. The unsupported cells and why:\n * - **dicom** `parse`/`fmt`. The model is binary (no faithful JSON view; `serializeDicom` emits a\n * Part-10 byte stream, not text). `inspect`/`validate` are supported.\n * - **ccda** `parse`: the canonical form is XML; there is no library-blessed JSON model, so `fmt`\n * (XML re-serialize) is the faithful surface. `inspect`/`fmt`/`validate` are supported.\n * - **mllp** `fmt`/`validate`: MLLP is a transport container the CLI de-frames to HL7; `parse` yields\n * the enclosed HL7 message(s) and `inspect` reports the frame count.\n *\n * @example\n * ```ts\n * import { OP_SUPPORT } from \"@cosyte/cli\";\n *\n * OP_SUPPORT.dicom.has(\"parse\"); // => false\n * OP_SUPPORT.hl7.has(\"validate\"); // => true\n * ```\n */\nexport const OP_SUPPORT: Readonly<Record<CosyteFormat, ReadonlySet<Op>>> = {\n hl7: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n fhir: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n x12: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n astm: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ncpdp: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ccda: new Set<Op>([\"inspect\", \"fmt\", \"validate\"]),\n dicom: new Set<Op>([\"inspect\", \"validate\"]),\n mllp: new Set<Op>([\"parse\", \"inspect\"]),\n};\n\n/**\n * True iff `format`'s wrapped parser supports `op` in this build (see {@link OP_SUPPORT}).\n *\n * @param format - The resolved format.\n * @param op - The wrapping operation.\n * @returns Whether the (format, op) pair is wired.\n * @example\n * ```ts\n * import { supportsOp } from \"@cosyte/cli\";\n *\n * supportsOp(\"x12\", \"fmt\"); // => true\n * supportsOp(\"dicom\", \"parse\"); // => false\n * ```\n */\nexport function supportsOp(format: CosyteFormat, op: Op): boolean {\n return OP_SUPPORT[format].has(op);\n}\n\n/**\n * The formats that support `op`, as a sorted, value-free list: used to build the \"does not support\"\n * diagnostic so the user is told which formats *do* support the operation they asked for.\n *\n * @param op - The wrapping operation.\n * @returns The supporting format names, sorted.\n * @example\n * ```ts\n * import { formatsSupporting } from \"@cosyte/cli\";\n *\n * formatsSupporting(\"fmt\"); // => [\"astm\", \"ccda\", \"fhir\", \"hl7\", \"ncpdp\", \"x12\"]\n * ```\n */\nexport function formatsSupporting(op: Op): readonly CosyteFormat[] {\n return (Object.keys(OP_SUPPORT) as CosyteFormat[]).filter((f) => OP_SUPPORT[f].has(op)).sort();\n}\n\n/* ── value-free helpers ──────────────────────────────────────────────────────────────────────── */\n\n/**\n * Render an arbitrary parser **position** object as a value-free locator string, keeping **only**\n * number-valued own properties (the parsers' positions are index-only): e.g. `{ segmentIndex: 3,\n * elementIndex: 2 }` → `segmentIndex[3].elementIndex[2]`. A non-number field (which a position should\n * never carry) is dropped, so a stray value can never reach a diagnostic. Falls back to `\"?\"` when no\n * numeric index is present.\n *\n * @param pos - A parser position object (index-only by the parser's contract).\n * @returns A value-free locator built solely from numeric indices.\n * @example\n * ```ts\n * import { valueFreeLocator } from \"@cosyte/cli\";\n *\n * valueFreeLocator({ segmentIndex: 3, elementIndex: 2 }); // => \"segmentIndex[3].elementIndex[2]\"\n * valueFreeLocator({}); // => \"?\"\n * ```\n */\nexport function valueFreeLocator(pos: unknown): string {\n if (typeof pos !== \"object\" || pos === null) return \"?\";\n const parts: string[] = [];\n for (const [k, v] of Object.entries(pos)) {\n if (typeof v === \"number\") parts.push(`${k}[${String(v)}]`);\n }\n return parts.length > 0 ? parts.join(\".\") : \"?\";\n}\n\n/** Severities that make an input **invalid** (exit `1`). Recovered warnings never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** Whether any finding is error/fatal severity (i.e. the input is invalid). */\nfunction anyError(findings: readonly Finding[]): boolean {\n return findings.some((f) => ERROR_SEVERITIES.has(f.severity));\n}\n\n/**\n * Lazy-import an **optional** parser package, mapping an *absent* package to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`): the graceful-degradation path for the `optionalDependencies`\n * breadth parsers. A genuine import that succeeds passes straight through; any error whose\n * shape is \"module not found\" becomes the value-free CLI error. Other errors propagate unchanged.\n *\n * @template T - The imported module's type.\n * @param format - The format whose optional parser is being loaded (named in the diagnostic).\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptional } from \"@cosyte/cli\";\n *\n * // a present parser resolves; an absent one throws CLI_PARSER_UNAVAILABLE\n * await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n * ```\n */\nexport async function loadOptional<T>(format: CosyteFormat, load: () => Promise<T>): Promise<T> {\n return loadOptionalPackage(\n `the @cosyte/${format} parser is not installed; install it to use this format ` +\n `(it is an optional dependency)`,\n load,\n );\n}\n\n/**\n * The same graceful-degradation path as {@link loadOptional}, keyed on a **package name** rather than\n * a {@link CosyteFormat}, with the diagnostic supplied by the caller.\n *\n * Two of the packages the CLI lazy-loads are not wire-format parsers and so cannot go through\n * {@link loadOptional}: `@cosyte/transform` (a conversion library, not one of the eight formats, so\n * calling it a \"parser\" in the diagnostic would be wrong) and `@cosyte/fhir` (a format, but absent for\n * a reason no reinstall fixes, which the message has to say). Both are reachable from a published\n * install only if the user already has them, so both must degrade to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`) instead of surfacing a raw resolver error and a stack frame.\n *\n * @template T - The imported module's type.\n * @param detail - The value-free diagnostic detail shown when the package is absent.\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptionalPackage } from \"@cosyte/cli\";\n *\n * await loadOptionalPackage(\"the conversion library is not installed\", () =>\n * import(\"@cosyte/transform\"),\n * );\n * ```\n */\nexport async function loadOptionalPackage<T>(detail: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (e) {\n if (isModuleNotFound(e)) {\n throw new CliError(CLI_CODES.CLI_PARSER_UNAVAILABLE, EXIT.UNAVAILABLE, detail);\n }\n throw e;\n }\n}\n\n/**\n * Why `@cosyte/fhir` is absent, in the words a user can act on. It is not on the npm registry, so it\n * cannot be a declared dependency of this package at all, and no reinstall of `@cosyte/cli` will\n * produce it. Value-free by construction: a package name and a statement of fact, no input echoed.\n */\nconst FHIR_UNAVAILABLE =\n \"the @cosyte/fhir parser is not installed, and it is not currently on the npm registry, \" +\n \"so it cannot be installed from there; FHIR support is unavailable in this install\";\n\n/**\n * Load `@cosyte/fhir`, degrading to a value-free `CLI_PARSER_UNAVAILABLE` when it is absent.\n *\n * Every FHIR branch in this file and the `convert` command go through here, so there is exactly one\n * place that decides what an absent FHIR library does. It is deliberately not re-exported from the\n * package entry point: consumers get {@link loadOptionalPackage}, not this repo's own wiring.\n *\n * @returns The `@cosyte/fhir` module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent.\n * @example\n * ```ts\n * const { parseResource } = await loadFhir();\n * ```\n */\nexport async function loadFhir(): Promise<typeof CosyteFhir> {\n return loadOptionalPackage(FHIR_UNAVAILABLE, () => import(\"@cosyte/fhir\"));\n}\n\n/** True iff `e` is a \"module not found\" failure, by Node's `code`, or the standard resolver message. */\nfunction isModuleNotFound(e: unknown): boolean {\n if (typeof e !== \"object\" || e === null) return false;\n const code = \"code\" in e ? e.code : undefined;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") return true;\n const message = \"message\" in e && typeof e.message === \"string\" ? e.message : \"\";\n return /Cannot find (package|module)|Failed to (load|resolve)/i.test(message);\n}\n\n/* ── parse ───────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Parse one record of `format` into the wrapped library's model + its value-free warnings. The model\n * is emitted verbatim on the data channel; the CLI adds no parsing of its own.\n *\n * @param format - A format for which `supportsOp(format, \"parse\")` is true.\n * @param bytes - The single record's bytes (already de-framed for MLLP: callers pass `\"hl7\"` there).\n * @returns The parsed model + value-free warnings.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * own rejection propagates for the command's value-free failure boundary to catch.\n * @example\n * ```ts\n * import { parseFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}');\n * (await parseFormat(\"fhir\", bytes)).warnings.length; // => 0\n * ```\n */\nexport async function parseFormat(format: CosyteFormat, bytes: Uint8Array): Promise<ParseResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return {\n model: msg.toJSON(),\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const text = decode(bytes);\n const { resource, issues } = parseResource(text);\n const model: unknown = JSON.parse(serializeResource(resource));\n return {\n model,\n warnings: issues.map((i) => ({\n code: i.code,\n severity: i.severity,\n expression: i.expression,\n })),\n };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return {\n model: ix,\n warnings: ix.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"dicom\":\n case \"ccda\":\n case \"mllp\":\n // Guarded upstream by supportsOp; a direct call for an unsupported (format, op) is value-free.\n throw unsupportedInternal(format, \"parse\");\n }\n}\n\n/* ── inspect ─────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Build the value-free structural summary of one input of `format`: counts and structural type codes\n * only, never a field value.\n *\n * @param format - A format for which `supportsOp(format, \"inspect\")` is true.\n * @param bytes - The input bytes.\n * @returns A {@link InspectSummary} variant for the format.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary.\n * @example\n * ```ts\n * import { inspectFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\"}');\n * (await inspectFormat(\"fhir\", bytes)).format; // => \"fhir\"\n * ```\n */\nexport async function inspectFormat(\n format: CosyteFormat,\n bytes: Uint8Array,\n): Promise<InspectSummary> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const segments: Record<string, number> = {};\n const all = msg.allSegments();\n for (const seg of all) segments[seg.type] = (segments[seg.type] ?? 0) + 1;\n return {\n format: \"hl7\",\n messageType: msg.meta.type ?? null,\n version: msg.meta.version ?? null,\n segmentCount: all.length,\n segments,\n warningCount: msg.warnings.length,\n };\n }\n case \"fhir\": {\n const { parseResource, resourceType, readBundle } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const rt = resourceType(resource) ?? null;\n if (rt === \"Bundle\") {\n const bundle = readBundle(resource);\n const entryResourceTypes: Record<string, number> = {};\n for (const e of bundle.entries) {\n const t = e.resourceType ?? \"(none)\";\n entryResourceTypes[t] = (entryResourceTypes[t] ?? 0) + 1;\n }\n return {\n format: \"fhir\",\n resourceType: rt,\n bundleType: bundle.type ?? null,\n entryCount: bundle.entries.length,\n entryResourceTypes,\n issueCount: issues.length,\n };\n }\n return { format: \"fhir\", resourceType: rt, issueCount: issues.length };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const transactionSetIds: Record<string, number> = {};\n let transactionCount = 0;\n let segmentCount = 0;\n for (const g of ix.groups) {\n for (const t of g.transactions) {\n transactionCount += 1;\n segmentCount += t.segments.length;\n const id = t.st.elements[1] ?? \"(unknown)\";\n transactionSetIds[id] = (transactionSetIds[id] ?? 0) + 1;\n }\n }\n return {\n format: \"x12\",\n groupCount: ix.groups.length,\n transactionCount,\n transactionSetIds,\n segmentCount,\n warningCount: ix.warnings.length,\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const recordTypes: Record<string, number> = {};\n for (const r of msg.records) recordTypes[r.type] = (recordTypes[r.type] ?? 0) + 1;\n return {\n format: \"astm\",\n messageKind: msg.classification.kind,\n recordCount: msg.records.length,\n recordTypes,\n warningCount: msg.warnings.length,\n };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const sectionCodes: string[] = [];\n for (const s of doc.sections) {\n const code = s.code?.code;\n if (typeof code === \"string\") sectionCodes.push(code);\n }\n return {\n format: \"ccda\",\n documentType: doc.documentType ?? null,\n sectionCount: doc.sections.length,\n sectionCodes,\n warningCount: doc.warnings.length,\n };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n let warningCount = 0;\n const ds = parseDicom(Buffer.from(bytes), { onWarning: () => (warningCount += 1) });\n return {\n format: \"dicom\",\n sopClassUid: ds.fileMeta?.mediaStorageSOPClassUID ?? null,\n transferSyntaxUid: ds.fileMeta?.transferSyntaxUID ?? null,\n elementCount: ds.elements().length,\n warningCount,\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n format: \"ncpdp\",\n standard: \"SCRIPT\",\n messageType: msg.body.kind ?? null,\n version: msg.header.version ?? null,\n warningCount: msg.warnings.length,\n };\n }\n case \"mllp\": {\n const { payloads, warningCount } = await deframeMllp(bytes);\n return { format: \"mllp\", frameCount: payloads.length, warningCount };\n }\n }\n}\n\n/* ── fmt ─────────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Canonically re-serialize one input of `format` via the wrapped library's spec-clean serializer. The\n * CLI never re-canonicalizes on its own; the output is exactly the serializer's.\n *\n * @param format - A format for which `supportsOp(format, \"fmt\")` is true.\n * @param bytes - The input bytes.\n * @returns The serialized text + a value-free warning count.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary (no partial emit).\n * @example\n * ```ts\n * import { fmtFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{ \"resourceType\":\"Patient\" , \"id\":\"x\" }');\n * (await fmtFormat(\"fhir\", bytes)).output.startsWith(\"{\"); // => true\n * ```\n */\nexport async function fmtFormat(format: CosyteFormat, bytes: Uint8Array): Promise<FmtResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return { output: msg.toString(), warningCount: msg.warnings.length };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n return { output: serializeResource(resource), warningCount: issues.length };\n }\n case \"x12\": {\n const { parseX12, serializeX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return { output: serializeX12(ix), warningCount: ix.warnings.length };\n }\n case \"astm\": {\n const { parseAstmRecords, serializeAstmRecords } = await loadOptional(\n \"astm\",\n () => import(\"@cosyte/astm\"),\n );\n const msg = parseAstmRecords(decode(bytes));\n return { output: serializeAstmRecords(msg), warningCount: msg.warnings.length };\n }\n case \"ccda\": {\n const { parseCcda, serializeCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n return { output: serializeCcda(doc), warningCount: doc.warnings.length };\n }\n case \"ncpdp\": {\n const { parseScript, serializeScript } = await loadOptional(\n \"ncpdp\",\n () => import(\"@cosyte/ncpdp\"),\n );\n const msg = parseScript(decode(bytes));\n return { output: serializeScript(msg), warningCount: msg.warnings.length };\n }\n case \"dicom\":\n case \"mllp\":\n throw unsupportedInternal(format, \"fmt\");\n }\n}\n\n/* ── validate ────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Run the format's validation surface and return a value-free {@link Verdict}. For the Postel's-Law\n * lenient parsers, a **parseable** input is valid: recovered deviations are non-fatal warnings the\n * library surfaces, never a stricter verdict the CLI invents. FHIR additionally runs `validateResource`\n * and is invalid on any error/fatal-severity issue.\n *\n * @param format - A format for which `supportsOp(format, \"validate\")` is true.\n * @param bytes - The input bytes.\n * @returns The value-free verdict (findings + validity).\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; an unparseable input\n * propagates as the wrapped parser's throw for the command to map to a data error (`65`).\n * @example\n * ```ts\n * import { validateFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}');\n * (await validateFormat(\"fhir\", bytes)).valid; // => true\n * ```\n */\nexport async function validateFormat(format: CosyteFormat, bytes: Uint8Array): Promise<Verdict> {\n switch (format) {\n case \"fhir\": {\n const { parseResource, validateResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const validation = validateResource(resource);\n const findings: Finding[] = [\n ...issues.map((i) => finding(i.code, i.severity, i.expression)),\n ...validation.issues.map((i) => finding(i.code, i.severity, i.expression, i.constraint)),\n ];\n return { findings, valid: !anyError(findings) };\n }\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", formatHl7Position(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const findings = ix.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const findings = doc.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n const findings: Finding[] = [];\n parseDicom(Buffer.from(bytes), {\n onWarning: (w) => findings.push(finding(w.code, \"warning\", valueFreeLocator(w.position))),\n });\n return { findings, valid: !anyError(findings) };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"mllp\":\n throw unsupportedInternal(format, \"validate\");\n }\n}\n\n/* ── MLLP de-framing (transport → HL7 payloads) ──────────────────────────────────────────────── */\n\n/**\n * De-frame an MLLP byte stream into its enclosed HL7 payloads via `@cosyte/mllp`'s `FrameReader`. MLLP\n * is a transport container, not a document format: each frame's payload is an HL7 v2 message the CLI\n * then parses/inspects with the `hl7` adapter. Multi-frame streams are the CLI's multi-message surface.\n *\n * @param bytes - The MLLP-framed input.\n * @returns The de-framed HL7 payloads (in stream order) + a value-free framing-warning count.\n * **Truncation is a data error, never a silent drop.** The `FrameReader` is a streaming decoder: an\n * unterminated trailing frame (a VT opened with no closing FS/CR) is left buffered and delivered by\n * *no* callback, so feeding a whole file and reading only `onFrame` would silently lose the partial\n * message with a green exit. We therefore detect an open trailing frame at the byte level (the last\n * VT sits after the last FS: MLLP payloads are HL7 v2 text and never carry the `0x0B`/`0x1C` framing\n * bytes) and reject the whole stream as a value-free `CLI_PARSE_FAILED` data error.\n *\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if `@cosyte/mllp` is absent; `CLI_PARSE_FAILED` (exit\n * `65`) on a truncated stream; a hard framing error propagates for the caller's value-free boundary.\n * @example\n * ```ts\n * import { deframeMllp } from \"@cosyte/cli\";\n *\n * // a VT-framed \"MSH|...\" message → one payload\n * (await deframeMllp(new Uint8Array([0x0b, 0x4d, 0x53, 0x48, 0x1c, 0x0d]))).payloads.length; // => 1\n * ```\n */\nexport async function deframeMllp(\n bytes: Uint8Array,\n): Promise<{ payloads: Buffer[]; warningCount: number }> {\n // Reject an unterminated trailing frame BEFORE de-framing: a VT after the last FS is an open frame\n // the streaming reader would buffer and silently drop. (MLLP payloads never contain 0x0B/0x1C.)\n if (bytes.lastIndexOf(0x0b) > bytes.lastIndexOf(0x1c)) {\n throw new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n \"truncated MLLP stream: an unterminated frame at the end of input (no closing FS/CR)\",\n );\n }\n const { FrameReader } = await loadOptional(\"mllp\", () => import(\"@cosyte/mllp\"));\n const payloads: Buffer[] = [];\n let warningCount = 0;\n const reader = new FrameReader({\n onFrame: (payload) => payloads.push(Buffer.from(payload)),\n onWarning: () => (warningCount += 1),\n });\n reader.push(Buffer.from(bytes));\n return { payloads, warningCount };\n}\n\n/* ── shared internals ────────────────────────────────────────────────────────────────────────── */\n\n/** Decode input bytes as tolerant UTF-8 (the text parsers accept a string). */\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n}\n\n/** Build one value-free {@link Finding}; a FHIR `constraint` (a public spec id) is appended if present. */\nfunction finding(code: string, severity: string, location: string, constraint?: string): Finding {\n const loc = constraint !== undefined ? `${location} (${constraint})` : location;\n return { code, severity, location: loc };\n}\n\n/** The value-free error for an internal (guarded-upstream) unsupported (format, op): a programming bug. */\nfunction unsupportedInternal(format: CosyteFormat, op: Op): CliError {\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\``,\n );\n}\n","/**\n * The shared **input + format resolution** every file-consuming command runs before it touches a\n * wrapped parser: resolve the `<file|->` argument, read its bytes (a file, or stdin for `-`), reject\n * empty input, then resolve the format: an explicit `--format` override (validated) or conservative\n * content autodetection, and confirm the format is actually wired in this build. Factored out of the\n * commands so `parse`/`validate`/`inspect`/`fmt` share one identical, value-free front door and the\n * exit-code contract is applied in exactly one place.\n *\n * Every failure is a value-free {@link CliError} rendered to a {@link RunResult}: a missing argument\n * is a usage error (`2`), an unreadable file a no-input error (`66`), empty/undetected/unwired input a\n * data error (`65`). None ever echoes an input byte.\n *\n * @packageDocumentation\n */\n\nimport { asCosyteFormat, detectFormat, detectionError, type CosyteFormat } from \"./format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { RunDeps } from \"./io.js\";\nimport { formatsSupporting, supportsOp, type Op } from \"./parsers.js\";\nimport type { RunResult } from \"./result.js\";\n\n/** A successfully-resolved input: the format (guaranteed to support the requested op) and the bytes. */\nexport interface ResolvedInput {\n /** The resolved format: guaranteed to satisfy `supportsOp(format, op)` for the requested op. */\n readonly format: CosyteFormat;\n /** The input bytes (a whole file or a drained stdin buffer); guaranteed non-empty. */\n readonly bytes: Uint8Array;\n}\n\n/**\n * The outcome of {@link resolveInput}: either the resolved input, or a ready-to-return value-free\n * {@link RunResult} carrying the diagnostic + exit code for whatever went wrong. A discriminated union\n * so a command reads `if (!r.ok) return r.result;` and then works with `r.input`.\n */\nexport type InputResolution =\n | { readonly ok: true; readonly input: ResolvedInput }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Resolve and read the input, and resolve its format, for a file-consuming command.\n *\n * @param source - The positional `<file|->` argument (or `undefined` when it was omitted).\n * @param formatOverride - The raw `--format` value, or `undefined` to autodetect by content.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param op - The wrapping operation the caller will run; the resolved format is confirmed to support\n * it (else a value-free `CLI_FORMAT_UNSUPPORTED` naming the supporting formats).\n * @returns `{ ok: true, input }` when the bytes read and the format resolved to a parser supporting\n * `op`; else `{ ok: false, result }` with a value-free usage/no-input/data-error {@link RunResult}.\n * @throws Propagates a **non-`CliError`** read failure unchanged, so the dispatcher maps it to\n * `CLI_INTERNAL` (a `CliError` read failure, e.g. a missing file, is caught and returned).\n * @example\n * ```ts\n * import { resolveInput } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await resolveInput(\"patient.json\", undefined, deps, \"parse\");\n * if (r.ok) r.input.format; // => \"fhir\"\n * ```\n */\nexport async function resolveInput(\n source: string | undefined,\n formatOverride: string | undefined,\n deps: RunDeps,\n op: Op,\n): Promise<InputResolution> {\n if (source === undefined) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <file> argument; pass a path or `-` to read stdin\",\n ),\n );\n }\n\n let bytes: Uint8Array;\n try {\n bytes = source === \"-\" ? await deps.readStdin() : await deps.readFile(source);\n } catch (e) {\n if (e instanceof CliError) return fail(e);\n throw e;\n }\n\n if (bytes.length === 0) {\n return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n // Resolve the format: an explicit --format override (validated), else content autodetection.\n let format: CosyteFormat;\n if (formatOverride !== undefined) {\n const narrowed = asCosyteFormat(formatOverride);\n if (narrowed === null) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"unknown --format value; expected one of hl7, fhir, dicom, x12, ccda, ncpdp, astm, mllp\",\n ),\n );\n }\n format = narrowed;\n } else {\n const detected = detectFormat(bytes);\n // `format` is non-null iff detection is `certain`; `none`/`ambiguous` become a value-free data error.\n if (detected.format === null) return fail(detectionError(detected));\n format = detected.format;\n }\n\n if (!supportsOp(format, op)) {\n return fail(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\` in this CLI build ` +\n `(${op} supports: ${formatsSupporting(op).join(\", \")})`,\n ),\n );\n }\n\n return { ok: true, input: { format, bytes } };\n}\n\n/** Wrap a {@link CliError} as a failed {@link InputResolution}. */\nfunction fail(e: CliError): InputResolution {\n return { ok: false, result: errorResult(e) };\n}\n","/**\n * The CLI's **global PHI display posture**: the single mechanism that gates whether *any* input\n * value may appear on a **secondary surface** (stderr, a diagnostic, a warning, a log line). The CLI\n * is **value-free by default**: every secondary surface carries only positional/structural context\n * (a stable code, a segment/field index, a byte offset, a file path, a format name), never a name, a\n * DOB, an MRN, or a field value. `stdout` is the **data channel** (the user's explicit request) and\n * is exempt: the posture governs everything *but* stdout.\n *\n * `--unsafe-show-values` is the **single, explicit, loud door** to a value on a secondary surface. It\n * is off by default, PHI-exposing by design, and its effect flows through exactly one chokepoint here\n * ({@link unsafeInputSuffix}) so the \"a value appears on a secondary surface **iff** the flag is set\"\n * property is provable in one place rather than scattered across commands.\n *\n * @packageDocumentation\n */\n\n/**\n * The resolved PHI display posture for one invocation. `showValues` is `true` **only** when the user\n * passed `--unsafe-show-values`; every value-echoing decision reads this one flag.\n */\nexport interface PhiPosture {\n /** `true` iff `--unsafe-show-values` was given: a value may appear on a secondary surface. */\n readonly showValues: boolean;\n}\n\n/** The default, safe posture: no value ever reaches a secondary surface. */\nexport const VALUE_FREE: PhiPosture = { showValues: false };\n\n/** The opted-in, PHI-exposing posture selected by `--unsafe-show-values`. */\nexport const SHOW_VALUES: PhiPosture = { showValues: true };\n\n/** The single global flag token that opts into showing values on secondary surfaces. */\nexport const UNSAFE_SHOW_VALUES_FLAG = \"--unsafe-show-values\";\n\n/**\n * The maximum number of leading input bytes an `--unsafe-show-values` diagnostic may echo. Bounded so\n * an unsafe excerpt stays a single, readable diagnostic line rather than dumping a whole message.\n */\nexport const UNSAFE_EXCERPT_MAX = 200;\n\n/**\n * Resolve the global `--unsafe-show-values` flag out of an argument vector, **order-independently**\n * (it may appear before or after the subcommand), and return the posture plus the argv with every\n * occurrence of the flag removed, so each command's own `parseArgs` never sees it and cannot reject\n * it as unknown. This is the one place the flag is recognised.\n *\n * @param argv - The raw arguments (after the program name).\n * @returns The resolved {@link PhiPosture} and the flag-stripped argv.\n * @example\n * ```ts\n * import { extractPhiPosture } from \"@cosyte/cli\";\n *\n * extractPhiPosture([\"parse\", \"x.hl7\"]).posture.showValues; // => false\n * extractPhiPosture([\"--unsafe-show-values\", \"parse\", \"x.hl7\"]).posture.showValues; // => true\n * extractPhiPosture([\"parse\", \"x.hl7\", \"--unsafe-show-values\"]).argv; // => [\"parse\", \"x.hl7\"]\n * ```\n */\nexport function extractPhiPosture(argv: readonly string[]): {\n posture: PhiPosture;\n argv: string[];\n} {\n const showValues = argv.includes(UNSAFE_SHOW_VALUES_FLAG);\n const cleaned = argv.filter((a) => a !== UNSAFE_SHOW_VALUES_FLAG);\n return { posture: showValues ? SHOW_VALUES : VALUE_FREE, argv: cleaned };\n}\n\n/**\n * Build the **only** value-bearing addition the CLI ever appends to a secondary (stderr) surface: a\n * bounded, single-line excerpt of the offending input, shown **iff** `--unsafe-show-values` is set.\n * Under the default value-free posture it returns the empty string, so a diagnostic stays value-free\n * unless the user explicitly opted in. This is the single chokepoint the PHI-leak matrix pins.\n *\n * @param bytes - The input the CLI is operating on (only the leading {@link UNSAFE_EXCERPT_MAX} bytes\n * are considered).\n * @param posture - The resolved {@link PhiPosture}.\n * @returns `\"\"` under the value-free default; otherwise a ` [unsafe-show-values] …` suffix carrying a\n * bounded, newline-flattened prefix of `bytes`.\n * @example\n * ```ts\n * import { unsafeInputSuffix, VALUE_FREE, SHOW_VALUES } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"bad message\");\n * unsafeInputSuffix(bytes, VALUE_FREE); // => \"\"\n * unsafeInputSuffix(bytes, SHOW_VALUES); // => \" [unsafe-show-values] offending input …: bad message\"\n * ```\n */\nexport function unsafeInputSuffix(bytes: Uint8Array, posture: PhiPosture): string {\n if (!posture.showValues) return \"\";\n const text = new TextDecoder(\"utf-8\", { fatal: false })\n .decode(bytes.subarray(0, UNSAFE_EXCERPT_MAX))\n .replace(/[\\r\\n\\t]+/g, \" \")\n .trim();\n if (text.length === 0) return \"\";\n return ` [unsafe-show-values] offending input (first ${String(UNSAFE_EXCERPT_MAX)} bytes): ${text}`;\n}\n","/**\n * The **wrapped-parser failure boundary**: the single, value-free way every command turns a thrown\n * parser/codec exception into a {@link RunResult}. A wrapped library raises a fatal on genuinely\n * unparseable input; its message (and, for HL7, its `snippet`) can embed the offending bytes, so the\n * CLI **never** surfaces that message. It surfaces only a stable, PHI-free code token (via\n * {@link extractStableCode}) plus the format name: the parsers' \"warning = code + position, never a\n * value\" rule at the CLI edge.\n *\n * The one, opt-in exception is `--unsafe-show-values`, whose bounded excerpt is appended through the\n * lone chokepoint in `core/phi.ts` ({@link unsafeInputSuffix}), so the \"a value appears on a\n * secondary surface **iff** the flag is set\" property stays provable in one place, uniformly across\n * `parse`/`validate`/`inspect`/`fmt`.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { CosyteFormat } from \"./format.js\";\nimport { unsafeInputSuffix, type PhiPosture } from \"./phi.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Pull a `code` off a thrown value **only** when it is a PHI-free constant token\n * (`^[A-Z][A-Z0-9_]*$`: a letter-led UPPER_SNAKE code like `MALFORMED_JSON`), e.g. a wrapped\n * parser's stable fatal code. Anything else (no `code`, a non-string, a non-token, or a **pure-digit**\n * value that could be a raw identifier) yields `null`, so a parser exception that embedded input bytes\n * in a `code`-shaped field can never reach a diagnostic.\n *\n * @param e - A caught value.\n * @returns The stable code token, or `null`.\n * @example\n * ```ts\n * import { extractStableCode } from \"@cosyte/cli\";\n *\n * extractStableCode({ code: \"MALFORMED_JSON\" }); // => \"MALFORMED_JSON\"\n * extractStableCode(new Error(\"boom\")); // => null\n * ```\n */\nexport function extractStableCode(e: unknown): string | null {\n if (typeof e === \"object\" && e !== null && \"code\" in e) {\n const raw: unknown = e.code;\n if (typeof raw === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(raw)) return raw;\n }\n return null;\n}\n\n/**\n * Build the value-free {@link RunResult} for a **wrapped-parser rejection**: a `CLI_PARSE_FAILED`\n * data error (exit `65`). The stderr line names the format and, when the thrown value carried one, a\n * stable code token in parentheses; it **never** echoes the parser's message or the input bytes. Under\n * `--unsafe-show-values` (and only then) a bounded excerpt of the offending input is appended via the\n * single {@link unsafeInputSuffix} chokepoint.\n *\n * @param format - The format whose parser rejected the input.\n * @param bytes - The offending input (only consulted for the opt-in unsafe excerpt).\n * @param posture - The resolved {@link PhiPosture}; the excerpt is appended only when it opts in.\n * @param e - The caught exception (its `code`, if a stable token, is surfaced: nothing else).\n * @returns A value-free `CLI_PARSE_FAILED` / exit-`65` {@link RunResult}.\n * @example\n * ```ts\n * import { parseFailureResult, VALUE_FREE } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"not hl7\");\n * parseFailureResult(\"hl7\", bytes, VALUE_FREE, { code: \"MISSING_MSH\" }).exit; // => 65\n * ```\n */\nexport function parseFailureResult(\n format: CosyteFormat,\n bytes: Uint8Array,\n posture: PhiPosture,\n e: unknown,\n): RunResult {\n const code = extractStableCode(e);\n const detail = code === null ? \"\" : ` (${code})`;\n const suffix = unsafeInputSuffix(bytes, posture);\n return {\n stdout: \"\",\n stderr: `cosyte: ${CLI_CODES.CLI_PARSE_FAILED}: the ${format} parser rejected the input${detail}${suffix}\\n`,\n exit: EXIT.DATAERR,\n };\n}\n","/**\n * `cosyte convert <file|-> --to fhir [--json] [--quiet] [--no-color]`\n *\n * Convert an **HL7 v2** message to **FHIR R4** via **`@cosyte/transform`**: the\n * consumer-of-consumers command. The CLI adds **no** mapping logic of its own: it parses the input\n * with `@cosyte/hl7`, hands the parsed message to `transform`'s `toFhir`, and serializes the resulting\n * FHIR `Bundle` with `@cosyte/fhir`. The mapping guarantees are the library's, graded by *its* gate;\n * `cosyte convert` equals `transform`'s programmatic output.\n *\n * The converted FHIR `Bundle` is the user's explicit request, so it goes to **stdout** (the data\n * channel). Every conversion problem is one of `transform`'s value-free {@link TransformIssue}s: a\n * stable code, a severity, and a positional locator (a v2 index and an optional FHIRPath), **never** a\n * field value: surfaced on stderr (or as value-free JSON under `--json`). The load-bearing rule\n * (mirroring `validate`): a conversion that produces an **error-severity** issue exits **`1`**, never\n * `0`: the tool worked, but the conversion has a real problem a CI gate must see.\n *\n * `--to fhir` is required and is the only supported target (HL7 v2 → FHIR R4). The source must be\n * HL7 v2: a recognised-but-non-HL7 input (e.g. a FHIR document) is a value-free\n * `CLI_FORMAT_UNSUPPORTED` data error (`65`), never a fake conversion.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { Finding } from \"../core/findings.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { loadFhir, loadOptionalPackage } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `convert` understands. */\nconst CONVERT_OPTIONS = {\n to: { type: \"string\" },\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** The only conversion target this build supports (HL7 v2 → FHIR R4). */\nconst SUPPORTED_TARGET = \"fhir\";\n\n/** Transform severities that make a conversion a **failure** (exit `1`). `transform` has no `fatal`. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** The value-free result of a conversion: the serialized FHIR bundle text + the library's findings. */\ninterface Conversion {\n readonly bundleText: string;\n readonly findings: readonly Finding[];\n}\n\n/**\n * Run the `convert` command.\n *\n * @param args - The arguments after the `convert` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on an HL7\n * parse-failure diagnostic; the converted bundle and the value-free findings are unaffected).\n * @returns A {@link RunResult}: the converted FHIR `Bundle` on `stdout` (the data channel), value-free\n * findings on `stderr` (or JSON under `--json`), and an exit code that carries the outcome: `0`\n * clean · `1` an error-severity conversion issue · `65` the HL7 input could not be parsed or is not\n * an HL7 v2 source · `66` no input · `2` usage.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { convertCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode(\"MSH|^~\\\\&|A|B|C|D|20240101||ADT^A01|1|P|2.5\\r\"),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await convertCommand([\"adt.hl7\", \"--to\", \"fhir\"], deps)).exit; // => 0\n * ```\n */\nexport async function convertCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n to?: string;\n format?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: CONVERT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `convert` (see `cosyte convert --help`)\",\n ),\n );\n }\n\n // `--to` is required and names the conversion target. Only `fhir` is supported today; requiring it\n // (rather than defaulting) keeps the surface explicit and future-proof for other targets.\n if (values.to === undefined) {\n return errorResult(\n new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"convert requires --to fhir (the only target)\"),\n );\n }\n if (values.to !== SUPPORTED_TARGET) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unsupported --to '${values.to}'; only --to fhir is supported (HL7 v2 → FHIR R4)`,\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // convert reads HL7 v2 and writes FHIR R4. A recognised-but-non-HL7 source (e.g. a FHIR document) is\n // not a convertible input: a value-free data error, never a fake or identity \"conversion\".\n if (format !== \"hl7\") {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `convert reads HL7 v2 and writes FHIR R4; the input is '${format}', not an HL7 v2 source`,\n ),\n );\n }\n\n const outcome = await runConvert(bytes, posture);\n if (!outcome.ok) return outcome.result;\n const conversion = outcome.conversion;\n\n const { hasError, report } = convertOutcome(conversion.findings);\n const exit = hasError ? EXIT.INVALID : EXIT.OK;\n\n if (values.json === true) {\n // Machine output on the data channel: the converted bundle plus the value-free findings.\n const body = {\n format: SUPPORTED_TARGET,\n bundle: JSON.parse(conversion.bundleText) as unknown,\n findings: conversion.findings,\n };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n // Default: the converted FHIR Bundle (the library's canonical serialization) IS the stdout data\n // channel; the value-free findings + a summary go to stderr unless suppressed by --quiet.\n const stderr = values.quiet === true ? \"\" : report;\n return { stdout: `${conversion.bundleText}\\n`, stderr, exit };\n}\n\n/** Either a completed conversion, or a ready value-free parse-failure {@link RunResult}. */\ntype ConvertOutcome =\n | { readonly ok: true; readonly conversion: Conversion }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Why `@cosyte/transform` is absent, in words a user can act on. **It deliberately does not say\n * \"install it\"**: `npm install @cosyte/transform` fails too (`E404` on its own `@cosyte/fhir` peer),\n * so telling someone to install it would send them at a command that cannot succeed. That is the same\n * defect the `@cosyte/fhir` diagnostic exists to avoid, and it is why neither goes through\n * `loadOptional()`, whose stock wording is exactly \"install it (it is an optional dependency)\".\n * Value-free by construction: package names and a statement of fact, no input echoed.\n */\nconst TRANSFORM_UNAVAILABLE =\n \"the @cosyte/transform conversion library is not installed, so convert is unavailable; it \" +\n \"requires @cosyte/fhir, which is not currently on the npm registry, so npm skips transform as \" +\n \"an unresolvable optional dependency and installing it directly fails for the same reason\";\n\n/**\n * Parse the HL7 v2 bytes and convert to FHIR: every library **lazy-loaded** so this code loads only\n * when `convert` runs. Only the `parseHL7` call is inside the failure boundary: a genuine parser\n * rejection becomes a value-free `CLI_PARSE_FAILED` (65), with the single opt-in excerpt (under\n * `--unsafe-show-values`) flowing through the shared core/wrap chokepoint. The `toFhir` + serialize\n * step is deliberately outside it: `toFhir` never throws for a well-formed message, so any throw there\n * is an unexpected bug the dispatcher maps to `CLI_INTERNAL` (70), never mislabelled as a rejection.\n *\n * Two of the three libraries are **not guaranteed present in an installed copy**, so both loads go\n * through the optional-package boundary and an absent one becomes a value-free\n * `CLI_PARSER_UNAVAILABLE` (69) rather than an unhandled resolver error. `@cosyte/hl7` is a hard\n * dependency and needs no such treatment.\n */\nasync function runConvert(bytes: Uint8Array, posture: PhiPosture): Promise<ConvertOutcome> {\n const [{ parseHL7 }, { toFhir }, { serializeResource }] = await Promise.all([\n import(\"@cosyte/hl7\"),\n loadOptionalPackage(TRANSFORM_UNAVAILABLE, () => import(\"@cosyte/transform\")),\n loadFhir(),\n ]);\n\n let msg: ReturnType<typeof parseHL7>;\n try {\n msg = parseHL7(Buffer.from(bytes));\n } catch (e) {\n return { ok: false, result: parseFailureResult(\"hl7\", bytes, posture, e) };\n }\n\n const { bundle, issues } = toFhir(msg);\n return {\n ok: true,\n conversion: {\n bundleText: serializeResource(bundle),\n findings: issues.map((i) => toFinding(i.code, i.severity, i.v2Location, i.fhirPath)),\n },\n };\n}\n\n/** Build one value-free {@link Finding} from a transform issue: v2 locator, and the FHIRPath if any. */\nfunction toFinding(code: string, severity: string, v2Location: string, fhirPath?: string): Finding {\n const location = fhirPath !== undefined ? `${v2Location} → ${fhirPath}` : v2Location;\n return { code, severity, location };\n}\n\n/**\n * Decide the conversion outcome from the library's value-free findings: whether any is\n * **error-severity** (which drives a non-zero exit: the load-bearing \"a conversion error is never\n * exit 0\" rule) and the value-free human report. The severity classification is\n * the library's: `@cosyte/transform` fixes each issue's severity; the CLI only reads it. Exported so\n * the exit-verdict and report logic is unit-testable with synthetic findings, independent of which HL7\n * message happens to produce an error.\n *\n * @param findings - The value-free {@link Finding}s the conversion produced.\n * @returns `hasError` (true iff any finding is error/fatal severity) and the rendered value-free\n * `report` (one line per finding + a summary line).\n * @example\n * ```ts\n * import { convertOutcome } from \"@cosyte/cli\";\n *\n * convertOutcome([{ code: \"TRANSFORM_RESOURCE_INVALID\", severity: \"error\", location: \"PID\" }])\n * .hasError; // => true\n * convertOutcome([{ code: \"TRANSFORM_ELEMENT_DROPPED\", severity: \"information\", location: \"PID.13\" }])\n * .hasError; // => false\n * ```\n */\nexport function convertOutcome(findings: readonly Finding[]): {\n readonly hasError: boolean;\n readonly report: string;\n} {\n const lines = findings.map((f) => `cosyte: convert: ${f.severity} ${f.code} at ${f.location}\\n`);\n const errors = findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = findings.length - errors;\n const summary =\n errors > 0\n ? `cosyte: convert: hl7 → fhir produced ${String(errors)} error(s), ${String(others)} other finding(s)\\n`\n : `cosyte: convert: hl7 → fhir OK (${String(findings.length)} finding(s))\\n`;\n return { hasError: errors > 0, report: lines.join(\"\") + summary };\n}\n","/**\n * `cosyte inspect <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * A human-readable, **value-free-by-default** structural summary of a message: its type, structural\n * counts, and a warning count: the \"what shape is this?\" answer, without ever printing a field\n * value. Unlike `parse`, whose stdout is the parsed model (the data channel), `inspect`'s\n * stdout is a *structural* summary composed only of counts and structural type **codes** (an HL7 message\n * type like `ADT^A01`, a FHIR `resourceType` like `Patient`, an X12 transaction-set id like `834`, a\n * DICOM SOP Class UID, an NCPDP `NewRx`): classification, never PHI. `--json` emits the same value-free\n * summary as machine JSON. The per-format summaries are built by the shared registry (`core/parsers.ts`).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { inspectFormat, type InspectSummary } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `inspect` understands. */\nconst INSPECT_OPTIONS = {\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `inspect` command.\n *\n * @param args - The arguments after the `inspect` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; the summary itself is always value-free).\n * @returns A {@link RunResult}: the value-free structural summary on `stdout` (human, or JSON under\n * `--json`), exit `0`; a parse failure is a data error (`65`), an unreadable file `66`, a bad flag `2`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { inspectCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await inspectCommand([\"patient.json\", \"--json\"], deps)).exit; // => 0\n * ```\n */\nexport async function inspectCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: { format?: string; json?: boolean; quiet?: boolean; \"no-color\"?: boolean };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: INSPECT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `inspect` (see `cosyte inspect --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"inspect\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let summary: InspectSummary;\n try {\n summary = await inspectFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const stdout = values.json === true ? `${JSON.stringify(summary)}\\n` : renderSummary(summary);\n return { stdout, stderr: \"\", exit: EXIT.OK };\n}\n\n/**\n * Render a value-free human structural summary. Only counts and structural type codes, never a value.\n * Exported for direct branch testing of the per-format render (not re-exported from the package root).\n *\n * @param summary - The value-free {@link InspectSummary} to render.\n * @returns The human-readable, value-free summary text.\n * @example\n * ```ts\n * import { renderSummary } from \"@cosyte/cli/dist/commands/inspect.js\";\n *\n * renderSummary({ format: \"mllp\", frameCount: 2, warningCount: 0 }).includes(\"frames\"); // => true\n * ```\n */\nexport function renderSummary(summary: InspectSummary): string {\n const lines: string[] = [];\n const countLines = (label: string, counts: Readonly<Record<string, number>>): void => {\n if (label.length > 0) lines.push(label);\n for (const key of Object.keys(counts).sort()) lines.push(` ${key}: ${String(counts[key])}`);\n };\n\n switch (summary.format) {\n case \"hl7\":\n lines.push(`format: hl7`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n countLines(\"\", summary.segments);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"fhir\":\n lines.push(`format: fhir`);\n lines.push(`resource type: ${summary.resourceType ?? \"(unknown)\"}`);\n if (summary.entryCount !== undefined) {\n lines.push(`bundle type: ${summary.bundleType ?? \"(unknown)\"}`);\n lines.push(`entries: ${String(summary.entryCount)}`);\n countLines(\"\", summary.entryResourceTypes ?? {});\n }\n lines.push(`issues: ${String(summary.issueCount)}`);\n break;\n case \"x12\":\n lines.push(`format: x12`);\n lines.push(`groups: ${String(summary.groupCount)}`);\n lines.push(`transactions: ${String(summary.transactionCount)}`);\n countLines(\"transaction sets:\", summary.transactionSetIds);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"astm\":\n lines.push(`format: astm`);\n lines.push(`message kind: ${summary.messageKind}`);\n lines.push(`records: ${String(summary.recordCount)}`);\n countLines(\"\", summary.recordTypes);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ccda\":\n lines.push(`format: ccda`);\n lines.push(`document type: ${summary.documentType ?? \"(unknown)\"}`);\n lines.push(`sections: ${String(summary.sectionCount)}`);\n if (summary.sectionCodes.length > 0) {\n lines.push(`section codes: ${summary.sectionCodes.join(\", \")}`);\n }\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"dicom\":\n lines.push(`format: dicom`);\n lines.push(`sop class uid: ${summary.sopClassUid ?? \"(unknown)\"}`);\n lines.push(`transfer syntax:${summary.transferSyntaxUid ?? \" (unknown)\"}`);\n lines.push(`elements: ${String(summary.elementCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ncpdp\":\n lines.push(`format: ncpdp`);\n lines.push(`standard: SCRIPT`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"mllp\":\n lines.push(`format: mllp`);\n lines.push(`frames: ${String(summary.frameCount)}`);\n lines.push(`warnings:${String(summary.warningCount)}`);\n break;\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n","/**\n * `cosyte parse <file|-> [--format …] [--ndjson] [--json] [--quiet] [--no-color]`\n *\n * Read a file (or stdin via `-`), **autodetect the format by content** (or honour `--format`), route to\n * the wrapped parser via the lazy per-format registry (`core/parsers.ts`) (so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code) and emit the parsed model as **typed JSON on stdout**. Every\n * failure is a value-free diagnostic on stderr with a stable `CLI_*` code and the documented exit code.\n *\n * **Multi-message / streaming.** A single message emits one pretty (or compact under `--json`)\n * JSON envelope, exactly as before. A **multi-record** input emits **NDJSON** (one compact envelope\n * per line) with per-record isolation: a record that fails to parse becomes a value-free\n * `{ record, error }` line and the stream continues, and the overall exit is a data error (`65`) if any\n * record failed. Two inputs are multi-record: an **MLLP** stream (each VT-framed frame is an enclosed\n * HL7 message) and any input under **`--ndjson`** (each non-empty line is a record: the FHIR bulk-data\n * convention).\n *\n * The CLI adds **no** parsing of its own: it routes, reads, and shapes output; `cosyte parse` equals the\n * wrapped library's programmatic parse.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { deframeMllp, parseFormat, type ParseWarning } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { extractStableCode, parseFailureResult } from \"../core/wrap.js\";\n\n// Re-exported from the shared wrapper boundary so the historical `@cosyte/cli` import path stays stable.\nexport { extractStableCode } from \"../core/wrap.js\";\n\n/** The typed JSON envelope a single `parse` emits on stdout: the format, the parsed model, warnings. */\ninterface ParseEnvelope {\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n}\n\n/** One line of NDJSON multi-record output: a parsed record, or a value-free per-record parse error. */\ntype RecordLine =\n | {\n readonly record: number;\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n }\n | { readonly record: number; readonly format: CosyteFormat; readonly error: string };\n\n/** The flags `parse` understands, parsed by {@link parseArgs}. */\nconst PARSE_OPTIONS = {\n format: { type: \"string\" },\n ndjson: { type: \"boolean\", default: false },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `parse` command.\n *\n * @param args - The arguments after the `parse` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture}. Defaults to {@link VALUE_FREE}; under\n * `--unsafe-show-values` a bounded excerpt of the offending input is appended to a `CLI_PARSE_FAILED`\n * diagnostic (the single, opt-in value-echoing surface): single-record mode only.\n * @returns A {@link RunResult}: the typed-JSON model (or NDJSON records) on `stdout`, a value-free note\n * (or nothing) on `stderr`, and the resolved exit code. Never throws a {@link CliError}: it resolves\n * it to a result; unexpected exceptions are caught by the dispatcher and mapped to `CLI_INTERNAL`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { parseCommand } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * const deps = {\n * readFile: async () => enc.encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await parseCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function parseCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n ndjson?: boolean;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: PARSE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `parse` (see `cosyte parse --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // MLLP is a transport container and `--ndjson` is explicit batch mode: both are multi-record.\n if (format === \"mllp\" || values.ndjson === true) {\n return await parseMulti(format, bytes, values.ndjson === true, values.quiet === true);\n }\n return await parseSingle(format, bytes, values.json === true, values.quiet === true, posture);\n}\n\n/** Parse a single message → one JSON envelope (pretty, or compact under `--json`). Preserves the\n * value-free failure boundary and the opt-in `--unsafe-show-values` excerpt. */\nasync function parseSingle(\n format: CosyteFormat,\n bytes: Uint8Array,\n json: boolean,\n quiet: boolean,\n posture: PhiPosture,\n): Promise<RunResult> {\n let result: { model: unknown; warnings: readonly ParseWarning[] };\n try {\n result = await parseFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, posture, e);\n }\n const envelope: ParseEnvelope = { format, model: result.model, warnings: result.warnings };\n const stdout = (json ? JSON.stringify(envelope) : JSON.stringify(envelope, null, 2)) + \"\\n\";\n\n const n = envelope.warnings.length;\n const stderr =\n n > 0 && !quiet\n ? `cosyte: parsed ${format} with ${String(n)} warning(s) (see .warnings in output)\\n`\n : \"\";\n return { stdout, stderr, exit: EXIT.OK };\n}\n\n/** Parse a multi-record input (MLLP frames, or `--ndjson` lines) → NDJSON, with per-record isolation. */\nasync function parseMulti(\n format: CosyteFormat,\n bytes: Uint8Array,\n ndjson: boolean,\n quiet: boolean,\n): Promise<RunResult> {\n // Resolve the records + the format each record is parsed as. MLLP de-frames to enclosed HL7 payloads.\n let records: Uint8Array[];\n let recordFormat: CosyteFormat;\n try {\n if (format === \"mllp\") {\n const { payloads } = await deframeMllp(bytes);\n records = payloads;\n recordFormat = \"hl7\";\n } else {\n records = splitLines(bytes);\n recordFormat = format;\n }\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, VALUE_FREE, e);\n }\n\n if (records.length === 0) {\n // A framed/ndjson input that yielded no record is a data error, never a silent success.\n return errorResult(\n new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n `no ${format === \"mllp\" ? \"MLLP frame\" : \"record\"} found in the input`,\n ),\n );\n }\n\n const lines: RecordLine[] = [];\n let failed = 0;\n let warnings = 0;\n for (let i = 0; i < records.length; i += 1) {\n const rec = records[i] as Uint8Array;\n try {\n const { model, warnings: ws } = await parseFormat(recordFormat, rec);\n warnings += ws.length;\n lines.push({ record: i, format: recordFormat, model, warnings: ws });\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // a parser-unavailable is fatal for the stream\n failed += 1;\n // Value-free per-record error: a stable code (if the throw carried one), never the bytes.\n lines.push({\n record: i,\n format: recordFormat,\n error: extractStableCode(e) ?? \"CLI_PARSE_FAILED\",\n });\n }\n }\n\n const stdout = lines.map((l) => JSON.stringify(l)).join(\"\\n\") + \"\\n\";\n const exit = failed > 0 ? EXIT.DATAERR : EXIT.OK;\n const stderr = quiet\n ? \"\"\n : `cosyte: parsed ${String(records.length)} ${recordFormat} record(s)` +\n ` (${String(warnings)} warning(s), ${String(failed)} failed)` +\n (ndjson ? \" [ndjson]\" : format === \"mllp\" ? \" [mllp]\" : \"\") +\n \"\\n\";\n return { stdout, stderr, exit };\n}\n\n/** Split input bytes into non-empty, whitespace-trimmed newline-delimited records (NDJSON input). */\nfunction splitLines(bytes: Uint8Array): Uint8Array[] {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n const enc = new TextEncoder();\n return text\n .split(/\\r?\\n/)\n .filter((line) => line.trim().length > 0)\n .map((line) => enc.encode(line));\n}\n","/**\n * `cosyte validate <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * Parse the input, run the **wrapped parser's own validation/conformance surface**, and let the\n * **exit code carry the verdict** so `cosyte validate` is usable as a CI gate: **`0` valid, `1`\n * invalid** (parseable but non-conformant), `65` unparseable, `66` no input, `2` usage. The\n * load-bearing rule: the CLI never prints a reassuring line and exits `0` on an invalid message.\n *\n * Findings are **value-free**: a stable code, a severity, and a positional locator (a FHIRPath, or an\n * HL7 segment/field index), never a field value. By default they render on **stderr**; `--json`\n * emits the same value-free verdict + findings as machine JSON on stdout. The CLI invents **no**\n * verdict of its own: FHIR validity is `@cosyte/fhir`'s `validateResource().valid` (plus any\n * error-severity read issue); HL7 validity is \"parseable\": its parser is Postel's-Law lenient and its\n * warnings are, by the library's design, non-fatal deviations (surfaced, never failing).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { validateFormat, type Verdict } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `validate` understands. */\nconst VALIDATE_OPTIONS = {\n format: { type: \"string\" },\n profile: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** Severities that make a resource **invalid** (exit `1`). Warnings/information never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/**\n * Run the `validate` command.\n *\n * @param args - The arguments after the `validate` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; a validation verdict is always value-free).\n * @returns A {@link RunResult} whose **exit code carries the verdict** (`0` valid / `1` invalid /\n * `65` unparseable / `66` no input / `2` usage). Value-free findings on `stderr`, or value-free\n * JSON on stdout under `--json`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { validateCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await validateCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function validateCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n profile?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: VALIDATE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `validate` (see `cosyte validate --help`)\",\n ),\n );\n }\n\n // Profile-based validation is a pass-through to the wrapped library's profile surface, but the CLI\n // bundles no profiles and cannot yet load one, so honouring `--profile` today would either fake a\n // verdict or silently ignore the flag (falsely implying a profile was applied). Both are forbidden\n // (ADR 0018): report a value-free \"unavailable\" and exit 69, without reading the input.\n if (values.profile !== undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_NOT_IMPLEMENTED,\n EXIT.UNAVAILABLE,\n \"profile-based validation is not yet available: the CLI bundles no profiles and cannot yet \" +\n \"load one; validating against `--profile` is gated on that surface. Re-run without --profile \" +\n \"for base validation.\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"validate\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let verdict: Verdict;\n try {\n verdict = await validateFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n // Unparseable input is a data error (65), NOT an invalid verdict (1): the tool could not run the\n // check at all. Value-free; the opt-in excerpt flows through the single core/wrap chokepoint.\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const exit = verdict.valid ? EXIT.OK : EXIT.INVALID;\n\n if (values.json === true) {\n // Machine output on the data channel: value-free (codes/severities/locations only).\n const body = { format, valid: verdict.valid, findings: verdict.findings };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n if (values.quiet === true) {\n // CI mode: the exit code is the whole signal. No stderr noise.\n return { stdout: \"\", stderr: \"\", exit };\n }\n\n return { stdout: \"\", stderr: renderReport(format, verdict), exit };\n}\n\n/** Render the value-free human report: one line per finding + a verdict summary line. */\nfunction renderReport(format: CosyteFormat, verdict: Verdict): string {\n const lines = verdict.findings.map(\n (f) => `cosyte: validate: ${f.severity} ${f.code} at ${f.location}\\n`,\n );\n const errors = verdict.findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = verdict.findings.length - errors;\n const summary = verdict.valid\n ? `cosyte: validate: ${format} is valid (${String(verdict.findings.length)} finding(s))\\n`\n : `cosyte: validate: ${format} is INVALID (${String(errors)} error(s), ${String(others)} other finding(s))\\n`;\n return lines.join(\"\") + summary;\n}\n","/**\n * The **agent-facing tool surface** of the cosyte MCP server: the *second adapter* over the same\n * `core`/`commands` the `cosyte` terminal command drives. This module\n * is deliberately **SDK-free**: it declares the tools (name, description, JSON-Schema input) and maps a\n * tool call onto the existing command handlers, returning a plain, value-free MCP-shaped result. The\n * `@modelcontextprotocol/sdk` wiring lives one layer up in `./server.ts`, so the tool *logic* is unit-\n * testable without the SDK and the SDK stays isolated behind the `./mcp` subpath.\n *\n * **The shared-core guarantee.** A tool does not re-implement anything: `parse` calls\n * {@link parseCommand}, `validate` calls {@link validateCommand}, etc., each with `--json` so the\n * library's result lands as machine JSON, so `cosyte parse` and the MCP `parse` tool agree by\n * construction. The tool feeds the caller's `content` string in as if it were piped on stdin (`-`).\n *\n * **The PHI posture (load-bearing).** Every tool runs under the {@link VALUE_FREE} posture. There is\n * **no** `--unsafe-show-values` door on the agent surface. A tool's *result* carries the requested data\n * (the parsed model / converted bundle: the explicit request, the data channel), but a tool *error*\n * carries only the value-free diagnostic the command already produced (a stable code + positional\n * context), never an input value.\n *\n * @packageDocumentation\n */\n\nimport { convertCommand } from \"../commands/convert.js\";\nimport { inspectCommand } from \"../commands/inspect.js\";\nimport { parseCommand } from \"../commands/parse.js\";\nimport { validateCommand } from \"../commands/validate.js\";\nimport { CLI_CODES, CliError, toCliError } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { VALUE_FREE } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\n\n/** A single text content block in an MCP tool result. */\nexport interface McpTextContent {\n readonly type: \"text\";\n readonly text: string;\n}\n\n/** Value-free metadata every tool result carries so an agent can branch on the outcome. */\nexport interface McpToolMeta {\n /** The CLI exit code the underlying command resolved to (the documented exit-code contract). */\n readonly exit: number;\n /** `true` iff the tool *call* succeeded (data was produced): distinct from a negative verdict. */\n readonly ok: boolean;\n}\n\n/**\n * The value-free result of dispatching one MCP tool call. Structurally an MCP `CallToolResult`: a text\n * content channel, an `isError` flag, and value-free `structuredContent` metadata.\n */\nexport interface McpToolResult {\n readonly content: readonly McpTextContent[];\n readonly isError: boolean;\n readonly structuredContent: McpToolMeta;\n}\n\n/** A JSON-Schema description of a tool's input (the wire schema advertised to `tools/list`). */\nexport interface McpToolInputSchema {\n readonly type: \"object\";\n readonly properties: Readonly<Record<string, unknown>>;\n readonly required?: readonly string[];\n readonly additionalProperties?: boolean;\n}\n\n/** A tool advertised by the server: an agent-callable name, a description, and its input schema. */\nexport interface McpToolDef {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: McpToolInputSchema;\n}\n\n/** The `content` property shared by every tool: the raw message text to operate on. */\nconst CONTENT_PROP = {\n content: {\n type: \"string\",\n description:\n \"The raw healthcare message to operate on (as text; e.g. an HL7 v2 message or a FHIR JSON resource).\",\n },\n} as const;\n\n/** The optional `format` override shared by the read commands (autodetected by content when omitted). */\nconst FORMAT_PROP = {\n format: {\n type: \"string\",\n enum: [\"hl7\", \"fhir\", \"dicom\", \"x12\", \"ccda\", \"ncpdp\", \"astm\", \"mllp\"],\n description:\n \"Optional format override; omit to autodetect by content. A format whose parser does not \" +\n \"support the requested operation returns a value-free CLI_FORMAT_UNSUPPORTED (never a fake).\",\n },\n} as const;\n\n/**\n * The tools this server exposes: the read/convert operations that share the `core` cleanly and whose\n * results are safe to hand an agent. `redact`/`deid` (gated on `@cosyte/deid`)\n * and `map-codes` are deliberately **not** exposed yet; they land when the terminal command's ground\n * layer and the tool's PHI/So shape are settled.\n */\nexport const TOOL_DEFS: readonly McpToolDef[] = [\n {\n name: \"parse\",\n description:\n \"Parse a healthcare message (HL7 v2 or FHIR R4) to typed JSON. Format is autodetected by content. \" +\n \"Returns the parsed model plus value-free warnings.\",\n inputSchema: {\n type: \"object\",\n properties: { ...CONTENT_PROP, ...FORMAT_PROP },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"validate\",\n description:\n \"Validate a message and carry the verdict: ok=true with a valid result, or a result reporting \" +\n \"value-free findings. The parsed-but-invalid verdict is a successful call (not a tool error).\",\n inputSchema: {\n type: \"object\",\n properties: { ...CONTENT_PROP, ...FORMAT_PROP },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"inspect\",\n description:\n \"Return a value-free structural summary of a message: its type, segment/entry counts, and a \" +\n \"warning/issue count. Never includes a field value.\",\n inputSchema: {\n type: \"object\",\n properties: { ...CONTENT_PROP, ...FORMAT_PROP },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"convert\",\n description:\n \"Convert an HL7 v2 message to a FHIR R4 Bundle via @cosyte/transform. Returns the converted \" +\n \"Bundle; an error-severity conversion issue is reported with ok=false.\",\n inputSchema: {\n type: \"object\",\n properties: {\n ...CONTENT_PROP,\n to: {\n type: \"string\",\n enum: [\"fhir\"],\n description: \"The conversion target (only FHIR R4 is supported today).\",\n },\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n];\n\n/** Build injected {@link RunDeps} that feed the tool's inline `content` as if it were piped on stdin. */\nfunction inlineDeps(content: string): RunDeps {\n const bytes = new TextEncoder().encode(content);\n const noFile = new CliError(\n CLI_CODES.CLI_NO_INPUT,\n EXIT.NOINPUT,\n \"the MCP tools operate on inline content, not a file path\",\n );\n return {\n readStdin: () => Promise.resolve(bytes),\n // The MCP tools always feed inline content via stdin (`-`); a file read is defensive and unreachable.\n /* v8 ignore next -- unreachable: no MCP tool passes a file path, only inline `-` stdin content */\n readFile: () => Promise.reject(noFile),\n };\n}\n\n/** Read a required string argument from a tool-call arguments object, or `null` when absent/mistyped. */\nfunction stringArg(args: Readonly<Record<string, unknown>>, key: string): string | null {\n const v = args[key];\n return typeof v === \"string\" ? v : null;\n}\n\n/**\n * Map a command's {@link RunResult} onto a value-free {@link McpToolResult}. A command emits its data on\n * `stdout` (non-empty) and only ever leaves `stdout` empty on a **hard** failure (unparseable / no\n * input / usage / unavailable / internal), so `stdout === \"\"` is exactly the \"tool call failed\" signal.\n * A negative *verdict* (validate-invalid, a convert error-severity issue) still emits its JSON on\n * stdout, so it is a successful call whose value-free payload reports the verdict.\n */\nfunction toToolResult(result: RunResult): McpToolResult {\n const hardError = result.stdout === \"\";\n const text = hardError ? result.stderr.trim() : result.stdout.trim();\n return {\n content: [\n { type: \"text\", text: text.length > 0 ? text : `cosyte: exit ${String(result.exit)}` },\n ],\n isError: hardError,\n structuredContent: { exit: result.exit, ok: !hardError },\n };\n}\n\n/** Build a value-free usage-error tool result (a bad/missing argument, never echoes the argument). */\nfunction usageError(message: string): McpToolResult {\n return {\n content: [{ type: \"text\", text: `cosyte: ${CLI_CODES.CLI_USAGE}: ${message}` }],\n isError: true,\n structuredContent: { exit: EXIT.USAGE, ok: false },\n };\n}\n\n/**\n * Map an unexpected thrown value to a **value-free** internal-error tool result: the agent-surface\n * mirror of the terminal dispatcher's `try/catch → toCliError` boundary (`core/run.ts`). {@link toCliError}\n * discards the original message, so a library exception that embedded input bytes can never reach the\n * client (which would otherwise see the SDK surface the raw `error.message`). Both adapters inherit the\n * value-free posture *in code*, not by trusting the wrapped libraries never to throw.\n */\nfunction internalError(e: unknown): McpToolResult {\n const err = toCliError(e);\n return {\n content: [{ type: \"text\", text: `cosyte: ${err.code}: ${err.message}` }],\n isError: true,\n structuredContent: { exit: err.exit, ok: false },\n };\n}\n\n/**\n * Dispatch one MCP tool call to the shared command layer and return a value-free {@link McpToolResult}.\n * This is the agent-surface analogue of {@link run}: it validates the arguments, feeds the inline\n * `content` through the same command handlers the terminal uses (under the always-on {@link VALUE_FREE}\n * posture), and maps the {@link RunResult} onto an MCP result. An unknown tool name or a missing\n * `content` argument is a value-free usage error, never a thrown stack trace carrying input.\n *\n * @param name - The tool name (one of {@link TOOL_DEFS}).\n * @param args - The tool-call arguments object.\n * @param deps - Optional {@link RunDeps} override (tests inject fakes); defaults to feeding `content` as\n * stdin. An unexpected throw from a command is mapped to a value-free `CLI_INTERNAL` result, never\n * propagated to the SDK (which would surface the raw message).\n * @returns A value-free {@link McpToolResult}; this function never throws.\n * @example\n * ```ts\n * import { dispatchTool } from \"@cosyte/cli/mcp\";\n *\n * const r = await dispatchTool(\"parse\", { content: '{\"resourceType\":\"Patient\"}' });\n * r.isError; // => false\n * ```\n */\nexport async function dispatchTool(\n name: string,\n args: Readonly<Record<string, unknown>>,\n deps?: RunDeps,\n): Promise<McpToolResult> {\n const content = stringArg(args, \"content\");\n if (content === null) {\n return usageError(\"missing required 'content' argument (the message text to operate on)\");\n }\n const runDeps = deps ?? inlineDeps(content);\n const format = stringArg(args, \"format\");\n const fmtFlag = format !== null ? [\"--format\", format] : [];\n\n try {\n switch (name) {\n case \"parse\":\n return toToolResult(await parseCommand([\"-\", \"--json\", ...fmtFlag], runDeps, VALUE_FREE));\n case \"validate\":\n return toToolResult(\n await validateCommand([\"-\", \"--json\", ...fmtFlag], runDeps, VALUE_FREE),\n );\n case \"inspect\":\n return toToolResult(await inspectCommand([\"-\", \"--json\", ...fmtFlag], runDeps, VALUE_FREE));\n case \"convert\": {\n const to = stringArg(args, \"to\") ?? \"fhir\";\n return toToolResult(await convertCommand([\"-\", \"--to\", to, \"--json\"], runDeps, VALUE_FREE));\n }\n default:\n return usageError(`unknown tool '${name}'`);\n }\n } catch (e) {\n // The agent-surface mirror of core/run.ts's dispatcher boundary: any unexpected throw becomes a\n // value-free CLI_INTERNAL result, so a library exception carrying input can never reach the client.\n return internalError(e);\n }\n}\n","/**\n * The **stdio MCP server**: the JSON-RPC/stdio adapter over the same shared `core`/`commands` the\n * `cosyte` terminal command drives. This is the **only** module that touches\n * `@modelcontextprotocol/sdk`, so the SDK (the CLI's single third-party runtime dependency) stays\n * **isolated behind the `./mcp` subpath and lazy-loaded**: a `cosyte parse` invocation never imports\n * this file and therefore never loads the SDK (proven by `mcp-isolation.test.ts`).\n *\n * The server is a **local stdio subprocess**, implicitly trusted by the user/agent that launched it,\n * not a hosted network endpoint. It is **stateless per call**: each tool request is one operation\n * over the wrapped libraries, with the same value-free PHI posture the CLI proves once and both\n * adapters inherit.\n *\n * @packageDocumentation\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { CallToolRequestSchema, ListToolsRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { VERSION } from \"../core/version.js\";\nimport { dispatchTool, TOOL_DEFS } from \"./tools.js\";\n\n/** The MCP server identity advertised to a client on connect. */\nexport const SERVER_INFO = { name: \"cosyte\", version: VERSION } as const;\n\n/**\n * Build the cosyte MCP {@link Server} with its two request handlers wired to the shared tool surface:\n * `tools/list` advertises {@link TOOL_DEFS}, and `tools/call` routes to {@link dispatchTool} (the same\n * command handlers the terminal uses). The returned server is **not yet connected** to a transport:\n * the caller connects it to stdio (in production) or to an in-memory transport (in tests), so the\n * handler wiring is drivable without a subprocess.\n *\n * @returns A configured, unconnected {@link Server}.\n * @example\n * ```ts\n * import { createMcpServer } from \"@cosyte/cli/mcp\";\n *\n * const server = createMcpServer();\n * typeof server.connect; // => \"function\"\n * ```\n */\nexport function createMcpServer(): Server {\n const server = new Server(SERVER_INFO, { capabilities: { tools: {} } });\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: TOOL_DEFS.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: {\n type: t.inputSchema.type,\n properties: { ...t.inputSchema.properties },\n ...(t.inputSchema.required !== undefined ? { required: [...t.inputSchema.required] } : {}),\n ...(t.inputSchema.additionalProperties !== undefined\n ? { additionalProperties: t.inputSchema.additionalProperties }\n : {}),\n },\n })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const result = await dispatchTool(name, args ?? {});\n return {\n content: result.content.map((c) => ({ type: c.type, text: c.text })),\n isError: result.isError,\n structuredContent: { exit: result.structuredContent.exit, ok: result.structuredContent.ok },\n };\n });\n\n return server;\n}\n\n/* v8 ignore start -- stdio transport wiring: connects the real process streams, exercised by the packaged bin smoke, not unit-covered */\n/**\n * Start the cosyte MCP server on **stdio** and resolve once the transport is connected. The process\n * then stays alive serving requests until its stdin closes. This is the entry both the `cosyte-mcp`\n * bin and the `cosyte mcp` subcommand call.\n *\n * @returns A promise that resolves when the stdio transport is connected.\n * @example\n * ```ts\n * import { startStdioServer } from \"@cosyte/cli/mcp\";\n *\n * typeof startStdioServer; // => \"function\"\n * ```\n */\nexport async function startStdioServer(): Promise<void> {\n const server = createMcpServer();\n await server.connect(new StdioServerTransport());\n}\n/* v8 ignore stop */\n","#!/usr/bin/env node\n/**\n * The `cosyte-mcp` executable: the stdio MCP server's process entry. It does exactly one untestable\n * thing: start the server on the real `process.stdin`/`process.stdout` and let the process stay alive\n * serving requests. All logic (the tool surface, the shared command core, the value-free PHI posture)\n * lives in the covered `mcp`/`core`/`commands` modules; this file is intentionally trivial and\n * coverage-excluded. It is the twin of `cosyte.ts` for the agent front door.\n *\n * @packageDocumentation\n */\n\n/* v8 ignore start -- process wiring: starts the stdio server on the real process streams, exercised by the packaged bin smoke, not unit-covered */\nimport { startStdioServer } from \"../mcp/server.js\";\n\nstartStdioServer().catch(() => {\n // A truly unexpected startup failure prints a value-free line and exits EX_SOFTWARE.\n process.stderr.write(\"cosyte-mcp: CLI_INTERNAL: the MCP server failed to start\\n\");\n process.exitCode = 70;\n});\n/* v8 ignore stop */\n"]}
1
+ {"version":3,"sources":["../../src/core/version.ts","../../src/core/exit-codes.ts","../../src/core/diagnostics.ts","../../src/core/format.ts","../../src/core/findings.ts","../../src/core/parsers.ts","../../src/core/input.ts","../../src/core/phi.ts","../../src/core/wrap.ts","../../src/commands/convert.ts","../../src/commands/inspect.ts","../../src/commands/parse.ts","../../src/commands/validate.ts","../../src/mcp/tools.ts","../../src/mcp/server.ts","../../src/bin/cosyte-mcp.ts"],"names":["ERROR_SEVERITIES","parseArgs","Server","ListToolsRequestSchema","CallToolRequestSchema","StdioServerTransport"],"mappings":";;;;;;;;;AAyBO,IAAM,OAAA,GAAkB,OAAA;;;ACYxB,IAAM,IAAA,GAAO;AAAA;AAAA,EAElB,EAAA,EAAI,CAAA;AAAA;AAAA;AAAA;AAAA,EAIJ,OAAA,EAAS,CAAA;AAAA;AAAA,EAET,KAAA,EAAO,CAAA;AAAA;AAAA,EAEP,OAAA,EAAS,EAAA;AAAA;AAAA,EAET,OAAA,EAAS,EAAA;AAAA;AAA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,CAAO,MAAM,4DAA4D,CAAA;AACjF,EAAA,OAAA,CAAQ,QAAA,GAAW,EAAA;AACrB,CAAC,CAAA","file":"cosyte-mcp.cjs","sourcesContent":["/**\n * The CLI version string, synced with `package.json#version` on release by `scripts/sync-version.mjs`,\n * which the `version` script runs immediately after `changeset version`. Kept in its own module so\n * both the programmatic entry point and the dispatcher share one source of truth.\n *\n * The declaration below is rewritten by that script and is matched at column 0, annotation included.\n * Renaming it or reflowing it makes the script exit non-zero rather than silently no-op; the shape is\n * pinned by `test/sanity.test.ts`, and the value is compared against `package.json` there too.\n *\n * @packageDocumentation\n */\n\n/**\n * The `@cosyte/cli` version. On the uniform `v0.0.x-until-first-alpha` ladder.\n *\n * Read by `cosyte --version` and by the MCP server's advertised `SERVER_INFO`, so it is a\n * user-visible surface on both front doors, not merely an export.\n *\n * @example\n * ```ts\n * import { VERSION } from \"@cosyte/cli\";\n *\n * console.log(`cosyte ${VERSION}`);\n * ```\n */\nexport const VERSION: string = \"0.0.6\";\n","/**\n * The `cosyte` CLI **exit-code contract**: a designed, documented surface that CI pipelines and\n * shell scripts branch on. Grounded in the Unix `sysexits.h` conventions.\n *\n * The load-bearing rule: **the CLI never prints a reassuring line and exits `0` on input it could not\n * handle.** An undetectable format, an unreadable file, or a parser that throws each map to a\n * distinct, stable non-zero code, never a silent success.\n *\n * | Code | Name | Meaning |\n * |------|------------|----------------------------------------------------------------------|\n * | `0` | `OK` | success: the operation completed; `validate` found the input **valid** |\n * | `1` | `INVALID` | operation-level failure: `validate` found the input **invalid** (a real, expected CI signal: the message is bad, the tool worked) |\n * | `2` | `USAGE` | usage error: unknown command, bad flag, missing argument (EX_USAGE) |\n * | `65` | `DATAERR` | data error: input could not be parsed / format not detected (EX_DATAERR) |\n * | `66` | `NOINPUT` | no input: the file does not exist or is unreadable (EX_NOINPUT) |\n * | `69` | `UNAVAILABLE` | a required capability is not yet available: e.g. `redact` before `@cosyte/deid` is wired (EX_UNAVAILABLE) |\n * | `70` | `SOFTWARE` | internal error: an unexpected exception, i.e. a bug (EX_SOFTWARE) |\n *\n * The load-bearing `validate` rule: a **parseable-but-invalid** message is exit `1`, never exit `0`.\n * The CLI must never print a reassuring line and exit green on a bad message. Exit `65` is reserved\n * for input that could not be **parsed** at all (a distinct signal from \"parsed, but does not\n * conform\").\n *\n * @packageDocumentation\n */\n\n/**\n * The stable exit-code map. Adding a code is a documented, tested change to the CLI's contract;\n * renaming or repurposing one is a breaking change.\n *\n * @example\n * ```ts\n * import { EXIT } from \"@cosyte/cli\";\n *\n * process.exitCode = EXIT.OK; // => 0\n * ```\n */\nexport const EXIT = {\n /** Success: the operation completed; `validate` found the input **valid**. */\n OK: 0,\n /** Operation-level failure: `validate` found the input **invalid** (parseable but non-conformant):\n * a real, expected CI signal that the message is bad and the tool worked. Never emitted for\n * unparseable input (that is `DATAERR`). */\n INVALID: 1,\n /** Usage error: unknown command, bad flag, missing argument (`EX_USAGE`). */\n USAGE: 2,\n /** Data error: input could not be parsed or its format could not be detected (`EX_DATAERR`). */\n DATAERR: 65,\n /** No input: the named file does not exist or is unreadable (`EX_NOINPUT`). */\n NOINPUT: 66,\n /** Unavailable: a required capability is not yet wired (e.g. `redact` before `@cosyte/deid`), a\n * distinct non-zero signal that is never a fake success (`EX_UNAVAILABLE`). */\n UNAVAILABLE: 69,\n /** Internal error: an unexpected exception (a bug), distinct from a handled bad input (`EX_SOFTWARE`). */\n SOFTWARE: 70,\n} as const;\n\n/**\n * A value from {@link EXIT}: the exit code a CLI invocation resolves to.\n */\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n","/**\n * The CLI's **value-free diagnostic channel**. Every error the CLI raises on its own behalf carries a\n * stable `CLI_*` code, a fixed exit code, and a **PHI-safe** message built only from positional /\n * structural context: a segment or field index, a byte offset, a file path, a format name, a warning\n * code. **A diagnostic never echoes an input value** (a name, a DOB, an MRN, a result). This is the\n * parsers' \"warning = code + position, never a value\" rule applied at the CLI edge.\n *\n * @packageDocumentation\n */\n\nimport { EXIT, type ExitCode } from \"./exit-codes.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Stable **CLI diagnostic code** registry: errors the CLI owns (routing, I/O, argument handling),\n * distinct from the wrapped library's own warning/issue codes which are passed through unchanged.\n * Each code is its own value (`key === value`) so the set survives `Object.values(...)`; renaming or\n * removing one is a **breaking change** because scripts branch on the stderr text.\n *\n * @example\n * ```ts\n * import { CLI_CODES } from \"@cosyte/cli\";\n *\n * if (diagnostic.code === CLI_CODES.CLI_FORMAT_UNDETECTED) {\n * // ask the user for --format\n * }\n * ```\n */\nexport const CLI_CODES = {\n /** A required argument was missing or a flag was invalid. Exit `2`. */\n CLI_USAGE: \"CLI_USAGE\",\n /** The named file does not exist or could not be read. Exit `66`. */\n CLI_NO_INPUT: \"CLI_NO_INPUT\",\n /** The input was empty, no bytes to detect or parse. Exit `65`. */\n CLI_EMPTY_INPUT: \"CLI_EMPTY_INPUT\",\n /** No format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_UNDETECTED: \"CLI_FORMAT_UNDETECTED\",\n /** More than one format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_AMBIGUOUS: \"CLI_FORMAT_AMBIGUOUS\",\n /** A recognised format whose parser does not support the requested operation (e.g. `parse` on a\n * format wired only for `inspect`). Names the format + operation, never the bytes. Exit `65`. */\n CLI_FORMAT_UNSUPPORTED: \"CLI_FORMAT_UNSUPPORTED\",\n /** The optional parser package for a recognised format is not installed. The six breadth parsers\n * (dicom/x12/ccda/ncpdp/astm/mllp) are `optionalDependencies`: normally installed, but if\n * one is absent the CLI degrades to this value-free signal rather than crashing. Exit `69`. */\n CLI_PARSER_UNAVAILABLE: \"CLI_PARSER_UNAVAILABLE\",\n /** The wrapped parser rejected the input. Positional context only, never the offending bytes. Exit `65`. */\n CLI_PARSE_FAILED: \"CLI_PARSE_FAILED\",\n /** The BYO ConceptMap supplied to `map-codes` is not valid JSON or not a loadable FHIR ConceptMap.\n * Names the stable terminology-loader code, never the map's bytes. Exit `65`. */\n CLI_MAP_INVALID: \"CLI_MAP_INVALID\",\n /** A command whose ground-layer library is not yet wired (e.g. `redact` before `@cosyte/deid` is\n * wired). Never a fake success: a distinct, value-free \"unavailable\" signal. Exit `69`. */\n CLI_NOT_IMPLEMENTED: \"CLI_NOT_IMPLEMENTED\",\n /** An unexpected internal error (a bug). Exit `70`. */\n CLI_INTERNAL: \"CLI_INTERNAL\",\n} as const;\n\n/**\n * A value from {@link CLI_CODES}: the stable code carried by a {@link CliError}.\n */\nexport type CliCode = (typeof CLI_CODES)[keyof typeof CLI_CODES];\n\n/**\n * A typed, PHI-safe CLI error. Its {@link CliError.message | message} is **value-free by\n * construction**: callers must build it from codes, indices, offsets, format names, and file paths,\n * never from an input value. It carries the {@link ExitCode} the invocation resolves to.\n *\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT } from \"@cosyte/cli\";\n *\n * throw new CliError(CLI_CODES.CLI_NO_INPUT, EXIT.NOINPUT, \"cannot read the named file\");\n * ```\n */\nexport class CliError extends Error {\n /** The stable diagnostic code. */\n public readonly code: CliCode;\n /** The exit code this error resolves the invocation to. */\n public readonly exit: ExitCode;\n\n /**\n * @param code - A stable {@link CliCode}.\n * @param exit - The {@link ExitCode} to resolve to.\n * @param message - A **value-free** explanation (positional/structural context only, never PHI).\n */\n public constructor(code: CliCode, exit: ExitCode, message: string) {\n super(message);\n this.name = \"CliError\";\n this.code = code;\n this.exit = exit;\n }\n}\n\n/**\n * Render a {@link CliError} as a single value-free `stderr` line: `cosyte: <CODE>: <message>`. The\n * message is already value-free by the {@link CliError} contract; this only prefixes the tool name\n * and the code so scripts and humans can branch on a stable token.\n *\n * @param err - The CLI error to render.\n * @returns The stderr line (no trailing newline).\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, formatDiagnostic } from \"@cosyte/cli\";\n *\n * formatDiagnostic(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file> argument\"));\n * // => \"cosyte: CLI_USAGE: missing <file> argument\"\n * ```\n */\nexport function formatDiagnostic(err: CliError): string {\n return `cosyte: ${err.code}: ${err.message}`;\n}\n\n/**\n * Resolve a {@link CliError} into a value-free {@link RunResult}: empty `stdout` (nothing reaches the\n * data channel on an error), the rendered diagnostic on `stderr`, and the error's exit code. The\n * single place the CLI turns an owned error into a result, so every command and the dispatcher render\n * errors identically.\n *\n * @param err - The CLI error to resolve.\n * @returns The value-free {@link RunResult}.\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, errorResult } from \"@cosyte/cli\";\n *\n * errorResult(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file>\")).exit; // => 2\n * ```\n */\nexport function errorResult(err: CliError): RunResult {\n return { stdout: \"\", stderr: `${formatDiagnostic(err)}\\n`, exit: err.exit };\n}\n\n/**\n * Coerce an unknown thrown value into a {@link CliError}. A {@link CliError} passes through; anything\n * else becomes a `CLI_INTERNAL` / {@link EXIT.SOFTWARE} error whose message is a **fixed, value-free\n * string**: the original message is deliberately discarded so a parser exception that embedded input\n * bytes can never reach stderr.\n *\n * @param err - The caught value.\n * @returns A {@link CliError} safe to render to stderr.\n * @example\n * ```ts\n * import { toCliError } from \"@cosyte/cli\";\n *\n * toCliError(new Error(\"boom\")).code; // => \"CLI_INTERNAL\"\n * ```\n */\nexport function toCliError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n return new CliError(\n CLI_CODES.CLI_INTERNAL,\n EXIT.SOFTWARE,\n \"an unexpected internal error occurred (no input is echoed)\",\n );\n}\n","/**\n * **Content-based format autodetection**: the feature that makes `cosyte parse <file>` feel magic,\n * and the one that must **fail safe**. Detection sniffs the leading bytes' *content*, never the file\n * extension: a `.txt` full of `MSH|^~\\&…` is HL7; a `.json` with a `resourceType` is FHIR.\n *\n * The hazard is a wrong sniff routing bytes to the wrong parser and yielding confident garbage. So\n * detection is **conservative**: a single confident signature match parses; **zero or more than one**\n * match is *not* a guess. It is a typed `none`/`ambiguous` result the caller turns into a data-error\n * exit asking for `--format`. This is the parsers' \"never a confident wrong value\" rule at the\n * routing layer.\n *\n * All eight cosyte formats carry a signature: **hl7** (`MSH` + field separator), **mllp**\n * (a leading `0x0B` VT frame byte: an MLLP-framed stream, de-framed to its enclosed HL7), **fhir** (a\n * JSON object declaring `resourceType`), **x12** (a leading `ISA` interchange header), **astm** (a\n * leading `H` record whose second byte is the field delimiter), **ccda** (a `<ClinicalDocument>` root),\n * **ncpdp** (a `<Message>` root in the NCPDP SCRIPT namespace), and **dicom** (the `DICM` magic at byte\n * 128). The signatures are **conservative and, on realistic inputs, mutually exclusive**: the\n * distinctive-lead formats (`MSH`, `ISA`, `H`+delimiter, `<ClinicalDocument>`, `<Message>`+ncpdp, the\n * `DICM` magic, `0x0B` VT, `{…\"resourceType\"`) don't overlap on a real message of any one type. They\n * are **not** disjoint in the absolute sense: a pathological input could satisfy two (an MLLP frame\n * enclosing a `<ClinicalDocument>` payload matches both `mllp` and `ccda`; a text file whose byte 128\n * is `DICM` matches both), which is exactly why the **`ambiguous` branch is load-bearing, not dead\n * code**: any co-match is a *detected* ambiguity (a value-free data error asking for `--format`),\n * **never a silent mis-route**.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\n\n/** The set of formats the `cosyte` command names. */\nexport type CosyteFormat = \"hl7\" | \"fhir\" | \"dicom\" | \"x12\" | \"ccda\" | \"ncpdp\" | \"astm\" | \"mllp\";\n\n/**\n * How confident autodetection is:\n * - `certain`: exactly one signature matched (`format` names it);\n * - `ambiguous`: more than one matched (`format` is `null`; `candidates` names them);\n * - `none`: nothing matched (`format` is `null`; `candidates` is empty).\n *\n * `format` is `null` unless `confidence` is `certain`, so a non-certain result can never be mistaken\n * for a routable format.\n */\nexport interface DetectResult {\n /** The detected format, or `null` when `confidence` is not `certain`. */\n readonly format: CosyteFormat | null;\n /** The detection confidence. */\n readonly confidence: \"certain\" | \"ambiguous\" | \"none\";\n /** The matching candidate formats (0 for `none`, 1 for `certain`, ≥2 for `ambiguous`). Value-free. */\n readonly candidates: readonly CosyteFormat[];\n}\n\n/** A single format signature: a value-free predicate over the input's decoded prefix + raw bytes. */\ninterface Signature {\n readonly format: CosyteFormat;\n readonly match: (prefix: string, bytes: Uint8Array) => boolean;\n}\n\n/** How many leading bytes to decode for text sniffing. Small: signatures live in the first line. */\nconst SNIFF_BYTES = 512;\n\n/** Strip a leading UTF-8 BOM and any leading ASCII whitespace for a tolerant sniff. Deliberately does\n * **not** strip the MLLP `0x0B` VT frame byte (`\\v`): that byte is the mllp signature, so consuming it\n * here would collide the hl7 and mllp signatures on a framed message. */\nfunction leadingText(bytes: Uint8Array): string {\n const slice = bytes.subarray(0, SNIFF_BYTES);\n let text = new TextDecoder(\"utf-8\", { fatal: false }).decode(slice);\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\n return text;\n}\n\n/** Trim only regular leading whitespace (space/tab/CR/LF/FF), never the `0x0B` VT MLLP frame byte. */\nfunction trimLeading(prefix: string): string {\n return prefix.replace(/^[ \\t\\r\\n\\f]+/, \"\");\n}\n\n/** True iff `ch` is a single printable, non-alphanumeric byte usable as a wire delimiter (e.g. `|`, `*`). */\nfunction isDelimiter(ch: string | undefined): boolean {\n if (ch === undefined) return false;\n const code = ch.charCodeAt(0);\n return code > 0x20 && code < 0x7f && !/[A-Za-z0-9]/.test(ch);\n}\n\n/**\n * HL7 v2: the message begins with an `MSH` segment whose 4th character is the field separator\n * (conventionally `|`) followed by the encoding characters. Conservative: requires `MSH` + a\n * non-alphanumeric single-char field separator. An MLLP-framed message (leading `0x0B`) is **not**\n * claimed here (it is the `mllp` signature) because {@link trimLeading} preserves the VT byte.\n */\nfunction looksLikeHl7(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"MSH\") && isDelimiter(s[3]);\n}\n\n/**\n * MLLP: a Minimal Lower Layer Protocol frame opens with the `0x0B` VT byte. This is a **transport\n * framing**, not a document format: the CLI de-frames it and parses the enclosed HL7 v2 payload(s).\n * The check is on the **raw first byte**, so it is disjoint from every text signature.\n */\nfunction looksLikeMllp(_prefix: string, bytes: Uint8Array): boolean {\n return bytes[0] === 0x0b;\n}\n\n/**\n * FHIR: a JSON object whose first non-whitespace byte is `{` and which declares a string-valued\n * top-level `resourceType` member near the top. Conservative: both the object framing and the\n * `resourceType` key must be present, so a bare JSON object without it is not claimed as FHIR.\n */\nfunction looksLikeFhir(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"{\")) return false;\n return /\"resourceType\"\\s*:\\s*\"/.test(s);\n}\n\n/**\n * X12 EDI: an interchange opens with the fixed 3-byte `ISA` segment id immediately followed by the\n * element separator (a non-alphanumeric byte: `*` conventionally, but delimiter-agnostic).\n */\nfunction looksLikeX12(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"ISA\") && isDelimiter(s[3]);\n}\n\n/**\n * ASTM E1394/E1381 records: the first record is an `H` (header) whose second byte is the field\n * delimiter and whose next three bytes are the repeat / component / escape **delimiter declarations**\n * (all punctuation: classically `\\^&`). Requiring the full 4-delimiter block, not just `H` + one\n * delimiter, keeps a mundane `H:...`/`H!...` text line from being confidently mis-routed to ASTM (it\n * would instead be a value-free `CLI_FORMAT_UNDETECTED`). Distinct from HL7 (`MSH`) and X12 (`ISA`).\n */\nfunction looksLikeAstm(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"H\") || s.length < 5) return false;\n // s[1] = field delimiter; s[2..4] = the repeat/component/escape delimiter declarations.\n return isDelimiter(s[1]) && isDelimiter(s[2]) && isDelimiter(s[3]) && isDelimiter(s[4]);\n}\n\n/** C-CDA: an HL7 v3 CDA document rooted at `<ClinicalDocument>` (XML). */\nfunction looksLikeCcda(prefix: string): boolean {\n return /<ClinicalDocument[\\s>]/.test(prefix);\n}\n\n/**\n * NCPDP SCRIPT: an ePrescribing message rooted at `<Message>` in the NCPDP SCRIPT namespace.\n * Requires **both** the `<Message>` root and the `ncpdp` namespace marker so a generic `<Message>`\n * XML is not mis-claimed (conservative: disjoint from C-CDA's `<ClinicalDocument>`).\n */\nfunction looksLikeNcpdp(prefix: string): boolean {\n return /<Message[\\s>]/.test(prefix) && /ncpdp/i.test(prefix);\n}\n\n/** DICOM Part 10: the `DICM` magic sits at byte offset 128, after the 128-byte preamble. */\nfunction looksLikeDicom(_prefix: string, bytes: Uint8Array): boolean {\n if (bytes.length < 132) return false;\n return (\n bytes[128] === 0x44 && bytes[129] === 0x49 && bytes[130] === 0x43 && bytes[131] === 0x4d // \"DICM\"\n );\n}\n\n/** The signature registry: disjoint by construction across all eight cosyte formats. */\nconst SIGNATURES: readonly Signature[] = [\n { format: \"hl7\", match: (prefix) => looksLikeHl7(prefix) },\n { format: \"mllp\", match: (prefix, bytes) => looksLikeMllp(prefix, bytes) },\n { format: \"fhir\", match: (prefix) => looksLikeFhir(prefix) },\n { format: \"x12\", match: (prefix) => looksLikeX12(prefix) },\n { format: \"astm\", match: (prefix) => looksLikeAstm(prefix) },\n { format: \"ccda\", match: (prefix) => looksLikeCcda(prefix) },\n { format: \"ncpdp\", match: (prefix) => looksLikeNcpdp(prefix) },\n { format: \"dicom\", match: (prefix, bytes) => looksLikeDicom(prefix, bytes) },\n];\n\n/** The formats content-autodetection can recognise (every format now carries a signature). */\nexport const DETECTABLE_FORMATS: readonly CosyteFormat[] = SIGNATURES.map((s) => s.format);\n\n/**\n * Detect the healthcare format of `bytes` by content, conservatively.\n *\n * @param bytes - The input bytes (a whole file or a stdin buffer). Only the leading prefix is sniffed.\n * @returns A {@link DetectResult}: `certain` + a `format` on a single match, else `ambiguous`/`none`\n * with `format: null` and the value-free `candidates` list. **Never guesses.**\n * @example\n * ```ts\n * import { detectFormat } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * detectFormat(enc.encode(\"MSH|^~\\\\&|A|B\\r\")).format; // => \"hl7\"\n * detectFormat(enc.encode('{\"resourceType\":\"Patient\"}')).format; // => \"fhir\"\n * detectFormat(enc.encode(\"hello\")).confidence; // => \"none\"\n * ```\n */\nexport function detectFormat(bytes: Uint8Array): DetectResult {\n if (bytes.length === 0) return classifyCandidates([]);\n const prefix = leadingText(bytes);\n const candidates = SIGNATURES.filter((sig) => sig.match(prefix, bytes)).map((sig) => sig.format);\n return classifyCandidates(candidates);\n}\n\n/**\n * Classify a list of matched candidate formats into a {@link DetectResult}: exactly one → `certain`,\n * zero → `none`, two-or-more → `ambiguous` (all with `format` `null` unless certain). Split out and\n * exported so the **ambiguity** contract is directly testable. It is otherwise unreachable while\n * every signature is disjoint, and it must stay a *detected* ambiguity, never a mis-route.\n *\n * @param candidates - The formats whose signatures matched the input.\n * @returns The classified {@link DetectResult}.\n * @example\n * ```ts\n * import { classifyCandidates } from \"@cosyte/cli\";\n *\n * classifyCandidates([\"hl7\"]).confidence; // => \"certain\"\n * classifyCandidates([]).confidence; // => \"none\"\n * classifyCandidates([\"hl7\", \"fhir\"]).confidence; // => \"ambiguous\"\n * ```\n */\nexport function classifyCandidates(candidates: readonly CosyteFormat[]): DetectResult {\n const [first, second] = candidates;\n if (second !== undefined) return { format: null, confidence: \"ambiguous\", candidates };\n if (first !== undefined) return { format: first, confidence: \"certain\", candidates };\n return { format: null, confidence: \"none\", candidates: [] };\n}\n\n/**\n * Build the value-free {@link CliError} for a **non-certain** detection: the data error the caller\n * returns instead of guessing a parser. `ambiguous` names the matching candidates (a value-free code\n * list); `none` asks for `--format`. Both map to the data-error exit (`65`). Never echoes input bytes.\n *\n * @param detected - A {@link DetectResult} whose `format` is `null` (i.e. not `certain`).\n * @returns A value-free `CLI_FORMAT_AMBIGUOUS` or `CLI_FORMAT_UNDETECTED` error.\n * @example\n * ```ts\n * import { classifyCandidates, detectionError } from \"@cosyte/cli\";\n *\n * detectionError(classifyCandidates([])).code; // => \"CLI_FORMAT_UNDETECTED\"\n * detectionError(classifyCandidates([\"hl7\", \"fhir\"])).code; // => \"CLI_FORMAT_AMBIGUOUS\"\n * ```\n */\nexport function detectionError(detected: DetectResult): CliError {\n if (detected.confidence === \"ambiguous\") {\n return new CliError(\n CLI_CODES.CLI_FORMAT_AMBIGUOUS,\n EXIT.DATAERR,\n `input matched multiple formats (${detected.candidates.join(\", \")}); disambiguate with --format`,\n );\n }\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNDETECTED,\n EXIT.DATAERR,\n `could not detect the input format; re-run with --format (detectable: ${DETECTABLE_FORMATS.join(\", \")})`,\n );\n}\n\n/** The full set of format names `--format` accepts as syntactically valid (a bad value is a usage error). */\nexport const KNOWN_FORMATS: readonly CosyteFormat[] = [\n \"hl7\",\n \"fhir\",\n \"dicom\",\n \"x12\",\n \"ccda\",\n \"ncpdp\",\n \"astm\",\n \"mllp\",\n];\n\n/**\n * Narrow an arbitrary `--format` string to a {@link CosyteFormat}, or `null` if it is not a known\n * format name (which the caller turns into a usage error, exit `2`).\n *\n * @param value - The raw `--format` argument.\n * @returns The narrowed format, or `null`.\n * @example\n * ```ts\n * import { asCosyteFormat } from \"@cosyte/cli\";\n *\n * asCosyteFormat(\"hl7\"); // => \"hl7\"\n * asCosyteFormat(\"nope\"); // => null\n * ```\n */\nexport function asCosyteFormat(value: string): CosyteFormat | null {\n return (KNOWN_FORMATS as readonly string[]).includes(value) ? (value as CosyteFormat) : null;\n}\n","/**\n * The CLI's **value-free finding** shape and the positional locators that populate it. A finding says\n * *what kind* of thing was observed (a stable code + severity) and *where* (a positional locator),\n * **never** the offending value. Shared by `validate` (conformance findings) and\n * `inspect` (structural summary) so both render locations identically and value-free.\n *\n * @packageDocumentation\n */\n\n/**\n * A single value-free finding: a stable code, a severity, and a positional locator. Every field is\n * safe to print, log, or serialize. None carries a name, DOB, MRN, or field value.\n */\nexport interface Finding {\n /** The stable diagnostic/warning code (the wrapped library's or the CLI's). */\n readonly code: string;\n /** The R4-style severity (`fatal` | `error` | `warning` | `information`), or `warning` for HL7. */\n readonly severity: string;\n /** A value-free positional locator: a FHIRPath expression, or an HL7 segment/field index path. */\n readonly location: string;\n}\n\n/** The minimal, value-free positional shape shared by HL7 warnings (indices only, never a value). */\ninterface Hl7PositionLike {\n readonly segmentIndex: number;\n readonly fieldIndex?: number;\n readonly repetitionIndex?: number;\n readonly componentIndex?: number;\n readonly subcomponentIndex?: number;\n}\n\n/**\n * Render an HL7 warning position as a **value-free** locator string built only from its numeric\n * indices: e.g. `seg[3].field[5].comp[1]`. No segment content, no field value, ever appears; only the\n * structural coordinates the parser reported.\n *\n * @param pos - The HL7 position (segment/field/repetition/component/subcomponent indices).\n * @returns A value-free locator, e.g. `\"seg[3].field[5]\"`.\n * @example\n * ```ts\n * import { formatHl7Position } from \"@cosyte/cli\";\n *\n * formatHl7Position({ segmentIndex: 3, fieldIndex: 5 }); // => \"seg[3].field[5]\"\n * formatHl7Position({ segmentIndex: 0 }); // => \"seg[0]\"\n * ```\n */\nexport function formatHl7Position(pos: Hl7PositionLike): string {\n let out = `seg[${String(pos.segmentIndex)}]`;\n if (pos.fieldIndex !== undefined) out += `.field[${String(pos.fieldIndex)}]`;\n if (pos.repetitionIndex !== undefined) out += `.rep[${String(pos.repetitionIndex)}]`;\n if (pos.componentIndex !== undefined) out += `.comp[${String(pos.componentIndex)}]`;\n if (pos.subcomponentIndex !== undefined) out += `.sub[${String(pos.subcomponentIndex)}]`;\n return out;\n}\n","/**\n * The **per-format parser adapter registry**: the single place the CLI routes a resolved format to\n * its wrapped `@cosyte/*` parser, for each of the four wrapping operations (`parse` / `inspect` /\n * `fmt` / `validate`). One lazy, value-free registry, so the wrapper boundary lives in exactly one\n * file.\n *\n * **Capability is per (format, operation).** Not every parser faithfully supports every operation:\n * DICOM's model is binary (no faithful JSON `parse`, no text `fmt`), C-CDA's canonical form is XML (no\n * library-blessed JSON `parse`), MLLP is a transport container (de-framed to HL7, `parse`/`inspect`\n * only). {@link OP_SUPPORT} is the honest matrix; an unsupported (format, op) is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, **never** a faked result.\n *\n * **Lazy + optional.** Every parser is imported dynamically inside its branch, so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code. The six breadth parsers are `optionalDependencies`: if\n * one is absent the dynamic import is caught and degrades to a value-free `CLI_PARSER_UNAVAILABLE`\n * (exit `69`) rather than an unhandled crash: the CLI core still works with any of them missing.\n *\n * @packageDocumentation\n */\n\nimport type * as CosyteFhir from \"@cosyte/fhir\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport { formatHl7Position, type Finding } from \"./findings.js\";\nimport type { CosyteFormat } from \"./format.js\";\n\n/** The four wrapping operations a command can ask a format's adapter to perform. */\nexport type Op = \"parse\" | \"inspect\" | \"fmt\" | \"validate\";\n\n/** A value-free parse warning: a stable code plus the parser's positional (index-only) context. */\nexport type ParseWarning = { readonly code: string } & Readonly<Record<string, unknown>>;\n\n/** The result of wrapping a parser's `parse`: the library's parsed model + its value-free warnings. */\nexport interface ParseResult {\n /** The wrapped library's parsed model: emitted verbatim as JSON on the data channel. */\n readonly model: unknown;\n /** The parser's value-free warnings (code + position). */\n readonly warnings: readonly ParseWarning[];\n}\n\n/** The result of a canonical re-serialization (`fmt`): the spec-clean text + a value-free warning count. */\nexport interface FmtResult {\n /** The wrapped serializer's output text. */\n readonly output: string;\n /** How many parse warnings the round-trip surfaced (value-free count only). */\n readonly warningCount: number;\n}\n\n/** The verdict of running a format's validation surface: value-free findings + the validity boolean. */\nexport interface Verdict {\n /** The value-free findings (code + severity + positional locator). */\n readonly findings: readonly Finding[];\n /** `true` iff the input is valid (no error/fatal-severity finding). */\n readonly valid: boolean;\n}\n\n/* ── value-free structural summaries (one variant per format) ─────────────────────────────────── */\n\n/** Value-free structural summary of an HL7 v2 message. */\nexport interface Hl7Summary {\n readonly format: \"hl7\";\n readonly messageType: string | null;\n readonly version: string | null;\n readonly segmentCount: number;\n readonly segments: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a FHIR resource. */\nexport interface FhirSummary {\n readonly format: \"fhir\";\n readonly resourceType: string | null;\n readonly bundleType?: string | null;\n readonly entryCount?: number;\n readonly entryResourceTypes?: Readonly<Record<string, number>>;\n readonly issueCount: number;\n}\n\n/** Value-free structural summary of an X12 interchange (envelope counts + transaction-set ids). */\nexport interface X12Summary {\n readonly format: \"x12\";\n readonly groupCount: number;\n readonly transactionCount: number;\n /** Count of each transaction-set identifier code (ST-01), e.g. `{ \"834\": 1 }`: value-free codes. */\n readonly transactionSetIds: Readonly<Record<string, number>>;\n readonly segmentCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an ASTM record message. */\nexport interface AstmSummary {\n readonly format: \"astm\";\n /** The host-query classification kind (`results` | `orders` | `host-query` | `indeterminate`). */\n readonly messageKind: string;\n readonly recordCount: number;\n /** Count of each single-letter record type, e.g. `{ H: 1, P: 1, O: 2, R: 4, L: 1 }`. */\n readonly recordTypes: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a C-CDA document (document type + section LOINC codes). */\nexport interface CcdaSummary {\n readonly format: \"ccda\";\n readonly documentType: string | null;\n readonly sectionCount: number;\n /** The LOINC `code` of each top-level section (value-free classification codes). */\n readonly sectionCodes: readonly string[];\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a DICOM dataset (classification UIDs + element count). */\nexport interface DicomSummary {\n readonly format: \"dicom\";\n /** The SOP Class UID (a standard OID identifying the object type: value-free classification). */\n readonly sopClassUid: string | null;\n /** The Transfer Syntax UID (encoding classification: value-free). */\n readonly transferSyntaxUid: string | null;\n readonly elementCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an NCPDP SCRIPT message. */\nexport interface NcpdpSummary {\n readonly format: \"ncpdp\";\n readonly standard: \"SCRIPT\";\n /** The SCRIPT message type (e.g. `NewRx`, `CancelRx`: a value-free classification). */\n readonly messageType: string | null;\n /** The SCRIPT version (e.g. `2017071`: value-free). */\n readonly version: string | null;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an MLLP stream (frame count only; the payloads are HL7). */\nexport interface MllpSummary {\n readonly format: \"mllp\";\n readonly frameCount: number;\n readonly warningCount: number;\n}\n\n/** The discriminated value-free structural summary `inspect` renders. */\nexport type InspectSummary =\n | Hl7Summary\n | FhirSummary\n | X12Summary\n | AstmSummary\n | CcdaSummary\n | DicomSummary\n | NcpdpSummary\n | MllpSummary;\n\n/* ── the capability matrix ───────────────────────────────────────────────────────────────────── */\n\n/**\n * The honest per-format operation matrix. A (format, op) pair absent here is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, never a faked result. The unsupported cells and why:\n * - **dicom** `parse`/`fmt`. The model is binary (no faithful JSON view; `serializeDicom` emits a\n * Part-10 byte stream, not text). `inspect`/`validate` are supported.\n * - **ccda** `parse`: the canonical form is XML; there is no library-blessed JSON model, so `fmt`\n * (XML re-serialize) is the faithful surface. `inspect`/`fmt`/`validate` are supported.\n * - **mllp** `fmt`/`validate`: MLLP is a transport container the CLI de-frames to HL7; `parse` yields\n * the enclosed HL7 message(s) and `inspect` reports the frame count.\n *\n * @example\n * ```ts\n * import { OP_SUPPORT } from \"@cosyte/cli\";\n *\n * OP_SUPPORT.dicom.has(\"parse\"); // => false\n * OP_SUPPORT.hl7.has(\"validate\"); // => true\n * ```\n */\nexport const OP_SUPPORT: Readonly<Record<CosyteFormat, ReadonlySet<Op>>> = {\n hl7: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n fhir: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n x12: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n astm: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ncpdp: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ccda: new Set<Op>([\"inspect\", \"fmt\", \"validate\"]),\n dicom: new Set<Op>([\"inspect\", \"validate\"]),\n mllp: new Set<Op>([\"parse\", \"inspect\"]),\n};\n\n/**\n * True iff `format`'s wrapped parser supports `op` in this build (see {@link OP_SUPPORT}).\n *\n * @param format - The resolved format.\n * @param op - The wrapping operation.\n * @returns Whether the (format, op) pair is wired.\n * @example\n * ```ts\n * import { supportsOp } from \"@cosyte/cli\";\n *\n * supportsOp(\"x12\", \"fmt\"); // => true\n * supportsOp(\"dicom\", \"parse\"); // => false\n * ```\n */\nexport function supportsOp(format: CosyteFormat, op: Op): boolean {\n return OP_SUPPORT[format].has(op);\n}\n\n/**\n * The formats that support `op`, as a sorted, value-free list: used to build the \"does not support\"\n * diagnostic so the user is told which formats *do* support the operation they asked for.\n *\n * @param op - The wrapping operation.\n * @returns The supporting format names, sorted.\n * @example\n * ```ts\n * import { formatsSupporting } from \"@cosyte/cli\";\n *\n * formatsSupporting(\"fmt\"); // => [\"astm\", \"ccda\", \"fhir\", \"hl7\", \"ncpdp\", \"x12\"]\n * ```\n */\nexport function formatsSupporting(op: Op): readonly CosyteFormat[] {\n return (Object.keys(OP_SUPPORT) as CosyteFormat[]).filter((f) => OP_SUPPORT[f].has(op)).sort();\n}\n\n/* ── value-free helpers ──────────────────────────────────────────────────────────────────────── */\n\n/**\n * Render an arbitrary parser **position** object as a value-free locator string, keeping **only**\n * number-valued own properties (the parsers' positions are index-only): e.g. `{ segmentIndex: 3,\n * elementIndex: 2 }` → `segmentIndex[3].elementIndex[2]`. A non-number field (which a position should\n * never carry) is dropped, so a stray value can never reach a diagnostic. Falls back to `\"?\"` when no\n * numeric index is present.\n *\n * @param pos - A parser position object (index-only by the parser's contract).\n * @returns A value-free locator built solely from numeric indices.\n * @example\n * ```ts\n * import { valueFreeLocator } from \"@cosyte/cli\";\n *\n * valueFreeLocator({ segmentIndex: 3, elementIndex: 2 }); // => \"segmentIndex[3].elementIndex[2]\"\n * valueFreeLocator({}); // => \"?\"\n * ```\n */\nexport function valueFreeLocator(pos: unknown): string {\n if (typeof pos !== \"object\" || pos === null) return \"?\";\n const parts: string[] = [];\n for (const [k, v] of Object.entries(pos)) {\n if (typeof v === \"number\") parts.push(`${k}[${String(v)}]`);\n }\n return parts.length > 0 ? parts.join(\".\") : \"?\";\n}\n\n/** Severities that make an input **invalid** (exit `1`). Recovered warnings never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** Whether any finding is error/fatal severity (i.e. the input is invalid). */\nfunction anyError(findings: readonly Finding[]): boolean {\n return findings.some((f) => ERROR_SEVERITIES.has(f.severity));\n}\n\n/**\n * Lazy-import an **optional** parser package, mapping an *absent* package to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`): the graceful-degradation path for the `optionalDependencies`\n * breadth parsers. A genuine import that succeeds passes straight through; any error whose\n * shape is \"module not found\" becomes the value-free CLI error. Other errors propagate unchanged.\n *\n * @template T - The imported module's type.\n * @param format - The format whose optional parser is being loaded (named in the diagnostic).\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptional } from \"@cosyte/cli\";\n *\n * // a present parser resolves; an absent one throws CLI_PARSER_UNAVAILABLE\n * await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n * ```\n */\nexport async function loadOptional<T>(format: CosyteFormat, load: () => Promise<T>): Promise<T> {\n return loadOptionalPackage(\n `the @cosyte/${format} parser is not installed; install it to use this format ` +\n `(it is an optional dependency)`,\n load,\n );\n}\n\n/**\n * The same graceful-degradation path as {@link loadOptional}, keyed on a **package name** rather than\n * a {@link CosyteFormat}, with the diagnostic supplied by the caller.\n *\n * Two of the packages the CLI lazy-loads are not wire-format parsers and so cannot go through\n * {@link loadOptional}: `@cosyte/transform` (a conversion library, not one of the eight formats, so\n * calling it a \"parser\" in the diagnostic would be wrong) and `@cosyte/fhir` (a format, but absent for\n * a reason no reinstall fixes, which the message has to say). Both are reachable from a published\n * install only if the user already has them, so both must degrade to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`) instead of surfacing a raw resolver error and a stack frame.\n *\n * @template T - The imported module's type.\n * @param detail - The value-free diagnostic detail shown when the package is absent.\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptionalPackage } from \"@cosyte/cli\";\n *\n * await loadOptionalPackage(\"the conversion library is not installed\", () =>\n * import(\"@cosyte/transform\"),\n * );\n * ```\n */\nexport async function loadOptionalPackage<T>(detail: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (e) {\n if (isModuleNotFound(e)) {\n throw new CliError(CLI_CODES.CLI_PARSER_UNAVAILABLE, EXIT.UNAVAILABLE, detail);\n }\n throw e;\n }\n}\n\n/**\n * Why `@cosyte/fhir` is absent, in the words a user can act on. It is not on the npm registry, so it\n * cannot be a declared dependency of this package at all, and no reinstall of `@cosyte/cli` will\n * produce it. Value-free by construction: a package name and a statement of fact, no input echoed.\n */\nconst FHIR_UNAVAILABLE =\n \"the @cosyte/fhir parser is not installed, and it is not currently on the npm registry, \" +\n \"so it cannot be installed from there; FHIR support is unavailable in this install\";\n\n/**\n * Load `@cosyte/fhir`, degrading to a value-free `CLI_PARSER_UNAVAILABLE` when it is absent.\n *\n * Every FHIR branch in this file and the `convert` command go through here, so there is exactly one\n * place that decides what an absent FHIR library does. It is deliberately not re-exported from the\n * package entry point: consumers get {@link loadOptionalPackage}, not this repo's own wiring.\n *\n * @returns The `@cosyte/fhir` module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent.\n * @example\n * ```ts\n * const { parseResource } = await loadFhir();\n * ```\n */\nexport async function loadFhir(): Promise<typeof CosyteFhir> {\n return loadOptionalPackage(FHIR_UNAVAILABLE, () => import(\"@cosyte/fhir\"));\n}\n\n/** True iff `e` is a \"module not found\" failure, by Node's `code`, or the standard resolver message. */\nfunction isModuleNotFound(e: unknown): boolean {\n if (typeof e !== \"object\" || e === null) return false;\n const code = \"code\" in e ? e.code : undefined;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") return true;\n const message = \"message\" in e && typeof e.message === \"string\" ? e.message : \"\";\n return /Cannot find (package|module)|Failed to (load|resolve)/i.test(message);\n}\n\n/* ── parse ───────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Parse one record of `format` into the wrapped library's model + its value-free warnings. The model\n * is emitted verbatim on the data channel; the CLI adds no parsing of its own.\n *\n * @param format - A format for which `supportsOp(format, \"parse\")` is true.\n * @param bytes - The single record's bytes (already de-framed for MLLP: callers pass `\"hl7\"` there).\n * @returns The parsed model + value-free warnings.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * own rejection propagates for the command's value-free failure boundary to catch.\n * @example\n * ```ts\n * import { parseFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}');\n * (await parseFormat(\"fhir\", bytes)).warnings.length; // => 0\n * ```\n */\nexport async function parseFormat(format: CosyteFormat, bytes: Uint8Array): Promise<ParseResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return {\n model: msg.toJSON(),\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const text = decode(bytes);\n const { resource, issues } = parseResource(text);\n const model: unknown = JSON.parse(serializeResource(resource));\n return {\n model,\n warnings: issues.map((i) => ({\n code: i.code,\n severity: i.severity,\n expression: i.expression,\n })),\n };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return {\n model: ix,\n warnings: ix.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"dicom\":\n case \"ccda\":\n case \"mllp\":\n // Guarded upstream by supportsOp; a direct call for an unsupported (format, op) is value-free.\n throw unsupportedInternal(format, \"parse\");\n }\n}\n\n/* ── inspect ─────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Build the value-free structural summary of one input of `format`: counts and structural type codes\n * only, never a field value.\n *\n * @param format - A format for which `supportsOp(format, \"inspect\")` is true.\n * @param bytes - The input bytes.\n * @returns A {@link InspectSummary} variant for the format.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary.\n * @example\n * ```ts\n * import { inspectFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\"}');\n * (await inspectFormat(\"fhir\", bytes)).format; // => \"fhir\"\n * ```\n */\nexport async function inspectFormat(\n format: CosyteFormat,\n bytes: Uint8Array,\n): Promise<InspectSummary> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const segments: Record<string, number> = {};\n const all = msg.allSegments();\n for (const seg of all) segments[seg.type] = (segments[seg.type] ?? 0) + 1;\n return {\n format: \"hl7\",\n messageType: msg.meta.type ?? null,\n version: msg.meta.version ?? null,\n segmentCount: all.length,\n segments,\n warningCount: msg.warnings.length,\n };\n }\n case \"fhir\": {\n const { parseResource, resourceType, readBundle } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const rt = resourceType(resource) ?? null;\n if (rt === \"Bundle\") {\n const bundle = readBundle(resource);\n const entryResourceTypes: Record<string, number> = {};\n for (const e of bundle.entries) {\n const t = e.resourceType ?? \"(none)\";\n entryResourceTypes[t] = (entryResourceTypes[t] ?? 0) + 1;\n }\n return {\n format: \"fhir\",\n resourceType: rt,\n bundleType: bundle.type ?? null,\n entryCount: bundle.entries.length,\n entryResourceTypes,\n issueCount: issues.length,\n };\n }\n return { format: \"fhir\", resourceType: rt, issueCount: issues.length };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const transactionSetIds: Record<string, number> = {};\n let transactionCount = 0;\n let segmentCount = 0;\n for (const g of ix.groups) {\n for (const t of g.transactions) {\n transactionCount += 1;\n segmentCount += t.segments.length;\n const id = t.st.elements[1] ?? \"(unknown)\";\n transactionSetIds[id] = (transactionSetIds[id] ?? 0) + 1;\n }\n }\n return {\n format: \"x12\",\n groupCount: ix.groups.length,\n transactionCount,\n transactionSetIds,\n segmentCount,\n warningCount: ix.warnings.length,\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const recordTypes: Record<string, number> = {};\n for (const r of msg.records) recordTypes[r.type] = (recordTypes[r.type] ?? 0) + 1;\n return {\n format: \"astm\",\n messageKind: msg.classification.kind,\n recordCount: msg.records.length,\n recordTypes,\n warningCount: msg.warnings.length,\n };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const sectionCodes: string[] = [];\n for (const s of doc.sections) {\n const code = s.code?.code;\n if (typeof code === \"string\") sectionCodes.push(code);\n }\n return {\n format: \"ccda\",\n documentType: doc.documentType ?? null,\n sectionCount: doc.sections.length,\n sectionCodes,\n warningCount: doc.warnings.length,\n };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n let warningCount = 0;\n const ds = parseDicom(Buffer.from(bytes), { onWarning: () => (warningCount += 1) });\n return {\n format: \"dicom\",\n sopClassUid: ds.fileMeta?.mediaStorageSOPClassUID ?? null,\n transferSyntaxUid: ds.fileMeta?.transferSyntaxUID ?? null,\n elementCount: ds.elements().length,\n warningCount,\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n format: \"ncpdp\",\n standard: \"SCRIPT\",\n messageType: msg.body.kind ?? null,\n version: msg.header.version ?? null,\n warningCount: msg.warnings.length,\n };\n }\n case \"mllp\": {\n const { payloads, warningCount } = await deframeMllp(bytes);\n return { format: \"mllp\", frameCount: payloads.length, warningCount };\n }\n }\n}\n\n/* ── fmt ─────────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Canonically re-serialize one input of `format` via the wrapped library's spec-clean serializer. The\n * CLI never re-canonicalizes on its own; the output is exactly the serializer's.\n *\n * @param format - A format for which `supportsOp(format, \"fmt\")` is true.\n * @param bytes - The input bytes.\n * @returns The serialized text + a value-free warning count.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary (no partial emit).\n * @example\n * ```ts\n * import { fmtFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{ \"resourceType\":\"Patient\" , \"id\":\"x\" }');\n * (await fmtFormat(\"fhir\", bytes)).output.startsWith(\"{\"); // => true\n * ```\n */\nexport async function fmtFormat(format: CosyteFormat, bytes: Uint8Array): Promise<FmtResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return { output: msg.toString(), warningCount: msg.warnings.length };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n return { output: serializeResource(resource), warningCount: issues.length };\n }\n case \"x12\": {\n const { parseX12, serializeX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return { output: serializeX12(ix), warningCount: ix.warnings.length };\n }\n case \"astm\": {\n const { parseAstmRecords, serializeAstmRecords } = await loadOptional(\n \"astm\",\n () => import(\"@cosyte/astm\"),\n );\n const msg = parseAstmRecords(decode(bytes));\n return { output: serializeAstmRecords(msg), warningCount: msg.warnings.length };\n }\n case \"ccda\": {\n const { parseCcda, serializeCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n return { output: serializeCcda(doc), warningCount: doc.warnings.length };\n }\n case \"ncpdp\": {\n const { parseScript, serializeScript } = await loadOptional(\n \"ncpdp\",\n () => import(\"@cosyte/ncpdp\"),\n );\n const msg = parseScript(decode(bytes));\n return { output: serializeScript(msg), warningCount: msg.warnings.length };\n }\n case \"dicom\":\n case \"mllp\":\n throw unsupportedInternal(format, \"fmt\");\n }\n}\n\n/* ── validate ────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Run the format's validation surface and return a value-free {@link Verdict}. For the Postel's-Law\n * lenient parsers, a **parseable** input is valid: recovered deviations are non-fatal warnings the\n * library surfaces, never a stricter verdict the CLI invents. FHIR additionally runs `validateResource`\n * and is invalid on any error/fatal-severity issue.\n *\n * @param format - A format for which `supportsOp(format, \"validate\")` is true.\n * @param bytes - The input bytes.\n * @returns The value-free verdict (findings + validity).\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; an unparseable input\n * propagates as the wrapped parser's throw for the command to map to a data error (`65`).\n * @example\n * ```ts\n * import { validateFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}');\n * (await validateFormat(\"fhir\", bytes)).valid; // => true\n * ```\n */\nexport async function validateFormat(format: CosyteFormat, bytes: Uint8Array): Promise<Verdict> {\n switch (format) {\n case \"fhir\": {\n const { parseResource, validateResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const validation = validateResource(resource);\n const findings: Finding[] = [\n ...issues.map((i) => finding(i.code, i.severity, i.expression)),\n ...validation.issues.map((i) => finding(i.code, i.severity, i.expression, i.constraint)),\n ];\n return { findings, valid: !anyError(findings) };\n }\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", formatHl7Position(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const findings = ix.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const findings = doc.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n const findings: Finding[] = [];\n parseDicom(Buffer.from(bytes), {\n onWarning: (w) => findings.push(finding(w.code, \"warning\", valueFreeLocator(w.position))),\n });\n return { findings, valid: !anyError(findings) };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"mllp\":\n throw unsupportedInternal(format, \"validate\");\n }\n}\n\n/* ── MLLP de-framing (transport → HL7 payloads) ──────────────────────────────────────────────── */\n\n/**\n * De-frame an MLLP byte stream into its enclosed HL7 payloads via `@cosyte/mllp`'s `FrameReader`. MLLP\n * is a transport container, not a document format: each frame's payload is an HL7 v2 message the CLI\n * then parses/inspects with the `hl7` adapter. Multi-frame streams are the CLI's multi-message surface.\n *\n * @param bytes - The MLLP-framed input.\n * @returns The de-framed HL7 payloads (in stream order) + a value-free framing-warning count.\n * **Truncation is a data error, never a silent drop.** The `FrameReader` is a streaming decoder: an\n * unterminated trailing frame (a VT opened with no closing FS/CR) is left buffered and delivered by\n * *no* callback, so feeding a whole file and reading only `onFrame` would silently lose the partial\n * message with a green exit. We therefore detect an open trailing frame at the byte level (the last\n * VT sits after the last FS: MLLP payloads are HL7 v2 text and never carry the `0x0B`/`0x1C` framing\n * bytes) and reject the whole stream as a value-free `CLI_PARSE_FAILED` data error.\n *\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if `@cosyte/mllp` is absent; `CLI_PARSE_FAILED` (exit\n * `65`) on a truncated stream; a hard framing error propagates for the caller's value-free boundary.\n * @example\n * ```ts\n * import { deframeMllp } from \"@cosyte/cli\";\n *\n * // a VT-framed \"MSH|...\" message → one payload\n * (await deframeMllp(new Uint8Array([0x0b, 0x4d, 0x53, 0x48, 0x1c, 0x0d]))).payloads.length; // => 1\n * ```\n */\nexport async function deframeMllp(\n bytes: Uint8Array,\n): Promise<{ payloads: Buffer[]; warningCount: number }> {\n // Reject an unterminated trailing frame BEFORE de-framing: a VT after the last FS is an open frame\n // the streaming reader would buffer and silently drop. (MLLP payloads never contain 0x0B/0x1C.)\n if (bytes.lastIndexOf(0x0b) > bytes.lastIndexOf(0x1c)) {\n throw new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n \"truncated MLLP stream: an unterminated frame at the end of input (no closing FS/CR)\",\n );\n }\n const { FrameReader } = await loadOptional(\"mllp\", () => import(\"@cosyte/mllp\"));\n const payloads: Buffer[] = [];\n let warningCount = 0;\n const reader = new FrameReader({\n onFrame: (payload) => payloads.push(Buffer.from(payload)),\n onWarning: () => (warningCount += 1),\n });\n reader.push(Buffer.from(bytes));\n return { payloads, warningCount };\n}\n\n/* ── shared internals ────────────────────────────────────────────────────────────────────────── */\n\n/** Decode input bytes as tolerant UTF-8 (the text parsers accept a string). */\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n}\n\n/** Build one value-free {@link Finding}; a FHIR `constraint` (a public spec id) is appended if present. */\nfunction finding(code: string, severity: string, location: string, constraint?: string): Finding {\n const loc = constraint !== undefined ? `${location} (${constraint})` : location;\n return { code, severity, location: loc };\n}\n\n/** The value-free error for an internal (guarded-upstream) unsupported (format, op): a programming bug. */\nfunction unsupportedInternal(format: CosyteFormat, op: Op): CliError {\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\``,\n );\n}\n","/**\n * The shared **input + format resolution** every file-consuming command runs before it touches a\n * wrapped parser: resolve the `<file|->` argument, read its bytes (a file, or stdin for `-`), reject\n * empty input, then resolve the format: an explicit `--format` override (validated) or conservative\n * content autodetection, and confirm the format is actually wired in this build. Factored out of the\n * commands so `parse`/`validate`/`inspect`/`fmt` share one identical, value-free front door and the\n * exit-code contract is applied in exactly one place.\n *\n * Every failure is a value-free {@link CliError} rendered to a {@link RunResult}: a missing argument\n * is a usage error (`2`), an unreadable file a no-input error (`66`), empty/undetected/unwired input a\n * data error (`65`). None ever echoes an input byte.\n *\n * @packageDocumentation\n */\n\nimport { asCosyteFormat, detectFormat, detectionError, type CosyteFormat } from \"./format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { RunDeps } from \"./io.js\";\nimport { formatsSupporting, supportsOp, type Op } from \"./parsers.js\";\nimport type { RunResult } from \"./result.js\";\n\n/** A successfully-resolved input: the format (guaranteed to support the requested op) and the bytes. */\nexport interface ResolvedInput {\n /** The resolved format: guaranteed to satisfy `supportsOp(format, op)` for the requested op. */\n readonly format: CosyteFormat;\n /** The input bytes (a whole file or a drained stdin buffer); guaranteed non-empty. */\n readonly bytes: Uint8Array;\n}\n\n/**\n * The outcome of {@link resolveInput}: either the resolved input, or a ready-to-return value-free\n * {@link RunResult} carrying the diagnostic + exit code for whatever went wrong. A discriminated union\n * so a command reads `if (!r.ok) return r.result;` and then works with `r.input`.\n */\nexport type InputResolution =\n | { readonly ok: true; readonly input: ResolvedInput }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Resolve and read the input, and resolve its format, for a file-consuming command.\n *\n * @param source - The positional `<file|->` argument (or `undefined` when it was omitted).\n * @param formatOverride - The raw `--format` value, or `undefined` to autodetect by content.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param op - The wrapping operation the caller will run; the resolved format is confirmed to support\n * it (else a value-free `CLI_FORMAT_UNSUPPORTED` naming the supporting formats).\n * @returns `{ ok: true, input }` when the bytes read and the format resolved to a parser supporting\n * `op`; else `{ ok: false, result }` with a value-free usage/no-input/data-error {@link RunResult}.\n * @throws Propagates a **non-`CliError`** read failure unchanged, so the dispatcher maps it to\n * `CLI_INTERNAL` (a `CliError` read failure, e.g. a missing file, is caught and returned).\n * @example\n * ```ts\n * import { resolveInput } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await resolveInput(\"patient.json\", undefined, deps, \"parse\");\n * if (r.ok) r.input.format; // => \"fhir\"\n * ```\n */\nexport async function resolveInput(\n source: string | undefined,\n formatOverride: string | undefined,\n deps: RunDeps,\n op: Op,\n): Promise<InputResolution> {\n if (source === undefined) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <file> argument; pass a path or `-` to read stdin\",\n ),\n );\n }\n\n let bytes: Uint8Array;\n try {\n bytes = source === \"-\" ? await deps.readStdin() : await deps.readFile(source);\n } catch (e) {\n if (e instanceof CliError) return fail(e);\n throw e;\n }\n\n if (bytes.length === 0) {\n return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n // Resolve the format: an explicit --format override (validated), else content autodetection.\n let format: CosyteFormat;\n if (formatOverride !== undefined) {\n const narrowed = asCosyteFormat(formatOverride);\n if (narrowed === null) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"unknown --format value; expected one of hl7, fhir, dicom, x12, ccda, ncpdp, astm, mllp\",\n ),\n );\n }\n format = narrowed;\n } else {\n const detected = detectFormat(bytes);\n // `format` is non-null iff detection is `certain`; `none`/`ambiguous` become a value-free data error.\n if (detected.format === null) return fail(detectionError(detected));\n format = detected.format;\n }\n\n if (!supportsOp(format, op)) {\n return fail(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\` in this CLI build ` +\n `(${op} supports: ${formatsSupporting(op).join(\", \")})`,\n ),\n );\n }\n\n return { ok: true, input: { format, bytes } };\n}\n\n/** Wrap a {@link CliError} as a failed {@link InputResolution}. */\nfunction fail(e: CliError): InputResolution {\n return { ok: false, result: errorResult(e) };\n}\n","/**\n * The CLI's **global PHI display posture**: the single mechanism that gates whether *any* input\n * value may appear on a **secondary surface** (stderr, a diagnostic, a warning, a log line). The CLI\n * is **value-free by default**: every secondary surface carries only positional/structural context\n * (a stable code, a segment/field index, a byte offset, a file path, a format name), never a name, a\n * DOB, an MRN, or a field value. `stdout` is the **data channel** (the user's explicit request) and\n * is exempt: the posture governs everything *but* stdout.\n *\n * `--unsafe-show-values` is the **single, explicit, loud door** to a value on a secondary surface. It\n * is off by default, PHI-exposing by design, and its effect flows through exactly one chokepoint here\n * ({@link unsafeInputSuffix}) so the \"a value appears on a secondary surface **iff** the flag is set\"\n * property is provable in one place rather than scattered across commands.\n *\n * @packageDocumentation\n */\n\n/**\n * The resolved PHI display posture for one invocation. `showValues` is `true` **only** when the user\n * passed `--unsafe-show-values`; every value-echoing decision reads this one flag.\n */\nexport interface PhiPosture {\n /** `true` iff `--unsafe-show-values` was given: a value may appear on a secondary surface. */\n readonly showValues: boolean;\n}\n\n/** The default, safe posture: no value ever reaches a secondary surface. */\nexport const VALUE_FREE: PhiPosture = { showValues: false };\n\n/** The opted-in, PHI-exposing posture selected by `--unsafe-show-values`. */\nexport const SHOW_VALUES: PhiPosture = { showValues: true };\n\n/** The single global flag token that opts into showing values on secondary surfaces. */\nexport const UNSAFE_SHOW_VALUES_FLAG = \"--unsafe-show-values\";\n\n/**\n * The maximum number of leading input bytes an `--unsafe-show-values` diagnostic may echo. Bounded so\n * an unsafe excerpt stays a single, readable diagnostic line rather than dumping a whole message.\n */\nexport const UNSAFE_EXCERPT_MAX = 200;\n\n/**\n * Resolve the global `--unsafe-show-values` flag out of an argument vector, **order-independently**\n * (it may appear before or after the subcommand), and return the posture plus the argv with every\n * occurrence of the flag removed, so each command's own `parseArgs` never sees it and cannot reject\n * it as unknown. This is the one place the flag is recognised.\n *\n * @param argv - The raw arguments (after the program name).\n * @returns The resolved {@link PhiPosture} and the flag-stripped argv.\n * @example\n * ```ts\n * import { extractPhiPosture } from \"@cosyte/cli\";\n *\n * extractPhiPosture([\"parse\", \"x.hl7\"]).posture.showValues; // => false\n * extractPhiPosture([\"--unsafe-show-values\", \"parse\", \"x.hl7\"]).posture.showValues; // => true\n * extractPhiPosture([\"parse\", \"x.hl7\", \"--unsafe-show-values\"]).argv; // => [\"parse\", \"x.hl7\"]\n * ```\n */\nexport function extractPhiPosture(argv: readonly string[]): {\n posture: PhiPosture;\n argv: string[];\n} {\n const showValues = argv.includes(UNSAFE_SHOW_VALUES_FLAG);\n const cleaned = argv.filter((a) => a !== UNSAFE_SHOW_VALUES_FLAG);\n return { posture: showValues ? SHOW_VALUES : VALUE_FREE, argv: cleaned };\n}\n\n/**\n * Build the **only** value-bearing addition the CLI ever appends to a secondary (stderr) surface: a\n * bounded, single-line excerpt of the offending input, shown **iff** `--unsafe-show-values` is set.\n * Under the default value-free posture it returns the empty string, so a diagnostic stays value-free\n * unless the user explicitly opted in. This is the single chokepoint the PHI-leak matrix pins.\n *\n * @param bytes - The input the CLI is operating on (only the leading {@link UNSAFE_EXCERPT_MAX} bytes\n * are considered).\n * @param posture - The resolved {@link PhiPosture}.\n * @returns `\"\"` under the value-free default; otherwise a ` [unsafe-show-values] …` suffix carrying a\n * bounded, newline-flattened prefix of `bytes`.\n * @example\n * ```ts\n * import { unsafeInputSuffix, VALUE_FREE, SHOW_VALUES } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"bad message\");\n * unsafeInputSuffix(bytes, VALUE_FREE); // => \"\"\n * unsafeInputSuffix(bytes, SHOW_VALUES); // => \" [unsafe-show-values] offending input …: bad message\"\n * ```\n */\nexport function unsafeInputSuffix(bytes: Uint8Array, posture: PhiPosture): string {\n if (!posture.showValues) return \"\";\n const text = new TextDecoder(\"utf-8\", { fatal: false })\n .decode(bytes.subarray(0, UNSAFE_EXCERPT_MAX))\n .replace(/[\\r\\n\\t]+/g, \" \")\n .trim();\n if (text.length === 0) return \"\";\n return ` [unsafe-show-values] offending input (first ${String(UNSAFE_EXCERPT_MAX)} bytes): ${text}`;\n}\n","/**\n * The **wrapped-parser failure boundary**: the single, value-free way every command turns a thrown\n * parser/codec exception into a {@link RunResult}. A wrapped library raises a fatal on genuinely\n * unparseable input; its message (and, for HL7, its `snippet`) can embed the offending bytes, so the\n * CLI **never** surfaces that message. It surfaces only a stable, PHI-free code token (via\n * {@link extractStableCode}) plus the format name: the parsers' \"warning = code + position, never a\n * value\" rule at the CLI edge.\n *\n * The one, opt-in exception is `--unsafe-show-values`, whose bounded excerpt is appended through the\n * lone chokepoint in `core/phi.ts` ({@link unsafeInputSuffix}), so the \"a value appears on a\n * secondary surface **iff** the flag is set\" property stays provable in one place, uniformly across\n * `parse`/`validate`/`inspect`/`fmt`.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { CosyteFormat } from \"./format.js\";\nimport { unsafeInputSuffix, type PhiPosture } from \"./phi.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Pull a `code` off a thrown value **only** when it is a PHI-free constant token\n * (`^[A-Z][A-Z0-9_]*$`: a letter-led UPPER_SNAKE code like `MALFORMED_JSON`), e.g. a wrapped\n * parser's stable fatal code. Anything else (no `code`, a non-string, a non-token, or a **pure-digit**\n * value that could be a raw identifier) yields `null`, so a parser exception that embedded input bytes\n * in a `code`-shaped field can never reach a diagnostic.\n *\n * @param e - A caught value.\n * @returns The stable code token, or `null`.\n * @example\n * ```ts\n * import { extractStableCode } from \"@cosyte/cli\";\n *\n * extractStableCode({ code: \"MALFORMED_JSON\" }); // => \"MALFORMED_JSON\"\n * extractStableCode(new Error(\"boom\")); // => null\n * ```\n */\nexport function extractStableCode(e: unknown): string | null {\n if (typeof e === \"object\" && e !== null && \"code\" in e) {\n const raw: unknown = e.code;\n if (typeof raw === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(raw)) return raw;\n }\n return null;\n}\n\n/**\n * Build the value-free {@link RunResult} for a **wrapped-parser rejection**: a `CLI_PARSE_FAILED`\n * data error (exit `65`). The stderr line names the format and, when the thrown value carried one, a\n * stable code token in parentheses; it **never** echoes the parser's message or the input bytes. Under\n * `--unsafe-show-values` (and only then) a bounded excerpt of the offending input is appended via the\n * single {@link unsafeInputSuffix} chokepoint.\n *\n * @param format - The format whose parser rejected the input.\n * @param bytes - The offending input (only consulted for the opt-in unsafe excerpt).\n * @param posture - The resolved {@link PhiPosture}; the excerpt is appended only when it opts in.\n * @param e - The caught exception (its `code`, if a stable token, is surfaced: nothing else).\n * @returns A value-free `CLI_PARSE_FAILED` / exit-`65` {@link RunResult}.\n * @example\n * ```ts\n * import { parseFailureResult, VALUE_FREE } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"not hl7\");\n * parseFailureResult(\"hl7\", bytes, VALUE_FREE, { code: \"MISSING_MSH\" }).exit; // => 65\n * ```\n */\nexport function parseFailureResult(\n format: CosyteFormat,\n bytes: Uint8Array,\n posture: PhiPosture,\n e: unknown,\n): RunResult {\n const code = extractStableCode(e);\n const detail = code === null ? \"\" : ` (${code})`;\n const suffix = unsafeInputSuffix(bytes, posture);\n return {\n stdout: \"\",\n stderr: `cosyte: ${CLI_CODES.CLI_PARSE_FAILED}: the ${format} parser rejected the input${detail}${suffix}\\n`,\n exit: EXIT.DATAERR,\n };\n}\n","/**\n * `cosyte convert <file|-> --to fhir [--json] [--quiet] [--no-color]`\n *\n * Convert an **HL7 v2** message to **FHIR R4** via **`@cosyte/transform`**: the\n * consumer-of-consumers command. The CLI adds **no** mapping logic of its own: it parses the input\n * with `@cosyte/hl7`, hands the parsed message to `transform`'s `toFhir`, and serializes the resulting\n * FHIR `Bundle` with `@cosyte/fhir`. The mapping guarantees are the library's, graded by *its* gate;\n * `cosyte convert` equals `transform`'s programmatic output.\n *\n * The converted FHIR `Bundle` is the user's explicit request, so it goes to **stdout** (the data\n * channel). Every conversion problem is one of `transform`'s value-free {@link TransformIssue}s: a\n * stable code, a severity, and a positional locator (a v2 index and an optional FHIRPath), **never** a\n * field value: surfaced on stderr (or as value-free JSON under `--json`). The load-bearing rule\n * (mirroring `validate`): a conversion that produces an **error-severity** issue exits **`1`**, never\n * `0`: the tool worked, but the conversion has a real problem a CI gate must see.\n *\n * `--to fhir` is required and is the only supported target (HL7 v2 → FHIR R4). The source must be\n * HL7 v2: a recognised-but-non-HL7 input (e.g. a FHIR document) is a value-free\n * `CLI_FORMAT_UNSUPPORTED` data error (`65`), never a fake conversion.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { Finding } from \"../core/findings.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { loadFhir, loadOptionalPackage } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `convert` understands. */\nconst CONVERT_OPTIONS = {\n to: { type: \"string\" },\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** The only conversion target this build supports (HL7 v2 → FHIR R4). */\nconst SUPPORTED_TARGET = \"fhir\";\n\n/** Transform severities that make a conversion a **failure** (exit `1`). `transform` has no `fatal`. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** The value-free result of a conversion: the serialized FHIR bundle text + the library's findings. */\ninterface Conversion {\n readonly bundleText: string;\n readonly findings: readonly Finding[];\n}\n\n/**\n * Run the `convert` command.\n *\n * @param args - The arguments after the `convert` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on an HL7\n * parse-failure diagnostic; the converted bundle and the value-free findings are unaffected).\n * @returns A {@link RunResult}: the converted FHIR `Bundle` on `stdout` (the data channel), value-free\n * findings on `stderr` (or JSON under `--json`), and an exit code that carries the outcome: `0`\n * clean · `1` an error-severity conversion issue · `65` the HL7 input could not be parsed or is not\n * an HL7 v2 source · `66` no input · `2` usage.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { convertCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode(\"MSH|^~\\\\&|A|B|C|D|20240101||ADT^A01|1|P|2.5\\r\"),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await convertCommand([\"adt.hl7\", \"--to\", \"fhir\"], deps)).exit; // => 0\n * ```\n */\nexport async function convertCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n to?: string;\n format?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: CONVERT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `convert` (see `cosyte convert --help`)\",\n ),\n );\n }\n\n // `--to` is required and names the conversion target. Only `fhir` is supported today; requiring it\n // (rather than defaulting) keeps the surface explicit and future-proof for other targets.\n if (values.to === undefined) {\n return errorResult(\n new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"convert requires --to fhir (the only target)\"),\n );\n }\n if (values.to !== SUPPORTED_TARGET) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unsupported --to '${values.to}'; only --to fhir is supported (HL7 v2 → FHIR R4)`,\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // convert reads HL7 v2 and writes FHIR R4. A recognised-but-non-HL7 source (e.g. a FHIR document) is\n // not a convertible input: a value-free data error, never a fake or identity \"conversion\".\n if (format !== \"hl7\") {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `convert reads HL7 v2 and writes FHIR R4; the input is '${format}', not an HL7 v2 source`,\n ),\n );\n }\n\n const outcome = await runConvert(bytes, posture);\n if (!outcome.ok) return outcome.result;\n const conversion = outcome.conversion;\n\n const { hasError, report } = convertOutcome(conversion.findings);\n const exit = hasError ? EXIT.INVALID : EXIT.OK;\n\n if (values.json === true) {\n // Machine output on the data channel: the converted bundle plus the value-free findings.\n const body = {\n format: SUPPORTED_TARGET,\n bundle: JSON.parse(conversion.bundleText) as unknown,\n findings: conversion.findings,\n };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n // Default: the converted FHIR Bundle (the library's canonical serialization) IS the stdout data\n // channel; the value-free findings + a summary go to stderr unless suppressed by --quiet.\n const stderr = values.quiet === true ? \"\" : report;\n return { stdout: `${conversion.bundleText}\\n`, stderr, exit };\n}\n\n/** Either a completed conversion, or a ready value-free parse-failure {@link RunResult}. */\ntype ConvertOutcome =\n | { readonly ok: true; readonly conversion: Conversion }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Why `@cosyte/transform` is absent, in words a user can act on. **It deliberately does not say\n * \"install it\"**: `npm install @cosyte/transform` fails too (`E404` on its own `@cosyte/fhir` peer),\n * so telling someone to install it would send them at a command that cannot succeed. That is the same\n * defect the `@cosyte/fhir` diagnostic exists to avoid, and it is why neither goes through\n * `loadOptional()`, whose stock wording is exactly \"install it (it is an optional dependency)\".\n * Value-free by construction: package names and a statement of fact, no input echoed.\n */\nconst TRANSFORM_UNAVAILABLE =\n \"the @cosyte/transform conversion library is not installed, so convert is unavailable; it \" +\n \"requires @cosyte/fhir, which is not currently on the npm registry, so npm skips transform as \" +\n \"an unresolvable optional dependency and installing it directly fails for the same reason\";\n\n/**\n * Parse the HL7 v2 bytes and convert to FHIR: every library **lazy-loaded** so this code loads only\n * when `convert` runs. Only the `parseHL7` call is inside the failure boundary: a genuine parser\n * rejection becomes a value-free `CLI_PARSE_FAILED` (65), with the single opt-in excerpt (under\n * `--unsafe-show-values`) flowing through the shared core/wrap chokepoint. The `toFhir` + serialize\n * step is deliberately outside it: `toFhir` never throws for a well-formed message, so any throw there\n * is an unexpected bug the dispatcher maps to `CLI_INTERNAL` (70), never mislabelled as a rejection.\n *\n * Two of the three libraries are **not guaranteed present in an installed copy**, so both loads go\n * through the optional-package boundary and an absent one becomes a value-free\n * `CLI_PARSER_UNAVAILABLE` (69) rather than an unhandled resolver error. `@cosyte/hl7` is a hard\n * dependency and needs no such treatment.\n */\nasync function runConvert(bytes: Uint8Array, posture: PhiPosture): Promise<ConvertOutcome> {\n const [{ parseHL7 }, { toFhir }, { serializeResource }] = await Promise.all([\n import(\"@cosyte/hl7\"),\n loadOptionalPackage(TRANSFORM_UNAVAILABLE, () => import(\"@cosyte/transform\")),\n loadFhir(),\n ]);\n\n let msg: ReturnType<typeof parseHL7>;\n try {\n msg = parseHL7(Buffer.from(bytes));\n } catch (e) {\n return { ok: false, result: parseFailureResult(\"hl7\", bytes, posture, e) };\n }\n\n const { bundle, issues } = toFhir(msg);\n return {\n ok: true,\n conversion: {\n bundleText: serializeResource(bundle),\n findings: issues.map((i) => toFinding(i.code, i.severity, i.v2Location, i.fhirPath)),\n },\n };\n}\n\n/** Build one value-free {@link Finding} from a transform issue: v2 locator, and the FHIRPath if any. */\nfunction toFinding(code: string, severity: string, v2Location: string, fhirPath?: string): Finding {\n const location = fhirPath !== undefined ? `${v2Location} → ${fhirPath}` : v2Location;\n return { code, severity, location };\n}\n\n/**\n * Decide the conversion outcome from the library's value-free findings: whether any is\n * **error-severity** (which drives a non-zero exit: the load-bearing \"a conversion error is never\n * exit 0\" rule) and the value-free human report. The severity classification is\n * the library's: `@cosyte/transform` fixes each issue's severity; the CLI only reads it. Exported so\n * the exit-verdict and report logic is unit-testable with synthetic findings, independent of which HL7\n * message happens to produce an error.\n *\n * @param findings - The value-free {@link Finding}s the conversion produced.\n * @returns `hasError` (true iff any finding is error/fatal severity) and the rendered value-free\n * `report` (one line per finding + a summary line).\n * @example\n * ```ts\n * import { convertOutcome } from \"@cosyte/cli\";\n *\n * convertOutcome([{ code: \"TRANSFORM_RESOURCE_INVALID\", severity: \"error\", location: \"PID\" }])\n * .hasError; // => true\n * convertOutcome([{ code: \"TRANSFORM_ELEMENT_DROPPED\", severity: \"information\", location: \"PID.13\" }])\n * .hasError; // => false\n * ```\n */\nexport function convertOutcome(findings: readonly Finding[]): {\n readonly hasError: boolean;\n readonly report: string;\n} {\n const lines = findings.map((f) => `cosyte: convert: ${f.severity} ${f.code} at ${f.location}\\n`);\n const errors = findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = findings.length - errors;\n const summary =\n errors > 0\n ? `cosyte: convert: hl7 → fhir produced ${String(errors)} error(s), ${String(others)} other finding(s)\\n`\n : `cosyte: convert: hl7 → fhir OK (${String(findings.length)} finding(s))\\n`;\n return { hasError: errors > 0, report: lines.join(\"\") + summary };\n}\n","/**\n * `cosyte inspect <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * A human-readable, **value-free-by-default** structural summary of a message: its type, structural\n * counts, and a warning count: the \"what shape is this?\" answer, without ever printing a field\n * value. Unlike `parse`, whose stdout is the parsed model (the data channel), `inspect`'s\n * stdout is a *structural* summary composed only of counts and structural type **codes** (an HL7 message\n * type like `ADT^A01`, a FHIR `resourceType` like `Patient`, an X12 transaction-set id like `834`, a\n * DICOM SOP Class UID, an NCPDP `NewRx`): classification, never PHI. `--json` emits the same value-free\n * summary as machine JSON. The per-format summaries are built by the shared registry (`core/parsers.ts`).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { inspectFormat, type InspectSummary } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `inspect` understands. */\nconst INSPECT_OPTIONS = {\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `inspect` command.\n *\n * @param args - The arguments after the `inspect` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; the summary itself is always value-free).\n * @returns A {@link RunResult}: the value-free structural summary on `stdout` (human, or JSON under\n * `--json`), exit `0`; a parse failure is a data error (`65`), an unreadable file `66`, a bad flag `2`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { inspectCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await inspectCommand([\"patient.json\", \"--json\"], deps)).exit; // => 0\n * ```\n */\nexport async function inspectCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: { format?: string; json?: boolean; quiet?: boolean; \"no-color\"?: boolean };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: INSPECT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `inspect` (see `cosyte inspect --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"inspect\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let summary: InspectSummary;\n try {\n summary = await inspectFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const stdout = values.json === true ? `${JSON.stringify(summary)}\\n` : renderSummary(summary);\n return { stdout, stderr: \"\", exit: EXIT.OK };\n}\n\n/**\n * Render a value-free human structural summary. Only counts and structural type codes, never a value.\n * Exported for direct branch testing of the per-format render (not re-exported from the package root).\n *\n * @param summary - The value-free {@link InspectSummary} to render.\n * @returns The human-readable, value-free summary text.\n * @example\n * ```ts\n * import { renderSummary } from \"@cosyte/cli/dist/commands/inspect.js\";\n *\n * renderSummary({ format: \"mllp\", frameCount: 2, warningCount: 0 }).includes(\"frames\"); // => true\n * ```\n */\nexport function renderSummary(summary: InspectSummary): string {\n const lines: string[] = [];\n const countLines = (label: string, counts: Readonly<Record<string, number>>): void => {\n if (label.length > 0) lines.push(label);\n for (const key of Object.keys(counts).sort()) lines.push(` ${key}: ${String(counts[key])}`);\n };\n\n switch (summary.format) {\n case \"hl7\":\n lines.push(`format: hl7`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n countLines(\"\", summary.segments);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"fhir\":\n lines.push(`format: fhir`);\n lines.push(`resource type: ${summary.resourceType ?? \"(unknown)\"}`);\n if (summary.entryCount !== undefined) {\n lines.push(`bundle type: ${summary.bundleType ?? \"(unknown)\"}`);\n lines.push(`entries: ${String(summary.entryCount)}`);\n countLines(\"\", summary.entryResourceTypes ?? {});\n }\n lines.push(`issues: ${String(summary.issueCount)}`);\n break;\n case \"x12\":\n lines.push(`format: x12`);\n lines.push(`groups: ${String(summary.groupCount)}`);\n lines.push(`transactions: ${String(summary.transactionCount)}`);\n countLines(\"transaction sets:\", summary.transactionSetIds);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"astm\":\n lines.push(`format: astm`);\n lines.push(`message kind: ${summary.messageKind}`);\n lines.push(`records: ${String(summary.recordCount)}`);\n countLines(\"\", summary.recordTypes);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ccda\":\n lines.push(`format: ccda`);\n lines.push(`document type: ${summary.documentType ?? \"(unknown)\"}`);\n lines.push(`sections: ${String(summary.sectionCount)}`);\n if (summary.sectionCodes.length > 0) {\n lines.push(`section codes: ${summary.sectionCodes.join(\", \")}`);\n }\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"dicom\":\n lines.push(`format: dicom`);\n lines.push(`sop class uid: ${summary.sopClassUid ?? \"(unknown)\"}`);\n lines.push(`transfer syntax:${summary.transferSyntaxUid ?? \" (unknown)\"}`);\n lines.push(`elements: ${String(summary.elementCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ncpdp\":\n lines.push(`format: ncpdp`);\n lines.push(`standard: SCRIPT`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"mllp\":\n lines.push(`format: mllp`);\n lines.push(`frames: ${String(summary.frameCount)}`);\n lines.push(`warnings:${String(summary.warningCount)}`);\n break;\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n","/**\n * `cosyte parse <file|-> [--format …] [--ndjson] [--json] [--quiet] [--no-color]`\n *\n * Read a file (or stdin via `-`), **autodetect the format by content** (or honour `--format`), route to\n * the wrapped parser via the lazy per-format registry (`core/parsers.ts`) (so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code) and emit the parsed model as **typed JSON on stdout**. Every\n * failure is a value-free diagnostic on stderr with a stable `CLI_*` code and the documented exit code.\n *\n * **Multi-message / streaming.** A single message emits one pretty (or compact under `--json`)\n * JSON envelope, exactly as before. A **multi-record** input emits **NDJSON** (one compact envelope\n * per line) with per-record isolation: a record that fails to parse becomes a value-free\n * `{ record, error }` line and the stream continues, and the overall exit is a data error (`65`) if any\n * record failed. Two inputs are multi-record: an **MLLP** stream (each VT-framed frame is an enclosed\n * HL7 message) and any input under **`--ndjson`** (each non-empty line is a record: the FHIR bulk-data\n * convention).\n *\n * The CLI adds **no** parsing of its own: it routes, reads, and shapes output; `cosyte parse` equals the\n * wrapped library's programmatic parse.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { deframeMllp, parseFormat, type ParseWarning } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { extractStableCode, parseFailureResult } from \"../core/wrap.js\";\n\n// Re-exported from the shared wrapper boundary so the historical `@cosyte/cli` import path stays stable.\nexport { extractStableCode } from \"../core/wrap.js\";\n\n/** The typed JSON envelope a single `parse` emits on stdout: the format, the parsed model, warnings. */\ninterface ParseEnvelope {\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n}\n\n/** One line of NDJSON multi-record output: a parsed record, or a value-free per-record parse error. */\ntype RecordLine =\n | {\n readonly record: number;\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n }\n | { readonly record: number; readonly format: CosyteFormat; readonly error: string };\n\n/** The flags `parse` understands, parsed by {@link parseArgs}. */\nconst PARSE_OPTIONS = {\n format: { type: \"string\" },\n ndjson: { type: \"boolean\", default: false },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `parse` command.\n *\n * @param args - The arguments after the `parse` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture}. Defaults to {@link VALUE_FREE}; under\n * `--unsafe-show-values` a bounded excerpt of the offending input is appended to a `CLI_PARSE_FAILED`\n * diagnostic (the single, opt-in value-echoing surface): single-record mode only.\n * @returns A {@link RunResult}: the typed-JSON model (or NDJSON records) on `stdout`, a value-free note\n * (or nothing) on `stderr`, and the resolved exit code. Never throws a {@link CliError}: it resolves\n * it to a result; unexpected exceptions are caught by the dispatcher and mapped to `CLI_INTERNAL`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { parseCommand } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * const deps = {\n * readFile: async () => enc.encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await parseCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function parseCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n ndjson?: boolean;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: PARSE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `parse` (see `cosyte parse --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // MLLP is a transport container and `--ndjson` is explicit batch mode: both are multi-record.\n if (format === \"mllp\" || values.ndjson === true) {\n return await parseMulti(format, bytes, values.ndjson === true, values.quiet === true);\n }\n return await parseSingle(format, bytes, values.json === true, values.quiet === true, posture);\n}\n\n/** Parse a single message → one JSON envelope (pretty, or compact under `--json`). Preserves the\n * value-free failure boundary and the opt-in `--unsafe-show-values` excerpt. */\nasync function parseSingle(\n format: CosyteFormat,\n bytes: Uint8Array,\n json: boolean,\n quiet: boolean,\n posture: PhiPosture,\n): Promise<RunResult> {\n let result: { model: unknown; warnings: readonly ParseWarning[] };\n try {\n result = await parseFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, posture, e);\n }\n const envelope: ParseEnvelope = { format, model: result.model, warnings: result.warnings };\n const stdout = (json ? JSON.stringify(envelope) : JSON.stringify(envelope, null, 2)) + \"\\n\";\n\n const n = envelope.warnings.length;\n const stderr =\n n > 0 && !quiet\n ? `cosyte: parsed ${format} with ${String(n)} warning(s) (see .warnings in output)\\n`\n : \"\";\n return { stdout, stderr, exit: EXIT.OK };\n}\n\n/** Parse a multi-record input (MLLP frames, or `--ndjson` lines) → NDJSON, with per-record isolation. */\nasync function parseMulti(\n format: CosyteFormat,\n bytes: Uint8Array,\n ndjson: boolean,\n quiet: boolean,\n): Promise<RunResult> {\n // Resolve the records + the format each record is parsed as. MLLP de-frames to enclosed HL7 payloads.\n let records: Uint8Array[];\n let recordFormat: CosyteFormat;\n try {\n if (format === \"mllp\") {\n const { payloads } = await deframeMllp(bytes);\n records = payloads;\n recordFormat = \"hl7\";\n } else {\n records = splitLines(bytes);\n recordFormat = format;\n }\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, VALUE_FREE, e);\n }\n\n if (records.length === 0) {\n // A framed/ndjson input that yielded no record is a data error, never a silent success.\n return errorResult(\n new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n `no ${format === \"mllp\" ? \"MLLP frame\" : \"record\"} found in the input`,\n ),\n );\n }\n\n const lines: RecordLine[] = [];\n let failed = 0;\n let warnings = 0;\n for (let i = 0; i < records.length; i += 1) {\n const rec = records[i] as Uint8Array;\n try {\n const { model, warnings: ws } = await parseFormat(recordFormat, rec);\n warnings += ws.length;\n lines.push({ record: i, format: recordFormat, model, warnings: ws });\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // a parser-unavailable is fatal for the stream\n failed += 1;\n // Value-free per-record error: a stable code (if the throw carried one), never the bytes.\n lines.push({\n record: i,\n format: recordFormat,\n error: extractStableCode(e) ?? \"CLI_PARSE_FAILED\",\n });\n }\n }\n\n const stdout = lines.map((l) => JSON.stringify(l)).join(\"\\n\") + \"\\n\";\n const exit = failed > 0 ? EXIT.DATAERR : EXIT.OK;\n const stderr = quiet\n ? \"\"\n : `cosyte: parsed ${String(records.length)} ${recordFormat} record(s)` +\n ` (${String(warnings)} warning(s), ${String(failed)} failed)` +\n (ndjson ? \" [ndjson]\" : format === \"mllp\" ? \" [mllp]\" : \"\") +\n \"\\n\";\n return { stdout, stderr, exit };\n}\n\n/** Split input bytes into non-empty, whitespace-trimmed newline-delimited records (NDJSON input). */\nfunction splitLines(bytes: Uint8Array): Uint8Array[] {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n const enc = new TextEncoder();\n return text\n .split(/\\r?\\n/)\n .filter((line) => line.trim().length > 0)\n .map((line) => enc.encode(line));\n}\n","/**\n * `cosyte validate <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * Parse the input, run the **wrapped parser's own validation/conformance surface**, and let the\n * **exit code carry the verdict** so `cosyte validate` is usable as a CI gate: **`0` valid, `1`\n * invalid** (parseable but non-conformant), `65` unparseable, `66` no input, `2` usage. The\n * load-bearing rule: the CLI never prints a reassuring line and exits `0` on an invalid message.\n *\n * Findings are **value-free**: a stable code, a severity, and a positional locator (a FHIRPath, or an\n * HL7 segment/field index), never a field value. By default they render on **stderr**; `--json`\n * emits the same value-free verdict + findings as machine JSON on stdout. The CLI invents **no**\n * verdict of its own: FHIR validity is `@cosyte/fhir`'s `validateResource().valid` (plus any\n * error-severity read issue); HL7 validity is \"parseable\": its parser is Postel's-Law lenient and its\n * warnings are, by the library's design, non-fatal deviations (surfaced, never failing).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { validateFormat, type Verdict } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `validate` understands. */\nconst VALIDATE_OPTIONS = {\n format: { type: \"string\" },\n profile: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** Severities that make a resource **invalid** (exit `1`). Warnings/information never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/**\n * Run the `validate` command.\n *\n * @param args - The arguments after the `validate` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; a validation verdict is always value-free).\n * @returns A {@link RunResult} whose **exit code carries the verdict** (`0` valid / `1` invalid /\n * `65` unparseable / `66` no input / `2` usage). Value-free findings on `stderr`, or value-free\n * JSON on stdout under `--json`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { validateCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await validateCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function validateCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n profile?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: VALIDATE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `validate` (see `cosyte validate --help`)\",\n ),\n );\n }\n\n // Profile-based validation is a pass-through to the wrapped library's profile surface, but the CLI\n // bundles no profiles and cannot yet load one, so honouring `--profile` today would either fake a\n // verdict or silently ignore the flag (falsely implying a profile was applied). Both are forbidden\n // (ADR 0018): report a value-free \"unavailable\" and exit 69, without reading the input.\n if (values.profile !== undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_NOT_IMPLEMENTED,\n EXIT.UNAVAILABLE,\n \"profile-based validation is not yet available: the CLI bundles no profiles and cannot yet \" +\n \"load one; validating against `--profile` is gated on that surface. Re-run without --profile \" +\n \"for base validation.\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"validate\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let verdict: Verdict;\n try {\n verdict = await validateFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n // Unparseable input is a data error (65), NOT an invalid verdict (1): the tool could not run the\n // check at all. Value-free; the opt-in excerpt flows through the single core/wrap chokepoint.\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const exit = verdict.valid ? EXIT.OK : EXIT.INVALID;\n\n if (values.json === true) {\n // Machine output on the data channel: value-free (codes/severities/locations only).\n const body = { format, valid: verdict.valid, findings: verdict.findings };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n if (values.quiet === true) {\n // CI mode: the exit code is the whole signal. No stderr noise.\n return { stdout: \"\", stderr: \"\", exit };\n }\n\n return { stdout: \"\", stderr: renderReport(format, verdict), exit };\n}\n\n/** Render the value-free human report: one line per finding + a verdict summary line. */\nfunction renderReport(format: CosyteFormat, verdict: Verdict): string {\n const lines = verdict.findings.map(\n (f) => `cosyte: validate: ${f.severity} ${f.code} at ${f.location}\\n`,\n );\n const errors = verdict.findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = verdict.findings.length - errors;\n const summary = verdict.valid\n ? `cosyte: validate: ${format} is valid (${String(verdict.findings.length)} finding(s))\\n`\n : `cosyte: validate: ${format} is INVALID (${String(errors)} error(s), ${String(others)} other finding(s))\\n`;\n return lines.join(\"\") + summary;\n}\n","/**\n * The **agent-facing tool surface** of the cosyte MCP server: the *second adapter* over the same\n * `core`/`commands` the `cosyte` terminal command drives. This module\n * is deliberately **SDK-free**: it declares the tools (name, description, JSON-Schema input) and maps a\n * tool call onto the existing command handlers, returning a plain, value-free MCP-shaped result. The\n * `@modelcontextprotocol/sdk` wiring lives one layer up in `./server.ts`, so the tool *logic* is unit-\n * testable without the SDK and the SDK stays isolated behind the `./mcp` subpath.\n *\n * **The shared-core guarantee.** A tool does not re-implement anything: `parse` calls\n * {@link parseCommand}, `validate` calls {@link validateCommand}, etc., each with `--json` so the\n * library's result lands as machine JSON, so `cosyte parse` and the MCP `parse` tool agree by\n * construction. The tool feeds the caller's `content` string in as if it were piped on stdin (`-`).\n *\n * **The PHI posture (load-bearing).** Every tool runs under the {@link VALUE_FREE} posture. There is\n * **no** `--unsafe-show-values` door on the agent surface. A tool's *result* carries the requested data\n * (the parsed model / converted bundle: the explicit request, the data channel), but a tool *error*\n * carries only the value-free diagnostic the command already produced (a stable code + positional\n * context), never an input value.\n *\n * @packageDocumentation\n */\n\nimport { convertCommand } from \"../commands/convert.js\";\nimport { inspectCommand } from \"../commands/inspect.js\";\nimport { parseCommand } from \"../commands/parse.js\";\nimport { validateCommand } from \"../commands/validate.js\";\nimport { CLI_CODES, CliError, toCliError } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { VALUE_FREE } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\n\n/** A single text content block in an MCP tool result. */\nexport interface McpTextContent {\n readonly type: \"text\";\n readonly text: string;\n}\n\n/** Value-free metadata every tool result carries so an agent can branch on the outcome. */\nexport interface McpToolMeta {\n /** The CLI exit code the underlying command resolved to (the documented exit-code contract). */\n readonly exit: number;\n /** `true` iff the tool *call* succeeded (data was produced): distinct from a negative verdict. */\n readonly ok: boolean;\n}\n\n/**\n * The value-free result of dispatching one MCP tool call. Structurally an MCP `CallToolResult`: a text\n * content channel, an `isError` flag, and value-free `structuredContent` metadata.\n */\nexport interface McpToolResult {\n readonly content: readonly McpTextContent[];\n readonly isError: boolean;\n readonly structuredContent: McpToolMeta;\n}\n\n/** A JSON-Schema description of a tool's input (the wire schema advertised to `tools/list`). */\nexport interface McpToolInputSchema {\n readonly type: \"object\";\n readonly properties: Readonly<Record<string, unknown>>;\n readonly required?: readonly string[];\n readonly additionalProperties?: boolean;\n}\n\n/** A tool advertised by the server: an agent-callable name, a description, and its input schema. */\nexport interface McpToolDef {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: McpToolInputSchema;\n}\n\n/** The `content` property shared by every tool: the raw message text to operate on. */\nconst CONTENT_PROP = {\n content: {\n type: \"string\",\n description:\n \"The raw healthcare message to operate on (as text; e.g. an HL7 v2 message or a FHIR JSON resource).\",\n },\n} as const;\n\n/** The optional `format` override shared by the read commands (autodetected by content when omitted). */\nconst FORMAT_PROP = {\n format: {\n type: \"string\",\n enum: [\"hl7\", \"fhir\", \"dicom\", \"x12\", \"ccda\", \"ncpdp\", \"astm\", \"mllp\"],\n description:\n \"Optional format override; omit to autodetect by content. A format whose parser does not \" +\n \"support the requested operation returns a value-free CLI_FORMAT_UNSUPPORTED (never a fake).\",\n },\n} as const;\n\n/**\n * The tools this server exposes: the read/convert operations that share the `core` cleanly and whose\n * results are safe to hand an agent. `redact`/`deid` (gated on `@cosyte/deid`)\n * and `map-codes` are deliberately **not** exposed yet; they land when the terminal command's ground\n * layer and the tool's PHI/So shape are settled.\n */\nexport const TOOL_DEFS: readonly McpToolDef[] = [\n {\n name: \"parse\",\n description:\n \"Parse a healthcare message (HL7 v2 or FHIR R4) to typed JSON. Format is autodetected by content. \" +\n \"Returns the parsed model plus value-free warnings.\",\n inputSchema: {\n type: \"object\",\n properties: { ...CONTENT_PROP, ...FORMAT_PROP },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"validate\",\n description:\n \"Validate a message and carry the verdict: ok=true with a valid result, or a result reporting \" +\n \"value-free findings. The parsed-but-invalid verdict is a successful call (not a tool error).\",\n inputSchema: {\n type: \"object\",\n properties: { ...CONTENT_PROP, ...FORMAT_PROP },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"inspect\",\n description:\n \"Return a value-free structural summary of a message: its type, segment/entry counts, and a \" +\n \"warning/issue count. Never includes a field value.\",\n inputSchema: {\n type: \"object\",\n properties: { ...CONTENT_PROP, ...FORMAT_PROP },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n {\n name: \"convert\",\n description:\n \"Convert an HL7 v2 message to a FHIR R4 Bundle via @cosyte/transform. Returns the converted \" +\n \"Bundle; an error-severity conversion issue is reported with ok=false.\",\n inputSchema: {\n type: \"object\",\n properties: {\n ...CONTENT_PROP,\n to: {\n type: \"string\",\n enum: [\"fhir\"],\n description: \"The conversion target (only FHIR R4 is supported today).\",\n },\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n },\n];\n\n/** Build injected {@link RunDeps} that feed the tool's inline `content` as if it were piped on stdin. */\nfunction inlineDeps(content: string): RunDeps {\n const bytes = new TextEncoder().encode(content);\n const noFile = new CliError(\n CLI_CODES.CLI_NO_INPUT,\n EXIT.NOINPUT,\n \"the MCP tools operate on inline content, not a file path\",\n );\n return {\n readStdin: () => Promise.resolve(bytes),\n // The MCP tools always feed inline content via stdin (`-`); a file read is defensive and unreachable.\n /* v8 ignore next -- unreachable: no MCP tool passes a file path, only inline `-` stdin content */\n readFile: () => Promise.reject(noFile),\n };\n}\n\n/** Read a required string argument from a tool-call arguments object, or `null` when absent/mistyped. */\nfunction stringArg(args: Readonly<Record<string, unknown>>, key: string): string | null {\n const v = args[key];\n return typeof v === \"string\" ? v : null;\n}\n\n/**\n * Map a command's {@link RunResult} onto a value-free {@link McpToolResult}. A command emits its data on\n * `stdout` (non-empty) and only ever leaves `stdout` empty on a **hard** failure (unparseable / no\n * input / usage / unavailable / internal), so `stdout === \"\"` is exactly the \"tool call failed\" signal.\n * A negative *verdict* (validate-invalid, a convert error-severity issue) still emits its JSON on\n * stdout, so it is a successful call whose value-free payload reports the verdict.\n */\nfunction toToolResult(result: RunResult): McpToolResult {\n const hardError = result.stdout === \"\";\n const text = hardError ? result.stderr.trim() : result.stdout.trim();\n return {\n content: [\n { type: \"text\", text: text.length > 0 ? text : `cosyte: exit ${String(result.exit)}` },\n ],\n isError: hardError,\n structuredContent: { exit: result.exit, ok: !hardError },\n };\n}\n\n/** Build a value-free usage-error tool result (a bad/missing argument, never echoes the argument). */\nfunction usageError(message: string): McpToolResult {\n return {\n content: [{ type: \"text\", text: `cosyte: ${CLI_CODES.CLI_USAGE}: ${message}` }],\n isError: true,\n structuredContent: { exit: EXIT.USAGE, ok: false },\n };\n}\n\n/**\n * Map an unexpected thrown value to a **value-free** internal-error tool result: the agent-surface\n * mirror of the terminal dispatcher's `try/catch → toCliError` boundary (`core/run.ts`). {@link toCliError}\n * discards the original message, so a library exception that embedded input bytes can never reach the\n * client (which would otherwise see the SDK surface the raw `error.message`). Both adapters inherit the\n * value-free posture *in code*, not by trusting the wrapped libraries never to throw.\n */\nfunction internalError(e: unknown): McpToolResult {\n const err = toCliError(e);\n return {\n content: [{ type: \"text\", text: `cosyte: ${err.code}: ${err.message}` }],\n isError: true,\n structuredContent: { exit: err.exit, ok: false },\n };\n}\n\n/**\n * Dispatch one MCP tool call to the shared command layer and return a value-free {@link McpToolResult}.\n * This is the agent-surface analogue of {@link run}: it validates the arguments, feeds the inline\n * `content` through the same command handlers the terminal uses (under the always-on {@link VALUE_FREE}\n * posture), and maps the {@link RunResult} onto an MCP result. An unknown tool name or a missing\n * `content` argument is a value-free usage error, never a thrown stack trace carrying input.\n *\n * @param name - The tool name (one of {@link TOOL_DEFS}).\n * @param args - The tool-call arguments object.\n * @param deps - Optional {@link RunDeps} override (tests inject fakes); defaults to feeding `content` as\n * stdin. An unexpected throw from a command is mapped to a value-free `CLI_INTERNAL` result, never\n * propagated to the SDK (which would surface the raw message).\n * @returns A value-free {@link McpToolResult}; this function never throws.\n * @example\n * ```ts\n * import { dispatchTool } from \"@cosyte/cli/mcp\";\n *\n * const r = await dispatchTool(\"parse\", { content: '{\"resourceType\":\"Patient\"}' });\n * r.isError; // => false\n * ```\n */\nexport async function dispatchTool(\n name: string,\n args: Readonly<Record<string, unknown>>,\n deps?: RunDeps,\n): Promise<McpToolResult> {\n const content = stringArg(args, \"content\");\n if (content === null) {\n return usageError(\"missing required 'content' argument (the message text to operate on)\");\n }\n const runDeps = deps ?? inlineDeps(content);\n const format = stringArg(args, \"format\");\n const fmtFlag = format !== null ? [\"--format\", format] : [];\n\n try {\n switch (name) {\n case \"parse\":\n return toToolResult(await parseCommand([\"-\", \"--json\", ...fmtFlag], runDeps, VALUE_FREE));\n case \"validate\":\n return toToolResult(\n await validateCommand([\"-\", \"--json\", ...fmtFlag], runDeps, VALUE_FREE),\n );\n case \"inspect\":\n return toToolResult(await inspectCommand([\"-\", \"--json\", ...fmtFlag], runDeps, VALUE_FREE));\n case \"convert\": {\n const to = stringArg(args, \"to\") ?? \"fhir\";\n return toToolResult(await convertCommand([\"-\", \"--to\", to, \"--json\"], runDeps, VALUE_FREE));\n }\n default:\n return usageError(`unknown tool '${name}'`);\n }\n } catch (e) {\n // The agent-surface mirror of core/run.ts's dispatcher boundary: any unexpected throw becomes a\n // value-free CLI_INTERNAL result, so a library exception carrying input can never reach the client.\n return internalError(e);\n }\n}\n","/**\n * The **stdio MCP server**: the JSON-RPC/stdio adapter over the same shared `core`/`commands` the\n * `cosyte` terminal command drives. This is the **only** module that touches\n * `@modelcontextprotocol/sdk`, so the SDK (the CLI's single third-party runtime dependency) stays\n * **isolated behind the `./mcp` subpath and lazy-loaded**: a `cosyte parse` invocation never imports\n * this file and therefore never loads the SDK (proven by `mcp-isolation.test.ts`).\n *\n * The server is a **local stdio subprocess**, implicitly trusted by the user/agent that launched it,\n * not a hosted network endpoint. It is **stateless per call**: each tool request is one operation\n * over the wrapped libraries, with the same value-free PHI posture the CLI proves once and both\n * adapters inherit.\n *\n * @packageDocumentation\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { CallToolRequestSchema, ListToolsRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { VERSION } from \"../core/version.js\";\nimport { dispatchTool, TOOL_DEFS } from \"./tools.js\";\n\n/** The MCP server identity advertised to a client on connect. */\nexport const SERVER_INFO = { name: \"cosyte\", version: VERSION } as const;\n\n/**\n * Build the cosyte MCP {@link Server} with its two request handlers wired to the shared tool surface:\n * `tools/list` advertises {@link TOOL_DEFS}, and `tools/call` routes to {@link dispatchTool} (the same\n * command handlers the terminal uses). The returned server is **not yet connected** to a transport:\n * the caller connects it to stdio (in production) or to an in-memory transport (in tests), so the\n * handler wiring is drivable without a subprocess.\n *\n * @returns A configured, unconnected {@link Server}.\n * @example\n * ```ts\n * import { createMcpServer } from \"@cosyte/cli/mcp\";\n *\n * const server = createMcpServer();\n * typeof server.connect; // => \"function\"\n * ```\n */\nexport function createMcpServer(): Server {\n const server = new Server(SERVER_INFO, { capabilities: { tools: {} } });\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: TOOL_DEFS.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: {\n type: t.inputSchema.type,\n properties: { ...t.inputSchema.properties },\n ...(t.inputSchema.required !== undefined ? { required: [...t.inputSchema.required] } : {}),\n ...(t.inputSchema.additionalProperties !== undefined\n ? { additionalProperties: t.inputSchema.additionalProperties }\n : {}),\n },\n })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const result = await dispatchTool(name, args ?? {});\n return {\n content: result.content.map((c) => ({ type: c.type, text: c.text })),\n isError: result.isError,\n structuredContent: { exit: result.structuredContent.exit, ok: result.structuredContent.ok },\n };\n });\n\n return server;\n}\n\n/* v8 ignore start -- stdio transport wiring: connects the real process streams, exercised by the packaged bin smoke, not unit-covered */\n/**\n * Start the cosyte MCP server on **stdio** and resolve once the transport is connected. The process\n * then stays alive serving requests until its stdin closes. This is the entry both the `cosyte-mcp`\n * bin and the `cosyte mcp` subcommand call.\n *\n * @returns A promise that resolves when the stdio transport is connected.\n * @example\n * ```ts\n * import { startStdioServer } from \"@cosyte/cli/mcp\";\n *\n * typeof startStdioServer; // => \"function\"\n * ```\n */\nexport async function startStdioServer(): Promise<void> {\n const server = createMcpServer();\n await server.connect(new StdioServerTransport());\n}\n/* v8 ignore stop */\n","#!/usr/bin/env node\n/**\n * The `cosyte-mcp` executable: the stdio MCP server's process entry. It does exactly one untestable\n * thing: start the server on the real `process.stdin`/`process.stdout` and let the process stay alive\n * serving requests. All logic (the tool surface, the shared command core, the value-free PHI posture)\n * lives in the covered `mcp`/`core`/`commands` modules; this file is intentionally trivial and\n * coverage-excluded. It is the twin of `cosyte.ts` for the agent front door.\n *\n * @packageDocumentation\n */\n\n/* v8 ignore start -- process wiring: starts the stdio server on the real process streams, exercised by the packaged bin smoke, not unit-covered */\nimport { startStdioServer } from \"../mcp/server.js\";\n\nstartStdioServer().catch(() => {\n // A truly unexpected startup failure prints a value-free line and exits EX_SOFTWARE.\n process.stderr.write(\"cosyte-mcp: CLI_INTERNAL: the MCP server failed to start\\n\");\n process.exitCode = 70;\n});\n/* v8 ignore stop */\n"]}