@cosyte/transform 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.
- package/CHANGELOG.md +67 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diagnostics/codes.ts","../src/diagnostics/issue.ts","../src/diagnostics/operation-outcome.ts","../src/terminology/naming-system.ts","../src/datatypes/datetime.ts","../src/datatypes/build.ts","../src/datatypes/identifier.ts","../src/datatypes/codeable-concept.ts","../src/datatypes/human-name.ts","../src/datatypes/address.ts","../src/datatypes/quantity.ts","../src/terminology/concept-map.ts","../src/messages/reference.ts","../src/messages/appointment.ts","../src/messages/diagnostic-report.ts","../src/messages/document-reference.ts","../src/messages/encounter.ts","../src/messages/emit-schemas.ts","../src/messages/immunization.ts","../src/messages/medication-request.ts","../src/messages/message-header.ts","../src/messages/observation.ts","../src/messages/orders.ts","../src/messages/oru.ts","../src/messages/patient.ts","../src/messages/related-person.ts","../src/messages/service-request.ts","../src/messages/to-fhir.ts","../src/index.ts"],"names":["primitive","list","complex","coding","text","decimal","translatedFrom","rawComponent","ORDER_INTENT"],"mappings":";;;;;AA8BO,IAAM,WAAA,GAAc;AAAA;AAAA;AAAA;AAAA,EAIzB,+BAAA,EAAiC,iCAAA;AAAA;AAAA,EAEjC,2BAAA,EAA6B,6BAAA;AAAA;AAAA;AAAA;AAAA,EAI7B,sCAAA,EAAwC,wCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxC,uBAAA,EAAyB,yBAAA;AAAA;AAAA;AAAA,EAGzB,gCAAA,EAAkC,kCAAA;AAAA;AAAA;AAAA;AAAA,EAIlC,uBAAA,EAAyB,yBAAA;AAAA;AAAA;AAAA;AAAA,EAIzB,gCAAA,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A;AACzB,QAAA,YAAA,CAAa,KAAK,EAAE,OAAA,EAAS,KAAK,QAAA,EAAU,KAAA,CAAM,OAAO,CAAA;AAAA,MAC3D;AAAA,IACF;AAAA,EACF;AAGA,EAAA,MAAM,KAAA,GAAQ;AAAA,IACZ,cAAA;AAAA,IACA,gBAAA;AAAA,IACA,GAAG,wBAAA;AAAA,IACH,GAAG,qBAAA;AAAA,IACH,GAAG,oBAAA;AAAA,IACH,GAAG,mBAAA;AAAA,IACH,GAAG;AAAA,GACL,CAAE,MAAA,CAAO,CAAC,CAAA,KAAmB,MAAM,MAAS,CAAA;AAC5C,EAAA,MAAM,MAAA,GAAS,kBAAA,CAAmB,GAAA,CAAI,IAAA,EAAM,KAAK,CAAA;AACjD,EAAA,MAAA,CAAO,IAAA,CAAK,GAAG,MAAA,CAAO,MAAM,CAAA;AAC5B,EAAA,MAAM,UAAmB,EAAC;AAC1B,EAAA,IAAI,MAAA,CAAO,UAAU,MAAA,IAAa,cAAA,CAAe,OAAO,KAAA,EAAO,KAAA,EAAO,eAAA,EAAiB,MAAM,CAAA,EAAG;AAC9F,IAAA,OAAA,CAAQ,IAAA,CAAK,EAAE,OAAA,EAAS,GAAA,CAAI,MAAK,EAAG,QAAA,EAAU,MAAA,CAAO,KAAA,EAAO,CAAA;AAAA,EAC9D;AACA,EAAA,OAAA,CAAQ,IAAA,CAAK,GAAG,YAAY,CAAA;AAE5B,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,GAAA,EAAK,OAAA,EAAS,KAAK,MAAM,CAAA;AACpD,EAAA,OAAO,EAAE,QAAQ,MAAA,EAAO;AAC1B;;;ACnbO,IAAM,OAAA,GAAkB","file":"index.mjs","sourcesContent":["/**\n * The stable code registries for the `@cosyte/transform` diagnostic channel.\n *\n * Two registries, both `key === value` so they survive `Object.values(...)` into a snapshot\n * tripwire, and both **part of the public contract**: consumers branch on these codes, so renaming\n * or removing one is a **breaking change** (mirrors the parser archetype's stable-warning-code rule).\n * New codes are **additions only**.\n *\n * - {@link ISSUE_CODES} — non-fatal, typed diagnostics carried on a {@link TransformResult}. Every\n * fail-safe decision the transform makes (a naked timestamp, an unresolvable assigning authority,\n * an unmapped code, a non-UCUM unit, a dropped element) surfaces as one of these — **never** a\n * silently-defaulted or fabricated FHIR value.\n * - {@link FATAL_CODES} — the small set of unrecoverable conditions reserved for message-level\n * entry points. **Nothing in this library throws one today**: the datatype converters and\n * `toFhir` alike fail safe to a value-free issue instead.\n *\n * @packageDocumentation\n */\n\n/**\n * Stable **non-fatal issue codes** — the typed diagnostics the fail-safe rule emits.\n *\n * @example\n * ```ts\n * import { ISSUE_CODES } from \"@cosyte/transform\";\n * if (issue.code === ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE) {\n * // a v2 timestamp had a time-of-day but no timezone offset — reduced to date precision\n * }\n * ```\n */\nexport const ISSUE_CODES = {\n /** A v2 DTM/TS carried a time-of-day but no timezone offset. FHIR forbids time-without-zone, so\n * the value was reduced to date precision (or an explicit sender offset applied via options) —\n * **never** a guessed UTC. */\n TRANSFORM_TIMESTAMP_NO_TIMEZONE: \"TRANSFORM_TIMESTAMP_NO_TIMEZONE\",\n /** A v2 DTM/TS could not be parsed into a valid FHIR date/time; no value was emitted. */\n TRANSFORM_TIMESTAMP_INVALID: \"TRANSFORM_TIMESTAMP_INVALID\",\n /** The assigning authority (HD) could not be resolved to a FHIR `Identifier.system` URI via the\n * NamingSystem registry. The identifier is emitted with its value and **no** system — a system URI\n * is **never** synthesized from HD.1 alone. */\n TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED: \"TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED\",\n /** A coded value could not be mapped to a FHIR concept — either it carried no coding-system context\n * (CWE.3 absent), or it is a table code the IG ConceptMap has **no target** for (e.g. an OBX-11/\n * OBR-25 result status the HL70085/HL70123 map does not carry, or an OBX-8 abnormal flag absent from\n * HL70078). The original code is preserved / the FHIR value left absent; **never** coerced to a\n * neighbor and **never** guessed to `final`/`normal`. */\n TRANSFORM_CODE_UNMAPPED: \"TRANSFORM_CODE_UNMAPPED\",\n /** A coding-system mnemonic (CWE.3 / CWE.6) was not recognized, so no canonical system URI could\n * be emitted. The code is preserved; a URI is **never** invented. */\n TRANSFORM_CODE_SYSTEM_UNRESOLVED: \"TRANSFORM_CODE_SYSTEM_UNRESOLVED\",\n /** A unit was not a valid UCUM code (or was not declared UCUM). It is preserved verbatim in\n * `Quantity.unit`; `Quantity.code`/`.system` are left absent — a UCUM code is **never** fabricated\n * and a magnitude is **never** converted. */\n TRANSFORM_UNIT_NOT_UCUM: \"TRANSFORM_UNIT_NOT_UCUM\",\n /** A v2 numeric value (NM) could not be represented as a FHIR `decimal` without altering it — e.g.\n * a leading `+`, a leading zero, or a trailing dot, which FHIR's `decimal` lexical form forbids. No\n * `Quantity` value is emitted rather than a canonicalized (and therefore altered) magnitude. */\n TRANSFORM_QUANTITY_VALUE_INVALID: \"TRANSFORM_QUANTITY_VALUE_INVALID\",\n /** A populated source element was not carried to its FHIR target and was dropped — either because\n * the IG map defines no target, or because that target's conversion is **not implemented**\n * (e.g. XTN→ContactPoint telecom, PV1 participants). Surfaced here rather than silently discarded,\n * never a fabricated value. */\n TRANSFORM_ELEMENT_DROPPED: \"TRANSFORM_ELEMENT_DROPPED\",\n /** An XPN.7 name-type code has no equivalent in the IG's HL70200 → name-use ConceptMap;\n * `HumanName.use` is left absent rather than guessed. */\n TRANSFORM_NAME_USE_UNMAPPED: \"TRANSFORM_NAME_USE_UNMAPPED\",\n /** An XAD.7 address-type code has no equivalent in the IG's HL70190 → address-use/type\n * ConceptMaps; `Address.use`/`.type` are left absent rather than guessed. */\n TRANSFORM_ADDRESS_USE_UNMAPPED: \"TRANSFORM_ADDRESS_USE_UNMAPPED\",\n /** The message's trigger event has no IG *message* map, so its resource graph was assembled from\n * the reusable IG *segment* maps rather than a message map. The graph is best-effort and flagged\n * as such — never a fabricated message map. */\n TRANSFORM_SEGMENT_ASSEMBLED: \"TRANSFORM_SEGMENT_ASSEMBLED\",\n /** A produced FHIR resource failed `@cosyte/fhir` R4 structural validation and was **withheld**\n * from the bundle rather than emitted as a silently-invalid resource — the conservative-emit gate. */\n TRANSFORM_RESOURCE_INVALID: \"TRANSFORM_RESOURCE_INVALID\",\n /** A FHIR-required element's value could not be faithfully derived from the source, so it was\n * emitted with a `data-absent-reason` extension (value `unknown`) rather than fabricated — e.g.\n * `MessageHeader.source.endpoint` from an MSH-3 application namespace that is not a URL. */\n TRANSFORM_REQUIRED_ELEMENT_UNKNOWN: \"TRANSFORM_REQUIRED_ELEMENT_UNKNOWN\",\n} as const;\n\n/** A value from {@link ISSUE_CODES} — the type consumers narrow `issue.code` against. */\nexport type IssueCode = (typeof ISSUE_CODES)[keyof typeof ISSUE_CODES];\n\n/**\n * Stable **fatal codes** — the reserved names for unrecoverable input conditions. **Nothing in this\n * library throws one today**; every path, datatype and message level alike, fails safe to a\n * value-free issue instead. They are declared so that a future one is an addition rather than a\n * rename.\n *\n * @example\n * ```ts\n * import { FATAL_CODES } from \"@cosyte/transform\";\n * void FATAL_CODES.EMPTY_INPUT;\n * ```\n */\nexport const FATAL_CODES = {\n /** The input carried nothing to transform. */\n EMPTY_INPUT: \"EMPTY_INPUT\",\n /** The input was not a shape this transform accepts. */\n TRANSFORM_UNSUPPORTED_INPUT: \"TRANSFORM_UNSUPPORTED_INPUT\",\n} as const;\n\n/** A value from {@link FATAL_CODES} — the type carried by a thrown fatal error. */\nexport type FatalCode = (typeof FATAL_CODES)[keyof typeof FATAL_CODES];\n","/**\n * The value-free {@link TransformIssue} — the single diagnostic shape the whole library emits.\n *\n * Every issue is **`OperationOutcome`-shaped and PHI-safe by construction**: it carries the *v2\n * location* (segment / field / component index — never a value) and the *FHIR path* it concerns,\n * plus a **static, per-code** severity and human-readable message drawn from {@link ISSUE_REGISTRY}.\n * Nothing in an issue is interpolated from patient data — the factory takes only positional metadata,\n * so there is no code path by which a name, DOB, MRN, or result value can reach a log line (the\n * discipline `@cosyte/fhir` already proved with its value-free `OperationOutcome`).\n *\n * @packageDocumentation\n */\n\nimport { ISSUE_CODES, type IssueCode } from \"./codes.js\";\n\n/** The severity a {@link TransformIssue} carries — an `OperationOutcome.issue.severity` value. */\nexport type TransformSeverity = \"error\" | \"warning\" | \"information\";\n\n/**\n * A single value-free diagnostic.\n *\n * @example\n * ```ts\n * import { ISSUE_CODES } from \"@cosyte/transform\";\n * // issue.code === ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE\n * // issue.v2Location === \"TS.1\"; issue.fhirPath === \"dateTime\"\n * ```\n */\nexport interface TransformIssue {\n /** The stable code. One of {@link ISSUE_CODES}. */\n readonly code: IssueCode;\n /** The `OperationOutcome`-style severity, fixed per code. */\n readonly severity: TransformSeverity;\n /** The v2 source location — a segment / field / component **index**, never a value. */\n readonly v2Location: string;\n /** The FHIR path this issue concerns (e.g. `Identifier.system`), when applicable. */\n readonly fhirPath?: string;\n /** A static, value-free description drawn from {@link ISSUE_REGISTRY}. */\n readonly message: string;\n}\n\n/** The fixed metadata for a code: its severity, its FHIR `issue-type` code, and a static message. */\ninterface IssueMeta {\n readonly severity: TransformSeverity;\n /** The FHIR `OperationOutcome.issue.code` (R4 `issue-type` value set) this maps to. */\n readonly fhirIssueType: string;\n /** A static, value-free message. Contains no interpolated data — safe to log verbatim. */\n readonly message: string;\n}\n\n/**\n * The per-code registry: severity, FHIR `issue-type`, and a static message. Frozen and exhaustive\n * over {@link ISSUE_CODES} (enforced by the `Record<IssueCode, …>` type — a new code will not\n * compile until it has an entry).\n */\nexport const ISSUE_REGISTRY: Readonly<Record<IssueCode, IssueMeta>> = Object.freeze({\n [ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"v2 timestamp carried a time-of-day but no timezone offset; reduced to date precision (FHIR forbids time without a zone).\",\n },\n [ISSUE_CODES.TRANSFORM_TIMESTAMP_INVALID]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message: \"v2 timestamp could not be parsed into a valid FHIR date/time; no value emitted.\",\n },\n [ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED]: {\n severity: \"warning\",\n fhirIssueType: \"not-found\",\n message:\n \"assigning authority could not be resolved to an Identifier.system; identifier emitted with value and no system (never synthesized from a bare namespace).\",\n },\n [ISSUE_CODES.TRANSFORM_CODE_UNMAPPED]: {\n severity: \"warning\",\n fhirIssueType: \"code-invalid\",\n message:\n \"coded value could not be mapped to a FHIR concept (no coding system, or no target in the IG ConceptMap); original code preserved / FHIR value left absent, never coerced or guessed.\",\n },\n [ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED]: {\n severity: \"warning\",\n fhirIssueType: \"code-invalid\",\n message: \"coding-system mnemonic not recognized; code preserved, no system URI invented.\",\n },\n [ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"unit is not a valid UCUM code; preserved verbatim in Quantity.unit, code/system absent, magnitude never converted.\",\n },\n [ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"numeric value is not a valid FHIR decimal literal (e.g. leading sign/zero or trailing dot); no Quantity value emitted rather than altering the magnitude.\",\n },\n [ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"populated source element was not carried to its FHIR target (no target in this map, or its conversion is not implemented); dropped.\",\n },\n [ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED]: {\n severity: \"information\",\n fhirIssueType: \"value\",\n message: \"name-type code has no equivalent in the HL70200 to name-use map; use left absent.\",\n },\n [ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED]: {\n severity: \"information\",\n fhirIssueType: \"value\",\n message:\n \"address-type code has no equivalent in the HL70190 to address-use/type maps; use/type left absent.\",\n },\n [ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"message trigger has no IG message map; resource graph assembled from IG segment maps, best-effort.\",\n },\n [ISSUE_CODES.TRANSFORM_RESOURCE_INVALID]: {\n severity: \"error\",\n fhirIssueType: \"structure\",\n message:\n \"produced resource failed FHIR R4 structural validation; withheld from the bundle rather than emitted invalid.\",\n },\n [ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"required FHIR element could not be derived from the source; emitted with a data-absent-reason extension, never fabricated.\",\n },\n});\n\n/**\n * Construct a value-free {@link TransformIssue}. The severity and message come from\n * {@link ISSUE_REGISTRY}; the caller supplies only positional metadata, so an issue can carry no PHI.\n *\n * @param code - The stable {@link IssueCode}.\n * @param v2Location - The v2 source location (segment / field / component index) — never a value.\n * @param fhirPath - The FHIR path the issue concerns, when applicable.\n * @example\n * ```ts\n * import { issue, ISSUE_CODES } from \"@cosyte/transform\";\n * const i = issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE, \"TS.1\", \"dateTime\");\n * void i.severity; // \"warning\"\n * ```\n */\nexport function issue(code: IssueCode, v2Location: string, fhirPath?: string): TransformIssue {\n const meta = ISSUE_REGISTRY[code];\n const base = {\n code,\n severity: meta.severity,\n v2Location,\n message: meta.message,\n };\n return fhirPath === undefined ? base : { ...base, fhirPath };\n}\n\n/**\n * The FHIR `issue-type` code for an {@link IssueCode} — used by the `OperationOutcome` renderer.\n *\n * @param code - The stable {@link IssueCode}.\n * @example\n * ```ts\n * import { fhirIssueTypeFor, ISSUE_CODES } from \"@cosyte/transform\";\n * fhirIssueTypeFor(ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED); // \"not-found\"\n * ```\n */\nexport function fhirIssueTypeFor(code: IssueCode): string {\n return ISSUE_REGISTRY[code].fhirIssueType;\n}\n","/**\n * Render a list of {@link TransformIssue}s as a FHIR `OperationOutcome` resource model.\n *\n * The transform's diagnostic channel is `OperationOutcome`-shaped by design; this is the adapter that\n * materializes it as an actual `@cosyte/fhir` resource node a consumer can serialize, validate, or\n * return alongside a bundle. It is **value-free**: every field is drawn from the issue's static\n * metadata (code, severity, message) and its positional locations (v2 location → `diagnostics`, FHIR\n * path → `expression`) — no patient data is reachable here.\n *\n * @packageDocumentation\n */\n\nimport { complex, list, primitive, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { fhirIssueTypeFor, type TransformIssue } from \"./issue.js\";\n\n/** The code system under which the transform's stable issue codes are carried in `details.coding`. */\nexport const TRANSFORM_ISSUE_SYSTEM = \"https://cosyte.com/fhir/CodeSystem/transform-issue-codes\";\n\nfunction prop(name: string, value: FhirNode): { name: string; value: FhirNode } {\n return { name, value };\n}\n\nfunction renderIssue(i: TransformIssue): FhirComplex {\n const details = complex([\n prop(\n \"coding\",\n list([\n complex([\n prop(\"system\", primitive(TRANSFORM_ISSUE_SYSTEM)),\n prop(\"code\", primitive(i.code)),\n ]),\n ]),\n ),\n prop(\"text\", primitive(i.message)),\n ]);\n\n const props = [\n prop(\"severity\", primitive(i.severity)),\n prop(\"code\", primitive(fhirIssueTypeFor(i.code))),\n prop(\"details\", details),\n // `diagnostics` carries the v2 source location — positional metadata, never a value.\n prop(\"diagnostics\", primitive(i.v2Location)),\n ];\n if (i.fhirPath !== undefined) {\n props.push(prop(\"expression\", list([primitive(i.fhirPath)])));\n }\n return complex(props);\n}\n\n/**\n * Build a FHIR `OperationOutcome` {@link FhirComplex} from the given issues. An empty list still\n * produces a structurally-valid `OperationOutcome` with a single `information` \"all clear\" issue\n * (FHIR requires `OperationOutcome.issue` to be non-empty).\n *\n * @param issues - The value-free diagnostics to render.\n * @example\n * ```ts\n * import { toOperationOutcome } from \"@cosyte/transform\";\n * const oo = toOperationOutcome([]);\n * // oo is a FhirComplex resource node with resourceType \"OperationOutcome\"\n * void oo;\n * ```\n */\nexport function toOperationOutcome(issues: readonly TransformIssue[]): FhirComplex {\n const rendered =\n issues.length > 0\n ? issues.map(renderIssue)\n : [\n complex([\n prop(\"severity\", primitive(\"information\")),\n prop(\"code\", primitive(\"informational\")),\n prop(\"details\", complex([prop(\"text\", primitive(\"No transform issues.\"))])),\n ]),\n ];\n return complex([\n prop(\"resourceType\", primitive(\"OperationOutcome\")),\n prop(\"issue\", list(rendered)),\n ]);\n}\n","/**\n * The NamingSystem registry — how an HL7 v2 identity/coding namespace becomes a FHIR canonical URI.\n *\n * Two resolutions live here, and both are **fail-safe by refusal**:\n *\n * 1. **Assigning authority (HD) → `Identifier.system`.** The IG's CX→Identifier map says CX.4 maps to\n * `Identifier.system` *only when the authority is in an identifier registry* — the URI comes from a\n * NamingSystem lookup, **not** string concatenation. There is no deterministic algorithm from an\n * HD to a URI, so this resolver **never synthesizes a system from HD.1 (the bare namespace\n * mnemonic) alone** — doing so would let two hospitals reusing \"MR\"/\"HOSPMRN\" collide and merge two\n * patients. The *only* auto-derivations are the unambiguous ones: `urn:oid:<oid>` when HD.2 is a\n * valid OID with HD.3 = `ISO`, and `urn:uuid:<uuid>` when HD.3 = `UUID`. Everything else must be an\n * explicit, caller-seeded registry entry, or it resolves to `undefined` and the caller emits a\n * typed issue.\n *\n * 2. **v2 coding-system mnemonic → canonical URI.** CWE.3/CWE.6 carry a v2 Table 0396 mnemonic\n * (`LN`, `SCT`, …); FHIR needs the canonical URI (`http://loinc.org`, …). {@link DEFAULT_V2_CODE_SYSTEMS}\n * seeds a small, license-clean set of the universally-fixed FHIR-core systems; an unrecognized\n * mnemonic resolves to `undefined` (the caller preserves the raw code and flags it — a URI is\n * never invented). The full HL7 THO crosswalk is not bundled.\n *\n * @packageDocumentation\n */\n\nimport type { HD } from \"@cosyte/hl7\";\n\n/**\n * The HL7 v2 Table 0203 identifier-type code system canonical URI — used to build `Identifier.type`.\n * (FHIR R4 terminologies-systems.html)\n */\nexport const V2_0203_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0203\";\n\n/**\n * A small, license-clean seed of v2 Table 0396 coding-system mnemonic → canonical URI, for the\n * FHIR-core-fixed systems whose URIs are universally cited (FHIR R4 terminologies-systems.html).\n * The full HL7 THO NamingSystem crosswalk is not bundled; callers extend this via\n * {@link createNamingSystem}. **No terminology *content* is bundled — only identity URIs.**\n */\nexport const DEFAULT_V2_CODE_SYSTEMS: Readonly<Record<string, string>> = Object.freeze({\n LN: \"http://loinc.org\",\n SCT: \"http://snomed.info/sct\",\n RXNORM: \"http://www.nlm.nih.gov/research/umls/rxnorm\",\n CVX: \"http://hl7.org/fhir/sid/cvx\",\n UCUM: \"http://unitsofmeasure.org\",\n});\n\n/** A seed for {@link createNamingSystem}: extra coding systems and explicit assigning authorities. */\nexport interface NamingSystemSeed {\n /** Extra v2 coding-system mnemonic → canonical URI entries (merged over the defaults). */\n readonly codeSystems?: Readonly<Record<string, string>>;\n /**\n * Explicit assigning-authority entries, keyed by **HD.1 namespace mnemonic** and/or **HD.2\n * universal ID (OID)** → the `Identifier.system` URI. This is the safe, caller-vetted path the IG\n * calls for; the registry never derives a system from a mnemonic on its own.\n */\n readonly authorities?: Readonly<Record<string, string>>;\n}\n\n/** The resolver consulted by the identity- and code-conversion paths. */\nexport interface NamingSystemRegistry {\n /**\n * Resolve an assigning authority (HD) to a FHIR `Identifier.system` URI, or `undefined` when it\n * cannot be resolved safely. **Never** synthesizes a URI from HD.1 alone.\n */\n readonly resolveAssigningAuthority: (hd: HD) => string | undefined;\n /** Resolve a v2 coding-system mnemonic to a canonical URI, or `undefined` when unrecognized. */\n readonly resolveCodeSystem: (mnemonic: string) => string | undefined;\n}\n\n/** A syntactically-valid ISO OID: dot-separated arcs, first arc 0–2, no leading zeros on multi-digit arcs. */\nfunction isOid(value: string): boolean {\n return /^[0-2](\\.(0|[1-9]\\d*))+$/.test(value);\n}\n\n/** A syntactically-valid UUID (any case). */\nfunction isUuid(value: string): boolean {\n return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(\n value,\n );\n}\n\n/**\n * Create a {@link NamingSystemRegistry}. With no seed it resolves the built-in FHIR-core code systems\n * and the two unambiguous HD auto-derivations (OID/UUID); a seed adds caller-vetted code systems and\n * explicit assigning-authority URIs.\n *\n * @example\n * ```ts\n * import { createNamingSystem } from \"@cosyte/transform\";\n * const registry = createNamingSystem({\n * authorities: { HOSPMRN: \"urn:oid:1.2.840.114350.1.13.1\" },\n * });\n * registry.resolveCodeSystem(\"LN\"); // => \"http://loinc.org\"\n * ```\n */\nexport function createNamingSystem(seed: NamingSystemSeed = {}): NamingSystemRegistry {\n const codeSystems: Record<string, string> = { ...DEFAULT_V2_CODE_SYSTEMS, ...seed.codeSystems };\n const authorities: Record<string, string> = { ...seed.authorities };\n\n return Object.freeze({\n resolveCodeSystem(mnemonic: string): string | undefined {\n if (mnemonic === \"\") return undefined;\n return Object.hasOwn(codeSystems, mnemonic) ? codeSystems[mnemonic] : undefined;\n },\n\n resolveAssigningAuthority(hd: HD): string | undefined {\n // 1. Explicit, caller-vetted registry entries win (by OID first, then by namespace mnemonic).\n if (hd.universalId !== undefined && Object.hasOwn(authorities, hd.universalId)) {\n return authorities[hd.universalId];\n }\n if (hd.namespaceId !== undefined && Object.hasOwn(authorities, hd.namespaceId)) {\n return authorities[hd.namespaceId];\n }\n // 2. The only safe auto-derivations — from the *universal* ID, never from HD.1.\n if (hd.universalId !== undefined && hd.universalId !== \"\") {\n if (hd.universalIdType === \"ISO\" && isOid(hd.universalId)) {\n return `urn:oid:${hd.universalId}`;\n }\n if (hd.universalIdType === \"UUID\" && isUuid(hd.universalId)) {\n return `urn:uuid:${hd.universalId.toLowerCase()}`;\n }\n }\n // 3. HD.1-only, or an unrecognized/unsafe universal ID → unresolved. Never synthesized.\n return undefined;\n },\n });\n}\n","/**\n * DTM / TS → FHIR `dateTime` — the single most dangerous conversion.\n *\n * Grounded on the IG datatype ConceptMap **DTM → dateTime** (`DTM.1` *is equivalent to* the FHIR\n * `dateTime.$value`, with the instruction to \"convert v2 date time format to FHIR date time format\")\n * and the **FHIR core datatype rule** it defers to: *\"if hours and minutes are specified, a timezone\n * offset SHALL be populated\"*, and the R4 `dateTime` grammar requires **full `hh:mm:ss` with an\n * offset** whenever a time is present. Two fail-safe consequences follow:\n *\n * - **Naked timestamp (no offset).** A `20260721143000` cannot become a valid zoned FHIR `dateTime`\n * without inventing an offset — assuming UTC would silently shift the clinical instant by hours. So\n * the value is **reduced to date precision** (`2026-07-21`) and {@link ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE}\n * is raised — unless the caller asserts the sender's offset via `options.assumeTimezoneOffsetMinutes`.\n * - **Partial-precision time (hour/minute only).** FHIR cannot represent `hh` or `hh:mm` without\n * seconds, and padding `:00` would fabricate precision, so such a value is likewise reduced to date\n * precision and flagged — never padded.\n *\n * Date-only precisions (`2026`, `2026-07`, `2026-07-21`) are preserved exactly — never zero-filled —\n * and need no offset (FHIR permits a bare date).\n *\n * @packageDocumentation\n */\n\nimport type { TS } from \"@cosyte/hl7\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformOptions } from \"../terminology/context.js\";\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, \"0\");\n}\n\n/** The signed FHIR offset suffix for a number of minutes east of UTC (e.g. `-300` → `-05:00`). */\nfunction formatOffset(offsetMinutes: number): string {\n const sign = offsetMinutes < 0 ? \"-\" : \"+\";\n const abs = Math.abs(offsetMinutes);\n return `${sign}${pad(Math.floor(abs / 60), 2)}:${pad(abs % 60, 2)}`;\n}\n\n/** The `YYYY[-MM[-DD]]` date portion of a parsed TS, at its stated precision. */\nfunction datePart(ts: TS): string {\n let out = pad(ts.year ?? 0, 4);\n if (ts.month !== undefined) out += `-${pad(ts.month, 2)}`;\n if (ts.day !== undefined) out += `-${pad(ts.day, 2)}`;\n return out;\n}\n\n/**\n * Convert a parsed HL7 v2 timestamp to a FHIR `dateTime` lexical string, fail-safe on timezone and\n * precision. Returns `{ value: undefined }` only when the timestamp is unparseable.\n *\n * @param ts - A parsed `@cosyte/hl7` `TS` (`DtmParts`).\n * @param options - Conversion policy; `assumeTimezoneOffsetMinutes` supplies a sender-asserted offset.\n * @example\n * ```ts\n * import { parseDtm } from \"@cosyte/hl7\";\n * import { toFhirDateTime } from \"@cosyte/transform\";\n * const { value } = toFhirDateTime(parseDtm(\"20260721\"));\n * // value === \"2026-07-21\"\n * void value;\n * ```\n */\nexport function toFhirDateTime(ts: TS, options: TransformOptions = {}): ConvertResult<string> {\n if (!ts.valid || ts.precision === undefined || ts.year === undefined) {\n return {\n value: undefined,\n issues: [issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_INVALID, \"TS.1\", \"dateTime\")],\n };\n }\n\n const date = datePart(ts);\n\n // No time-of-day → a bare date is a valid FHIR dateTime; preserve precision exactly.\n if (ts.hour === undefined) {\n return { value: date, issues: [] };\n }\n\n // Time-of-day present. FHIR requires full hh:mm:ss + an offset; anything less cannot be emitted.\n const hasFullTime = ts.precision === \"second\" || ts.precision === \"fraction\";\n const offset = ts.hasTimezone ? ts.offsetMinutes : options.assumeTimezoneOffsetMinutes;\n\n if (hasFullTime && offset !== undefined) {\n const frac =\n ts.precision === \"fraction\" && ts.fractionalSeconds !== undefined\n ? `.${ts.fractionalSeconds}`\n : \"\";\n const value = `${date}T${pad(ts.hour, 2)}:${pad(ts.minute ?? 0, 2)}:${pad(ts.second ?? 0, 2)}${frac}${formatOffset(offset)}`;\n // If the offset was asserted by the caller rather than present on the wire, say so (value-free).\n const issues = ts.hasTimezone\n ? []\n : [issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE, \"TS.1\", \"dateTime\")];\n return { value, issues };\n }\n\n // Cannot emit a valid zoned/full-precision time → reduce to date precision, never pad, never assume UTC.\n const code =\n !ts.hasTimezone && offset === undefined\n ? ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE\n : ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED;\n return { value: date, issues: [issue(code, \"TS.1\", \"dateTime\")] };\n}\n","/**\n * Small builders over the `@cosyte/fhir` generic element model, so each converter reads as the\n * datatype it produces rather than as node plumbing. All of them **omit absent/empty parts** — a\n * FHIR datatype node never carries an empty-string leaf or an empty list.\n *\n * @packageDocumentation\n */\n\nimport { complex, list, primitive, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\n/** A `(name, value)` pair for {@link object}; a `undefined` value is dropped. */\nexport type Field = readonly [name: string, value: FhirNode | undefined];\n\n/**\n * A FHIR string/code/uri primitive, or `undefined` for an absent/empty source value.\n *\n * @param value - The source string.\n * @example\n * ```ts\n * // text(\"MA\") -> a FHIR primitive; text(\"\") and text(undefined) -> undefined\n * ```\n */\nexport function text(value: string | undefined): FhirNode | undefined {\n return value === undefined || value === \"\" ? undefined : primitive(value);\n}\n\n/**\n * A FHIR list of the present items, or `undefined` when none are present.\n *\n * @param items - The candidate items; `undefined` entries are dropped.\n * @example\n * ```ts\n * // arr([text(\"Jane\"), text(undefined)]) -> a list of one item\n * ```\n */\nexport function arr(items: readonly (FhirNode | undefined)[]): FhirNode | undefined {\n const present = items.filter((i): i is FhirNode => i !== undefined);\n return present.length === 0 ? undefined : list(present);\n}\n\n/**\n * A FHIR complex node from the present fields, or `undefined` when every field is absent (so an\n * all-empty datatype collapses to \"nothing to emit\" rather than an empty object).\n *\n * @param fields - The candidate `(name, value)` pairs; pairs with a `undefined` value are dropped.\n * @example\n * ```ts\n * // object([[\"city\", text(\"Boston\")], [\"state\", text(undefined)]]) -> a complex with one property\n * ```\n */\nexport function object(fields: readonly Field[]): FhirComplex | undefined {\n const props = fields\n .filter((f): f is readonly [string, FhirNode] => f[1] !== undefined)\n .map(([name, value]) => ({ name, value }));\n return props.length === 0 ? undefined : complex(props);\n}\n","/**\n * CX → FHIR `Identifier` — the patient-identity-integrity path.\n *\n * Grounded on the IG datatype ConceptMap **CX → Identifier**: `CX.1` → `Identifier.value`, `CX.4`\n * (assigning authority HD) → `Identifier.system` *when the authority resolves in a registry* (else\n * the IG maps it to `Identifier.assigner` — a message-level Organization reference this library does\n * not build), and `CX.5` (Table 0203) → `Identifier.type`.\n *\n * The load-bearing fail-safe: the assigning authority is resolved through the\n * {@link NamingSystemRegistry}, which **never synthesizes a system URI from HD.1 (the bare namespace)\n * alone** — two hospitals reusing \"MR\"/\"HOSPMRN\" would otherwise collide and merge two patients. On\n * an unresolved authority the identifier is emitted with its **value and no system**, plus a typed\n * {@link ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED} issue — never a guessed system.\n *\n * @packageDocumentation\n */\n\nimport type { CX } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/** Build `Identifier.type` (a CodeableConcept over v2-0203) from CX.5, or `undefined` when absent. */\nfunction buildType(typeCode: string | undefined): FhirComplex | undefined {\n if (typeCode === undefined || typeCode === \"\") return undefined;\n const coding = object([\n [\"system\", text(V2_0203_SYSTEM)],\n [\"code\", text(typeCode)],\n ]);\n return object([[\"coding\", arr([coding])]]);\n}\n\n/**\n * Convert a parsed HL7 v2 CX to a FHIR `Identifier` node, fail-safe on the assigning authority.\n * Returns `{ value: undefined }` when the CX carries no identifier value at all.\n *\n * @param cx - A parsed `@cosyte/hl7` `CX`.\n * @param ctx - The transform context; `ctx.namingSystem` resolves the assigning authority (HD).\n * @example\n * ```ts\n * import { toFhirIdentifier, createNamingSystem } from \"@cosyte/transform\";\n * const { value, issues } = toFhirIdentifier(\n * { idNumber: \"12345\", assigningAuthority: { namespaceId: \"HOSPMRN\" } },\n * { namingSystem: createNamingSystem() },\n * );\n * // no registry entry for a bare \"HOSPMRN\" namespace → value emitted, system absent, one issue\n * void value;\n * void issues;\n * ```\n */\nexport function toFhirIdentifier(cx: CX, ctx: TransformContext = {}): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // Nothing to key an identifier on → emit nothing (an empty CX is not an error).\n if (cx.idNumber === undefined || cx.idNumber === \"\") {\n return { value: undefined, issues };\n }\n\n // CX.4 (HD) → Identifier.system, never synthesized from HD.1 alone.\n let system: string | undefined;\n const hd = cx.assigningAuthority;\n const hasAuthority =\n hd !== undefined &&\n (hd.namespaceId !== undefined ||\n hd.universalId !== undefined ||\n hd.universalIdType !== undefined);\n if (hd !== undefined && hasAuthority) {\n system = ctx.namingSystem?.resolveAssigningAuthority(hd);\n if (system === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED, \"CX.4\", \"Identifier.system\"),\n );\n }\n }\n\n // Identifier element order (FHIR): use, type, system, value, period, assigner.\n const identifier = object([\n [\"type\", buildType(cx.identifierTypeCode)],\n [\"system\", text(system)],\n [\"value\", text(cx.idNumber)],\n ]);\n\n // CX.7 / CX.8 (effective / expiration date) map to Identifier.period in the IG, but a faithful\n // period needs the dateTime timezone policy — deferred to a later phase and flagged, not silent.\n if (cx.effectiveDate !== undefined && cx.effectiveDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.7\", \"Identifier.period\"));\n }\n if (cx.expirationDate !== undefined && cx.expirationDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.8\", \"Identifier.period\"));\n }\n // CX.9 / CX.10 (jurisdiction / agency) have no place on Identifier — flag the loss (§2 non-goals).\n if (cx.assigningJurisdiction !== undefined && cx.assigningJurisdiction !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.9\"));\n }\n if (cx.assigningAgencyOrDepartment !== undefined && cx.assigningAgencyOrDepartment !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.10\"));\n }\n\n return { value: identifier, issues };\n}\n","/**\n * CWE / CE → FHIR `CodeableConcept` — the code-fidelity path.\n *\n * Grounded on the IG datatype ConceptMap **CWE → CodeableConcept**: `CWE.1`→`coding[0].code`,\n * `CWE.2`→`coding[0].display`, `CWE.3`→`coding[0].system` **(indirect — the vocabulary table gives\n * the actual URI)**, `CWE.7`→`coding[0].version`, the alternate triplet `CWE.4/5/6`→`coding[1]` (+\n * `CWE.8`→`coding[1].version`), and `CWE.9`→`text`. `CE` is the 6-component subset of `CWE` and maps\n * through the same shape.\n *\n * Two fail-safes, neither of which ever fabricates a code:\n * - **Unrecognized coding-system mnemonic** (CWE.3/CWE.6) → the code is preserved with **no system**,\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED}. A canonical URI is never invented.\n * - **A bare code with no coding system at all** (CWE.1 present, CWE.3 absent) → preserved verbatim,\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}. Never coerced to a plausible neighbor.\n *\n * This converter does **no ConceptMap value translation** (that is\n * `toFhirCodeableConceptVia`); it recognizes systems and preserves codes.\n *\n * @packageDocumentation\n */\n\nimport type { CWE } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/** The subset of CWE fields a CE also provides — so `toFhirCodeableConcept` accepts both. */\nexport type CodedElement = Pick<\n CWE,\n | \"identifier\"\n | \"text\"\n | \"nameOfCodingSystem\"\n | \"alternateIdentifier\"\n | \"alternateText\"\n | \"nameOfAlternateCodingSystem\"\n | \"codingSystemVersionId\"\n | \"alternateCodingSystemVersionId\"\n | \"originalText\"\n>;\n\n/** The four inputs to {@link buildCoding} — one CWE/CE coding triplet (code, display, system, version). */\nexport interface CodingParts {\n readonly code: string | undefined;\n readonly display: string | undefined;\n readonly mnemonic: string | undefined;\n readonly version: string | undefined;\n}\n\n/**\n * Build one `Coding` and accumulate any system/unmapped issue against it. Returns `undefined` when\n * the triplet carries no code and no display (nothing to emit). Exported so the value-translation\n * engine ({@link ../terminology/concept-map.js}) can reuse the exact same alternate-triplet\n * (`CWE.4/5/6`) resolution + fail-safe flagging when it builds an additively-translated concept.\n *\n * @param parts - The one coding triplet's code/display/system-mnemonic/version.\n * @param ctx - The transform context (its `namingSystem` resolves the mnemonic to a canonical URI).\n * @param codeLocation - The v2 location of the code component (e.g. `\"CWE.4\"`), for a value-free issue.\n * @param systemLocation - The v2 location of the coding-system component (e.g. `\"CWE.6\"`).\n * @param issues - The issue sink this call appends any system/unmapped diagnostic to.\n * @example\n * ```ts\n * // Internal helper (re-used by the terminology engine):\n * // const issues = [];\n * // const coding = buildCoding(\n * // { code: \"789-8\", display: \"Hgb\", mnemonic: \"LN\", version: undefined },\n * // { namingSystem: createNamingSystem() }, \"CWE.1\", \"CWE.3\", issues,\n * // );\n * ```\n */\nexport function buildCoding(\n parts: CodingParts,\n ctx: TransformContext,\n codeLocation: string,\n systemLocation: string,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (\n (parts.code === undefined || parts.code === \"\") &&\n (parts.display === undefined || parts.display === \"\")\n ) {\n return undefined;\n }\n\n let system: string | undefined;\n if (parts.mnemonic !== undefined && parts.mnemonic !== \"\") {\n system = ctx.namingSystem?.resolveCodeSystem(parts.mnemonic);\n if (system === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED, systemLocation, \"Coding.system\"),\n );\n }\n } else if (parts.code !== undefined && parts.code !== \"\") {\n // A code with no coding-system context at all — preserved, but unmapped to any FHIR system.\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, codeLocation, \"Coding.code\"));\n }\n\n return object([\n [\"system\", text(system)],\n [\"version\", text(parts.version)],\n [\"code\", text(parts.code)],\n [\"display\", text(parts.display)],\n ]);\n}\n\n/**\n * Convert a parsed HL7 v2 CWE (or CE) to a FHIR `CodeableConcept` node, fail-safe on the coding\n * system and on unmapped codes. Returns `{ value: undefined }` when the element is empty.\n *\n * @param cwe - A parsed `@cosyte/hl7` `CWE` (a `CE` is accepted as its subset).\n * @param ctx - The transform context; `ctx.namingSystem` resolves the coding-system mnemonic.\n * @example\n * ```ts\n * import { toFhirCodeableConcept, createNamingSystem } from \"@cosyte/transform\";\n * const { value } = toFhirCodeableConcept(\n * { identifier: \"789-8\", text: \"Hemoglobin\", nameOfCodingSystem: \"LN\" },\n * { namingSystem: createNamingSystem() },\n * );\n * // coding[0] === { system: \"http://loinc.org\", code: \"789-8\", display: \"Hemoglobin\" }\n * void value;\n * ```\n */\nexport function toFhirCodeableConcept(\n cwe: CodedElement,\n ctx: TransformContext = {},\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n const primary = buildCoding(\n {\n code: cwe.identifier,\n display: cwe.text,\n mnemonic: cwe.nameOfCodingSystem,\n version: cwe.codingSystemVersionId,\n },\n ctx,\n \"CWE.1\",\n \"CWE.3\",\n issues,\n );\n const alternate = buildCoding(\n {\n code: cwe.alternateIdentifier,\n display: cwe.alternateText,\n mnemonic: cwe.nameOfAlternateCodingSystem,\n version: cwe.alternateCodingSystemVersionId,\n },\n ctx,\n \"CWE.4\",\n \"CWE.6\",\n issues,\n );\n\n const value = object([\n [\"coding\", arr([primary, alternate])],\n [\"text\", text(cwe.originalText)],\n ]);\n\n return { value, issues };\n}\n","/**\n * XPN → FHIR `HumanName`.\n *\n * Grounded on the IG datatype ConceptMap **XPN → HumanName**: `XPN.1`→`family`, `XPN.2`→`given[0]`,\n * `XPN.3`→`given[1]`, `XPN.4`→`suffix`, `XPN.5`→`prefix`, `XPN.6` (degree)→`suffix`,\n * `XPN.7`→`use` (via the IG **HL70200 → name-use** ConceptMap), `XPN.14` (professional suffix)→`suffix`.\n *\n * `XPN.7`→`use` is a **lossy code translation**: only the codes the IG's HL70200→name-use map covers\n * are translated; any other name-type code leaves `use` **absent** and raises\n * {@link ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED} — never guessed. Not converted, and flagged:\n * the name-validity period (`XPN.12`/`XPN.13`), whose FHIR `period` needs the timezone policy of the\n * dateTime path.\n *\n * @packageDocumentation\n */\n\nimport type { XPN } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/**\n * HL7 v2 Table 0200 name-type code → FHIR `name-use`, exactly per the IG **HL70200 → name-use**\n * ConceptMap (every row is \"is equivalent to\"). Codes absent here (A, B, C, F, I, K, NB, NOUSE, P,\n * REL, S, T, U, …) have **no FHIR equivalent** and are surfaced, never guessed.\n */\nexport const NAME_USE_MAP: Readonly<Record<string, string>> = Object.freeze({\n BAD: \"old\",\n D: \"usual\",\n L: \"official\",\n M: \"maiden\",\n MSK: \"anonymous\",\n N: \"nickname\",\n NAV: \"temp\",\n R: \"official\",\n TEMP: \"temp\",\n});\n\n/**\n * Convert a parsed HL7 v2 XPN to a FHIR `HumanName` node. Returns `{ value: undefined }` when the\n * name carries no emittable part.\n *\n * @param xpn - A parsed `@cosyte/hl7` `XPN`.\n * @example\n * ```ts\n * import { toFhirHumanName } from \"@cosyte/transform\";\n * const { value } = toFhirHumanName({ familyName: \"Public\", givenName: \"Jane\", nameTypeCode: \"L\" });\n * // value === HumanName { use: \"official\", family: \"Public\", given: [\"Jane\"] }\n * void value;\n * ```\n */\nexport function toFhirHumanName(xpn: XPN): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // XPN.7 → use, via the HL70200 → name-use map; unmapped → absent + flagged.\n let use: string | undefined;\n if (xpn.nameTypeCode !== undefined && xpn.nameTypeCode !== \"\") {\n use = Object.hasOwn(NAME_USE_MAP, xpn.nameTypeCode)\n ? NAME_USE_MAP[xpn.nameTypeCode]\n : undefined;\n if (use === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED, \"XPN.7\", \"HumanName.use\"));\n }\n }\n\n // XPN.12 / XPN.13 name-validity period is deferred (needs the dateTime timezone policy) — flagged.\n if (xpn.effectiveDate !== undefined && xpn.effectiveDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"XPN.12\", \"HumanName.period\"));\n }\n if (xpn.expirationDate !== undefined && xpn.expirationDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"XPN.13\", \"HumanName.period\"));\n }\n\n const value = object([\n [\"use\", text(use)],\n [\"family\", text(xpn.familyName)],\n [\"given\", arr([text(xpn.givenName), text(xpn.secondName)])],\n [\"prefix\", arr([text(xpn.prefix)])],\n // XPN.4 (suffix), XPN.6 (degree), XPN.14 (professional suffix) all land in HumanName.suffix.\n [\"suffix\", arr([text(xpn.suffix), text(xpn.degree), text(xpn.professionalSuffix)])],\n ]);\n\n return { value, issues };\n}\n","/**\n * XAD → FHIR `Address`.\n *\n * Grounded on the IG datatype ConceptMap **XAD → Address**: `XAD.1`/`XAD.2`→`line`, `XAD.3`→`city`,\n * `XAD.4`→`state`, `XAD.5`→`postalCode`, `XAD.6`→`country`, `XAD.9` (county/parish)→`district`, and\n * the **value-conditional `XAD.7`** split across two independent FHIR axes:\n * - `XAD.7 IN {BA, BI, C, B, H, O}` → `Address.use` (via the IG **HL70190 → address-use** map);\n * - `XAD.7 IN {M, SH}` → `Address.type` (via the IG **HL70190 → address-type** map);\n * - a vacation address (`V` in Table 0190; the datatype map references `HV`) → an ISO-21090 extension\n * the IG defines — **not emitted**, and flagged rather than invented;\n * - any other code → `use`/`type` left absent, flagged {@link ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED}.\n *\n * FHIR deliberately separates `use` (home/work/temp) from `type` (postal/physical), so one v2 code\n * cannot always populate both axes — round-trip is not stable, and the drop is surfaced, never hidden.\n * `XAD.8` (other geographic designation) has no FHIR target and is flagged dropped.\n *\n * @packageDocumentation\n */\n\nimport type { XAD } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/** HL7 v2 Table 0190 address-type code → FHIR `address-use`, exactly per the IG HL70190→address-use map. */\nexport const ADDRESS_USE_MAP: Readonly<Record<string, string>> = Object.freeze({\n BA: \"old\",\n BI: \"billing\",\n C: \"temp\",\n B: \"work\",\n H: \"home\",\n O: \"work\",\n});\n\n/** HL7 v2 Table 0190 address-type code → FHIR `address-type`, exactly per the IG HL70190→address-type map. */\nexport const ADDRESS_TYPE_MAP: Readonly<Record<string, string>> = Object.freeze({\n M: \"postal\",\n SH: \"postal\",\n});\n\n/**\n * Convert a parsed HL7 v2 XAD to a FHIR `Address` node. Returns `{ value: undefined }` when the\n * address carries no emittable part.\n *\n * @param xad - A parsed `@cosyte/hl7` `XAD`.\n * @example\n * ```ts\n * import { toFhirAddress } from \"@cosyte/transform\";\n * const { value } = toFhirAddress({ street: \"1 Main St\", city: \"Boston\", stateOrProvince: \"MA\", addressType: \"H\" });\n * // value === Address { use: \"home\", line: [\"1 Main St\"], city: \"Boston\", state: \"MA\" }\n * void value;\n * ```\n */\nexport function toFhirAddress(xad: XAD): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // XAD.7 → use and/or type across the two independent axes; unmapped (incl. HV) → flagged, absent.\n let use: string | undefined;\n let type: string | undefined;\n if (xad.addressType !== undefined && xad.addressType !== \"\") {\n use = Object.hasOwn(ADDRESS_USE_MAP, xad.addressType)\n ? ADDRESS_USE_MAP[xad.addressType]\n : undefined;\n type = Object.hasOwn(ADDRESS_TYPE_MAP, xad.addressType)\n ? ADDRESS_TYPE_MAP[xad.addressType]\n : undefined;\n if (use === undefined && type === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED, \"XAD.7\", \"Address.use\"));\n }\n }\n\n // XAD.8 (other geographic designation) has no FHIR target — flag the drop.\n if (xad.otherGeographicDesignation !== undefined && xad.otherGeographicDesignation !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"XAD.8\"));\n }\n\n const value = object([\n [\"use\", text(use)],\n [\"type\", text(type)],\n [\"line\", arr([text(xad.street), text(xad.otherDesignation)])],\n [\"city\", text(xad.city)],\n [\"district\", text(xad.countyParishCode)],\n [\"state\", text(xad.stateOrProvince)],\n [\"postalCode\", text(xad.zipOrPostalCode)],\n [\"country\", text(xad.country)],\n ]);\n\n return { value, issues };\n}\n","/**\n * NM + units (CWE) → FHIR `Quantity`.\n *\n * Grounded on the IG datatype maps for OBX-5 (NM)→`Quantity.value` and OBX-6 (CWE units)→\n * `Quantity.unit`/`.code`/`.system`. Two hard fail-safes:\n *\n * - **Never convert magnitudes.** The numeric value is carried through **precision-exact** via\n * `@cosyte/fhir`'s string-backed `decimal` (a dose or lab value is never routed through a JS\n * `number`). UCUM magnitude conversion (mg/dL ↔ mmol/L) is analyte-dependent and a\n * clinical-safety footgun — an explicit non-goal, never a transform side effect.\n * - **Never fabricate a UCUM code.** A unit is emitted into `Quantity.code`/`.system` **only** when\n * it is declared UCUM and passes `@cosyte/fhir`'s UCUM shape check. Any other unit is preserved\n * verbatim in `Quantity.unit` with `code`/`system` absent, flagged\n * {@link ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM}.\n *\n * @packageDocumentation\n */\n\nimport type { CWE, NM } from \"@cosyte/hl7\";\nimport {\n decimal,\n primitive,\n UCUM_SYSTEM,\n validateUcumShape,\n type FhirComplex,\n type FhirNode,\n} from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { object, text } from \"./build.js\";\n\n/**\n * Convert a parsed HL7 v2 numeric value plus its units to a FHIR `Quantity` node, fail-safe on the\n * unit. Returns `{ value: undefined }` when the numeric magnitude is absent or non-numeric (a\n * Quantity without a value cannot be safely emitted).\n *\n * @param value - A parsed `@cosyte/hl7` `NM` (its `.raw` carries the exact lexical value).\n * @param units - The units component (an OBX-6 `CWE`); its CWE.1 is the candidate UCUM code.\n * @param ctx - The transform context; used to recognize the UCUM coding system.\n * @example\n * ```ts\n * import { toFhirQuantity } from \"@cosyte/transform\";\n * const { value } = toFhirQuantity(\n * { raw: \"5.4\", value: 5.4 },\n * { identifier: \"mg/dL\", nameOfCodingSystem: \"UCUM\" },\n * );\n * // value === Quantity { value: 5.4, unit: \"mg/dL\", system: \"http://unitsofmeasure.org\", code: \"mg/dL\" }\n * void value;\n * ```\n */\nexport function toFhirQuantity(\n value: NM,\n units: CWE,\n ctx: TransformContext = {},\n): ConvertResult<FhirComplex> {\n // No numeric magnitude → nothing safe to emit as a Quantity (never guess a value).\n if (value.value === undefined || value.raw === \"\") {\n return { value: undefined, issues: [] };\n }\n return quantityFromRawMagnitude(value.raw, units, ctx);\n}\n\n/**\n * Build a FHIR `Quantity` from a **raw lexical magnitude string** plus its units, fail-safe on both\n * the magnitude and the unit, with an optional `Quantity.comparator`. This is the shared core behind\n * {@link toFhirQuantity} (NM) and the SN → `valueQuantity`/`valueRange`/`valueRatio` observation path.\n * Both must carry the magnitude through **precision-exact** as a string-backed `decimal` and\n * apply the identical no-fabricated-UCUM unit gate — so they share one implementation rather than two\n * that could drift.\n *\n * Returns `{ value: undefined }` (+ a {@link ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID} issue) when\n * the raw magnitude is not a faithful FHIR `decimal` literal — never a canonicalized (altered) value.\n *\n * @param raw - The magnitude's exact lexical form (e.g. OBX-5 NM `.raw`, or an SN component string).\n * @param units - The units component (a CWE); its CWE.1 is the candidate UCUM code.\n * @param ctx - The transform context; used to recognize the UCUM coding system.\n * @param comparator - An optional FHIR `Quantity.comparator` (`<` `<=` `>=` `>`), from an SN comparator.\n * @param valueLocation - The v2 location of the magnitude, for the invalid-value issue (default `OBX.5`).\n * @param unitLocation - The v2 location of the units, for the not-UCUM issue (default `OBX.6`).\n * @example\n * ```ts\n * // internal shared core (used by toFhirQuantity for NM and the observation SN path):\n * // const { value } = quantityFromRawMagnitude(\"90\", { identifier: \"mg/dL\", nameOfCodingSystem: \"UCUM\" }, {}, \">\");\n * // value === Quantity { comparator: \">\", value: 90, unit: \"mg/dL\", system: UCUM, code: \"mg/dL\" }\n * ```\n */\nexport function quantityFromRawMagnitude(\n raw: string,\n units: CWE,\n ctx: TransformContext = {},\n comparator?: string,\n valueLocation = \"OBX.5\",\n unitLocation = \"OBX.6\",\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n if (raw === \"\") {\n return { value: undefined, issues };\n }\n // A raw magnitude keeps its v2 lexical form (v2 allows a leading `+`, leading zeros, a trailing dot),\n // but the FHIR `decimal` literal forbids those. Rather than canonicalize — which would ALTER the\n // magnitude's lexical form — fail safe: if a faithful decimal can't be built, emit a typed issue and\n // no value. (`decimal` throws on a non-conforming literal; catch it so this never throws — §4.6.)\n let valueNode: FhirNode;\n try {\n valueNode = primitive(decimal(raw));\n } catch {\n return {\n value: undefined,\n issues: [\n issue(ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID, valueLocation, \"Quantity.value\"),\n ],\n };\n }\n\n const unitCode = units.identifier; // CWE.1 — the candidate coded (UCUM) unit\n const unitDisplay = units.text; // CWE.2 — the human display unit\n const hasUnit =\n (unitCode !== undefined && unitCode !== \"\") ||\n (unitDisplay !== undefined && unitDisplay !== \"\");\n\n let ucumCode: string | undefined;\n let system: string | undefined;\n let unitStr: string | undefined = unitDisplay ?? unitCode;\n\n if (hasUnit) {\n const mnemonic = units.nameOfCodingSystem;\n const declaredUcum =\n mnemonic === \"UCUM\" ||\n (mnemonic !== undefined && ctx.namingSystem?.resolveCodeSystem(mnemonic) === UCUM_SYSTEM);\n if (\n declaredUcum &&\n unitCode !== undefined &&\n unitCode !== \"\" &&\n validateUcumShape(unitCode) === \"ok\"\n ) {\n ucumCode = unitCode;\n system = UCUM_SYSTEM;\n unitStr = unitDisplay ?? unitCode;\n } else {\n // Non-UCUM or unvalidatable → preserve verbatim, no code/system, magnitude untouched.\n issues.push(issue(ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM, unitLocation, \"Quantity.code\"));\n }\n }\n\n const quantity = object([\n [\"comparator\", text(comparator)],\n [\"value\", valueNode],\n [\"unit\", text(unitStr)],\n [\"system\", text(system)],\n [\"code\", text(ucumCode)],\n ]);\n\n return { value: quantity, issues };\n}\n","/**\n * The `$translate`-shaped ConceptMap-application engine + the **license-clean** v2-table → FHIR\n * value maps it applies. This is the layer that value-**translates** a coded v2\n * field — not merely carrying its code structurally, but mapping the source table code to the FHIR\n * target coding the IG's segment-map `mappedVia` ConceptMap prescribes.\n *\n * **Grounded firsthand on the raw published IG ConceptMaps** (`hl7.fhir.uv.v2mappings`, STU1 —\n * `ConceptMap-table-*.json`). Each shipped map below cites the exact IG ConceptMap it transcribes and\n * was verified against that resource's JSON (its `group.element[].target[]` rows and its `unmatched`\n * `(unmapped)` group). The engine is **fail-safe by refusal**: a source code the IG map has **no\n * target** for (its `(unmapped)` group) is never coerced to a plausible neighbor — the caller flags it\n * and preserves the raw coding, or withholds the value, but a target is **never fabricated**.\n *\n * **License posture.** Only maps whose target CodeSystem is **freely redistributable** are\n * shipped here: the HL7 THO v2 tables (`v2-0162`, `v2-0550`, `v2-0277`, `v2-0161`) and HL7 v3\n * (`v3-RouteOfAdministration`) are HL7's own, license-clean. The IG's `*-to-sct` value maps —\n * **RXR-4 method** (`table-hl70165-to-sct`) and **SCH-7 reason** (`table-hl70276-to-sct`) — translate\n * **into SNOMED CT**, which is **license-encumbered and is NOT bundled**; those fields stay\n * structurally carried (BYO ConceptMap), never value-translated here (see their message modules).\n *\n * **Additive, never mutating.** A successful translation preserves the raw source coding\n * (its code, display, version, and any `CWE.4/5/6` alternate triplet) and *adds* the derived target\n * coding — recognition never overwrites or discards what the message said; it augments it with the\n * IG-mapped equivalent. And it only fires when the field's primary coding is genuinely from the map's\n * **bound source table** (CWE.3 absent, or naming that table): a field that declares a *foreign*\n * coding system (a local `99…`, SNOMED, …) is carried structurally and flagged — its code is **never**\n * asserted to be the standard concept just because the string happens to collide with a table code.\n *\n * @packageDocumentation\n */\n\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport {\n buildCoding,\n toFhirCodeableConcept,\n type CodedElement,\n} from \"../datatypes/codeable-concept.js\";\nimport type { TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"./context.js\";\n\n// ── Target CodeSystem canonical URIs (all license-clean HL7 THO / v3) ────────────────────────────\n\n/** HL7 v2 Table 0162 (Route of Administration) THO CodeSystem URI. */\nexport const V2_0162_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0162\";\n/** HL7 v3 RouteOfAdministration CodeSystem URI (the IG's remap target for the six common routes). */\nexport const V3_ROUTE_OF_ADMINISTRATION_SYSTEM =\n \"http://terminology.hl7.org/CodeSystem/v3-RouteOfAdministration\";\n/** HL7 v2 Table 0550 (Body Parts) THO CodeSystem URI. */\nexport const V2_0550_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0550\";\n/** HL7 v2 Table 0277 (Appointment Type Codes) THO CodeSystem URI. */\nexport const V2_0277_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0277\";\n/** HL7 v2 Table 0161 (Allow Substitution) THO CodeSystem URI. */\nexport const V2_0161_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0161\";\n\n/** A translated FHIR target coding: the target CodeSystem URI + code, and the IG's target display. */\nexport interface CodedTarget {\n /** The FHIR target CodeSystem canonical URI. */\n readonly system: string;\n /** The FHIR target code. */\n readonly code: string;\n /** The IG map's target display, when it carries one (absent for the identity table maps). */\n readonly display?: string;\n}\n\n/**\n * A license-clean v2-table → FHIR value ConceptMap: it translates a **source table code** to its\n * {@link CodedTarget}, or `undefined` when the code is not in the map's *mapped* group (the IG's\n * `(unmapped)` group). Never fabricates a target.\n */\nexport interface CodedValueMap {\n /** The IG ConceptMap id this map transcribes (its citation). */\n readonly name: string;\n /** The source table's canonical CodeSystem URI (what the raw v2 code is a member of when mapped). */\n readonly sourceSystem: string;\n /**\n * The CWE.3 (`nameOfCodingSystem`) mnemonics that denote this map's **bound source table** — the\n * HL7 forms (`\"HL70162\"`, `\"0162\"`, …). Translation applies **only** when the field's primary\n * coding is from the bound table: CWE.3 absent/empty (a positionally-bound bare code) **or** CWE.3 ∈\n * this set. A CWE that declares a **different** coding system (a local `99…`, or SNOMED) is not a\n * source-table code, so the map is not applied to it — the raw coding is carried structurally + its\n * system flagged, never asserted as the standard concept.\n */\n readonly sourceMnemonics: ReadonlySet<string>;\n /** Translate a source table code to its FHIR target, or `undefined` when the IG map has no target. */\n readonly translate: (code: string) => CodedTarget | undefined;\n}\n\n/** Build a {@link CodedValueMap} from an explicit source-code → target table + its bound mnemonics. */\nfunction valueMap(\n name: string,\n sourceSystem: string,\n sourceMnemonics: readonly string[],\n targets: Readonly<Record<string, CodedTarget>>,\n): CodedValueMap {\n return Object.freeze({\n name,\n sourceSystem,\n sourceMnemonics: new Set(sourceMnemonics),\n translate: (code: string): CodedTarget | undefined =>\n Object.hasOwn(targets, code) ? targets[code] : undefined,\n });\n}\n\n/** Build an identity target table (each code maps to itself in `system`) from a code list. */\nfunction identityTargets(system: string, codes: readonly string[]): Record<string, CodedTarget> {\n const t: Record<string, CodedTarget> = {};\n for (const code of codes) t[code] = { system, code };\n return t;\n}\n\n// ── The shipped, license-clean value maps (each verified firsthand against its IG ConceptMap) ────\n\n/**\n * **RXR-1 Route** — IG `ConceptMap/table-hl70162-to-v2-0162`. Two IG groups, transcribed verbatim:\n * a 41-code **identity** group (source `v2-0162` → target `v2-0162`, each `equivalent`) and a 6-code\n * **remap** group into `v3-RouteOfAdministration` (`ID→IDINJ`, `IM→IM`, `IV→IVINJ`, `PO→PO`, `SC→SQ`,\n * `TD→TRNSDERM`, each `equivalent`, with the IG target displays). The two source-code sets are\n * disjoint. Any other v2-0162 code (or a non-table code) is unmapped → the raw coding is preserved\n * and flagged, never coerced.\n */\nexport const ROUTE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70162-to-v2-0162\",\n V2_0162_SYSTEM,\n [\"HL70162\", \"0162\"],\n {\n ...identityTargets(V2_0162_SYSTEM, [\n \"AP\",\n \"B\",\n \"DT\",\n \"EP\",\n \"ET\",\n \"GTT\",\n \"GU\",\n \"IMR\",\n \"IA\",\n \"IB\",\n \"IC\",\n \"ICV\",\n \"IH\",\n \"IHA\",\n \"IN\",\n \"IO\",\n \"IP\",\n \"IS\",\n \"IT\",\n \"IU\",\n \"MTH\",\n \"MM\",\n \"NS\",\n \"NG\",\n \"NP\",\n \"NT\",\n \"OP\",\n \"OT\",\n \"OTH\",\n \"PF\",\n \"PR\",\n \"RM\",\n \"SD\",\n \"SL\",\n \"TP\",\n \"TRA\",\n \"TL\",\n \"UR\",\n \"VG\",\n \"VM\",\n \"WND\",\n ]),\n ID: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"IDINJ\",\n display: \"Injection, intradermal\",\n },\n IM: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"IM\",\n display: \"Injection, intramuscular\",\n },\n IV: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"IVINJ\",\n display: \"Injection, intravenous\",\n },\n PO: { system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM, code: \"PO\", display: \"Swallow, oral\" },\n SC: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"SQ\",\n display: \"Injection, subcutaneous\",\n },\n TD: { system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM, code: \"TRNSDERM\", display: \"Transdermal\" },\n },\n);\n\n/**\n * **RXR-2 Administration Site** — IG `ConceptMap/table-hl70550-to-v2-0550`. A single **identity**\n * group of 443 body-part codes (source `v2-0550` → target `v2-0550`, each `equivalent`), transcribed\n * verbatim from the published STU1 ConceptMap — **including** its as-published data-quality artifacts\n * (`CHESTÂ`, a lone `Â`, `KIDNÂ`, where a stray U+00C2 leaked from the IG's source\n * encoding). They are preserved for source-fidelity; they are inert (a clean `CHEST`/`KIDN` simply\n * falls through to unmapped). A code not in the table is unmapped → raw coding preserved + flagged.\n */\nexport const SITE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70550-to-v2-0550\",\n V2_0550_SYSTEM,\n [\"HL70550\", \"0550\"],\n identityTargets(V2_0550_SYSTEM, [\n \"JUGE\",\n \"ADB\",\n \"ACET\",\n \"ACHIL\",\n \"ADE\",\n \"ADR\",\n \"AMN\",\n \"AMS\",\n \"ANAL\",\n \"ANKL\",\n \"ANTEC\",\n \"ANTECF\",\n \"ANTR\",\n \"ANUS\",\n \"AORTA\",\n \"AR\",\n \"AV\",\n \"APDX\",\n \"AREO\",\n \"ARM\",\n \"ARTE\",\n \"ASCIT\",\n \"ASCT\",\n \"ATR\",\n \"AURI\",\n \"AXI\",\n \"BACK\",\n \"BARTD\",\n \"BARTG\",\n \"BRTGF\",\n \"BPH\",\n \"BID\",\n \"BIFL\",\n \"BLAD\",\n \"BLOOD\",\n \"BLDA\",\n \"BLDC\",\n \"BLDV\",\n \"CBLD\",\n \"BLD\",\n \"BDY\",\n \"BON\",\n \"BMAR\",\n \"BOWEL\",\n \"BOWLA\",\n \"BOWSM\",\n \"BRA\",\n \"BRAIN\",\n \"BCYS\",\n \"BRST\",\n \"BRSTFL\",\n \"BRO\",\n \"BROCH\",\n \"BRONC\",\n \"BRV\",\n \"BUCCA\",\n \"BURSA\",\n \"BURSF\",\n \"BUTT\",\n \"CALF\",\n \"CANAL\",\n \"CANLI\",\n \"CNL\",\n \"CANTH\",\n \"CDM\",\n \"CARO\",\n \"CARP\",\n \"CAVIT\",\n \"CHE\",\n \"CECUM\",\n \"CSF\",\n \"CVX\",\n \"CERVUT\",\n \"CHEEK\",\n \"CHES\",\n \"CHESTÂ\",\n \"CHIN\",\n \"CIRCU\",\n \"CLAVI\",\n \"CLITO\",\n \"CLIT\",\n \"COCCG\",\n \"COCCY\",\n \"COLON\",\n \"COLOS\",\n \"COS\",\n \"CDUCT\",\n \"CONJ\",\n \"CORAL\",\n \"COR\",\n \"CORD\",\n \"CORN\",\n \"CRANE\",\n \"CRANF\",\n \"CRANO\",\n \"CRANP\",\n \"CRANS\",\n \"CRANT\",\n \"CUBIT\",\n \"CUFF\",\n \"CULD\",\n \"CULDO\",\n \"DELT\",\n \"DENTA\",\n \"DEN\",\n \"DIAF\",\n \"DPH\",\n \"DIGIT\",\n \"DISC\",\n \"DORS\",\n \"DUFL\",\n \"DUODE\",\n \"DUR\",\n \"EAR\",\n \"EARBI\",\n \"EARBM\",\n \"EARBS\",\n \"EARLO\",\n \"ELBOW\",\n \"ELBOWJ\",\n \"ENDC\",\n \"EC\",\n \"EOLPH\",\n \"ENDM\",\n \"ET\",\n \"EUR\",\n \"EOS\",\n \"EPICA\",\n \"EPICM\",\n \"EPD\",\n \"EPIDU\",\n \"EPIGL\",\n \"ESOPG\",\n \"ESO\",\n \"ETHMO\",\n \"Â\",\n \"EYE\",\n \"BROW\",\n \"EYELI\",\n \"FACE\",\n \"FBINC\",\n \"FBLAC\",\n \"FBMAX\",\n \"FBNAS\",\n \"FBPAL\",\n \"FBVOM\",\n \"FBZYG\",\n \"FALLT\",\n \"FEMOR\",\n \"FMH\",\n \"FEMUR\",\n \"FET\",\n \"FIBU\",\n \"FING\",\n \"FINGN\",\n \"FOL\",\n \"FOOT\",\n \"FOREA\",\n \"FOREH\",\n \"FORES\",\n \"FOURC\",\n \"GB\",\n \"GEN\",\n \"GVU\",\n \"GENC\",\n \"GL\",\n \"GENL\",\n \"GLAND\",\n \"GLANS\",\n \"GLUTE\",\n \"GLUT\",\n \"GLUTM\",\n \"GROIN\",\n \"GUM\",\n \"HAR\",\n \"HAL\",\n \"HAND\",\n \"HEAD\",\n \"HART\",\n \"HV\",\n \"HVB\",\n \"HVT\",\n \"HEEL\",\n \"HEM\",\n \"HIP\",\n \"HIPJ\",\n \"HUMER\",\n \"HYMEN\",\n \"ILC\",\n \"ILE\",\n \"ILEOS\",\n \"ILEUM\",\n \"ILIAC\",\n \"ILCR\",\n \"ILCON\",\n \"INGUI\",\n \"JUGI\",\n \"INT\",\n \"ICX\",\n \"INASA\",\n \"INTRU\",\n \"INTRO\",\n \"ISCHI\",\n \"JAW\",\n \"KIDNÂ\",\n \"KNEE\",\n \"KNEEF\",\n \"KNEEJ\",\n \"LABIA\",\n \"LABMA\",\n \"LABMI\",\n \"LACRI\",\n \"LAM\",\n \"INSTL\",\n \"LARYN\",\n \"LEG\",\n \"LENS\",\n \"WBC\",\n \"LING\",\n \"LINGU\",\n \"LIP\",\n \"STOOLL\",\n \"LIVER\",\n \"LOBE\",\n \"LOCH\",\n \"ISH\",\n \"LUMBA\",\n \"LMN\",\n \"LUNG\",\n \"LN\",\n \"LNG\",\n \"LYM\",\n \"MAC\",\n \"MALLE\",\n \"MANDI\",\n \"MAR\",\n \"MAST\",\n \"MAXIL\",\n \"MAXS\",\n \"MEATU\",\n \"MEC\",\n \"MEDST\",\n \"MEDU\",\n \"MOU\",\n \"MPB\",\n \"METAC\",\n \"METAT\",\n \"MILK\",\n \"MITRL\",\n \"MOLAR\",\n \"MP\",\n \"MONSU\",\n \"MONSV\",\n \"MOUTH\",\n \"MRSA2\",\n \"MYO\",\n \"NAIL\",\n \"NAILB\",\n \"NAILF\",\n \"NAILT\",\n \"NARES\",\n \"NASL\",\n \"NSS\",\n \"NLACR\",\n \"NP\",\n \"NTRAC\",\n \"NAVEL\",\n \"NECK\",\n \"NERVE\",\n \"NIPPL\",\n \"NOS\",\n \"NOSE\",\n \"NOSTR\",\n \"OCCIP\",\n \"OLECR\",\n \"OMEN\",\n \"ORBIT\",\n \"ORO\",\n \"OSCOX\",\n \"OVARY\",\n \"PALAT\",\n \"PLATH\",\n \"PLATS\",\n \"PALM\",\n \"PANCR\",\n \"PAFL\",\n \"PAS\",\n \"PARAT\",\n \"PARIE\",\n \"PARON\",\n \"PAROT\",\n \"PATEL\",\n \"PELV\",\n \"PENSH\",\n \"PENIS\",\n \"PANAL\",\n \"PERI\",\n \"PCARD\",\n \"PCLIT\",\n \"PERIH\",\n \"PNEAL\",\n \"PERIN\",\n \"PNEPH\",\n \"PNM\",\n \"PORBI\",\n \"PERRA\",\n \"PERIS\",\n \"PER\",\n \"PERT\",\n \"PERIT\",\n \"PTONS\",\n \"PERIU\",\n \"PERIV\",\n \"PHALA\",\n \"PILO\",\n \"PINNA\",\n \"PLC\",\n \"PLACF\",\n \"PLACM\",\n \"PLANT\",\n \"PLEUR\",\n \"PLEU\",\n \"PLR\",\n \"POPLI\",\n \"PREAU\",\n \"PRERE\",\n \"PRST\",\n \"PROS\",\n \"PUBIC\",\n \"PUL\",\n \"RADI\",\n \"RADIUS\",\n \"RECTL\",\n \"RECTU\",\n \"RBC\",\n \"RENL\",\n \"RNP\",\n \"RPERI\",\n \"RIB\",\n \"SACRA\",\n \"SACRO\",\n \"SACIL\",\n \"SACRU\",\n \"SALGL\",\n \"SCALP\",\n \"SCAPU\",\n \"SCLER\",\n \"SCROT\",\n \"SEMN\",\n \"SEM\",\n \"SEPTU\",\n \"SEROM\",\n \"SHIN\",\n \"SHOLJ\",\n \"SHOL\",\n \"SIGMO\",\n \"SINUS\",\n \"SKM\",\n \"SKENE\",\n \"SKULL\",\n \"INSTS\",\n \"SOLE\",\n \"SPRM\",\n \"SPHEN\",\n \"SPCOR\",\n \"SPLN\",\n \"STER\",\n \"STOM\",\n \"USTOM\",\n \"STOMA\",\n \"STUMP\",\n \"SCLV\",\n \"SDP\",\n \"SUB\",\n \"SUBD\",\n \"SGF\",\n \"SUBM\",\n \"SUBX\",\n \"SUBME\",\n \"SUBPH\",\n \"SPX\",\n \"SCLAV\",\n \"SUPRA\",\n \"SUPB\",\n \"SWT\",\n \"SWTG\",\n \"SYNOL\",\n \"SYN\",\n \"SYNOV\",\n \"TARS\",\n \"TDUCT\",\n \"TEAR\",\n \"TEMPL\",\n \"TEMPO\",\n \"TML\",\n \"TESTI\",\n \"THIGH\",\n \"THORA\",\n \"THRB\",\n \"THUMB\",\n \"TNL\",\n \"THM\",\n \"THYRD\",\n \"TIBIA\",\n \"TOE\",\n \"TOEN\",\n \"TONG\",\n \"TONS\",\n \"TOOTH\",\n \"TSK\",\n \"TRCHE\",\n \"TBRON\",\n \"TCN\",\n \"ULNA\",\n \"UMB\",\n \"UMBL\",\n \"URET\",\n \"URTH\",\n \"UTERI\",\n \"SAC\",\n \"UTER\",\n \"VAGIN\",\n \"VCUFF\",\n \"VGV\",\n \"VAL\",\n \"VAS\",\n \"VASTL\",\n \"VAULT\",\n \"VEIN\",\n \"VENTG\",\n \"VCSF\",\n \"VERMI\",\n \"VERTC\",\n \"VERTL\",\n \"VERTT\",\n \"VESI\",\n \"VESCL\",\n \"VESFLD\",\n \"VESTI\",\n \"VITR\",\n \"VOC\",\n \"VULVA\",\n \"WRIST\",\n ]),\n);\n\n/**\n * **SCH-8 Appointment Type** — IG `ConceptMap/table-hl70277-to-v2-0277`. A single **identity** group\n * of the three v2-0277 codes (`Normal`, `Tentative`, `Complete` → themselves, each `equivalent`,\n * source and target both `v2-0277`). Any other code is unmapped → raw coding preserved + flagged.\n */\nexport const APPOINTMENT_TYPE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70277-to-v2-0277\",\n V2_0277_SYSTEM,\n [\"HL70277\", \"0277\"],\n identityTargets(V2_0277_SYSTEM, [\"Normal\", \"Tentative\", \"Complete\"]),\n);\n\n/**\n * **RXO-9 Allow Substitutions** — IG `ConceptMap/table-hl70161-to-v2-0161`. A single **identity**\n * group of the three v2-0161 codes (`N` NOT authorized, `G` generic, `T` therapeutic → themselves,\n * each `equivalent`, source and target both `v2-0161`), the target for\n * `MedicationRequest.substitution.allowedCodeableConcept`. Any other code is unmapped → the\n * substitution is withheld + flagged, never a fabricated substitution permission.\n */\nexport const SUBSTITUTION_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70161-to-v2-0161\",\n V2_0161_SYSTEM,\n [\"HL70161\", \"0161\"],\n identityTargets(V2_0161_SYSTEM, [\"N\", \"G\", \"T\"]),\n);\n\n// ── Application: the $translate-shaped, additive, fail-safe engine ────────────────────────────────\n\n/** Build a FHIR `Coding` node (system, optional version, code, optional display). */\nfunction codingFrom(\n system: string,\n code: string,\n display: string | undefined,\n version?: string,\n): FhirComplex {\n const props: { name: string; value: FhirNode }[] = [{ name: \"system\", value: primitive(system) }];\n if (version !== undefined && version !== \"\")\n props.push({ name: \"version\", value: primitive(version) });\n props.push({ name: \"code\", value: primitive(code) });\n if (display !== undefined && display !== \"\")\n props.push({ name: \"display\", value: primitive(display) });\n return complex(props);\n}\n\n/**\n * The bound-table target for a coded element's **primary** coding, or `undefined` when the map does\n * not faithfully apply — i.e. the primary declares a coding system that is **not** this map's bound\n * table (CWE.3 present and not in {@link CodedValueMap.sourceMnemonics}), the primary code is empty, or\n * the code is in the IG map's `(unmapped)` group. Never asserts a standard translation for a foreign\n * coding system, and never fabricates a target.\n *\n * @param cwe - The parsed coded element (its `identifier` is the candidate source-table code).\n * @param map - The license-clean value map to consider applying.\n * @example\n * ```ts\n * import { translateBound, ROUTE_VALUE_MAP } from \"@cosyte/transform\";\n * translateBound({ identifier: \"IM\" }, ROUTE_VALUE_MAP)?.code; // \"IM\" (v3 route)\n * translateBound({ identifier: \"IM\", nameOfCodingSystem: \"99LOCAL\" }, ROUTE_VALUE_MAP); // undefined\n * ```\n */\nexport function translateBound(cwe: CodedElement, map: CodedValueMap): CodedTarget | undefined {\n const mnemonic = cwe.nameOfCodingSystem;\n const fromBoundTable =\n mnemonic === undefined || mnemonic === \"\" || map.sourceMnemonics.has(mnemonic);\n if (!fromBoundTable) return undefined;\n const code = cwe.identifier;\n return code === undefined || code === \"\" ? undefined : map.translate(code);\n}\n\n/**\n * Build a FHIR `CodeableConcept` node for a {@link CodedTarget} — the single translated coding, with\n * an optional free-`text`. Used by translate-or-withhold callers (e.g. substitution) that build the\n * CodeableConcept only on a successful translation.\n *\n * @param target - The translated target coding.\n * @param text - The original free text (`CWE.9`) to carry as `CodeableConcept.text`, if any.\n * @example\n * ```ts\n * import { codeableConceptFromTarget, V2_0161_SYSTEM } from \"@cosyte/transform\";\n * const cc = codeableConceptFromTarget({ system: V2_0161_SYSTEM, code: \"G\" });\n * void cc;\n * ```\n */\nexport function codeableConceptFromTarget(target: CodedTarget, text?: string): FhirComplex {\n const props: { name: string; value: FhirNode }[] = [\n { name: \"coding\", value: list([codingFrom(target.system, target.code, target.display)]) },\n ];\n if (text !== undefined && text !== \"\") props.push({ name: \"text\", value: primitive(text) });\n return complex(props);\n}\n\n/**\n * Value-translate a coded v2 element to a FHIR `CodeableConcept` **via** a license-clean\n * {@link CodedValueMap}, **additively** and fail-safe — never mutating or discarding what the message\n * said:\n *\n * - **Primary code recognized as a bound-table code** ({@link translateBound} — CWE.3 absent or names\n * the bound table, and the code is in the IG map's mapped group) → the **primary** coding is emitted\n * in the recognized source-table system (`map.sourceSystem`, carrying `CWE.7` version) and the\n * **derived** target coding is *appended* when it differs (a remap such as `SC→SQ`); the **alternate\n * triplet** (`CWE.4/5/6`, via {@link buildCoding}, with its own system resolution + flags) and the\n * original `CWE.9` text are preserved. No primary unmapped flag — the value was faithfully recognized.\n * - **Otherwise** — the primary declares a **foreign** coding system (not the bound table), the code is\n * empty, or it is in the IG's `(unmapped)` group → this defers entirely to the **structural**\n * {@link toFhirCodeableConcept}, which preserves the raw coding (and its `CWE.4/5/6` alternate and\n * `CWE.7` version) and flags it ({@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} /\n * `TRANSFORM_CODE_SYSTEM_UNRESOLVED`). A target is **never** fabricated, and a code that declares a\n * foreign system is **never** asserted to be the standard concept.\n *\n * @param cwe - The parsed `@cosyte/hl7` coded element (its `identifier` is the candidate table code).\n * @param map - The license-clean value map to apply (e.g. {@link ROUTE_VALUE_MAP}).\n * @param ctx - The transform context (threaded to the structural path + the alternate-triplet resolver).\n * @example\n * ```ts\n * import { toFhirCodeableConceptVia, ROUTE_VALUE_MAP } from \"@cosyte/transform\";\n * const { value } = toFhirCodeableConceptVia({ identifier: \"IM\" }, ROUTE_VALUE_MAP);\n * // coding === [{ system: \".../v2-0162\", code: \"IM\" },\n * // { system: \".../v3-RouteOfAdministration\", code: \"IM\", display: \"Injection, intramuscular\" }]\n * void value;\n * ```\n */\nexport function toFhirCodeableConceptVia(\n cwe: CodedElement,\n map: CodedValueMap,\n ctx: TransformContext = {},\n): ConvertResult<FhirComplex> {\n const target = translateBound(cwe, map);\n\n if (target === undefined) {\n // Foreign coding system, empty code, or IG-unmapped → structural carry (raw preserved + flagged).\n return toFhirCodeableConcept(cwe, ctx);\n }\n\n const issues: TransformIssue[] = [];\n const codings: FhirComplex[] = [];\n\n // Primary coding — recognized as a bound-table code: emitted in the source-table system (no flag),\n // carrying the CWE.2 display and CWE.7 version.\n codings.push(\n codingFrom(map.sourceSystem, cwe.identifier as string, cwe.text, cwe.codingSystemVersionId),\n );\n\n // Derived (translated) target coding — appended only for a remap (target ≠ the primary coding);\n // for an identity map the primary already IS the target, so no duplicate is added.\n const isIdentity = target.system === map.sourceSystem && target.code === cwe.identifier;\n if (!isIdentity) codings.push(codingFrom(target.system, target.code, target.display));\n\n // Alternate triplet (CWE.4/5/6 + CWE.8 version) — preserved via the same structural builder the\n // datatype path uses, so its system resolution and fail-safe flags are identical, never dropped.\n const alternate = buildCoding(\n {\n code: cwe.alternateIdentifier,\n display: cwe.alternateText,\n mnemonic: cwe.nameOfAlternateCodingSystem,\n version: cwe.alternateCodingSystemVersionId,\n },\n ctx,\n \"CWE.4\",\n \"CWE.6\",\n issues,\n );\n if (alternate !== undefined) codings.push(alternate);\n\n const props: { name: string; value: FhirNode }[] = [{ name: \"coding\", value: list(codings) }];\n if (cwe.originalText !== undefined && cwe.originalText !== \"\") {\n props.push({ name: \"text\", value: primitive(cwe.originalText) });\n }\n return { value: complex(props), issues };\n}\n","/**\n * Bundle-assembly primitives shared by the segment→resource builders: fresh `urn:uuid:` identities,\n * FHIR `Reference` nodes, and the small coding/data-absent helpers the message maps need.\n *\n * The identities are the wiring of the resource graph — a produced resource is registered under a\n * `urn:uuid:` `fullUrl`, and every intra-bundle reference (Encounter→subject→Patient,\n * RelatedPerson→patient→Patient, MessageHeader→focus→…) points at that same `fullUrl` so references\n * always resolve **within** the bundle. Identities come from {@link TransformOptions.generateId}\n * (default `crypto.randomUUID`) so output can be made reproducible for golden fixtures.\n *\n * @packageDocumentation\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { complex, primitive, list, type FhirComplex } from \"@cosyte/fhir\";\n\nimport type { TransformOptions } from \"../terminology/context.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\n\n/** The FHIR `data-absent-reason` extension canonical URL. */\nconst DATA_ABSENT_REASON_URL = \"http://hl7.org/fhir/StructureDefinition/data-absent-reason\";\n\n/**\n * Allocates `urn:uuid:` identities for the resources of one bundle, from the caller's\n * {@link TransformOptions.generateId} (default `crypto.randomUUID`).\n *\n * @example\n * ```ts\n * // const ids = new IdAllocator({ generateId: () => \"1-2-3\" });\n * // ids.next(); // \"urn:uuid:1-2-3\"\n * ```\n */\nexport class IdAllocator {\n private readonly gen: () => string;\n\n /**\n * @param options - The transform options; `options.generateId` overrides the default UUID source.\n */\n constructor(options: TransformOptions | undefined) {\n this.gen = options?.generateId ?? (() => randomUUID());\n }\n\n /** Mint one fresh `urn:uuid:<id>` fullUrl. */\n next(): string {\n return `urn:uuid:${this.gen()}`;\n }\n}\n\n/**\n * A FHIR `Reference` node pointing at a bundle `fullUrl`.\n *\n * @param fullUrl - The `urn:uuid:` fullUrl of the referenced entry.\n * @example\n * ```ts\n * // reference(\"urn:uuid:1-2-3\") -> { reference: \"urn:uuid:1-2-3\" }\n * ```\n */\nexport function reference(fullUrl: string): FhirComplex {\n return complex([{ name: \"reference\", value: primitive(fullUrl) }]);\n}\n\n/**\n * A single FHIR `Coding` node (`system` + `code`, optional `display`), or `undefined` when no code\n * is present.\n *\n * @param system - The canonical system URI.\n * @param code - The code.\n * @param display - The optional display.\n * @example\n * ```ts\n * // coding(\"http://terminology.hl7.org/CodeSystem/v3-ActCode\", \"IMP\", \"inpatient encounter\")\n * ```\n */\nexport function coding(\n system: string,\n code: string | undefined,\n display?: string,\n): FhirComplex | undefined {\n if (code === undefined || code === \"\") return undefined;\n const props = [\n { name: \"system\", value: primitive(system) },\n { name: \"code\", value: primitive(code) },\n ];\n if (display !== undefined && display !== \"\") {\n props.push({ name: \"display\", value: primitive(display) });\n }\n return complex(props);\n}\n\n/**\n * Build one order `identifier` (an EI's EI.1 → `Identifier.value`) with a v2-0203 identifier-type\n * coding, or `undefined` when the value is empty. Shared by the order/result-anchoring resources\n * whose IG maps route the placer/filler order numbers (OBR-2/ORC-2 `PLAC`, OBR-3/ORC-3 `FILL`) to\n * `Identifier` with a `type` from HL7 Table 0203 — `DiagnosticReport` and `ServiceRequest`\n * both use it, so the shape lives here rather than being duplicated per builder.\n *\n * @param value - The order number (EI.1); an empty string yields `undefined`.\n * @param typeCode - The v2-0203 identifier-type code (`PLAC` placer, `FILL` filler).\n * @example\n * ```ts\n * // orderIdentifier(\"PLACER123\", \"PLAC\") -> { type: { coding: [{ system: v2-0203, code: \"PLAC\" }] }, value: \"PLACER123\" }\n * ```\n */\nexport function orderIdentifier(value: string, typeCode: string): FhirComplex | undefined {\n if (value === \"\") return undefined;\n return complex([\n {\n name: \"type\",\n value: complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V2_0203_SYSTEM) },\n { name: \"code\", value: primitive(typeCode) },\n ]),\n ]),\n },\n ]),\n },\n { name: \"value\", value: primitive(value) },\n ]);\n}\n\n/**\n * A value-absent FHIR primitive carrying only a `data-absent-reason` extension — the spec-clean way\n * to satisfy a required primitive whose value is genuinely unknown, **without fabricating one**.\n *\n * @param reasonCode - The `data-absent-reason` code (e.g. `\"unknown\"`).\n * @example\n * ```ts\n * // used for MessageHeader.source.endpoint when MSH-3 is an app name, not a URL\n * ```\n */\nexport function dataAbsent(reasonCode: string): ReturnType<typeof primitive> {\n const ext = complex([\n { name: \"url\", value: primitive(DATA_ABSENT_REASON_URL) },\n { name: \"valueCode\", value: primitive(reasonCode) },\n ]);\n return primitive(undefined, { extension: [ext] });\n}\n","/**\n * SIU_S12 → FHIR `Appointment` — the thin IG single for scheduling, grounded\n * firsthand on the IG **SIU_S12 message map**, the **SCH/AIS/PID → Appointment** segment maps, the\n * **Table HL70278 → AppointmentStatus** ConceptMap, and the **TQ → Appointment** datatype map\n * (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-message-siu-s12-to-bundle.json`,\n * `ConceptMap-segment-sch-to-appointment.json`, `ConceptMap-segment-ais-to-appointment.json`,\n * `ConceptMap-segment-pid-to-appointment.json`, `ConceptMap-table-hl70278-to-appointmentstatus.json`,\n * `ConceptMap-datatype-tq-to-appointment.json`). Per the message map an SIU message yields **one**\n * `Appointment` created from the `SCH` segment; `PID` contributes the patient participant and `AIS`\n * the service type.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | SCH-25 Filler Status Code | `status` (required 1..1) | {@link APPOINTMENT_STATUS_MAP} (HL70278) |\n * | SCH-1 Placer / SCH-2 Filler Appointment ID | `identifier` | EI.1 → `Identifier.value` |\n * | SCH-7 Appointment Reason (CWE) | `reasonCode` | {@link toFhirCodeableConcept} (structural — SNOMED target, BYO) |\n * | SCH-8 Appointment Type (CWE) | `appointmentType` | {@link APPOINTMENT_TYPE_VALUE_MAP} (HL70277, value-translated) |\n * | SCH-9 Duration + SCH-10 Units | `minutesDuration` | integer, only when SCH-10 is minutes |\n * | SCH-11 Appointment Timing Quantity (TQ) | `start` / `end` (instant) | TQ.4/TQ.5 → {@link toFhirDateTime} |\n * | AIS-3 Universal Service Identifier (CWE) | `serviceType` | {@link toFhirCodeableConcept} |\n * | PID (bundle Patient) | `participant.actor` (required 1..*) | reference wiring |\n *\n * **Fail-safes (never a confident wrong appointment).**\n * - **`status` (required 1..1).** SCH-25 → {@link APPOINTMENT_STATUS_MAP} (HL70278). The three HL70278\n * codes the IG leaves unmatched (`Discontinued`, `Blocked`, `Overbook`) and an absent SCH-25 leave\n * `status` absent + flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}; the required-`status` emit gate\n * then **withholds** the Appointment — never guessed.\n * - **`participant` (required 1..*).** The bundle Patient is emitted as the required participant. Its\n * `participant.status` (a required-bound `code` the IG supplies no source for) is emitted as a\n * `data-absent-reason` primitive (value `unknown`) + flagged {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}\n * — the spec-clean way to satisfy a required code whose value is genuinely unknown, never fabricated. An\n * Appointment with no resolvable Patient (and no other groundable actor this library builds) has no\n * participant and is withheld.\n * - **`start`/`end` (instant).** SCH-11's TQ.4/TQ.5 become `start`/`end` only when they are fully-zoned\n * instants; a naked (unzoned) timing is dropped + flagged rather than assigned a fabricated UTC offset,\n * mirroring `Bundle.timestamp`.\n * - **`appointmentType` value translation.** SCH-8 → {@link APPOINTMENT_TYPE_VALUE_MAP}\n * (HL70277 `Normal`/`Tentative`/`Complete` identity into `v2-0277`); a code outside the table is\n * preserved + flagged, never coerced. **`reasonCode` is NOT value-translated:** SCH-7's IG map target\n * is SNOMED CT (`table-hl70276-to-sct`) — encumbered, **not bundled** — so the reason is carried\n * structurally (BYO ConceptMap), never SNOMED-translated here. (The IG's SCH→Appointment map *also*\n * carries a redundant SCH-7 → `appointmentType[1]` row via `table-hl70277-to-v2-0277`; it is not\n * applied — SCH-7 carries HL70276 *reason* codes, not HL70277 *type* codes, so translating them through\n * the type table would only ever produce spurious unmapped flags. `appointmentType` comes from SCH-8,\n * the appointment-*type* field, per that same map's SCH-8 → `appointmentType[1]` row.)\n *\n * Deferred and flagged elsewhere, not silently mapped: SCH-12/16/20 contact participants and AIP/AIL/AIG\n * actors (need Practitioner/Location resources), SCH-26/27 `basedOn` ServiceRequest, AIS participant periods.\n *\n * @packageDocumentation\n */\n\nimport { parseDtm, type Hl7Message, type Segment, type TS } from \"@cosyte/hl7\";\nimport { complex, decimal, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport {\n toFhirCodeableConceptVia,\n APPOINTMENT_TYPE_VALUE_MAP,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { dataAbsent, reference } from \"./reference.js\";\n\n/**\n * HL7 v2 Table 0278 (Filler Status Code) → FHIR `appointmentstatus` (`Appointment.status`), per the IG\n * **Table HL70278 to AppointmentStatus** ConceptMap (each `is equivalent to`). The three source codes\n * the IG leaves **unmatched** (`Discontinued`, `Blocked`, `Overbook`) are absent here on purpose — an\n * SCH-25 carrying one of them (or any local code) leaves `Appointment.status` absent + flagged and the\n * required-`status` emit gate withholds the Appointment.\n */\nexport const APPOINTMENT_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n Pending: \"pending\",\n Waitlist: \"waitlist\",\n Booked: \"booked\",\n Started: \"checked-in\",\n Complete: \"fulfilled\",\n Cancelled: \"cancelled\",\n Deleted: \"entered-in-error\",\n Noshow: \"noshow\",\n});\n\n/** The `data-absent-reason` code for the patient participant's unknown required `status`. */\nconst PARTICIPANT_STATUS_UNKNOWN = \"unknown\";\n/** UCUM / HL7 unit codes SCH-10 uses to declare that SCH-9 is expressed in minutes. */\nconst MINUTE_UNITS: ReadonlySet<string> = new Set([\"min\", \"MIN\", \"minutes\", \"m\"]);\n/** A FHIR `positiveInt` lexical form (a leading-non-zero positive integer, no sign, no leading zero). */\nconst POSITIVE_INT = /^[1-9][0-9]*$/;\n\n/** Convert an SCH-11 TQ timing component (a raw v2 timestamp) to a fully-zoned FHIR `instant`, or drop. */\nfunction tqInstant(\n raw: string | undefined,\n ctx: TransformContext,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): string | undefined {\n if (raw === undefined || raw === \"\") return undefined;\n const ts: TS = parseDtm(raw);\n const dt = toFhirDateTime(ts, ctx.options);\n issues.push(...dt.issues);\n if (dt.value === undefined) return undefined;\n // Appointment.start/.end are `instant`: only a fully-zoned datetime qualifies, else drop + flag.\n if (\n dt.value.includes(\"T\") &&\n (dt.value.includes(\"+\") || dt.value.endsWith(\"Z\") || /-\\d{2}:\\d{2}$/.test(dt.value))\n ) {\n return dt.value;\n }\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, fhirPath));\n return undefined;\n}\n\n/** The raw first-subcomponent of a field's component at 0-based `index`, or `undefined` when empty. */\nfunction rawComponent(seg: Segment, field: number, index: number): string | undefined {\n const c = seg.field(field).repetitions[0]?.components[index]?.subcomponents[0];\n return c === undefined || c === \"\" ? undefined : c;\n}\n\n/** Build the required patient `participant` (actor → Patient, status data-absent), or `undefined`. */\nfunction patientParticipant(\n patientFullUrl: string | undefined,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (patientFullUrl === undefined) return undefined;\n // participant.status is a required-bound code with no IG source for the patient participant → the\n // spec-clean data-absent-reason primitive, flagged, rather than a fabricated ParticipationStatus.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"SIU\", \"Appointment.participant.status\"),\n );\n return complex([\n { name: \"actor\", value: reference(patientFullUrl) },\n { name: \"status\", value: dataAbsent(PARTICIPANT_STATUS_UNKNOWN) },\n ]);\n}\n\n/**\n * Build a FHIR `Appointment` resource node from an SIU message's `SCH` segment (+ the first `AIS`), with\n * the bundle Patient wired as the required participant. Returns `{ value: undefined }` when there is no\n * `SCH`. `Appointment.status` is left absent (and the resource withheld by the emit gate) when SCH-25\n * cannot be grounded via HL70278 — never guessed.\n *\n * @param sch - The `SCH` `@cosyte/hl7` `Segment` (the schedule anchor).\n * @param ais - The first `AIS` service segment, when present (supplies `serviceType`).\n * @param patientFullUrl - The bundle's Patient fullUrl → the required `participant.actor` (Patient).\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const sch = parseHL7(raw).segments(\"SCH\")[0];\n * // const { value } = buildAppointment(sch!, undefined, \"urn:uuid:pat\", {});\n * ```\n */\nexport function buildAppointment(\n sch: Segment,\n ais: Segment | undefined,\n patientFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Appointment\") },\n ];\n\n // SCH-25 → status (HL70278, required 1..1). Absent/unmapped → left absent (emit gate withholds).\n const fillerStatus = sch.field(25).value;\n if (fillerStatus !== \"\") {\n const status = Object.hasOwn(APPOINTMENT_STATUS_MAP, fillerStatus)\n ? APPOINTMENT_STATUS_MAP[fillerStatus]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"SCH.25\", \"Appointment.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // SCH-1 / SCH-2 → identifier (placer / filler appointment id; EI.1 → Identifier.value).\n const identifiers = [sch.field(1).value, sch.field(2).value]\n .filter((v) => v !== \"\")\n .map((v) => complex([{ name: \"value\", value: primitive(v) }]));\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n // SCH-8 → appointmentType (HL70277 → v2-0277; value-translated via the license-clean identity map).\n if (sch.field(8).value !== \"\") {\n const appointmentType = toFhirCodeableConceptVia(\n sch.field(8).asCwe(),\n APPOINTMENT_TYPE_VALUE_MAP,\n ctx,\n );\n issues.push(...appointmentType.issues);\n if (appointmentType.value !== undefined)\n props.push({ name: \"appointmentType\", value: appointmentType.value });\n }\n\n // AIS-3 → serviceType.\n if (ais !== undefined && ais.field(3).value !== \"\") {\n const serviceType = toFhirCodeableConcept(ais.field(3).asCwe(), ctx);\n issues.push(...serviceType.issues);\n if (serviceType.value !== undefined)\n props.push({ name: \"serviceType\", value: list([serviceType.value]) });\n }\n\n // SCH-7 → reasonCode (default table HL70276).\n if (sch.field(7).value !== \"\") {\n const reason = toFhirCodeableConcept(sch.field(7).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"reasonCode\", value: list([reason.value]) });\n }\n\n // SCH-9 + SCH-10 → minutesDuration, only when SCH-10 declares units of minutes (per the IG condition).\n const duration = sch.field(9).value;\n if (\n duration !== \"\" &&\n POSITIVE_INT.test(duration) &&\n MINUTE_UNITS.has(rawComponent(sch, 10, 0) ?? \"\")\n ) {\n props.push({ name: \"minutesDuration\", value: primitive(decimal(duration)) });\n }\n\n // SCH-11 (TQ) → start / end via TQ.4 / TQ.5 (instant; naked timing dropped + flagged).\n const start = tqInstant(rawComponent(sch, 11, 3), ctx, \"SCH.11\", \"Appointment.start\", issues);\n if (start !== undefined) props.push({ name: \"start\", value: primitive(start) });\n const end = tqInstant(rawComponent(sch, 11, 4), ctx, \"SCH.11\", \"Appointment.end\", issues);\n if (end !== undefined) props.push({ name: \"end\", value: primitive(end) });\n\n // participant (required 1..*): the bundle Patient (participant.status data-absent + flagged).\n const participant = patientParticipant(patientFullUrl, issues);\n if (participant !== undefined) props.push({ name: \"participant\", value: list([participant]) });\n\n return { value: complex(props), issues };\n}\n\n/**\n * The first `SCH` and first `AIS` of an SIU message, for the single-Appointment build.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { sch, ais } = collectAppointment(parseHL7(raw));\n * ```\n */\nexport function collectAppointment(msg: Hl7Message): {\n sch: Segment | undefined;\n ais: Segment | undefined;\n} {\n let sch: Segment | undefined;\n let ais: Segment | undefined;\n for (const seg of msg.allSegments()) {\n if (seg.type === \"SCH\" && sch === undefined) sch = seg;\n else if (seg.type === \"AIS\" && ais === undefined) ais = seg;\n }\n return { sch, ais };\n}\n","/**\n * OBR → FHIR `DiagnosticReport` — the ORU results-report anchor, grounded firsthand\n * on the IG **Segment OBR to DiagnosticReport** ConceptMap and its **Table HL70123 to Diagnostic Report\n * Status** ConceptMap (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-obr-to-diagnosticreport.html`,\n * `ConceptMap-table-hl70123-queries-to-diagnostic-report-status.html`):\n *\n * | OBR field | FHIR target | via |\n * |---|---|---|\n * | OBR-2 Placer Order Number | `identifier` (type `PLAC`) | EI.1 → `Identifier.value`, v2-0203 type |\n * | OBR-3 Filler Order Number | `identifier` (type `FILL`) | EI.1 → `Identifier.value`, v2-0203 type |\n * | OBR-4 Universal Service Identifier (CWE) | `DiagnosticReport.code` | {@link toFhirCodeableConcept} |\n * | OBR-7 Observation Date/Time | `effectiveDateTime` / `effectivePeriod.start` | {@link toFhirDateTime} |\n * | OBR-8 Observation End Date/Time | `effectivePeriod.end` (start moves to the period when valued) | — |\n * | OBR-22 Results Rpt/Status Chng Date/Time | `DiagnosticReport.issued` (an `instant`) | {@link toFhirDateTime} |\n * | OBR-24 Diagnostic Serv Sect ID | `DiagnosticReport.category` | v2-0074 coding |\n * | OBR-25 Result Status | `DiagnosticReport.status` | {@link DIAGNOSTIC_REPORT_STATUS_MAP} (HL70123) |\n * | (OBX children) | `DiagnosticReport.result` | reference wiring from the assembler |\n *\n * **Fail-safes.** `DiagnosticReport.status` is required (R4 1..1) and the IG itself notes an unvalued\n * OBR-25 is an error; so an absent OBR-25 — or an OBR-25 code the HL70123 map does not carry (`A`, `M`,\n * `N`, `Y`, `Z`) — leaves `status` absent + flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, and the\n * required-`status` emit gate withholds the report rather than emitting an invalid one or guessing\n * `final`. `OBR-25 = C`→`corrected` / `X`→`cancelled` are modelled exactly. OBR-22 becomes `issued`\n * only when it is a fully-zoned instant; a date-only/naked OBR-22 is dropped + flagged (never a\n * fabricated UTC), mirroring `Bundle.timestamp`. Deferred and flagged elsewhere, not silently mapped:\n * OBR-32/34/35 performers (need PractitionerRole resources), specimen, and `basedOn` ServiceRequest.\n *\n * @packageDocumentation\n */\n\nimport type { Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { orderIdentifier, reference } from \"./reference.js\";\n\n/** The HL7 v2 Table 0074 (Diagnostic Service Section ID) canonical system — `DiagnosticReport.category`. */\nconst V2_0074_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0074\";\n\n/**\n * HL7 v2 Table 0123 (Result Status) → FHIR `diagnostic-report-status` (`DiagnosticReport.status`), per\n * the IG **Table HL70123 [Queries] to Diagnostic Report Status** ConceptMap (each `is equivalent to`).\n * Only these **eight** source codes carry a target; the IG leaves `A`, `M`, `N`, `Y`, `Z` unmapped\n * (verified firsthand against the published v1.0.0 ConceptMap — `N` \"Procedure completed, results\n * pending\" is in the `(not mapped)` group, and the map declares no `unmapped` default), so an OBR-25\n * with one of them leaves `status` absent + flagged and the report is withheld. In particular a\n * results-**pending** `N` is **never** emitted as the post-final `appended`. **`C`→`corrected` and\n * `X`→`cancelled` guarantee a corrected/cancelled report never emits as `final`.**\n */\nexport const DIAGNOSTIC_REPORT_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n O: \"registered\",\n I: \"registered\",\n S: \"registered\",\n P: \"preliminary\",\n R: \"partial\",\n C: \"corrected\",\n F: \"final\",\n X: \"cancelled\",\n});\n\n/**\n * Build a FHIR `DiagnosticReport` resource node from one parsed HL7 v2 OBR segment and the fullUrls of\n * the `Observation`s produced under it. Returns `{ value: undefined }` when OBR-4 (the report `code`,\n * required 1..1) is absent. `DiagnosticReport.status` is left absent (and the report withheld by the\n * emit gate) when OBR-25 is missing or has no HL70123 target — never guessed.\n *\n * @param obr - The OBR `@cosyte/hl7` `Segment`.\n * @param resultFullUrls - The `urn:uuid:` fullUrls of this report's emitted `Observation`s → `.result`.\n * @param subjectFullUrl - The bundle's Patient fullUrl → `DiagnosticReport.subject`.\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `DiagnosticReport.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const obr = parseHL7(raw).segments(\"OBR\")[0];\n * // const { value } = buildDiagnosticReport(obr!, [\"urn:uuid:obs1\"], \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildDiagnosticReport(\n obr: Segment,\n resultFullUrls: readonly string[],\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"DiagnosticReport\") },\n ];\n\n // OBR-2 / OBR-3 → DiagnosticReport.identifier (PLAC / FILL, v2-0203 types).\n const identifiers = [\n orderIdentifier(obr.field(2).value, \"PLAC\"),\n orderIdentifier(obr.field(3).value, \"FILL\"),\n ].filter((i): i is FhirComplex => i !== undefined);\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n // OBR-25 → DiagnosticReport.status (HL70123). Absent/unmapped → left absent (emit gate withholds),\n // never guessed; a corrected/cancelled result is modelled exactly, never emitted as `final`.\n const statusCode = obr.field(25).value;\n if (statusCode !== \"\") {\n const status = Object.hasOwn(DIAGNOSTIC_REPORT_STATUS_MAP, statusCode)\n ? DIAGNOSTIC_REPORT_STATUS_MAP[statusCode]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBR.25\", \"DiagnosticReport.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // OBR-24 → DiagnosticReport.category (v2-0074 diagnostic service section).\n const section = obr.field(24).value;\n if (section !== \"\") {\n props.push({\n name: \"category\",\n value: list([\n complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V2_0074_SYSTEM) },\n { name: \"code\", value: primitive(section) },\n ]),\n ]),\n },\n ]),\n ]),\n });\n }\n\n // OBR-4 → DiagnosticReport.code (required 1..1). Absent → nothing emittable.\n const code = toFhirCodeableConcept(obr.field(4).asCwe(), ctx);\n issues.push(...code.issues);\n if (code.value === undefined) return { value: undefined, issues };\n props.push({ name: \"code\", value: code.value });\n\n // subject / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined) {\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n }\n\n // OBR-7 / OBR-8 → effectiveDateTime, or effectivePeriod when an end (OBR-8) is valued.\n const hasEnd = obr.field(8).value !== \"\";\n if (obr.field(7).value !== \"\") {\n const start = toFhirDateTime(obr.field(7).asTs(), ctx.options);\n issues.push(...start.issues);\n if (start.value !== undefined && !hasEnd) {\n props.push({ name: \"effectiveDateTime\", value: primitive(start.value) });\n } else if (start.value !== undefined) {\n const end = toFhirDateTime(obr.field(8).asTs(), ctx.options);\n issues.push(...end.issues);\n const periodProps: { name: string; value: FhirNode }[] = [\n { name: \"start\", value: primitive(start.value) },\n ];\n if (end.value !== undefined) periodProps.push({ name: \"end\", value: primitive(end.value) });\n props.push({ name: \"effectivePeriod\", value: complex(periodProps) });\n }\n }\n\n // OBR-22 → DiagnosticReport.issued (an `instant`): only a fully-zoned datetime qualifies; a\n // date-only/naked OBR-22 is dropped + flagged rather than emitted as an invalid or fabricated instant.\n if (obr.field(22).value !== \"\") {\n const issued = toFhirDateTime(obr.field(22).asTs(), ctx.options);\n issues.push(...issued.issues);\n if (issued.value !== undefined && issued.value.includes(\"T\")) {\n props.push({ name: \"issued\", value: primitive(issued.value) });\n } else if (issued.value !== undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBR.22\", \"DiagnosticReport.issued\"),\n );\n }\n }\n\n // DiagnosticReport.result → the emitted Observations under this OBR.\n if (resultFullUrls.length > 0) {\n props.push({ name: \"result\", value: list(resultFullUrls.map((u) => reference(u))) });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * MDM_T02 → FHIR `DocumentReference` — the thin IG single for clinical documents,\n * grounded firsthand on the IG **MDM_T02 message map** and the **TXA/OBX → DocumentReference** segment\n * maps (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-message-mdm-t02-to-bundle.json`,\n * `ConceptMap-segment-txa-to-documentreference.json`, `ConceptMap-segment-obx-to-documentreference.json`).\n * Per the message map an MDM message yields **one** `DocumentReference` created from the `TXA` segment,\n * with the document body carried by the `OBX` segments.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | TXA-19 Document Availability Status | `status` (required 1..1) | `AV` → `current` only (see below) |\n * | TXA-2 Document Type (CWE) | `type` | {@link toFhirCodeableConcept} (structural — no IG value map) |\n * | TXA-6 Origination Date/Time (DTM) | `date` (an `instant`) | {@link toFhirDateTime}, fully-zoned only |\n * | TXA-12 Unique Document Number | `masterIdentifier` | EI.1 → `Identifier.value` |\n * | TXA-16 Unique Document File Name | `identifier` | ST → `Identifier.value` |\n * | TXA-25 Document Title | `description` | verbatim |\n * | OBX-5 (per OBX-2) | `content.attachment` (required 1..*) | {@link buildContent} |\n * | (message-map wiring) | `subject` | the bundle's Patient |\n *\n * **Fail-safes (never a confident wrong document record).**\n * - **`status` (required 1..1) — grounded only for `AV`.** The IG conditions TXA-19 → `status` on\n * `IF TXA-19 = \"AV\"` and ships **no** value ConceptMap (there is no HL70273 → document-reference-status\n * table in the IG). \"AV\" (Available) has exactly one faithful target in the required\n * `document-reference-status` binding (`current` | `superseded` | `entered-in-error`): **`current`**, so\n * `AV → current` is emitted. Every other TXA-19 value — `CA`/`OB`/`UN` (whose IG target is a\n * `status.extension` construct that is not valid R4) and any local code — is **unmapped**\n * ({@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}); `status` is left absent and the required-`status` emit\n * gate **withholds** the DocumentReference. Never guessed.\n * - **`content` (required 1..*).** Built from the `OBX` document body via {@link buildContent}. When no\n * OBX yields a groundable attachment the DocumentReference has no content and is withheld + flagged —\n * a document reference that references nothing is never emitted.\n * - **`docStatus` — unmapped, left absent.** TXA-17 → `docStatus` has **no** IG value ConceptMap\n * (HL70271 → composition-status is genuinely ambiguous), so a valued TXA-17 is flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} and `docStatus` (0..1) is left absent — never guessed.\n * - **`content.attachment.contentType`.** Taken from the IG's OBX-2 assignment (`application/text` for\n * TX, `text/hl7v2` for FT — see {@link BODY_CONTENT_TYPE}), **not** from TXA-3 — the TXA-3 → contentType\n * row carries HL70191 codes that are not MIME types, so TXA-3 is flagged dropped rather than emitted as\n * an invalid `contentType`. The document body itself is **carried, never interpreted** (TX/FT text is\n * base64-encoded verbatim into `content.attachment.data`).\n *\n * Deferred and flagged elsewhere, not silently mapped: TXA-9/10 author/authenticator (Practitioner),\n * TXA-18 securityLabel, the ED-encapsulated OBX body, and the COMMON_ORDER ORC → ServiceRequest graph.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/** The only faithful `document-reference-status` target for TXA-19 = \"AV\" (Document is Available). */\nconst STATUS_AVAILABLE_TARGET = \"current\";\n/**\n * The `content.attachment.contentType` the IG assigns per OBX-2 body type (verified firsthand against\n * `ConceptMap-segment-obx-to-documentreference.json`: `content[4].contentType` = `\"application/text\"`\n * for `IF OBX-2=\"TX\"`, `content[2].contentType` = `\"text/hl7v2\"` for `IF OBX-2=\"FT\"`).\n */\nconst BODY_CONTENT_TYPE: Readonly<Record<string, string>> = Object.freeze({\n TX: \"application/text\",\n FT: \"text/hl7v2\",\n});\n\n/**\n * Build one `DocumentReference.content` entry from a body `OBX`, discriminated by OBX-2 per the IG\n * **OBX → DocumentReference** map: `TX` → `content.attachment.data` (the text base64-encoded) + the\n * IG-assigned `application/text` contentType; `FT` → the same, with `text/hl7v2`; `RP` →\n * `content.attachment.url` (the reference pointer). The IG also maps `ED` → `content.attachment`, but\n * that requires decoding the ED encapsulated-data composite (a later concern), so `ED` — and any\n * non-document OBX-2 — is flagged {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} and deferred, never\n * fabricated. The document body itself is carried verbatim, never interpreted.\n */\nfunction buildContent(\n obx: Segment,\n index: number,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const valueType = obx.field(2).value.toUpperCase();\n const raw = obx.field(5).value;\n if (raw === \"\") return undefined;\n\n if (Object.hasOwn(BODY_CONTENT_TYPE, valueType)) {\n // The document body is carried, never interpreted: the verbatim text is base64-encoded into\n // Attachment.data (a base64Binary), with the IG-assigned contentType for this body type.\n const data = Buffer.from(raw, \"utf8\").toString(\"base64\");\n return complex([\n {\n name: \"attachment\",\n value: complex([\n { name: \"contentType\", value: primitive(BODY_CONTENT_TYPE[valueType]) },\n { name: \"data\", value: primitive(data) },\n ]),\n },\n ]);\n }\n\n if (valueType === \"RP\") {\n // RP (reference pointer): the first component is the pointer/URL to the document body.\n return complex([\n {\n name: \"attachment\",\n value: complex([{ name: \"url\", value: primitive(raw) }]),\n },\n ]);\n }\n\n // ED-encapsulated (deferred) and non-document OBX-2 bodies are flagged and dropped, never fabricated.\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n `OBX[${String(index)}].5`,\n \"DocumentReference.content\",\n ),\n );\n return undefined;\n}\n\n/**\n * Build a FHIR `DocumentReference` resource node from an MDM message's `TXA` segment and its body `OBX`\n * segments. Returns `{ value: undefined }` when there is no `TXA`. `status` (from TXA-19 = \"AV\") and\n * `content` (from the OBX body) are both required 1..1 / 1..*; when either cannot be grounded the\n * resource is left incomplete and later **withheld** by the conservative-emit gate — never guessed.\n *\n * @param txa - The `TXA` `@cosyte/hl7` `Segment` (the document metadata anchor).\n * @param obxs - The document-body `OBX` segments, in document order.\n * @param subjectFullUrl - The bundle's Patient fullUrl → `DocumentReference.subject`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const txa = parseHL7(raw).segments(\"TXA\")[0];\n * // const obxs = parseHL7(raw).segments(\"OBX\");\n * // const { value } = buildDocumentReference(txa!, obxs, \"urn:uuid:pat\", {});\n * ```\n */\nexport function buildDocumentReference(\n txa: Segment,\n obxs: readonly Segment[],\n subjectFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"DocumentReference\") },\n ];\n\n // TXA-19 → status (required 1..1). Grounded only for \"AV\" → \"current\"; anything else is unmapped and\n // the required-status emit gate withholds the resource.\n const availability = txa.field(19).value;\n if (availability === \"AV\") {\n props.push({ name: \"status\", value: primitive(STATUS_AVAILABLE_TARGET) });\n } else if (availability !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TXA.19\", \"DocumentReference.status\"));\n }\n\n // TXA-17 → docStatus: no IG value map exists → flag when valued, leave docStatus (0..1) absent.\n if (txa.field(17).value !== \"\") {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TXA.17\", \"DocumentReference.docStatus\"),\n );\n }\n\n // TXA-2 → type: carried **structurally** (system recognized, value preserved). The IG's\n // TXA→DocumentReference segment map ships **no** `mappedVia` value ConceptMap for TXA-2 (verified\n // firsthand — only TXA-18 securityLabel carries one), so a value translation is never invented for it\n // (ADR 0018 applied to mappings); the document-type code (typically LOINC) is emitted as-is.\n if (txa.field(2).value !== \"\") {\n const type = toFhirCodeableConcept(txa.field(2).asCwe(), ctx);\n issues.push(...type.issues);\n if (type.value !== undefined) props.push({ name: \"type\", value: type.value });\n }\n\n // TXA-12 → masterIdentifier; TXA-16 → identifier[1] (both EI/ST → Identifier.value).\n if (txa.field(12).value !== \"\") {\n props.push({\n name: \"masterIdentifier\",\n value: complex([{ name: \"value\", value: primitive(txa.field(12).value) }]),\n });\n }\n if (txa.field(16).value !== \"\") {\n props.push({\n name: \"identifier\",\n value: list([complex([{ name: \"value\", value: primitive(txa.field(16).value) }])]),\n });\n }\n\n // subject → the bundle's Patient (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n\n // TXA-6 → date (an `instant`): only a fully-zoned datetime qualifies (the IG's \"IF time is included\"\n // condition), else dropped + flagged rather than emitted as an invalid or fabricated instant.\n if (txa.field(6).value !== \"\") {\n const date = toFhirDateTime(txa.field(6).asTs(), ctx.options);\n issues.push(...date.issues);\n if (date.value !== undefined && date.value.includes(\"T\")) {\n props.push({ name: \"date\", value: primitive(date.value) });\n } else if (date.value !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TXA.6\", \"DocumentReference.date\"));\n }\n }\n\n // TXA-3 → content.attachment.contentType: HL70191 codes are not MIME types, so a valued TXA-3 is\n // flagged dropped rather than emitted as an invalid contentType (the body type drives it instead).\n if (txa.field(3).value !== \"\") {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"TXA.3\",\n \"DocumentReference.content.attachment.contentType\",\n ),\n );\n }\n\n // TXA-25 → description.\n if (txa.field(25).value !== \"\")\n props.push({ name: \"description\", value: primitive(txa.field(25).value) });\n\n // OBX body → content (required 1..*). No groundable content → resource withheld by the emit gate.\n const contents: FhirComplex[] = [];\n for (let i = 0; i < obxs.length; i++) {\n const obx = obxs[i];\n if (obx === undefined) continue;\n const content = buildContent(obx, i, issues);\n if (content !== undefined) contents.push(content);\n }\n if (contents.length > 0) props.push({ name: \"content\", value: list(contents) });\n\n return { value: complex(props), issues };\n}\n\n/**\n * The first `TXA` and all body `OBX` segments of an MDM message, for the single-DocumentReference build.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { txa, obxs } = collectDocument(parseHL7(raw));\n * ```\n */\nexport function collectDocument(msg: Hl7Message): {\n txa: Segment | undefined;\n obxs: readonly Segment[];\n} {\n let txa: Segment | undefined;\n const obxs: Segment[] = [];\n for (const seg of msg.allSegments()) {\n if (seg.type === \"TXA\" && txa === undefined) txa = seg;\n else if (seg.type === \"OBX\") obxs.push(seg);\n }\n return { txa, obxs };\n}\n","/**\n * PV1 → FHIR `Encounter` — grounded on the IG **Segment PV1 to Encounter** ConceptMap plus the two\n * **Table HL70004** ConceptMaps (to V3 ActCode, and to Encounter Status), all verified firsthand\n * against the published `hl7.fhir.uv.v2mappings` STU1 maps:\n *\n * | PV1 field | FHIR target | condition / via |\n * |---|---|---|\n * | PV1-2 Patient Class | `Encounter.class` (Coding) | Table 0004 → V3 ActCode ({@link ENCOUNTER_CLASS_V3_MAP}); the self-mapped classes stay in v2-0004 |\n * | PV1-2 Patient Class | `Encounter.status` (code) | Table 0004 → Encounter Status ({@link ENCOUNTER_STATUS_MAP}), *only IF PV1-45 not valued* |\n * | PV1-19 Visit Number | `Encounter.identifier` (type `VN`) | v2-0203 identifier-type system |\n * | PV1-44 Admit Date/Time | `Encounter.period.start` | {@link toFhirDateTime} |\n * | PV1-45 Discharge Date/Time | `Encounter.period.end` + `status = finished` | {@link toFhirDateTime} |\n *\n * Fail-safe: an unmapped patient class leaves `Encounter.class` absent and flags\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} (never coerced); `Encounter.subject` is wired to the\n * bundle's Patient (the identity anchor) and omitted only when no valid Patient was produced.\n * Deferred and flagged, not silently mapped: PV1-3 location (Reference(Location), no Location resource\n * is built), PV1-7/8 attending/referring doctor (Reference(Practitioner), no Practitioner resource\n * is built).\n *\n * @packageDocumentation\n */\n\nimport type { Visit } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\nimport { coding, reference } from \"./reference.js\";\n\n/** The v3 ActCode canonical system (FHIR `Encounter.class` binding). */\nconst V3_ACTCODE_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v3-ActCode\";\n/** The HL7 v2 Table 0004 (Patient Class) canonical system — for classes with no v3 ActCode row. */\nconst V2_0004_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0004\";\n\n/**\n * HL7 v2 Table 0004 (Patient Class) → FHIR v3 ActCode (`Encounter.class`), per the IG **Table HL70004\n * to V3 ActCode** ConceptMap (each \"is equivalent to\"). Only these four v2 classes have a v3 ActCode\n * equivalent; the remaining classes (R/B/C/N/U) map to themselves and stay in the v2-0004 system\n * ({@link V2_0004_SYSTEM}) per the same map's V2→V2 rows.\n */\nexport const ENCOUNTER_CLASS_V3_MAP: Readonly<Record<string, { code: string; display: string }>> =\n Object.freeze({\n E: { code: \"EMER\", display: \"emergency\" },\n I: { code: \"IMP\", display: \"inpatient encounter\" },\n O: { code: \"AMB\", display: \"ambulatory\" },\n P: { code: \"PRENC\", display: \"pre-admission\" },\n });\n\n/** The v2-0004 classes the IG maps to themselves (no v3 ActCode equivalent). */\nconst V2_SELF_CLASSES: ReadonlySet<string> = new Set([\"R\", \"B\", \"C\", \"N\", \"U\"]);\n\n/**\n * HL7 v2 Table 0004 (Patient Class) → FHIR `Encounter.status`, per the IG **Table HL70004 to\n * Encounter Status** ConceptMap. Applied only when PV1-45 (discharge date) is *not* valued — a valued\n * discharge sets `status = finished` per the PV1→Encounter map.\n */\nexport const ENCOUNTER_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n E: \"in-progress\",\n I: \"in-progress\",\n O: \"in-progress\",\n R: \"in-progress\",\n B: \"in-progress\",\n C: \"in-progress\",\n N: \"in-progress\",\n P: \"planned\",\n U: \"unknown\",\n});\n\n/** Build `Encounter.class` from PV1-2, or `undefined` (+ push an issue) when it cannot be mapped. */\nfunction buildClass(\n patientClass: string | undefined,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (patientClass === undefined || patientClass === \"\") return undefined;\n const v3 = ENCOUNTER_CLASS_V3_MAP[patientClass];\n if (v3 !== undefined) return coding(V3_ACTCODE_SYSTEM, v3.code, v3.display);\n if (V2_SELF_CLASSES.has(patientClass)) return coding(V2_0004_SYSTEM, patientClass);\n // Unknown patient-class code — never coerced to a neighbor; class left absent and flagged.\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"PV1.2\", \"Encounter.class\"));\n return undefined;\n}\n\n/**\n * Build a FHIR `Encounter` resource node from a parsed HL7 v2 PV1 view.\n *\n * @param visit - The `@cosyte/hl7` `Visit` view (PV1-derived).\n * @param subjectFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient, or `undefined` when none\n * was produced (then `Encounter.subject` is omitted and flagged).\n * @param ctx - The transform context (carries the timezone policy for the period).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildEncounter(parseHL7(raw).visit!, \"urn:uuid:1-2-3\", {});\n * ```\n */\nexport function buildEncounter(\n visit: Visit,\n subjectFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Encounter\") },\n ];\n\n // PV1-19 → Encounter.identifier (type VN, v2-0203).\n if (visit.visitNumber !== undefined && visit.visitNumber !== \"\") {\n const vnCoding = complex([\n { name: \"system\", value: primitive(V2_0203_SYSTEM) },\n { name: \"code\", value: primitive(\"VN\") },\n ]);\n const identifier = complex([\n { name: \"type\", value: complex([{ name: \"coding\", value: list([vnCoding]) }]) },\n { name: \"value\", value: primitive(visit.visitNumber) },\n ]);\n props.push({ name: \"identifier\", value: list([identifier]) });\n }\n\n // PV1-2 / PV1-45 → Encounter.status. A valued discharge means \"finished\"; else Table 0004 status.\n const discharged = visit.dischargeDateTime !== undefined;\n let status: string | undefined;\n if (discharged) {\n status = \"finished\";\n } else if (visit.patientClass !== undefined && visit.patientClass !== \"\") {\n status = Object.hasOwn(ENCOUNTER_STATUS_MAP, visit.patientClass)\n ? ENCOUNTER_STATUS_MAP[visit.patientClass]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"PV1.2\", \"Encounter.status\"));\n }\n }\n if (status !== undefined) props.push({ name: \"status\", value: primitive(status) });\n\n // PV1-2 → Encounter.class (Table 0004 → V3 ActCode; self-mapped classes stay in v2-0004).\n const encounterClass = buildClass(visit.patientClass, issues);\n if (encounterClass !== undefined) props.push({ name: \"class\", value: encounterClass });\n\n // Encounter.subject → the bundle's Patient (the message map's reference wiring).\n if (subjectFullUrl !== undefined) {\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n } else {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PID\", \"Encounter.subject\"));\n }\n\n // PV1-44 / PV1-45 → Encounter.period.start / .end.\n const periodProps: { name: string; value: FhirNode }[] = [];\n if (visit.admitDateTime !== undefined) {\n const start = toFhirDateTime(visit.admitDateTime, ctx.options);\n issues.push(...start.issues);\n if (start.value !== undefined)\n periodProps.push({ name: \"start\", value: primitive(start.value) });\n }\n if (visit.dischargeDateTime !== undefined) {\n const end = toFhirDateTime(visit.dischargeDateTime, ctx.options);\n issues.push(...end.issues);\n if (end.value !== undefined) periodProps.push({ name: \"end\", value: primitive(end.value) });\n }\n if (periodProps.length > 0) props.push({ name: \"period\", value: complex(periodProps) });\n\n // Deferred, flagged: PV1-3 location, PV1-7/8 doctors need Location/Practitioner resources.\n if (visit.location !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.3\", \"Encounter.location\"));\n }\n if (visit.attendingDoctor !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.7\", \"Encounter.participant\"));\n }\n if (visit.referringDoctor !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.8\", \"Encounter.participant\"));\n }\n\n if (props.length === 1) return { value: undefined, issues };\n return { value: complex(props), issues };\n}\n","/**\n * Minimal R4 **required-cardinality** schemas for the resource types this library emits, so the\n * conservative-emit gate ({@link ../messages/to-fhir.js}) actually catches a structurally-invalid\n * resource rather than waving it through.\n *\n * `@cosyte/fhir.validateResource` models only `Patient` out of the box; every other resource type\n * degrades to a base-elements schema and validates as `valid` regardless of its own required\n * elements. These schemas restore the R4 required (`min: 1`) elements for the types we produce, and\n * the gate applies them in **lenient** mode — so a *missing required* element is an error (the\n * resource is withheld), while the resource's other (unmodeled-here) elements are warnings, never a\n * false rejection. Grounded on the FHIR R4 resource definitions:\n *\n * - **Encounter**: `status` (1..1 code) and `class` (1..1 Coding) are both required.\n * - **MessageHeader**: `event[x]` (1..1) is required; we only ever emit the `eventCoding` form, so a\n * header with no `eventCoding` (MSH-9 without a trigger event) is withheld rather than shipped\n * without its mandatory event.\n * - **RelatedPerson**: `patient` (1..1 Reference) is required (defence-in-depth; the assembler only\n * builds a RelatedPerson when a Patient exists to anchor it).\n * - **DiagnosticReport**: `status` (1..1 code) and `code` (1..1 CodeableConcept) are both required — so\n * a report from an unmapped/absent OBR-25 result status (no `status`) is withheld, never guessed.\n * - **Observation**: `status` (1..1 code) and `code` (1..1 CodeableConcept) are both required — so a\n * result from an unmapped/absent OBX-11 status (no `status`) is withheld, never emitted as `final`.\n * - **ServiceRequest**: `status` (1..1 code), `intent` (1..1 code), and `subject` (1..1 Reference) are\n * all required — so an order whose `status` could not be grounded via HL70119 (or whose Patient was\n * withheld) is withheld, never emitted with a guessed status or a dangling subject.\n * - **MedicationRequest**: `status` (1..1 code), `intent` (1..1 code), `subject` (1..1 Reference), and\n * `medication[x]` (1..1) are all required; the assembler only ever emits the `medicationCodeableConcept`\n * form, so it is required here — a pharmacy order with no give code (no `medication[x]`) is withheld.\n *\n * @packageDocumentation\n */\n\nimport { UNBOUNDED, type ResourceSchema } from \"@cosyte/fhir\";\n\n/** The required-cardinality schemas the emit gate applies (lenient) to the non-`Patient` resources. */\nexport const EMIT_SCHEMAS: readonly ResourceSchema[] = Object.freeze([\n {\n type: \"Encounter\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n class: { min: 1, max: 1, types: [\"Coding\"] },\n },\n },\n {\n type: \"MessageHeader\",\n elements: {\n eventCoding: { min: 1, max: 1, types: [\"Coding\"] },\n },\n },\n {\n type: \"RelatedPerson\",\n elements: {\n patient: { min: 1, max: 1, types: [\"Reference\"] },\n },\n },\n {\n type: \"DiagnosticReport\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n code: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n },\n },\n {\n type: \"Observation\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n code: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n },\n },\n {\n type: \"ServiceRequest\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n intent: { min: 1, max: 1, types: [\"code\"] },\n subject: { min: 1, max: 1, types: [\"Reference\"] },\n },\n },\n {\n type: \"MedicationRequest\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n intent: { min: 1, max: 1, types: [\"code\"] },\n subject: { min: 1, max: 1, types: [\"Reference\"] },\n medicationCodeableConcept: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n },\n },\n {\n // Immunization: status (1..1 code), vaccineCode (1..1 CodeableConcept), patient (1..1 Reference), and\n // occurrence[x] (1..1) are all required — the assembler only ever emits the occurrenceDateTime form, so\n // it is required here. An RXA with no groundable status/vaccine/occurrence, or no bundle Patient, is\n // withheld rather than emitted incomplete.\n type: \"Immunization\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n vaccineCode: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n patient: { min: 1, max: 1, types: [\"Reference\"] },\n occurrenceDateTime: { min: 1, max: 1, types: [\"dateTime\"] },\n },\n },\n {\n // Appointment: status (1..1 code) and participant (1..* BackboneElement) are both required — an\n // Appointment whose SCH-25 status could not be grounded via HL70278, or that has no resolvable Patient\n // participant, is withheld rather than emitted with a guessed status or no participant.\n type: \"Appointment\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n participant: { min: 1, max: UNBOUNDED, types: [\"BackboneElement\"] },\n },\n },\n {\n // DocumentReference: status (1..1 code) and content (1..* BackboneElement) are both required — a\n // reference whose TXA-19 is not \"AV\" (no groundable status), or that carries no document body from its\n // OBX segments, is withheld rather than emitted with a guessed status or referencing nothing.\n type: \"DocumentReference\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n content: { min: 1, max: UNBOUNDED, types: [\"BackboneElement\"] },\n },\n },\n]);\n","/**\n * VXU_V04 → FHIR `Immunization` — the thin IG single for immunization administration,\n * grounded firsthand on the IG **VXU_V04 message map** and the **RXA/RXR/ORC → Immunization**\n * segment maps (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-message-vxu-v04-to-bundle.json`,\n * `ConceptMap-segment-rxa-to-immunization.json`, `ConceptMap-segment-rxr-to-immunization.json`,\n * `ConceptMap-segment-orc-to-immunization.json`). Per the VXU message map, **each `ORC` creates an\n * `Immunization`** and the `RXA` (+ `RXR` route) in the same order group are *incorporated into it*, so\n * one builder consumes all three; the order-group `OBX`s become standalone patient `Observation`s\n * (`Observation[2]` in the IG bundle), handled by the assembler.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | RXA-5 Administered Code (CE) | `vaccineCode` (required 1..1) | {@link toFhirCodeableConcept} (structural — no IG value map) |\n * | RXA-3 Date/Time Start of Administration (DTM) | `occurrenceDateTime` (required, occurrence[x]) | {@link toFhirDateTime} |\n * | RXA-20 Completion Status + RXA-21 Action Code | `status` (required 1..1) | {@link buildStatus} (HL70322 + IG assignments) |\n * | RXA-6 Administered Amount + RXA-7 Units | `doseQuantity` | {@link quantityFromRawMagnitude} |\n * | RXA-15 Substance Lot Number (ST) | `lotNumber` | verbatim |\n * | RXA-16 Substance Expiration Date (DT) | `expirationDate` (a `date`) | {@link toFhirDateTime}, date-only |\n * | RXA-18 Substance/Treatment Refusal Reason (CWE) | `statusReason` | {@link toFhirCodeableConcept} |\n * | RXA-19 Indication (CWE) | `reasonCode` | {@link toFhirCodeableConcept} |\n * | RXA-22 System Entry Date/Time (DTM) | `recorded` | {@link toFhirDateTime} (ORC-9 fallback) |\n * | RXR-1 Route (CWE) | `route` | {@link ROUTE_VALUE_MAP} (HL70162, value-translated) |\n * | RXR-2 Administration Site (CWE) | `site` | {@link SITE_VALUE_MAP} (HL70550, value-translated) |\n * | ORC-2 / ORC-3 Placer/Filler Order Number | `identifier` (PLAC / FILL) | {@link orderIdentifier} |\n * | ORC-9 Date/Time of Order Event | `recorded` (fallback) | {@link toFhirDateTime} |\n * | (message-map wiring) | `patient` (required 1..1) / `encounter` | the bundle's Patient / Encounter |\n *\n * **Fail-safes (never a confident wrong immunization record).**\n * - **`status` (required 1..1).** The IG ships **three conditioned status rows** (verified firsthand\n * against `ConceptMap-segment-rxa-to-immunization.json`): **RXA-21 = \"D\"** (delete) → the IG-assigned\n * `entered-in-error`; **RXA-20 not valued and RXA-21 ≠ \"D\"** → the IG-assigned `completed`; **RXA-20\n * valued and RXA-21 ≠ \"D\"** → translated via {@link IMMUNIZATION_STATUS_MAP} (the HL70322 →\n * event-status ConceptMap, whose targets `completed`/`not-done` are all valid `immunization-status`\n * members). A **valued** RXA-20 the HL70322 map has no target for is flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, `status` left absent, and the required-`status` emit gate\n * **withholds** the Immunization — never guessed, never coerced.\n * - **`vaccineCode` (required 1..1) + `occurrence[x]` (required 1..1) + `patient` (required 1..1).** An\n * absent RXA-5, RXA-3, or bundle Patient leaves the resource missing a required element, so it is\n * withheld by the emit gate rather than emitted incomplete.\n * - **Dose.** RXA-6/RXA-7 → `doseQuantity` via {@link quantityFromRawMagnitude}: precision-exact magnitude,\n * non-UCUM unit preserved verbatim with `.code`/`.system` absent + flagged — never a fabricated UCUM code.\n * - **Route/site value translation.** RXR-1 route → {@link ROUTE_VALUE_MAP} (HL70162) and\n * RXR-2 site → {@link SITE_VALUE_MAP} (HL70550) are value-translated additively (derived target coding\n * added, raw coding preserved); a code outside the table is preserved + flagged, never coerced.\n * - **`vaccineCode` is NOT value-translated — by grounding, not omission.** RXA-5 has **no** `mappedVia`\n * value ConceptMap in the IG's RXA→Immunization segment map (verified firsthand), so the code (typically\n * CVX) is carried **structurally** (system recognized, value preserved) — a translation is never\n * invented for it.\n *\n * Deferred and flagged elsewhere, not silently mapped: RXA-10 performer, RXA-17 manufacturer, RXA-27/28\n * location, ORC-12 performer (all need Practitioner/Organization/Location resources this library does not\n * build).\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { quantityFromRawMagnitude } from \"../datatypes/quantity.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport {\n toFhirCodeableConceptVia,\n ROUTE_VALUE_MAP,\n SITE_VALUE_MAP,\n type CodedValueMap,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { orderIdentifier, reference } from \"./reference.js\";\n\n/**\n * HL7 v2 Table 0322 (Completion Status) → FHIR `Immunization.status`, per the IG **Table HL70322 to\n * Event Status** ConceptMap (each `is equivalent to`). Table 0322 has exactly these **four** source\n * codes and every one carries a target; the two distinct targets (`completed`, `not-done`) are both\n * valid members of the `immunization-status` required binding, so applying this map to\n * `Immunization.status` is faithful. Consulted only for a **valued** RXA-20 when **RXA-21 ≠ \"D\"** (the\n * IG's `mappedVia` condition on that row); the two other IG status rows assign fixed values directly (a\n * delete → `entered-in-error`, an unvalued RXA-20 → `completed`) and do not consult this map. See\n * {@link buildStatus}.\n */\nexport const IMMUNIZATION_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n CP: \"completed\",\n PA: \"completed\",\n RE: \"not-done\",\n NA: \"not-done\",\n});\n\n/** One VXU order group: an optional `ORC` anchor, its `RXA` administration, and the first `RXR` route. */\nexport interface ImmunizationGroup {\n /** The `ORC` segment that opened the order (supplies identifiers + a fallback `recorded`), if any. */\n readonly orc: Segment | undefined;\n /** The `RXA` administration segment — the Immunization's clinical core (vaccine, dose, status). */\n readonly rxa: Segment;\n /** The first `RXR` route/site segment beneath the administration, when present. */\n readonly rxr: Segment | undefined;\n}\n\ninterface MutableImmGroup {\n orc: Segment | undefined;\n rxa: Segment | undefined;\n rxr: Segment | undefined;\n}\n\n/**\n * Group a VXU message's `ORC`/`RXA`/`RXR` segments into immunization order groups. Per the VXU_V04\n * message map an `ORC` opens the order and the following `RXA` (+ `RXR`) is incorporated; an `RXA`\n * with no preceding open group anchors its own group (a bare administration). Only groups that carry\n * an `RXA` are returned — an `ORC` with no `RXA` has no vaccine to immunize and is dropped.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { groups } = collectImmunizationGroups(parseHL7(raw));\n * // groups[0]?.rxa; groups[0]?.rxr; groups[0]?.orc;\n * ```\n */\nexport function collectImmunizationGroups(msg: Hl7Message): readonly ImmunizationGroup[] {\n const groups: MutableImmGroup[] = [];\n let current: MutableImmGroup | undefined;\n\n const open = (): MutableImmGroup => {\n const g: MutableImmGroup = { orc: undefined, rxa: undefined, rxr: undefined };\n groups.push(g);\n current = g;\n return g;\n };\n\n for (const seg of msg.allSegments()) {\n switch (seg.type) {\n case \"ORC\":\n open().orc = seg;\n break;\n case \"RXA\":\n // Incorporate into the current ORC-opened group when it has no RXA yet; else open a bare group.\n if (current === undefined || current.rxa !== undefined) open();\n (current as MutableImmGroup).rxa = seg;\n break;\n case \"RXR\":\n // First route only (Immunization.route is 0..1); ignored if the group has no administration.\n if (current !== undefined && current.rxa !== undefined && current.rxr === undefined) {\n current.rxr = seg;\n }\n break;\n default:\n break;\n }\n }\n\n return groups\n .filter((g): g is MutableImmGroup & { rxa: Segment } => g.rxa !== undefined)\n .map((g) => ({ orc: g.orc, rxa: g.rxa, rxr: g.rxr }));\n}\n\n/** Build `Immunization.status` from RXA-20/RXA-21 per the IG's three conditioned status rows. */\nfunction buildStatus(rxa: Segment, issues: TransformIssue[]): string | undefined {\n const actionCode = rxa.field(21).value;\n // RXA-21 = \"D\" (delete): the IG assigns `status = \"entered-in-error\"` (the FHIR retraction state).\n if (actionCode === \"D\") return \"entered-in-error\";\n const completion = rxa.field(20).value;\n // RXA-20 not valued (and not a delete): the IG assigns `status = \"completed\"`.\n if (completion === \"\") return \"completed\";\n // RXA-20 valued: translate via HL70322 → event-status; a code with no target is flagged (the\n // resource is then withheld by the required-status emit gate), never guessed.\n const mapped = Object.hasOwn(IMMUNIZATION_STATUS_MAP, completion)\n ? IMMUNIZATION_STATUS_MAP[completion]\n : undefined;\n if (mapped === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"RXA.20\", \"Immunization.status\"));\n }\n return mapped;\n}\n\n/**\n * Value-translate an RXR CWE field (route/site) to a CodeableConcept via a license-clean\n * {@link CodedValueMap} (HL70162 route / HL70550 site), additive and fail-safe; `undefined` when empty.\n */\nfunction translatedFrom(\n seg: Segment,\n index: number,\n map: CodedValueMap,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (seg.field(index).value === \"\") return undefined;\n const cc = toFhirCodeableConceptVia(seg.field(index).asCwe(), map, ctx);\n issues.push(...cc.issues);\n return cc.value;\n}\n\n/**\n * Build a FHIR `Immunization` resource node from a VXU order group's `RXA` (+ `RXR`, `ORC`). Returns\n * `{ value: undefined }` when RXA-5 (the vaccine code, required 1..1) is absent. `status`,\n * `occurrenceDateTime`, and `patient` are all required 1..1; when any cannot be grounded the resource is\n * left incomplete and later **withheld** by the conservative-emit gate — never guessed.\n *\n * @param rxa - The `RXA` `@cosyte/hl7` `Segment` (the administration).\n * @param rxr - The first `RXR` route/site `Segment` beneath the administration, when present.\n * @param orc - The `ORC` `Segment` that opened the order, when present (identifiers + `recorded` fallback).\n * @param patientFullUrl - The bundle's Patient fullUrl → `Immunization.patient` (required 1..1).\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `Immunization.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const rxa = parseHL7(raw).segments(\"RXA\")[0];\n * // const { value } = buildImmunization(rxa!, undefined, undefined, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildImmunization(\n rxa: Segment,\n rxr: Segment | undefined,\n orc: Segment | undefined,\n patientFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // RXA-5 → vaccineCode (required 1..1). Absent → nothing emittable.\n if (rxa.field(5).value === \"\") return { value: undefined, issues };\n const vaccineCode = toFhirCodeableConcept(rxa.field(5).asCwe(), ctx);\n issues.push(...vaccineCode.issues);\n if (vaccineCode.value === undefined) return { value: undefined, issues };\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Immunization\") },\n ];\n\n // ORC-2 / ORC-3 → identifier (PLAC / FILL, v2-0203 types).\n if (orc !== undefined) {\n const identifiers = [\n orderIdentifier(orc.field(2).value, \"PLAC\"),\n orderIdentifier(orc.field(3).value, \"FILL\"),\n ].filter((i): i is FhirComplex => i !== undefined);\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n }\n\n // RXA-20/RXA-21 → status (required 1..1). Absent/unmapped → left absent (emit gate withholds).\n const status = buildStatus(rxa, issues);\n if (status !== undefined) props.push({ name: \"status\", value: primitive(status) });\n\n props.push({ name: \"vaccineCode\", value: vaccineCode.value });\n\n // patient / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (patientFullUrl !== undefined)\n props.push({ name: \"patient\", value: reference(patientFullUrl) });\n if (encounterFullUrl !== undefined)\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n\n // RXA-3 → occurrenceDateTime (required, occurrence[x]). Absent → emit gate withholds.\n if (rxa.field(3).value !== \"\") {\n const occurrence = toFhirDateTime(rxa.field(3).asTs(), ctx.options);\n issues.push(...occurrence.issues);\n if (occurrence.value !== undefined)\n props.push({ name: \"occurrenceDateTime\", value: primitive(occurrence.value) });\n }\n\n // RXA-22 → recorded (a dateTime; date-only ok), falling back to ORC-9 when RXA-22 is unvalued.\n const recordedTs =\n rxa.field(22).value !== \"\"\n ? rxa.field(22).asTs()\n : orc !== undefined && orc.field(9).value !== \"\"\n ? orc.field(9).asTs()\n : undefined;\n if (recordedTs !== undefined) {\n const recorded = toFhirDateTime(recordedTs, ctx.options);\n issues.push(...recorded.issues);\n if (recorded.value !== undefined)\n props.push({ name: \"recorded\", value: primitive(recorded.value) });\n }\n\n // RXA-6 / RXA-7 → doseQuantity (magnitude precision-exact; non-UCUM unit preserved verbatim).\n const doseRaw = rxa.field(6).asNm().raw;\n if (doseRaw !== \"\") {\n const dose = quantityFromRawMagnitude(\n doseRaw,\n rxa.field(7).asCwe(),\n ctx,\n undefined,\n \"RXA.6\",\n \"RXA.7\",\n );\n issues.push(...dose.issues);\n if (dose.value !== undefined) props.push({ name: \"doseQuantity\", value: dose.value });\n }\n\n // RXA-15 → lotNumber (verbatim string).\n if (rxa.field(15).value !== \"\")\n props.push({ name: \"lotNumber\", value: primitive(rxa.field(15).value) });\n\n // RXA-16 → expirationDate (a FHIR `date`): emit only a date-precision value; a value carrying a\n // time-of-day is not a valid `date` and is dropped + flagged rather than truncated silently.\n if (rxa.field(16).value !== \"\") {\n const exp = toFhirDateTime(rxa.field(16).asTs(), ctx.options);\n issues.push(...exp.issues);\n if (exp.value !== undefined && !exp.value.includes(\"T\")) {\n props.push({ name: \"expirationDate\", value: primitive(exp.value) });\n } else if (exp.value !== undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"RXA.16\", \"Immunization.expirationDate\"),\n );\n }\n }\n\n // RXA-18 → statusReason; RXA-19 → reasonCode.\n if (rxa.field(18).value !== \"\") {\n const reason = toFhirCodeableConcept(rxa.field(18).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"statusReason\", value: reason.value });\n }\n if (rxa.field(19).value !== \"\") {\n const indication = toFhirCodeableConcept(rxa.field(19).asCwe(), ctx);\n issues.push(...indication.issues);\n if (indication.value !== undefined)\n props.push({ name: \"reasonCode\", value: list([indication.value]) });\n }\n\n // RXR-1 → route (HL70162); RXR-2 → site (HL70550) — both value-translated via their license-clean maps.\n if (rxr !== undefined) {\n const route = translatedFrom(rxr, 1, ROUTE_VALUE_MAP, ctx, issues);\n if (route !== undefined) props.push({ name: \"route\", value: route });\n const site = translatedFrom(rxr, 2, SITE_VALUE_MAP, ctx, issues);\n if (site !== undefined) props.push({ name: \"site\", value: site });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * RXO (+ RXR route) → FHIR `MedicationRequest` — the pharmacy-order request,\n * grounded firsthand on the IG **Segment RXO to MedicationRequest** and **Segment RXR to\n * MedicationRequest** ConceptMaps (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-rxo-to-medicationrequest.html`, `ConceptMap-segment-rxr-to-medicationrequest.html`).\n * Per the **ORM_O01 message map**, an `RXO` in the order-detail is a `MedicationRequest`; the `ORC`\n * that opened the order supplies `authoredOn`.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | RXO-1 Requested Give Code (CWE) | `medicationCodeableConcept` | {@link toFhirCodeableConcept} |\n * | RXO-2 / RXO-3 Give Amount Min/Max (NM) | `dosageInstruction.doseAndRate.doseRange.low`/`.high` | {@link quantityFromRawMagnitude} + RXO-4 units |\n * | RXO-11 / RXO-12 Requested Dispense Amount / Units | `dispenseRequest.quantity` | {@link quantityFromRawMagnitude} |\n * | RXO-13 Number of Refills (NM) | `dispenseRequest.numberOfRepeatsAllowed` (unsignedInt) | integer-valued `decimal` |\n * | RXR-1 Route (CWE) | `dosageInstruction.route` | {@link ROUTE_VALUE_MAP} (HL70162, value-translated) |\n * | RXR-2 Site (CWE) | `dosageInstruction.site` | {@link SITE_VALUE_MAP} (HL70550, value-translated) |\n * | RXR-4 Method (CWE) | `dosageInstruction.method` | {@link toFhirCodeableConcept} (structural — SNOMED target, BYO) |\n * | RXO-9 Allow Substitutions (CWE) | `substitution.allowedCodeableConcept` | {@link SUBSTITUTION_VALUE_MAP} (HL70161) |\n * | ORC-9 Date/Time of Order Event | `authoredOn` | {@link toFhirDateTime}, *IF ORC-1 = `NW`* |\n * | (order message context) | `intent` = `order` | see below |\n * | (message-map wiring) | `subject` / `encounter` | the bundle's Patient / Encounter |\n *\n * **Fail-safes (never a confident wrong medication order).**\n * - **`medication[x]` (required 1..1).** Emitted as `medicationCodeableConcept` from RXO-1 only; a\n * pharmacy order with no give code has nothing to prescribe and is not built (`{ value: undefined }`).\n * The ingredient/strength paths (RXO-5/18/19/25/26 → a *contained* `Medication` with `ingredient`)\n * and `medicationReference` are deferred, not fabricated.\n * - **`status` (required 1..1) = `unknown` + flag.** Unlike `ServiceRequest`, the IG ships **no**\n * status source for `MedicationRequest` at all — there is no RXO→status row and no orc-to-\n * medicationrequest map, and the `request-status` codes HL70119 yields (`revoked`, …) are **not**\n * valid `medicationrequest-status` codes, so borrowing that table would emit invalid FHIR. Rather\n * than guess a clinical state, `status` is set to the value-set's own `unknown` (an honest\n * \"not known\", asserting nothing) and flagged {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}.\n * - **`intent` (required 1..1) = `order`.** The IG maps RXO → `intent` `equivalent` with no value\n * ConceptMap; the ORM_O01 family is an *order* message, so `intent` is fixed to `order` from that\n * message context — a resource-level constant, not a fabricated per-code row (as for `ServiceRequest`).\n * - **Dose/dispense units.** Carried through {@link quantityFromRawMagnitude}: a magnitude is\n * precision-exact (string-backed `decimal`, never rescaled), and a non-UCUM unit is preserved\n * verbatim in `.unit` with `.code`/`.system` absent + flagged — a UCUM code is never fabricated.\n * - **Route/site value translation.** RXR-1 route → {@link ROUTE_VALUE_MAP} (HL70162: a\n * 41-code identity group into `v2-0162` plus a 6-code remap into `v3-RouteOfAdministration` —\n * `IM→IM`, `SC→SQ`, …) and RXR-2 site → {@link SITE_VALUE_MAP} (HL70550: 443-code identity into\n * `v2-0550`). Both are additive: the derived target coding is added and the raw coding preserved; a\n * code outside the table is preserved + flagged, never coerced. RXR-4 method's IG target is SNOMED CT\n * (encumbered — **not bundled**), so method stays structurally carried (BYO), never SNOMED-translated.\n * - **Substitution.** RXO-9 → `substitution.allowedCodeableConcept` via\n * {@link SUBSTITUTION_VALUE_MAP} (HL70161 `N`/`G`/`T` identity into `v2-0161`). A valued RXO-9 the map\n * has no target for is flagged and the **substitution backbone is withheld** — a substitution\n * permission (whether the pharmacist may swap the drug) is never emitted from an unrecognized code.\n *\n * **`RXE` is out of scope by grounding, not omission.** The STU1 IG ships no `RXE` segment map and no\n * `RDE`/`RGV` message map; the assembler flags any `RXE` rather than mapping it here (an RXE layout is\n * never guessed from the RXO map — the field positions differ).\n *\n * @packageDocumentation\n */\n\nimport type { CWE, Segment } from \"@cosyte/hl7\";\nimport { complex, decimal, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { quantityFromRawMagnitude } from \"../datatypes/quantity.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport {\n codeableConceptFromTarget,\n toFhirCodeableConceptVia,\n translateBound,\n ROUTE_VALUE_MAP,\n SITE_VALUE_MAP,\n SUBSTITUTION_VALUE_MAP,\n type CodedValueMap,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/** The `medicationrequest-status` code emitted when the IG grounds no status (an honest \"not known\"). */\nconst STATUS_UNKNOWN = \"unknown\";\n/** The `medicationrequest Intent` code fixed for order-message requests (see the module fail-safe note). */\nconst ORDER_INTENT = \"order\";\n/** A FHIR `unsignedInt` lexical form: `0` or a leading-non-zero positive integer (no sign, no leading zero). */\nconst UNSIGNED_INT = /^(0|[1-9][0-9]*)$/;\n\n/**\n * Build a `dosageInstruction.method` CodeableConcept from RXR-4 **structurally** (no value translation).\n * The IG maps RXR-4 → method via `table-hl70165-to-sct`, whose target is **SNOMED CT** — license-\n * encumbered and **not bundled**. So the code is carried structurally (system recognized if the\n * CWE declares one, else flagged) and the SNOMED translation is left BYO — never fabricated here.\n */\nfunction codeableFrom(\n seg: Segment,\n index: number,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (seg.field(index).value === \"\") return undefined;\n const cc = toFhirCodeableConcept(seg.field(index).asCwe(), ctx);\n issues.push(...cc.issues);\n return cc.value;\n}\n\n/** Value-translate an RXR CWE field to a CodeableConcept via a license-clean {@link CodedValueMap}. */\nfunction translatedFrom(\n seg: Segment,\n index: number,\n map: CodedValueMap,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (seg.field(index).value === \"\") return undefined;\n const cc = toFhirCodeableConceptVia(seg.field(index).asCwe(), map, ctx);\n issues.push(...cc.issues);\n return cc.value;\n}\n\n/** Build a dose-range endpoint `Quantity` from an RXO amount field (NM) sharing the RXO-4 units. */\nfunction doseEndpoint(\n rxo: Segment,\n amountIndex: number,\n units: CWE,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const raw = rxo.field(amountIndex).asNm().raw;\n if (raw === \"\") return undefined;\n const q = quantityFromRawMagnitude(\n raw,\n units,\n ctx,\n undefined,\n `RXO.${String(amountIndex)}`,\n \"RXO.4\",\n );\n issues.push(...q.issues);\n return q.value;\n}\n\n/** Build the single `dosageInstruction` (route/site/method + dose range), or `undefined` when empty. */\nfunction buildDosageInstruction(\n rxo: Segment | undefined,\n rxr: Segment | undefined,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n\n if (rxr !== undefined) {\n // RXR-1 route / RXR-2 site are value-translated via the license-clean HL70162 / HL70550 maps.\n const route = translatedFrom(rxr, 1, ROUTE_VALUE_MAP, ctx, issues);\n if (route !== undefined) props.push({ name: \"route\", value: route });\n const site = translatedFrom(rxr, 2, SITE_VALUE_MAP, ctx, issues);\n if (site !== undefined) props.push({ name: \"site\", value: site });\n // RXR-4 method stays structural (its IG target is SNOMED CT — encumbered, BYO; see codeableFrom).\n const method = codeableFrom(rxr, 4, ctx, issues);\n if (method !== undefined) props.push({ name: \"method\", value: method });\n }\n\n if (rxo !== undefined) {\n const units = rxo.field(4).asCwe();\n const low = doseEndpoint(rxo, 2, units, ctx, issues);\n const high = doseEndpoint(rxo, 3, units, ctx, issues);\n const rangeProps: { name: string; value: FhirNode }[] = [];\n if (low !== undefined) rangeProps.push({ name: \"low\", value: low });\n if (high !== undefined) rangeProps.push({ name: \"high\", value: high });\n if (rangeProps.length > 0) {\n props.push({\n name: \"doseAndRate\",\n value: list([complex([{ name: \"doseRange\", value: complex(rangeProps) }])]),\n });\n }\n }\n\n return props.length === 0 ? undefined : complex(props);\n}\n\n/** Build `dispenseRequest` (RXO-11/12 quantity + RXO-13 refills), or `undefined` when empty. */\nfunction buildDispenseRequest(\n rxo: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n\n const amount = rxo.field(11).asNm().raw;\n if (amount !== \"\") {\n const q = quantityFromRawMagnitude(\n amount,\n rxo.field(12).asCwe(),\n ctx,\n undefined,\n \"RXO.11\",\n \"RXO.12\",\n );\n issues.push(...q.issues);\n if (q.value !== undefined) props.push({ name: \"quantity\", value: q.value });\n }\n\n const refills = rxo.field(13).value;\n if (refills !== \"\") {\n if (UNSIGNED_INT.test(refills)) {\n props.push({ name: \"numberOfRepeatsAllowed\", value: primitive(decimal(refills)) });\n } else {\n // A non-unsignedInt refill count is dropped rather than emitted as an invalid primitive.\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"RXO.13\",\n \"dispenseRequest.numberOfRepeatsAllowed\",\n ),\n );\n }\n }\n\n return props.length === 0 ? undefined : complex(props);\n}\n\n/**\n * Build a FHIR `MedicationRequest` resource node from an order group's `RXO` and `RXR` segments and\n * its opening `ORC`. Returns `{ value: undefined }` when RXO-1 (the give code) is absent — a\n * medication request with no `medication[x]` cannot be emitted.\n *\n * @param rxo - The `RXO` `@cosyte/hl7` `Segment` (the pharmacy order detail).\n * @param rxr - The first `RXR` route `Segment` beneath the order, when present.\n * @param orc - The `ORC` `Segment` that opened the order, when present (supplies `authoredOn`).\n * @param subjectFullUrl - The bundle's Patient fullUrl → `MedicationRequest.subject` (required 1..1).\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `MedicationRequest.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const rxo = parseHL7(raw).segments(\"RXO\")[0];\n * // const { value } = buildMedicationRequest(rxo, undefined, undefined, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildMedicationRequest(\n rxo: Segment | undefined,\n rxr: Segment | undefined,\n orc: Segment | undefined,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // RXO-1 → medicationCodeableConcept (required 1..1). Absent → nothing emittable.\n if (rxo === undefined || rxo.field(1).value === \"\") return { value: undefined, issues };\n const medication = toFhirCodeableConcept(rxo.field(1).asCwe(), ctx);\n issues.push(...medication.issues);\n if (medication.value === undefined) return { value: undefined, issues };\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"MedicationRequest\") },\n ];\n\n // status (required) = unknown — the IG grounds no MedicationRequest status; an honest \"not known\".\n props.push({ name: \"status\", value: primitive(STATUS_UNKNOWN) });\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"RXO\", \"MedicationRequest.status\"),\n );\n\n // intent (required) = order — the order-message context, not a per-code translation.\n props.push({ name: \"intent\", value: primitive(ORDER_INTENT) });\n\n props.push({ name: \"medicationCodeableConcept\", value: medication.value });\n\n // subject / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined)\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n\n // ORC-9 → authoredOn, only for a new order (ORC-1 = NW). authoredOn is a `dateTime` (date-only ok).\n if (orc !== undefined && orc.field(1).value === \"NW\" && orc.field(9).value !== \"\") {\n const authored = toFhirDateTime(orc.field(9).asTs(), ctx.options);\n issues.push(...authored.issues);\n if (authored.value !== undefined)\n props.push({ name: \"authoredOn\", value: primitive(authored.value) });\n }\n\n const dosage = buildDosageInstruction(rxo, rxr, ctx, issues);\n if (dosage !== undefined) props.push({ name: \"dosageInstruction\", value: list([dosage]) });\n\n const dispense = buildDispenseRequest(rxo, ctx, issues);\n if (dispense !== undefined) props.push({ name: \"dispenseRequest\", value: dispense });\n\n // RXO-9 → substitution.allowedCodeableConcept (HL70161 → v2-0161; value-translated, translate-or-\n // withhold). Only N/G/T carry a target; a valued RXO-9 the map has no target for is flagged and the\n // substitution backbone is withheld rather than emitted with a fabricated substitution permission.\n const cwe9 = rxo.field(9).asCwe();\n if (cwe9.identifier !== undefined && cwe9.identifier !== \"\") {\n // translateBound withholds a translation for a foreign coding system (CWE.3 ≠ HL70161) too, not\n // just an unmapped code — a substitution permission is never asserted from a non-v2-0161 code.\n const target = translateBound(cwe9, SUBSTITUTION_VALUE_MAP);\n if (target === undefined) {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_CODE_UNMAPPED,\n \"RXO.9\",\n \"MedicationRequest.substitution.allowedCodeableConcept\",\n ),\n );\n } else {\n props.push({\n name: \"substitution\",\n value: complex([\n {\n name: \"allowedCodeableConcept\",\n value: codeableConceptFromTarget(target, cwe9.originalText),\n },\n ]),\n });\n }\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * MSH → FHIR `MessageHeader` — grounded on the IG **Segment MSH to MessageHeader** ConceptMap\n * (`hl7.fhir.uv.v2mappings`, STU1), scoped to the R4 elements that can be produced faithfully:\n *\n * | MSH field | FHIR target | note |\n * |---|---|---|\n * | MSH-9 Message Type (trigger event) | `MessageHeader.eventCoding` | v2-0003 event-type system |\n * | MSH-3 Sending Application (HD) | `MessageHeader.source.name` / `.endpoint` | endpoint is a URL; an app namespace is not one |\n *\n * R4 requires `MessageHeader.source.endpoint` (1..1, a URL). An MSH-3 application *namespace* is not a\n * URL, so rather than fabricate one, the endpoint is emitted with a `data-absent-reason` extension\n * (value `unknown`) and flagged {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN} — the\n * spec-clean way to satisfy a required primitive whose value is genuinely unknown. `MessageHeader.focus`\n * wires the header to the message's focal resources (Patient, Encounter). MSH-10 (message control id)\n * is carried on `Bundle.identifier` by the assembler (R4 `MessageHeader` has no identifier element);\n * MSH-4/5/6 sender/destination Organizations and MessageHeader.timestamp (an R5 element) are deferred.\n *\n * @packageDocumentation\n */\n\nimport type { Meta } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport { coding, dataAbsent, reference } from \"./reference.js\";\n\n/** HL7 v2 Table 0003 (Event Type) canonical system — the `MessageHeader.eventCoding` code system. */\nconst V2_0003_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0003\";\n\n/**\n * Build a FHIR `MessageHeader` resource node from the MSH-derived message metadata.\n *\n * @param meta - The `@cosyte/hl7` `Meta` view (MSH-derived).\n * @param focusFullUrls - The `urn:uuid:` fullUrls of the message's focal resources (Patient,\n * Encounter), wired into `MessageHeader.focus`.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildMessageHeader(parseHL7(raw).meta, [\"urn:uuid:1-2-3\"]);\n * ```\n */\nexport function buildMessageHeader(\n meta: Meta,\n focusFullUrls: readonly string[],\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"MessageHeader\") },\n ];\n\n // MSH-9 trigger event → MessageHeader.eventCoding (Table 0003).\n const eventCoding = coding(V2_0003_SYSTEM, meta.triggerEvent);\n if (eventCoding !== undefined) {\n props.push({ name: \"eventCoding\", value: eventCoding });\n } else {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"MSH.9\", \"MessageHeader.eventCoding\"));\n }\n\n // MSH-3 → MessageHeader.source. endpoint (a URL) is required by R4 but an app namespace is not a\n // URL, so it is emitted data-absent (unknown) rather than fabricated.\n const sourceProps: { name: string; value: FhirNode }[] = [];\n if (meta.sendingApp !== undefined && meta.sendingApp !== \"\") {\n sourceProps.push({ name: \"name\", value: primitive(meta.sendingApp) });\n }\n sourceProps.push({ name: \"endpoint\", value: dataAbsent(\"unknown\") });\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"MSH.3\", \"MessageHeader.source.endpoint\"),\n );\n props.push({ name: \"source\", value: complex(sourceProps) });\n\n // MessageHeader.focus → the focal resources of the message.\n if (focusFullUrls.length > 0) {\n props.push({ name: \"focus\", value: list(focusFullUrls.map((url) => reference(url))) });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * OBX → FHIR `Observation` — the highest-clinical-stakes segment map,\n * grounded firsthand on the IG **Segment OBX to Observation** ConceptMap plus its two governing table\n * ConceptMaps (`hl7.fhir.uv.v2mappings`, STU1). The rows used here, verified against the published maps\n * (`ConceptMap-segment-obx-to-observation.html`, `-table-hl70078-to-v3-observationinterpretation.html`,\n * `-table-hl70085-to-observation-status.html`):\n *\n * | OBX field | FHIR target | via |\n * |---|---|---|\n * | OBX-2 Value Type | discriminates OBX-5 → `value[x]` | {@link buildValue} — never assume `Quantity` |\n * | OBX-3 Observation Identifier (CWE) | `Observation.code` | {@link toFhirCodeableConcept} |\n * | OBX-5 Observation Value | `Observation.value[x]` | per OBX-2 |\n * | OBX-6 Units (CWE) | `valueQuantity.unit`/`.code`/`.system` | {@link quantityFromRawMagnitude} |\n * | OBX-7 Reference Range | `Observation.referenceRange.text` | mapped to `.text` (never decomposed) |\n * | OBX-8 Abnormal Flags | `Observation.interpretation` | {@link HL70078_INTERPRETATION_CODES} |\n * | OBX-11 Result Status | `Observation.status` | {@link OBSERVATION_STATUS_MAP} (HL70085) |\n * | OBX-14 Date/Time of Observation | `Observation.effectiveDateTime` | {@link toFhirDateTime} |\n *\n * **The \"never a confident wrong result\" fail-safes:**\n * - **OBX-2 drives `value[x]`.** `NM`→`valueQuantity`, `CWE`/`CE`/`CF`/`CNE`/`IS`→`valueCodeableConcept`,\n * `SN`→structured (`valueQuantity` with a comparator / `valueRange` / `valueRatio`), `ST`/`TX`/`FT`→\n * `valueString`. A value type with no first-class target here (`NA`, `ED`, `DR`, `TM`, `NR`, unknown)\n * preserves the raw value as `valueString` and flags {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED}\n * (the richer FHIR type is deferred) — never a fabricated `Quantity`.\n * - **A corrected/cancelled result never emits as `final`.** OBX-11 `C`→`corrected`, `X`→`cancelled`,\n * `D`/`W`→`entered-in-error` (HL70085). A status code with **no** HL70085 target leaves\n * `Observation.status` absent (flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}); the required-`status`\n * emit gate then **withholds** the Observation rather than shipping it — never coerced to `final`.\n * - **An unrecognized abnormal flag is surfaced, never coerced to normal.** Each OBX-8 flag in\n * {@link HL70078_INTERPRETATION_CODES} becomes an `interpretation` coding (the map is code-preserving);\n * a flag absent from the table is flagged and dropped, never emitted as `N`/normal.\n *\n * Numeric magnitudes (NM, SN) are read from the **raw OBX-5 field** — not the `@cosyte/hl7`\n * `Observation` view's JS `number` — so a reported lab value's exact lexical precision (`120.50`) is\n * carried through the string-backed FHIR `decimal`, never routed through a lossy `number`.\n *\n * @packageDocumentation\n */\n\nimport type { CWE, Field, Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { quantityFromRawMagnitude } from \"../datatypes/quantity.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/** The v3 ObservationInterpretation canonical system (FHIR `Observation.interpretation` binding). */\nconst V3_OBSERVATION_INTERPRETATION_SYSTEM =\n \"http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation\";\n\n/**\n * HL7 v2 Table 0078 (Abnormal Flags) → FHIR v3 ObservationInterpretation (`Observation.interpretation`),\n * per the IG **Table HL70078 to v3 ObservationInterpretation** ConceptMap. Every mapped row is\n * `is equivalent to` an **identically-spelled** v3 code (the map is code-preserving), so this is the set\n * of codes that carry a target — a flag **absent** from this set has no equivalent and is flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, never coerced (the IG leaves `AC`/`HM`/`OBX`/`QCF`/`TOX`\n * and any local flag unmapped, and declares no `unmapped` default).\n */\nexport const HL70078_INTERPRETATION_CODES: ReadonlySet<string> = new Set([\n \"<\",\n \">\",\n \"A\",\n \"AA\",\n \"B\",\n \"CAR\",\n \"D\",\n \"DET\",\n \"E\",\n \"EX\",\n \"EXP\",\n \"H\",\n \"HH\",\n \"HU\",\n \"I\",\n \"IE\",\n \"IND\",\n \"L\",\n \"LL\",\n \"LU\",\n \"MS\",\n \"N\",\n \"NCL\",\n \"ND\",\n \"NEG\",\n \"NR\",\n \"NS\",\n \"POS\",\n \"R\",\n \"RR\",\n \"S\",\n \"SDD\",\n \"SYN-R\",\n \"SYN-S\",\n \"U\",\n \"UNE\",\n \"VS\",\n \"W\",\n \"WR\",\n]);\n\n/**\n * HL7 v2 Table 0085 (Observation Result Status) → FHIR `observation-status` (`Observation.status`),\n * per the IG **Table HL70085 to Observation Status** ConceptMap (each `is equivalent to`). Only these\n * seven source codes carry a target; the codes the IG leaves unmapped (`B`, `I`, `N`, `O`, `R`, `S`,\n * `U`, `V`) are **absent here on purpose** — an OBX-11 with one of them (or any local code) leaves\n * `Observation.status` absent + flagged, and the required-`status` emit gate withholds the Observation.\n * **`C`→`corrected` and `X`→`cancelled` guarantee a corrected/cancelled result never emits as `final`.**\n */\nexport const OBSERVATION_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n A: \"amended\",\n C: \"corrected\",\n D: \"entered-in-error\",\n F: \"final\",\n P: \"preliminary\",\n W: \"entered-in-error\",\n X: \"cancelled\",\n});\n\n/** The FHIR `Quantity.comparator` codes an SN.1 comparator can populate (SN `=`/`<>` do not). */\nconst SN_COMPARATORS: ReadonlySet<string> = new Set([\">\", \"<\", \">=\", \"<=\"]);\n\n/** OBX-2 value types the IG maps to `valueCodeableConcept`. */\nconst CODED_VALUE_TYPES: ReadonlySet<string> = new Set([\"CWE\", \"CE\", \"CF\", \"CNE\", \"IS\"]);\n/** OBX-2 value types the IG maps to `valueDateTime`. */\nconst DATETIME_VALUE_TYPES: ReadonlySet<string> = new Set([\"DT\", \"DTM\", \"TS\"]);\n/** OBX-2 value types the IG maps directly to `valueString`. */\nconst STRING_VALUE_TYPES: ReadonlySet<string> = new Set([\"ST\", \"TX\", \"FT\"]);\n\n/** The decoded first-subcomponent of a field's component at 0-based `index`, or `undefined` when empty. */\nfunction rawComponent(field: Field, index: number): string | undefined {\n const c = field.repetitions[0]?.components[index]?.subcomponents[0];\n return c === undefined || c === \"\" ? undefined : c;\n}\n\n/** Reconstruct an SN's human string (`>90`, `10-20`, `1:2`) from its raw components — for a fallback. */\nfunction snText(field: Field): string {\n return [0, 1, 2, 3].map((i) => rawComponent(field, i) ?? \"\").join(\"\");\n}\n\n/** A `valueString` property carrying the raw OBX-5 text (a faithful, never-fabricated fallback). */\nfunction valueStringProp(raw: string): { name: string; value: FhirNode } {\n return { name: \"valueString\", value: primitive(raw) };\n}\n\n/**\n * Build a FHIR `Quantity` node wrapped as a `valueRange`/`valueRatio` endpoint pair, or `undefined`\n * when either magnitude is not a faithful decimal. Both endpoints share the OBX-6 units.\n */\nfunction endpointPair(\n field: Field,\n units: CWE,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { first: FhirComplex; second: FhirComplex } | undefined {\n const n1 = rawComponent(field, 1);\n const n2 = rawComponent(field, 3);\n if (n1 === undefined || n2 === undefined) return undefined;\n const first = quantityFromRawMagnitude(n1, units, ctx);\n const second = quantityFromRawMagnitude(n2, units, ctx);\n issues.push(...first.issues, ...second.issues);\n if (first.value === undefined || second.value === undefined) return undefined;\n return { first: first.value, second: second.value };\n}\n\n/**\n * SN (structured numeric) → `value[x]`, per the IG's OBX-2 = `SN` conditional: a separator `-` with two\n * numbers is a `valueRange`; a `:`/`/` separator is a `valueRatio`; a comparator with a single number is\n * a `valueQuantity` (comparator carried); anything else preserves the raw SN string as `valueString`.\n */\nfunction buildSnValue(\n field: Field,\n units: CWE,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { name: string; value: FhirNode } {\n const sn = field.asSn();\n const separator = sn?.separatorOrSuffix;\n\n if (separator === \"-\") {\n const pair = endpointPair(field, units, ctx, issues);\n if (pair !== undefined) {\n return {\n name: \"valueRange\",\n value: complex([\n { name: \"low\", value: pair.first },\n { name: \"high\", value: pair.second },\n ]),\n };\n }\n return valueStringProp(snText(field));\n }\n\n if (separator === \":\" || separator === \"/\") {\n const pair = endpointPair(field, units, ctx, issues);\n if (pair !== undefined) {\n return {\n name: \"valueRatio\",\n value: complex([\n { name: \"numerator\", value: pair.first },\n { name: \"denominator\", value: pair.second },\n ]),\n };\n }\n return valueStringProp(snText(field));\n }\n\n // Comparator + single number → valueQuantity. SN `<>` (unequal) has no FHIR comparator → string.\n const comparator = sn?.comparator;\n const num1 = rawComponent(field, 1);\n if (comparator !== \"<>\" && num1 !== undefined) {\n const fhirComparator =\n comparator !== undefined && SN_COMPARATORS.has(comparator) ? comparator : undefined;\n const q = quantityFromRawMagnitude(num1, units, ctx, fhirComparator);\n issues.push(...q.issues);\n if (q.value !== undefined) return { name: \"valueQuantity\", value: q.value };\n }\n return valueStringProp(snText(field));\n}\n\n/**\n * Discriminate OBX-5 by OBX-2 value type into the correct FHIR `Observation.value[x]` property, or\n * `undefined` when OBX-5 is empty. Never assumes `Quantity`; a value type with no first-class target\n * degrades to `valueString` + a {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} flag, never fabricated.\n */\nfunction buildValue(\n obx: Segment,\n valueType: string,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { name: string; value: FhirNode } | undefined {\n const field = obx.field(5);\n const rawValue = field.value;\n const vt = valueType.toUpperCase();\n\n if (vt === \"NM\") {\n const q = quantityFromRawMagnitude(field.asNm().raw, obx.field(6).asCwe(), ctx);\n issues.push(...q.issues);\n if (q.value !== undefined) return { name: \"valueQuantity\", value: q.value };\n // A present-but-non-decimal NM: preserve the raw text rather than drop the result.\n return rawValue === \"\" ? undefined : valueStringProp(rawValue);\n }\n\n if (vt === \"SN\") {\n if (rawValue === \"\" && snText(field) === \"\") return undefined;\n return buildSnValue(field, obx.field(6).asCwe(), ctx, issues);\n }\n\n if (CODED_VALUE_TYPES.has(vt)) {\n const cc = toFhirCodeableConcept(field.asCwe(), ctx);\n issues.push(...cc.issues);\n return cc.value === undefined ? undefined : { name: \"valueCodeableConcept\", value: cc.value };\n }\n\n if (DATETIME_VALUE_TYPES.has(vt)) {\n if (rawValue === \"\") return undefined;\n const dt = toFhirDateTime(field.asTs(), ctx.options);\n issues.push(...dt.issues);\n return dt.value === undefined\n ? undefined\n : { name: \"valueDateTime\", value: primitive(dt.value) };\n }\n\n if (rawValue === \"\") return undefined;\n if (STRING_VALUE_TYPES.has(vt)) return valueStringProp(rawValue);\n\n // A value type with no first-class FHIR value[x] here (NA, ED, RP, DR, TM, NR, ID, unknown): the raw\n // value is preserved as a string and the richer typed mapping is flagged as deferred — never guessed.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBX.5\", \"Observation.value[x]\"));\n return valueStringProp(rawValue);\n}\n\n/** Build `Observation.interpretation` from OBX-8 abnormal flags (HL70078), or `undefined` when none map. */\nfunction buildInterpretation(obx: Segment, issues: TransformIssue[]): FhirNode | undefined {\n const flags = obx\n .field(8)\n .repetitions.map((r) => r.components[0]?.subcomponents[0] ?? \"\")\n .filter((f) => f !== \"\");\n const codings: FhirComplex[] = [];\n for (const flag of flags) {\n if (HL70078_INTERPRETATION_CODES.has(flag)) {\n codings.push(\n complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V3_OBSERVATION_INTERPRETATION_SYSTEM) },\n { name: \"code\", value: primitive(flag) },\n ]),\n ]),\n },\n ]),\n );\n } else {\n // An unrecognized abnormal flag is surfaced and dropped — NEVER coerced to `N`/normal.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBX.8\", \"Observation.interpretation\"),\n );\n }\n }\n return codings.length === 0 ? undefined : list(codings);\n}\n\n/**\n * Build a FHIR `Observation` resource node from one parsed HL7 v2 OBX segment. Returns\n * `{ value: undefined }` when the OBX carries no observation identifier (OBX-3) — an Observation with\n * no `code` cannot be emitted. `Observation.status` is left absent (and the resource later withheld by\n * the emit gate) when OBX-11 is missing or has no HL70085 target — never guessed.\n *\n * @param obx - The OBX `@cosyte/hl7` `Segment`.\n * @param subjectFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient, wired to `Observation.subject`.\n * @param encounterFullUrl - The `urn:uuid:` fullUrl of the bundle's Encounter, wired to `.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const obx = parseHL7(raw).segments(\"OBX\")[0];\n * // const { value } = buildObservation(obx!, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildObservation(\n obx: Segment,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Observation\") },\n ];\n\n // OBX-11 → Observation.status (HL70085). Absent/unmapped → left absent (emit gate withholds), never\n // guessed; a corrected/cancelled status is modelled exactly, never emitted as `final`.\n const statusCode = obx.field(11).value;\n if (statusCode !== \"\") {\n const status = Object.hasOwn(OBSERVATION_STATUS_MAP, statusCode)\n ? OBSERVATION_STATUS_MAP[statusCode]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBX.11\", \"Observation.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // OBX-3 → Observation.code (required 1..1). Absent → nothing emittable.\n const code = toFhirCodeableConcept(obx.field(3).asCwe(), ctx);\n issues.push(...code.issues);\n if (code.value === undefined) return { value: undefined, issues };\n props.push({ name: \"code\", value: code.value });\n\n // Observation.subject / .encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined) {\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n }\n\n // OBX-14 → Observation.effectiveDateTime.\n if (obx.field(14).value !== \"\") {\n const effective = toFhirDateTime(obx.field(14).asTs(), ctx.options);\n issues.push(...effective.issues);\n if (effective.value !== undefined) {\n props.push({ name: \"effectiveDateTime\", value: primitive(effective.value) });\n }\n }\n\n // OBX-2 / OBX-5 → Observation.value[x] (value-type discriminated; never assume Quantity).\n const value = buildValue(obx, obx.field(2).value, ctx, issues);\n if (value !== undefined) props.push(value);\n\n // OBX-8 → Observation.interpretation (HL70078; unrecognized flag surfaced, never coerced to normal).\n const interpretation = buildInterpretation(obx, issues);\n if (interpretation !== undefined) props.push({ name: \"interpretation\", value: interpretation });\n\n // OBX-7 → Observation.referenceRange.text (the IG maps it to `.text`; never decomposed/evaluated).\n const refRange = obx.field(7).value;\n if (refRange !== \"\") {\n props.push({\n name: \"referenceRange\",\n value: list([complex([{ name: \"text\", value: primitive(refRange) }])]),\n });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * Order-message grouping — the message-map structure the ServiceRequest / MedicationRequest graph is\n * assembled over, grounded firsthand on the IG **ORM_O01** and **OML_O21** message\n * maps (`ConceptMap-message-orm-o01-to-bundle.html`, `ConceptMap-message-oml-o21-to-bundle.html`).\n *\n * Both message maps model the ORDER group the same way: **`ORC` creates the request** and the\n * following **ORDER_DETAIL** segment is *incorporated into that same request* — `OBR` →\n * `ServiceRequest`, `RXO` (+ `RXR` route) → `MedicationRequest`. So one order group is an `ORC`\n * anchor plus at most one order-detail segment (an `OBR` for a service order, an `RXO` for a\n * pharmacy order) and the `RXR` route segments beneath a pharmacy order. This walks the segments in\n * document order and buckets each detail segment under the most recent `ORC` — the same positional\n * grouping `@cosyte/hl7`'s `orders()` performs, done here so the raw `ORC`/`OBR`/`RXO`/`RXR`\n * `Segment`s (the request/dose fields the lean `Order` view omits) are available.\n *\n * A detail segment that precedes any `ORC` still anchors its own group (a bare `OBR`/`RXO` order),\n * and any `RXE` — for which the IG ships **no** segment map at all (verified against the STU1\n * artifacts index) — is counted by {@link OrderGrouping.rxeCount} so the assembler can flag it as\n * un-grounded rather than fabricate an RXE→MedicationRequest layout.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\n\n/** One order group: an optional `ORC` request anchor and its incorporated order-detail segments. */\nexport interface OrderGroup {\n /** The `ORC` segment anchoring this order (absent for a bare `OBR`/`RXO` with no preceding `ORC`). */\n readonly orc: Segment | undefined;\n /** The `OBR` order-detail segment → `ServiceRequest`, when this is a service order. */\n readonly obr: Segment | undefined;\n /** The `RXO` order-detail segment → `MedicationRequest`, when this is a pharmacy order. */\n readonly rxo: Segment | undefined;\n /** The `RXR` route segments beneath a pharmacy order (in document order). */\n readonly rxrs: readonly Segment[];\n}\n\n/** The result of grouping an order message: the order groups plus the count of un-mappable `RXE`s. */\nexport interface OrderGrouping {\n /** The order groups, in document order. */\n readonly groups: readonly OrderGroup[];\n /** The count of `RXE` segments — the IG ships no RXE map, so they are flagged, never assembled. */\n readonly rxeCount: number;\n}\n\ninterface MutableGroup {\n orc: Segment | undefined;\n obr: Segment | undefined;\n rxo: Segment | undefined;\n rxrs: Segment[];\n}\n\n/**\n * Group an order message's `ORC`/`OBR`/`RXO`/`RXR` segments into order groups (each `ORC` with the\n * order-detail segment incorporated into it, or a bare detail segment as its own group).\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { groups } = collectOrderGroups(parseHL7(raw));\n * // groups[0]?.orc; groups[0]?.obr; groups[0]?.rxo;\n * ```\n */\nexport function collectOrderGroups(msg: Hl7Message): OrderGrouping {\n const groups: MutableGroup[] = [];\n let current: MutableGroup | undefined;\n let rxeCount = 0;\n\n const open = (): MutableGroup => {\n const g: MutableGroup = { orc: undefined, obr: undefined, rxo: undefined, rxrs: [] };\n groups.push(g);\n current = g;\n return g;\n };\n\n for (const seg of msg.allSegments()) {\n switch (seg.type) {\n case \"ORC\":\n // A new ORC always opens a new order group (ORM/OML: one request per ORC).\n open().orc = seg;\n break;\n case \"OBR\":\n // Incorporate into the current group when it has no detail yet; else open a bare group.\n if (current === undefined || current.obr !== undefined || current.rxo !== undefined) open();\n (current as MutableGroup).obr = seg;\n break;\n case \"RXO\":\n if (current === undefined || current.obr !== undefined || current.rxo !== undefined) open();\n (current as MutableGroup).rxo = seg;\n break;\n case \"RXR\":\n // Route belongs to the current pharmacy order; harmless (unused) if the group has no RXO.\n if (current !== undefined) current.rxrs.push(seg);\n break;\n case \"RXE\":\n // No IG segment map exists for RXE — surfaced for a flag, never assembled.\n rxeCount += 1;\n break;\n default:\n break;\n }\n }\n\n return {\n groups: groups.map((g) => ({ orc: g.orc, obr: g.obr, rxo: g.rxo, rxrs: g.rxrs })),\n rxeCount,\n };\n}\n","/**\n * ORU^R01 order/result grouping — the message-map structure the DiagnosticReport/Observation graph is\n * assembled over, grounded on the IG **ORU_R01 message map**\n * (`ConceptMap-message-oru-r01-to-bundle.html`).\n *\n * An ORU message is a sequence of order groups, each an **OBR** followed by its **OBX** results. This\n * walks the segments in document order and buckets each OBX under the most recent OBR — the same\n * positional grouping `@cosyte/hl7`'s `orders()` performs, done here so the raw OBR/OBX `Segment`s are\n * available (the report/result fields the lean `Order` view omits — OBR-7/22/24/25 — and the exact\n * lexical OBX-5 magnitude the `Observation` view rounds to a JS `number`). An OBX that precedes any OBR\n * has no report to anchor it and is surfaced by {@link ReportGrouping.orphanObxCount} rather than\n * silently dropped.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\n\n/** One ORU report group: an OBR anchor and the OBX result segments beneath it, in document order. */\nexport interface ReportGroup {\n /** The OBR segment anchoring this report. */\n readonly obr: Segment;\n /** The OBX result segments grouped under this OBR (positional grouping). */\n readonly observations: readonly Segment[];\n}\n\n/** The result of grouping an ORU message: the report groups plus any OBX with no preceding OBR. */\nexport interface ReportGrouping {\n /** The OBR-anchored report groups, in document order. */\n readonly groups: readonly ReportGroup[];\n /** The count of OBX segments that appeared before any OBR (no report to anchor them). */\n readonly orphanObxCount: number;\n}\n\n/**\n * Group an ORU message's OBR/OBX segments into report groups (each OBR with its trailing OBX children).\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { groups } = collectReportGroups(parseHL7(raw));\n * // groups[0]?.obr; groups[0]?.observations.length;\n * ```\n */\nexport function collectReportGroups(msg: Hl7Message): ReportGrouping {\n const groups: { obr: Segment; observations: Segment[] }[] = [];\n let current: { obr: Segment; observations: Segment[] } | undefined;\n let orphanObxCount = 0;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"OBR\") {\n current = { obr: seg, observations: [] };\n groups.push(current);\n } else if (seg.type === \"OBX\") {\n if (current === undefined) orphanObxCount += 1;\n else current.observations.push(seg);\n }\n }\n\n return { groups, orphanObxCount };\n}\n","/**\n * PID → FHIR `Patient` — grounded on the IG **Segment PID to Patient** ConceptMap\n * (`hl7.fhir.uv.v2mappings`, STU1). The field→element rows used here, verified firsthand against the\n * published map:\n *\n * | PID field | FHIR target | via |\n * |---|---|---|\n * | PID-3 Patient Identifier List (CX) | `Patient.identifier` | {@link toFhirIdentifier} |\n * | PID-5 Patient Name (XPN) | `Patient.name` | {@link toFhirHumanName} |\n * | PID-7 Date/Time of Birth (DTM) | `Patient.birthDate` | {@link toFhirDateTime} reduced to a `date` |\n * | PID-8 Administrative Sex (CWE) | `Patient.gender` | {@link ADMINISTRATIVE_GENDER_MAP} (Table 0001) |\n * | PID-11 Patient Address (XAD) | `Patient.address` | {@link toFhirAddress} |\n *\n * Fail-safe throughout: each datatype conversion carries its own value-free issues, an unmapped\n * administrative-sex code leaves `gender` absent (never guessed), and a birth *time* (PID-7 with a\n * time-of-day) is dropped to `date` precision with a flag — the US Core `patient-birthTime` extension\n * is a profile concern this library does not cover. Deferred and flagged, not silently mapped:\n * PID-13/14 telecom (no XTN→ContactPoint converter), and PID-10/15/22/29/30 (US Core race/ethnicity\n * extensions, communication language, deceased).\n *\n * @packageDocumentation\n */\n\nimport type { Patient } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirIdentifier } from \"../datatypes/identifier.js\";\nimport { toFhirHumanName } from \"../datatypes/human-name.js\";\nimport { toFhirAddress } from \"../datatypes/address.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\n\n/**\n * HL7 v2 Table 0001 (Administrative Sex) → FHIR `administrative-gender`, exactly per the IG\n * **Table HL70001 to Administrative Gender** ConceptMap (every row \"is equivalent to\"). `A`\n * (Ambiguous) and `N` (Not applicable) both narrow to `other` — the map's stated equivalence, carried\n * as-is. A code absent here (the map defines no `unmapped` default) leaves `gender` absent and is\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} — never coerced to `unknown`.\n */\nexport const ADMINISTRATIVE_GENDER_MAP: Readonly<Record<string, string>> = Object.freeze({\n F: \"female\",\n M: \"male\",\n O: \"other\",\n U: \"unknown\",\n A: \"other\",\n N: \"other\",\n});\n\n/** Wrap present items as a FHIR list property value, or `undefined` when none are present. */\nfunction listOrUndefined(items: readonly FhirComplex[]): FhirNode | undefined {\n return items.length === 0 ? undefined : list(items);\n}\n\n/**\n * Build a FHIR `Patient` resource node from a parsed HL7 v2 PID view. Returns `{ value: undefined }`\n * only when the PID carried nothing emittable at all.\n *\n * @param patient - The `@cosyte/hl7` `Patient` view (PID-derived).\n * @param ctx - The transform context; `ctx.namingSystem` resolves identifier assigning authorities.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildPatient(parseHL7(raw).patient!, { namingSystem: createNamingSystem() });\n * ```\n */\nexport function buildPatient(patient: Patient, ctx: TransformContext): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Patient\") },\n ];\n\n // PID-3 → Patient.identifier (each CX repetition, fail-safe on the assigning authority).\n const identifiers: FhirComplex[] = [];\n for (const cx of patient.identifiers) {\n const { value, issues: idIssues } = toFhirIdentifier(cx, ctx);\n issues.push(...idIssues);\n if (value !== undefined) identifiers.push(value);\n }\n const identifierList = listOrUndefined(identifiers);\n if (identifierList !== undefined) props.push({ name: \"identifier\", value: identifierList });\n\n // PID-5 → Patient.name (first repetition; additional repetitions are a later-phase concern).\n const name = toFhirHumanName(patient.name);\n issues.push(...name.issues);\n if (name.value !== undefined) props.push({ name: \"name\", value: list([name.value]) });\n\n // PID-8 → Patient.gender via Table 0001; unmapped → absent + flagged (never guessed).\n if (patient.sex !== undefined && patient.sex !== \"\") {\n const gender = Object.hasOwn(ADMINISTRATIVE_GENDER_MAP, patient.sex)\n ? ADMINISTRATIVE_GENDER_MAP[patient.sex]\n : undefined;\n if (gender === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"PID.8\", \"Patient.gender\"));\n } else {\n props.push({ name: \"gender\", value: primitive(gender) });\n }\n }\n\n // PID-7 → Patient.birthDate. FHIR birthDate is a `date`; a birth time-of-day is dropped to date\n // precision (the birthTime extension is a Phase-8 profile concern) with a flag.\n if (patient.dateOfBirth !== undefined) {\n const dob = toFhirDateTime(patient.dateOfBirth, ctx.options);\n issues.push(...dob.issues);\n if (dob.value !== undefined) {\n const tIndex = dob.value.indexOf(\"T\");\n if (tIndex === -1) {\n props.push({ name: \"birthDate\", value: primitive(dob.value) });\n } else {\n props.push({ name: \"birthDate\", value: primitive(dob.value.slice(0, tIndex)) });\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PID.7\", \"Patient.birthDate\"));\n }\n }\n }\n\n // PID-11 → Patient.address (first repetition of the home address view).\n if (patient.address !== undefined) {\n const address = toFhirAddress(patient.address);\n issues.push(...address.issues);\n if (address.value !== undefined) props.push({ name: \"address\", value: list([address.value]) });\n }\n\n // PID-13/14 → Patient.telecom is deferred (no XTN→ContactPoint converter yet); flag the drop.\n if (patient.phoneNumbers.length > 0) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PID.13\", \"Patient.telecom\"));\n }\n\n // Only `resourceType` present → nothing emittable.\n if (props.length === 1) return { value: undefined, issues };\n return { value: complex(props), issues };\n}\n","/**\n * NK1 → FHIR `RelatedPerson` — grounded on the IG **Segment NK1 to RelatedPerson** ConceptMap\n * (`hl7.fhir.uv.v2mappings`, STU1), verified firsthand:\n *\n * | NK1 field | FHIR target | via |\n * |---|---|---|\n * | NK1-2 Name (XPN) | `RelatedPerson.name` | {@link toFhirHumanName} |\n * | NK1-3 Relationship (CWE) | `RelatedPerson.relationship` | {@link toFhirCodeableConcept} |\n * | NK1-4 Address (XAD) | `RelatedPerson.address` | {@link toFhirAddress} |\n *\n * `RelatedPerson.patient` is FHIR-required (1..1); the message structure supplies it — it is wired to\n * the bundle's Patient, so a RelatedPerson is produced only when a Patient was. Deferred and flagged,\n * not silently mapped: NK1-5/6 telecom (no XTN→ContactPoint converter yet), NK1-15 gender, NK1-16\n * birthDate, NK1-20 communication language (not surfaced by the `@cosyte/hl7` next-of-kin view).\n *\n * @packageDocumentation\n */\n\nimport type { NextOfKin } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirHumanName } from \"../datatypes/human-name.js\";\nimport { toFhirAddress } from \"../datatypes/address.js\";\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/**\n * Build a FHIR `RelatedPerson` resource node from a parsed HL7 v2 NK1 view. Always carries the\n * required `patient` reference to the bundle's Patient. Returns `{ value: undefined }` when the NK1\n * carried nothing beyond the patient link.\n *\n * @param nk1 - The `@cosyte/hl7` `NextOfKin` view (NK1-derived).\n * @param patientFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient (required by FHIR).\n * @param ctx - The transform context; `ctx.namingSystem` resolves the relationship coding system.\n * @param setIndex - The 0-based NK1 repetition index, for value-free issue locations.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildRelatedPerson(parseHL7(raw).nextOfKin()[0], \"urn:uuid:1-2-3\", {}, 0);\n * ```\n */\nexport function buildRelatedPerson(\n nk1: NextOfKin,\n patientFullUrl: string,\n ctx: TransformContext,\n setIndex: number,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const loc = `NK1[${String(setIndex)}]`;\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"RelatedPerson\") },\n { name: \"patient\", value: reference(patientFullUrl) },\n ];\n\n let hasContent = false;\n\n // NK1-3 → RelatedPerson.relationship.\n if (nk1.relationship !== undefined) {\n const rel = toFhirCodeableConcept(nk1.relationship, ctx);\n issues.push(...rel.issues);\n if (rel.value !== undefined) {\n props.push({ name: \"relationship\", value: list([rel.value]) });\n hasContent = true;\n }\n }\n\n // NK1-2 → RelatedPerson.name.\n if (nk1.name !== undefined) {\n const name = toFhirHumanName(nk1.name);\n issues.push(...name.issues);\n if (name.value !== undefined) {\n props.push({ name: \"name\", value: list([name.value]) });\n hasContent = true;\n }\n }\n\n // NK1-4 → RelatedPerson.address.\n if (nk1.address !== undefined) {\n const address = toFhirAddress(nk1.address);\n issues.push(...address.issues);\n if (address.value !== undefined) {\n props.push({ name: \"address\", value: list([address.value]) });\n hasContent = true;\n }\n }\n\n // NK1-5/6 → RelatedPerson.telecom is deferred (no XTN→ContactPoint converter yet); flag the drop.\n if (nk1.phone !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `${loc}.5`, \"RelatedPerson.telecom\"));\n }\n\n if (!hasContent) return { value: undefined, issues };\n return { value: complex(props), issues };\n}\n","/**\n * ORC + OBR → FHIR `ServiceRequest` — the order-entry request, grounded firsthand\n * on the IG **Segment ORC to ServiceRequest** and **Segment OBR to ServiceRequest** ConceptMaps and\n * the **Table HL70119 to Request Status** ConceptMap (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-orc-to-servicerequest.html`, `ConceptMap-segment-obr-to-servicerequest.html`,\n * `ConceptMap-table-hl70119-to-request-status.html`). Per the **ORM_O01 / OML_O21 message maps**,\n * `ORC` *creates* the `ServiceRequest` and `OBR` is *incorporated into that same* request, so one\n * builder consumes both:\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | ORC-1 Order Control | `ServiceRequest.status` | {@link REQUEST_STATUS_MAP} (HL70119), *only IF ORC-5 not valued* |\n * | ORC-2 / OBR-2 Placer Order Number | `identifier` (type `PLAC`) | {@link orderIdentifier} (EI.1, v2-0203) |\n * | ORC-3 / OBR-3 Filler Order Number | `identifier` (type `FILL`) | {@link orderIdentifier} |\n * | ORC-9 Date/Time of Order Event | `authoredOn` | {@link toFhirDateTime}, *IF ORC-1 = `NW`* |\n * | OBR-4 Universal Service Identifier (CWE) | `ServiceRequest.code` | {@link toFhirCodeableConcept} |\n * | OBR-5 Priority (v2-0485) | `ServiceRequest.priority` | {@link SERVICE_REQUEST_PRIORITY_MAP} (HL70485) |\n * | OBR-6 Requested Date/Time | `occurrenceDateTime` | {@link toFhirDateTime} |\n * | OBR-31 Reason for Study (CWE) | `reasonCode` | {@link toFhirCodeableConcept} |\n * | (order message context) | `intent` = `order` | see below |\n * | (message-map wiring) | `subject` / `encounter` | the bundle's Patient / Encounter |\n *\n * **Fail-safes (never a confident wrong request).**\n * - **`status` (required 1..1).** ORC-1 → HL70119 carries a target for only the 19 codes in\n * {@link REQUEST_STATUS_MAP}; the many codes the IG leaves in its `(unmapped)` group (CH, CP, PA,\n * RE, RF, RP, SC, the U* \"unable to …\" family, …) have **no** target and leave `status` absent +\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}. When **ORC-5** (Order Status) is valued the\n * IG routes status through ORC-5 via an *unspecified* mapping (no code table) — so we cannot derive\n * it, flag ORC-5 unmapped, and leave `status` absent rather than mis-applying the ORC-1 table\n * against the IG's own condition. The required-`status` emit gate then **withholds** the request —\n * never guessed, never coerced.\n * - **`intent` (required 1..1) = `order`.** The IG maps ORC-1/OBR → `intent` as `equivalent` but ships\n * **no value ConceptMap** for it; the ORM_O01/OML_O21 families are, by definition, *order* messages\n * (their message maps create a `ServiceRequest`/`MedicationRequest` per order), so `intent` is fixed\n * to the `request-intent` code `order` from that message context. This is a resource-level constant\n * grounded in the message family — **not** a fabricated per-code translation row. The finer\n * OBR-11-conditioned intent refinement is deferred.\n * - **`subject` (required 1..1).** Wired to the bundle's Patient; a request with no resolvable Patient\n * is withheld rather than emitted with a dangling/absent subject.\n *\n * - **`priority` (0..1) — value-translated.** OBR-5 → `ServiceRequest.priority` via the IG\n * **Table HL70485 to Request Priority** ConceptMap ({@link SERVICE_REQUEST_PRIORITY_MAP}): only\n * `S→stat`, `A→asap`, `R→routine` carry a target (each `equivalent`, and all three are valid\n * `request-priority` members). Every other v2-0485 code — `P`, `C`, `T`, the `T{S,M,H,D,W,L}<integer>`\n * timing-critical family, `PRN` — sits in the IG map's `(unmapped)` group, so a valued OBR-5 the map\n * has no target for leaves `priority` absent + flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED},\n * never guessed. (`priority` is 0..1, so an unmapped value simply omits it — the request still emits.)\n *\n * Deferred and flagged elsewhere, not silently mapped: ORC-7/OBR-27 timing (`$this`), ORC-12/OBR-16\n * requester + ORC-21..24 ordering facility/provider (need Practitioner/PractitionerRole/Organization\n * resources), OBR-29 basedOn, specimen, and the ORC-1/ORC-9/OBR-13 order-control/supporting-info\n * extensions.\n *\n * @packageDocumentation\n */\n\nimport type { Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { orderIdentifier, reference } from \"./reference.js\";\n\n/**\n * HL7 v2 Table 0119 (Order Control Codes) → FHIR `request-status` (`ServiceRequest.status`), per the\n * IG **Table HL70119 to Request Status** ConceptMap (each `is equivalent to`). Only these **19** source\n * codes carry a target; every other v2-0119 code sits in the IG's explicit `(unmapped)` group\n * (verified firsthand against the published v1.0.0 ConceptMap — CH/CN/CP/DE/LI/NA/OE/OF/OP/OR/PA/RE/\n * RF/RP/RR/RU/SC/SN/SR/SS/UA/UC/UD/UF/UH/UM/UN/UR/UX/XO/XR/XX/MC are all `unmatched`, and the map\n * declares no `unmapped` default), so an ORC-1 with one of them leaves `status` absent + flagged and\n * the request is withheld. `request-status` has no `cancelled`; the cancel/discontinue codes map to\n * `revoked` and the hold codes to `on-hold`, exactly as the IG table specifies.\n */\nexport const REQUEST_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n AF: \"active\",\n CA: \"active\",\n CR: \"revoked\",\n DC: \"revoked\",\n DF: \"revoked\",\n DR: \"revoked\",\n FU: \"completed\",\n HD: \"active\",\n HR: \"on-hold\",\n NW: \"active\",\n OC: \"revoked\",\n OD: \"revoked\",\n OH: \"on-hold\",\n OK: \"active\",\n PR: \"active\",\n PY: \"active\",\n RL: \"active\",\n RO: \"active\",\n RQ: \"active\",\n});\n\n/**\n * HL7 v2 Table 0485 (Extended Priority Codes) → FHIR `request-priority` (`ServiceRequest.priority`),\n * per the IG **Table HL70485 to Request Priority** ConceptMap (each `is equivalent to`; verified\n * firsthand against the published v1.0.0 ConceptMap). Only these **three** source codes carry a\n * target; every other v2-0485 code — `P` (Preop), `C` (Callback), `T` (Timing critical), the\n * `T{S,M,H,D,W,L}<integer>` timing-critical family, and `PRN` (As needed) — sits in the IG's\n * `(unmapped)` group with no target, so an OBR-5 carrying one leaves `priority` absent + flagged.\n * All three targets (`stat`/`asap`/`routine`) are valid `request-priority` members.\n */\nexport const SERVICE_REQUEST_PRIORITY_MAP: Readonly<Record<string, string>> = Object.freeze({\n S: \"stat\",\n A: \"asap\",\n R: \"routine\",\n});\n\n/** The `request-intent` code fixed for order-message requests (see the module fail-safe note). */\nconst ORDER_INTENT = \"order\";\n\n/** The decoded value of a field on an optional segment (empty string when the segment is absent). */\nfunction fieldValue(seg: Segment | undefined, index: number): string {\n return seg === undefined ? \"\" : seg.field(index).value;\n}\n\n/**\n * Build a FHIR `ServiceRequest` resource node from an order group's `ORC` and/or `OBR` segments.\n * Returns `{ value: undefined }` only when both segments are absent (nothing to build).\n * `ServiceRequest.status` is left absent (and the request withheld by the emit gate) when it cannot be\n * grounded via HL70119 — never guessed.\n *\n * @param orc - The `ORC` `@cosyte/hl7` `Segment`, when the order carries one.\n * @param obr - The `OBR` `@cosyte/hl7` `Segment`, when the order carries one.\n * @param subjectFullUrl - The bundle's Patient fullUrl → `ServiceRequest.subject` (required 1..1).\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `ServiceRequest.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const orc = parseHL7(raw).segments(\"ORC\")[0];\n * // const obr = parseHL7(raw).segments(\"OBR\")[0];\n * // const { value } = buildServiceRequest(orc, obr, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildServiceRequest(\n orc: Segment | undefined,\n obr: Segment | undefined,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n if (orc === undefined && obr === undefined) return { value: undefined, issues };\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"ServiceRequest\") },\n ];\n\n // ORC-1 → status (HL70119), only when ORC-5 is not valued; else the IG routes status through ORC-5\n // via an unspecified mapping (no code table) → cannot derive → flag, leave absent, withhold.\n const orc1 = fieldValue(orc, 1);\n const orc5 = fieldValue(orc, 5);\n if (orc5 !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"ORC.5\", \"ServiceRequest.status\"));\n } else if (orc1 !== \"\") {\n const status = Object.hasOwn(REQUEST_STATUS_MAP, orc1) ? REQUEST_STATUS_MAP[orc1] : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"ORC.1\", \"ServiceRequest.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // intent (required) = order — the order-message context, not a per-code translation (see module note).\n props.push({ name: \"intent\", value: primitive(ORDER_INTENT) });\n\n // ORC-2/OBR-2 (placer) + ORC-3/OBR-3 (filler) → identifier. The IG conditions each on the other\n // (\"OBR-2 IF ORC-2 NOT VALUED\" and vice-versa); prefer OBR, fall back to ORC — either way, one each.\n const placer = fieldValue(obr, 2) !== \"\" ? fieldValue(obr, 2) : fieldValue(orc, 2);\n const filler = fieldValue(obr, 3) !== \"\" ? fieldValue(obr, 3) : fieldValue(orc, 3);\n const identifiers = [orderIdentifier(placer, \"PLAC\"), orderIdentifier(filler, \"FILL\")].filter(\n (i): i is FhirComplex => i !== undefined,\n );\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n // OBR-4 → ServiceRequest.code (0..1).\n if (obr !== undefined && obr.field(4).value !== \"\") {\n const code = toFhirCodeableConcept(obr.field(4).asCwe(), ctx);\n issues.push(...code.issues);\n if (code.value !== undefined) props.push({ name: \"code\", value: code.value });\n }\n\n // OBR-5 → priority (HL70485 → request-priority; value-translated). Applied only when OBR-5 is a\n // v2-0485 code (CWE.3 absent or names HL70485); a code from a foreign coding system, or one the IG\n // leaves in its (unmapped) group, is flagged and priority left absent (0..1) — never guessed.\n const obr5cwe = obr?.field(5).asCwe();\n const obr5 = obr5cwe?.identifier ?? \"\";\n if (obr5 !== \"\") {\n const mnemonic = obr5cwe?.nameOfCodingSystem;\n const fromTable =\n mnemonic === undefined || mnemonic === \"\" || mnemonic === \"HL70485\" || mnemonic === \"0485\";\n const priority =\n fromTable && Object.hasOwn(SERVICE_REQUEST_PRIORITY_MAP, obr5)\n ? SERVICE_REQUEST_PRIORITY_MAP[obr5]\n : undefined;\n if (priority === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBR.5\", \"ServiceRequest.priority\"));\n } else {\n props.push({ name: \"priority\", value: primitive(priority) });\n }\n }\n\n // subject / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined)\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n\n // ORC-9 → authoredOn, only for a new order (ORC-1 = NW), per the IG condition. authoredOn is a\n // `dateTime`, so a date-only value is valid (unlike the `instant` fields) — no timezone gate needed.\n if (orc1 === \"NW\" && fieldValue(orc, 9) !== \"\" && orc !== undefined) {\n const authored = toFhirDateTime(orc.field(9).asTs(), ctx.options);\n issues.push(...authored.issues);\n if (authored.value !== undefined)\n props.push({ name: \"authoredOn\", value: primitive(authored.value) });\n }\n\n // OBR-6 → occurrenceDateTime (Requested Date/Time).\n if (obr !== undefined && obr.field(6).value !== \"\") {\n const occurrence = toFhirDateTime(obr.field(6).asTs(), ctx.options);\n issues.push(...occurrence.issues);\n if (occurrence.value !== undefined)\n props.push({ name: \"occurrenceDateTime\", value: primitive(occurrence.value) });\n }\n\n // OBR-31 → reasonCode (Reason for Study).\n if (obr !== undefined && obr.field(31).value !== \"\") {\n const reason = toFhirCodeableConcept(obr.field(31).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"reasonCode\", value: list([reason.value]) });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * `toFhir` — the message-level entry point: assemble a parsed HL7 v2 message into a FHIR R4\n * **message Bundle** (a `MessageHeader` first, then the focal resources), grounded on the IG message\n * and segment maps. The **ADT** family becomes **Patient + Encounter** (+ `RelatedPerson`\n * from NK1); the **ORU^R01** results graph becomes `DiagnosticReport` + `Observation`; the\n * order-entry graph — **ORM_O01 / OML_O21** ORC/OBR → `ServiceRequest` and **RXO** (+ RXR) →\n * `MedicationRequest`; and the thin IG singles — **VXU_V04** RXA/RXR/ORC → `Immunization`,\n * **SIU_S12** SCH/AIS/PID → `Appointment`, and **MDM_T02** TXA/OBX → `DocumentReference`.\n *\n * The fail-safe rule holds at the message level. Two message-level fail-safes join the datatype ones:\n *\n * - **Segment-assembled, not fabricated.** For an ADT trigger the IG maps ({@link IG_MAPPED_ADT_TRIGGERS}),\n * the graph is message-map-grounded. For any other trigger there is no IG *message* map, so the\n * graph is assembled from the reusable IG *segment* maps and flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED} — never a fabricated message map.\n * - **Conservative emit gate.** Every produced resource is run through `@cosyte/fhir.validateResource`\n * before it can join the bundle — `Patient` against the built-in schema in `strict` mode, and the\n * other types against the minimal required-cardinality {@link EMIT_SCHEMAS} in `lenient` mode (so a\n * missing required element errors and withholds, while unmodeled sibling elements do not\n * false-reject). A resource with any structural error is **withheld** from the bundle and flagged\n * {@link ISSUE_CODES.TRANSFORM_RESOURCE_INVALID} rather than shipped as silently-invalid FHIR. When\n * the Patient is withheld, the Encounter's `subject` and any RelatedPerson are dropped rather than\n * left dangling — references always resolve within the bundle.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\nimport {\n complex,\n primitive,\n list,\n resourceType,\n validateResource,\n type FhirComplex,\n type FhirNode,\n} from \"@cosyte/fhir\";\n\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport { createNamingSystem } from \"../terminology/naming-system.js\";\nimport type { TransformContext, TransformOptions } from \"../terminology/context.js\";\nimport { buildAppointment, collectAppointment } from \"./appointment.js\";\nimport { buildDiagnosticReport } from \"./diagnostic-report.js\";\nimport { buildDocumentReference, collectDocument } from \"./document-reference.js\";\nimport { buildEncounter } from \"./encounter.js\";\nimport { EMIT_SCHEMAS } from \"./emit-schemas.js\";\nimport { buildImmunization, collectImmunizationGroups } from \"./immunization.js\";\nimport { buildMedicationRequest } from \"./medication-request.js\";\nimport { buildMessageHeader } from \"./message-header.js\";\nimport { buildObservation } from \"./observation.js\";\nimport { collectOrderGroups } from \"./orders.js\";\nimport { collectReportGroups } from \"./oru.js\";\nimport { buildPatient } from \"./patient.js\";\nimport { buildRelatedPerson } from \"./related-person.js\";\nimport { IdAllocator } from \"./reference.js\";\nimport { buildServiceRequest } from \"./service-request.js\";\n\n/**\n * The immutable result of a message-level transform: the FHIR `Bundle` model and the value-free\n * diagnostics raised assembling it.\n */\nexport interface TransformResult {\n /** The FHIR R4 `Bundle` resource node (a message Bundle: MessageHeader first, then focal resources). */\n readonly bundle: FhirComplex;\n /** The value-free diagnostics raised during assembly, in emission order. */\n readonly issues: readonly TransformIssue[];\n}\n\n/**\n * The ADT trigger events the IG ships a **message** map for. Other triggers still transform — from the\n * reusable segment maps — but are flagged {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_ADT_TRIGGERS: ReadonlySet<string> = new Set([\n \"A01\",\n \"A02\",\n \"A05\",\n \"A06\",\n \"A09\",\n \"A11\",\n \"A17\",\n]);\n\n/**\n * The ORU trigger events the IG ships a **message** map for. The IG maps only `R01`; other ORU triggers\n * still assemble their results graph from the reusable OBR/OBX segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_ORU_TRIGGERS: ReadonlySet<string> = new Set([\"R01\"]);\n\n/**\n * The order-message trigger events the IG ships a **message** map for, keyed `CODE^TRIGGER`. Only\n * `ORM^O01` and `OML^O21` are message-map-grounded; other order families (`OMP`, `OMG`, `RDE`, …)\n * still assemble their request graph from the reusable ORC/OBR/RXO/RXR segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_ORDER_TRIGGERS: ReadonlySet<string> = new Set([\"ORM^O01\", \"OML^O21\"]);\n\n/**\n * The immunization trigger the IG ships a **message** map for. The IG maps only `VXU^V04`; other VXU\n * triggers still assemble their Immunization graph from the reusable RXA/RXR/ORC segment maps but are\n * flagged {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_IMMUNIZATION_TRIGGERS: ReadonlySet<string> = new Set([\"V04\"]);\n\n/**\n * The scheduling trigger the IG ships a **message** map for. The IG maps only `SIU^S12`; other SIU\n * triggers still assemble their Appointment from the reusable SCH/AIS/PID segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_APPOINTMENT_TRIGGERS: ReadonlySet<string> = new Set([\"S12\"]);\n\n/**\n * The medical-document trigger the IG ships a **message** map for. The IG maps only `MDM^T02`; other MDM\n * triggers still assemble their DocumentReference from the reusable TXA/OBX segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_DOCUMENT_TRIGGERS: ReadonlySet<string> = new Set([\"T02\"]);\n\ninterface Entry {\n readonly fullUrl: string;\n readonly resource: FhirComplex;\n}\n\n/**\n * The conservative-emit gate: validate a produced resource against `@cosyte/fhir` before it can join\n * the bundle. Returns `true` when it is safe to emit, or pushes a\n * {@link ISSUE_CODES.TRANSFORM_RESOURCE_INVALID} issue and returns `false` when it has any structural\n * error (the resource is then **withheld** — never shipped invalid).\n *\n * `@cosyte/fhir` models only `Patient` natively, so `Patient` is validated `strict` (its value domains\n * and unknown elements both caught). The other emitted types are validated `lenient` against the\n * minimal required-cardinality {@link EMIT_SCHEMAS}: a **missing required** element (e.g. a\n * class-less/status-less Encounter from an unmapped patient class) is an error and withholds the\n * resource, while the resource's other elements degrade to warnings rather than false rejections.\n */\nfunction passesEmitGate(\n resource: FhirComplex,\n v2Location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): boolean {\n const result =\n resourceType(resource) === \"Patient\"\n ? validateResource(resource, { mode: \"strict\" })\n : validateResource(resource, { mode: \"lenient\", schemas: EMIT_SCHEMAS });\n if (result.valid) return true;\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_INVALID, v2Location, fhirPath));\n return false;\n}\n\n/** Assemble the FHIR message `Bundle` envelope from its ordered entries. */\nfunction buildBundle(\n msg: Hl7Message,\n entries: readonly Entry[],\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex {\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Bundle\") },\n ];\n\n // MSH-10 message control id → Bundle.identifier (R4 MessageHeader carries no identifier element).\n const controlId = msg.meta.controlId;\n if (controlId !== undefined && controlId !== \"\") {\n props.push({\n name: \"identifier\",\n value: complex([{ name: \"value\", value: primitive(controlId) }]),\n });\n }\n\n props.push({ name: \"type\", value: primitive(\"message\") });\n\n // MSH-7 → Bundle.timestamp (an `instant`: only a fully-zoned datetime qualifies; else omit + flag).\n if (msg.meta.timestamp !== undefined) {\n const ts = toFhirDateTime(msg.meta.timestamp, ctx.options);\n issues.push(...ts.issues);\n if (ts.value !== undefined && ts.value.includes(\"T\")) {\n props.push({ name: \"timestamp\", value: primitive(ts.value) });\n } else if (ts.value !== undefined) {\n // A date-only or unzoned MSH-7 is not a valid FHIR `instant`; omit rather than emit invalid.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"MSH.7\", \"Bundle.timestamp\"));\n }\n }\n\n const entryNodes = entries.map((e) =>\n complex([\n { name: \"fullUrl\", value: primitive(e.fullUrl) },\n { name: \"resource\", value: e.resource },\n ]),\n );\n if (entryNodes.length > 0) props.push({ name: \"entry\", value: list(entryNodes) });\n\n return complex(props);\n}\n\n/**\n * Transform a parsed HL7 v2 message into a FHIR R4 message `Bundle`. Never throws for a well-formed\n * {@link Hl7Message}; every ambiguity, unmapped code, dropped element, or withheld resource surfaces\n * as a value-free {@link TransformIssue}.\n *\n * @param msg - A parsed `@cosyte/hl7` message.\n * @param opts - Transform options: the {@link TransformOptions.namingSystem} registry, the naked-\n * timestamp {@link TransformOptions.assumeTimezoneOffsetMinutes} policy, and a\n * {@link TransformOptions.generateId} allocator for reproducible fullUrls.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * import { toFhir, createNamingSystem } from \"@cosyte/transform\";\n * const { bundle, issues } = toFhir(parseHL7(raw), { namingSystem: createNamingSystem() });\n * void bundle;\n * void issues;\n * ```\n */\nexport function toFhir(msg: Hl7Message, opts: TransformOptions = {}): TransformResult {\n const issues: TransformIssue[] = [];\n const namingSystem = opts.namingSystem ?? createNamingSystem();\n const ctx: TransformContext = { namingSystem, options: opts };\n const ids = new IdAllocator(opts);\n\n // Dispatch: an IG-mapped ADT or ORU trigger is message-map-grounded; anything else is\n // segment-assembled (best-effort from the reusable IG segment maps, flagged as such).\n const code = msg.meta.messageCode;\n const trigger = msg.meta.triggerEvent;\n const messageMapGrounded =\n trigger !== undefined &&\n ((code === \"ADT\" && IG_MAPPED_ADT_TRIGGERS.has(trigger)) ||\n (code === \"ORU\" && IG_MAPPED_ORU_TRIGGERS.has(trigger)) ||\n (code === \"VXU\" && IG_MAPPED_IMMUNIZATION_TRIGGERS.has(trigger)) ||\n (code === \"SIU\" && IG_MAPPED_APPOINTMENT_TRIGGERS.has(trigger)) ||\n (code === \"MDM\" && IG_MAPPED_DOCUMENT_TRIGGERS.has(trigger)) ||\n IG_MAPPED_ORDER_TRIGGERS.has(`${code ?? \"\"}^${trigger}`));\n if (!messageMapGrounded) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED, \"MSH.9\"));\n }\n\n const focalEntries: Entry[] = [];\n\n // PID → Patient (the identity anchor). Gated before it can anchor references.\n let patientFullUrl: string | undefined;\n const patientView = msg.patient;\n if (patientView !== undefined) {\n const built = buildPatient(patientView, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"PID\", \"Patient\", issues)) {\n patientFullUrl = ids.next();\n focalEntries.push({ fullUrl: patientFullUrl, resource: built.value });\n }\n }\n\n // PV1 → Encounter, subject wired to the Patient (omitted if no valid Patient).\n let encounterFullUrl: string | undefined;\n const visitView = msg.visit;\n if (visitView !== undefined) {\n const built = buildEncounter(visitView, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"PV1\", \"Encounter\", issues)) {\n encounterFullUrl = ids.next();\n focalEntries.push({ fullUrl: encounterFullUrl, resource: built.value });\n }\n }\n\n // NK1 → RelatedPerson, patient wired to the Patient. Requires a Patient (FHIR-required reference).\n const nextOfKin = msg.nextOfKin();\n if (patientFullUrl !== undefined) {\n for (let i = 0; i < nextOfKin.length; i++) {\n const nk1 = nextOfKin[i];\n if (nk1 === undefined) continue;\n const built = buildRelatedPerson(nk1, patientFullUrl, ctx, i);\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, `NK1[${String(i)}]`, \"RelatedPerson\", issues)\n ) {\n focalEntries.push({ fullUrl: ids.next(), resource: built.value });\n }\n }\n } else if (nextOfKin.length > 0) {\n // No Patient to anchor RelatedPerson.patient — dropped rather than emitted with a dangling ref.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"NK1\", \"RelatedPerson.patient\"));\n }\n\n // ORU → the DiagnosticReport + Observation results graph (Phase 3). OBR anchors a DiagnosticReport;\n // its OBX children become Observations, each subject-wired to the Patient. A withheld Observation is\n // simply absent from DiagnosticReport.result (references always resolve within the bundle), and a\n // withheld DiagnosticReport (unmapped/absent OBR-25 status) still leaves its valid Observations.\n const diagnosticReportFullUrls: string[] = [];\n if (code === \"ORU\") {\n const { groups, orphanObxCount } = collectReportGroups(msg);\n if (orphanObxCount > 0) {\n // OBX with no preceding OBR — no report to anchor it; surfaced rather than silently dropped.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBX\", \"DiagnosticReport.result\"));\n }\n for (const group of groups) {\n const resultFullUrls: string[] = [];\n const observationEntries: Entry[] = [];\n for (let i = 0; i < group.observations.length; i++) {\n const obx = group.observations[i];\n if (obx === undefined) continue;\n const built = buildObservation(obx, patientFullUrl, encounterFullUrl, ctx);\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, `OBX[${String(i)}]`, \"Observation\", issues)\n ) {\n const url = ids.next();\n resultFullUrls.push(url);\n observationEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n const report = buildDiagnosticReport(\n group.obr,\n resultFullUrls,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...report.issues);\n if (\n report.value !== undefined &&\n passesEmitGate(report.value, \"OBR\", \"DiagnosticReport\", issues)\n ) {\n const reportUrl = ids.next();\n diagnosticReportFullUrls.push(reportUrl);\n focalEntries.push({ fullUrl: reportUrl, resource: report.value });\n }\n // The Observations follow their report in the bundle (references resolve regardless of order).\n focalEntries.push(...observationEntries);\n }\n }\n\n // Order messages (ORM/OML, and segment-assembled OMP/OMG/RDE/…) → the ServiceRequest /\n // MedicationRequest graph (Phase 4). Each ORC-anchored order becomes one request: an OBR order\n // detail → ServiceRequest, an RXO pharmacy detail → MedicationRequest, both subject-wired to the\n // Patient. ORU is excluded — there its OBR anchors a DiagnosticReport, not a ServiceRequest.\n const orderResourceFullUrls: string[] = [];\n if (code !== \"ORU\" && code !== \"VXU\" && code !== \"SIU\" && code !== \"MDM\") {\n const { groups, rxeCount } = collectOrderGroups(msg);\n if (rxeCount > 0) {\n // RXE has no IG segment map (nor RDE message map) — surfaced, never assembled from a guess.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"RXE\", \"MedicationRequest\"));\n }\n for (const group of groups) {\n // ServiceRequest: an OBR order detail, or an ORC that opened a non-pharmacy order.\n if (group.obr !== undefined || (group.orc !== undefined && group.rxo === undefined)) {\n const built = buildServiceRequest(\n group.orc,\n group.obr,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...built.issues);\n const loc = group.orc !== undefined ? \"ORC\" : \"OBR\";\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, loc, \"ServiceRequest\", issues)\n ) {\n const url = ids.next();\n orderResourceFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n // MedicationRequest: an RXO pharmacy order detail (+ its first RXR route, its opening ORC).\n if (group.rxo !== undefined) {\n const built = buildMedicationRequest(\n group.rxo,\n group.rxrs[0],\n group.orc,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, \"RXO\", \"MedicationRequest\", issues)\n ) {\n const url = ids.next();\n orderResourceFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n }\n }\n\n // VXU → the Immunization graph (Phase 5). Each ORC-anchored order group's RXA (+ RXR route, + ORC\n // identifiers) becomes one Immunization, subject-wired to the Patient; the order-group OBX bodies\n // become standalone patient Observations (the IG's Observation[2]).\n const immunizationFullUrls: string[] = [];\n if (code === \"VXU\") {\n for (const group of collectImmunizationGroups(msg)) {\n const built = buildImmunization(\n group.rxa,\n group.rxr,\n group.orc,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"RXA\", \"Immunization\", issues)) {\n const url = ids.next();\n immunizationFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n // OBX in a VXU are patient/immunization observations (Observation[1]/[2] in the IG bundle).\n for (const seg of msg.allSegments()) {\n if (seg.type !== \"OBX\") continue;\n const built = buildObservation(seg, patientFullUrl, encounterFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"OBX\", \"Observation\", issues)) {\n focalEntries.push({ fullUrl: ids.next(), resource: built.value });\n }\n }\n }\n\n // SIU → a single Appointment (Phase 5). SCH anchors the Appointment; the bundle Patient is the\n // required participant; AIS supplies the service type.\n const appointmentFullUrls: string[] = [];\n if (code === \"SIU\") {\n const { sch, ais } = collectAppointment(msg);\n if (sch !== undefined) {\n const built = buildAppointment(sch, ais, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"SCH\", \"Appointment\", issues)) {\n const url = ids.next();\n appointmentFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n }\n\n // MDM → a single DocumentReference (Phase 5). TXA anchors the document metadata; the OBX segments\n // carry the document body; the reference is subject-wired to the Patient.\n const documentFullUrls: string[] = [];\n if (code === \"MDM\") {\n const { txa, obxs } = collectDocument(msg);\n if (txa !== undefined) {\n const built = buildDocumentReference(txa, obxs, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, \"TXA\", \"DocumentReference\", issues)\n ) {\n const url = ids.next();\n documentFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n }\n\n // MSH → MessageHeader (first entry of a message Bundle), focus = the focal resources.\n const focus = [\n patientFullUrl,\n encounterFullUrl,\n ...diagnosticReportFullUrls,\n ...orderResourceFullUrls,\n ...immunizationFullUrls,\n ...appointmentFullUrls,\n ...documentFullUrls,\n ].filter((u): u is string => u !== undefined);\n const header = buildMessageHeader(msg.meta, focus);\n issues.push(...header.issues);\n const entries: Entry[] = [];\n if (header.value !== undefined && passesEmitGate(header.value, \"MSH\", \"MessageHeader\", issues)) {\n entries.push({ fullUrl: ids.next(), resource: header.value });\n }\n entries.push(...focalEntries);\n\n const bundle = buildBundle(msg, entries, ctx, issues);\n return { bundle, issues };\n}\n","/**\n * Public entry point for `@cosyte/transform` — the HL7 v2 → FHIR R4 transformation library.\n *\n * `@cosyte/transform` is **not** a parser; it is a **consumer** one tier above the parser suite. It\n * takes already-parsed `@cosyte/hl7` composites and produces validated `@cosyte/fhir` model nodes,\n * grounded on the official **HL7 Version 2 to FHIR** Implementation Guide (`hl7.fhir.uv.v2mappings`,\n * STU Edition 1). Its whole promise is narrow and honest: **IG-grounded, fail-safe transformation\n * with typed, value-free diagnostics — never a confident wrong FHIR value.**\n *\n * This module ships the six safety-critical datatype converters, the immutable\n * `OperationOutcome`-shaped diagnostic channel and the NamingSystem resolver they consult,\n * the message-level assembly — HL7 v2 **ADT → FHIR Patient + Encounter**, the\n * **ORU^R01 → DiagnosticReport + Observation** results graph, the order-entry graph\n * (**ORM_O01 / OML_O21 → ServiceRequest** and **RXO → MedicationRequest**), and the thin IG\n * singles (**VXU_V04 → Immunization**, **SIU_S12 → Appointment**, **MDM_T02 → DocumentReference**),\n * all through `toFhir(msg)` — and the **terminology value-translation** layer: a\n * `$translate`-shaped {@link toFhirCodeableConceptVia} engine applying the license-clean IG value\n * ConceptMaps to the previously structural-only coded fields (route/site, appointment type, order\n * priority, substitution). Terminology **depth beyond these maps**, profiles, and the reverse\n * FHIR → v2 direction are not implemented.\n *\n * @packageDocumentation\n */\n\n/**\n * Package version marker exported from the `@cosyte/transform` root.\n *\n * Kept in lockstep with `package.json` by `scripts/sync-version.mjs`, which the `version` script\n * runs immediately after `changeset version`. The `: string` annotation is deliberate: without it\n * TypeScript infers the *literal* type (`declare const VERSION = \"0.0.0\"`), which leaks the current\n * release into consumers' types and makes an equality check against any other version a compile\n * error.\n *\n * @example\n * ```typescript\n * import { VERSION } from \"@cosyte/transform\";\n * console.log(VERSION);\n * ```\n */\nexport const VERSION: string = \"0.0.5\";\n\n// ── The diagnostic channel (the fail-safe rule, materialized) ──────────────────────────────────\nexport { ISSUE_CODES, FATAL_CODES } from \"./diagnostics/codes.js\";\nexport type { IssueCode, FatalCode } from \"./diagnostics/codes.js\";\nexport { issue, fhirIssueTypeFor, ISSUE_REGISTRY } from \"./diagnostics/issue.js\";\nexport type { TransformIssue, TransformSeverity } from \"./diagnostics/issue.js\";\nexport type { ConvertResult } from \"./diagnostics/result.js\";\nexport { toOperationOutcome, TRANSFORM_ISSUE_SYSTEM } from \"./diagnostics/operation-outcome.js\";\n\n// ── The transform context + the NamingSystem resolver ──────────────────────────────────────────\nexport type { TransformContext, TransformOptions } from \"./terminology/context.js\";\nexport {\n createNamingSystem,\n DEFAULT_V2_CODE_SYSTEMS,\n V2_0203_SYSTEM,\n} from \"./terminology/naming-system.js\";\nexport type { NamingSystemRegistry, NamingSystemSeed } from \"./terminology/naming-system.js\";\n\n// ── The six safety-critical datatype converters ────────────────────────────────────────────────\nexport { toFhirDateTime } from \"./datatypes/datetime.js\";\nexport { toFhirIdentifier } from \"./datatypes/identifier.js\";\nexport { toFhirCodeableConcept } from \"./datatypes/codeable-concept.js\";\nexport type { CodedElement } from \"./datatypes/codeable-concept.js\";\nexport { toFhirHumanName, NAME_USE_MAP } from \"./datatypes/human-name.js\";\nexport { toFhirAddress, ADDRESS_USE_MAP, ADDRESS_TYPE_MAP } from \"./datatypes/address.js\";\nexport { toFhirQuantity } from \"./datatypes/quantity.js\";\n\n// ── Message-level assembly: HL7 v2 ADT → FHIR Patient + Encounter graph (Phase 2) ────────────────\nexport {\n toFhir,\n IG_MAPPED_ADT_TRIGGERS,\n IG_MAPPED_ORU_TRIGGERS,\n IG_MAPPED_ORDER_TRIGGERS,\n} from \"./messages/to-fhir.js\";\nexport type { TransformResult } from \"./messages/to-fhir.js\";\nexport { ADMINISTRATIVE_GENDER_MAP } from \"./messages/patient.js\";\nexport { ENCOUNTER_CLASS_V3_MAP, ENCOUNTER_STATUS_MAP } from \"./messages/encounter.js\";\n\n// ── Message-level assembly: HL7 v2 ORU^R01 → FHIR DiagnosticReport + Observation graph (Phase 3) ──\nexport { OBSERVATION_STATUS_MAP, HL70078_INTERPRETATION_CODES } from \"./messages/observation.js\";\nexport { DIAGNOSTIC_REPORT_STATUS_MAP } from \"./messages/diagnostic-report.js\";\n\n// ── Message-level assembly: HL7 v2 ORM/OML → ServiceRequest, RXO → MedicationRequest (Phase 4) ────\nexport { REQUEST_STATUS_MAP } from \"./messages/service-request.js\";\n\n// ── Message-level assembly: the thin IG singles — VXU/SIU/MDM (Phase 5) ──────────────────────────\nexport {\n IG_MAPPED_IMMUNIZATION_TRIGGERS,\n IG_MAPPED_APPOINTMENT_TRIGGERS,\n IG_MAPPED_DOCUMENT_TRIGGERS,\n} from \"./messages/to-fhir.js\";\nexport { IMMUNIZATION_STATUS_MAP } from \"./messages/immunization.js\";\nexport { APPOINTMENT_STATUS_MAP } from \"./messages/appointment.js\";\n\n// ── Terminology value translation: the $translate-shaped ConceptMap engine + maps (Phase 6) ──────\nexport {\n toFhirCodeableConceptVia,\n translateBound,\n codeableConceptFromTarget,\n ROUTE_VALUE_MAP,\n SITE_VALUE_MAP,\n APPOINTMENT_TYPE_VALUE_MAP,\n SUBSTITUTION_VALUE_MAP,\n V2_0162_SYSTEM,\n V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n V2_0550_SYSTEM,\n V2_0277_SYSTEM,\n V2_0161_SYSTEM,\n} from \"./terminology/concept-map.js\";\nexport type { CodedTarget, CodedValueMap } from \"./terminology/concept-map.js\";\nexport { SERVICE_REQUEST_PRIORITY_MAP } from \"./messages/service-request.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/diagnostics/codes.ts","../src/diagnostics/issue.ts","../src/diagnostics/operation-outcome.ts","../src/terminology/naming-system.ts","../src/datatypes/datetime.ts","../src/datatypes/build.ts","../src/datatypes/identifier.ts","../src/datatypes/codeable-concept.ts","../src/datatypes/human-name.ts","../src/datatypes/address.ts","../src/datatypes/quantity.ts","../src/terminology/concept-map.ts","../src/messages/reference.ts","../src/messages/appointment.ts","../src/messages/diagnostic-report.ts","../src/messages/document-reference.ts","../src/messages/encounter.ts","../src/messages/emit-schemas.ts","../src/messages/immunization.ts","../src/messages/medication-request.ts","../src/messages/message-header.ts","../src/messages/observation.ts","../src/messages/orders.ts","../src/messages/oru.ts","../src/messages/patient.ts","../src/messages/related-person.ts","../src/messages/service-request.ts","../src/messages/to-fhir.ts","../src/index.ts"],"names":["primitive","list","complex","coding","text","decimal","translatedFrom","rawComponent","ORDER_INTENT"],"mappings":";;;;;AA8BO,IAAM,WAAA,GAAc;AAAA;AAAA;AAAA;AAAA,EAIzB,+BAAA,EAAiC,iCAAA;AAAA;AAAA,EAEjC,2BAAA,EAA6B,6BAAA;AAAA;AAAA;AAAA;AAAA,EAI7B,sCAAA,EAAwC,wCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxC,uBAAA,EAAyB,yBAAA;AAAA;AAAA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`key === value` so they survive `Object.values(...)` into a snapshot\n * tripwire, and both **part of the public contract**: consumers branch on these codes, so renaming\n * or removing one is a **breaking change** (mirrors the parser archetype's stable-warning-code rule).\n * New codes are **additions only**.\n *\n * - {@link ISSUE_CODES} — non-fatal, typed diagnostics carried on a {@link TransformResult}. Every\n * fail-safe decision the transform makes (a naked timestamp, an unresolvable assigning authority,\n * an unmapped code, a non-UCUM unit, a dropped element) surfaces as one of these — **never** a\n * silently-defaulted or fabricated FHIR value.\n * - {@link FATAL_CODES} — the small set of unrecoverable conditions reserved for message-level\n * entry points. **Nothing in this library throws one today**: the datatype converters and\n * `toFhir` alike fail safe to a value-free issue instead.\n *\n * @packageDocumentation\n */\n\n/**\n * Stable **non-fatal issue codes** — the typed diagnostics the fail-safe rule emits.\n *\n * @example\n * ```ts\n * import { ISSUE_CODES } from \"@cosyte/transform\";\n * if (issue.code === ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE) {\n * // a v2 timestamp had a time-of-day but no timezone offset — reduced to date precision\n * }\n * ```\n */\nexport const ISSUE_CODES = {\n /** A v2 DTM/TS carried a time-of-day but no timezone offset. FHIR forbids time-without-zone, so\n * the value was reduced to date precision (or an explicit sender offset applied via options) —\n * **never** a guessed UTC. */\n TRANSFORM_TIMESTAMP_NO_TIMEZONE: \"TRANSFORM_TIMESTAMP_NO_TIMEZONE\",\n /** A v2 DTM/TS could not be parsed into a valid FHIR date/time; no value was emitted. */\n TRANSFORM_TIMESTAMP_INVALID: \"TRANSFORM_TIMESTAMP_INVALID\",\n /** The assigning authority (HD) could not be resolved to a FHIR `Identifier.system` URI via the\n * NamingSystem registry. The identifier is emitted with its value and **no** system — a system URI\n * is **never** synthesized from HD.1 alone. */\n TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED: \"TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED\",\n /** A coded value could not be mapped to a FHIR concept — either it carried no coding-system context\n * (CWE.3 absent), or it is a table code the IG ConceptMap has **no target** for (e.g. an OBX-11/\n * OBR-25 result status the HL70085/HL70123 map does not carry, or an OBX-8 abnormal flag absent from\n * HL70078). The original code is preserved / the FHIR value left absent; **never** coerced to a\n * neighbor and **never** guessed to `final`/`normal`. */\n TRANSFORM_CODE_UNMAPPED: \"TRANSFORM_CODE_UNMAPPED\",\n /** A coding-system mnemonic (CWE.3 / CWE.6) was not recognized, so no canonical system URI could\n * be emitted. The code is preserved; a URI is **never** invented. */\n TRANSFORM_CODE_SYSTEM_UNRESOLVED: \"TRANSFORM_CODE_SYSTEM_UNRESOLVED\",\n /** A unit was not a valid UCUM code (or was not declared UCUM). It is preserved verbatim in\n * `Quantity.unit`; `Quantity.code`/`.system` are left absent — a UCUM code is **never** fabricated\n * and a magnitude is **never** converted. */\n TRANSFORM_UNIT_NOT_UCUM: \"TRANSFORM_UNIT_NOT_UCUM\",\n /** A v2 numeric value (NM) could not be represented as a FHIR `decimal` without altering it — e.g.\n * a leading `+`, a leading zero, or a trailing dot, which FHIR's `decimal` lexical form forbids. No\n * `Quantity` value is emitted rather than a canonicalized (and therefore altered) magnitude. */\n TRANSFORM_QUANTITY_VALUE_INVALID: \"TRANSFORM_QUANTITY_VALUE_INVALID\",\n /** A populated source element was not carried to its FHIR target and was dropped — either because\n * the IG map defines no target, or because that target's conversion is **not implemented**\n * (e.g. XTN→ContactPoint telecom, PV1 participants). Surfaced here rather than silently discarded,\n * never a fabricated value. */\n TRANSFORM_ELEMENT_DROPPED: \"TRANSFORM_ELEMENT_DROPPED\",\n /** An XPN.7 name-type code has no equivalent in the IG's HL70200 → name-use ConceptMap;\n * `HumanName.use` is left absent rather than guessed. */\n TRANSFORM_NAME_USE_UNMAPPED: \"TRANSFORM_NAME_USE_UNMAPPED\",\n /** An XAD.7 address-type code has no equivalent in the IG's HL70190 → address-use/type\n * ConceptMaps; `Address.use`/`.type` are left absent rather than guessed. */\n TRANSFORM_ADDRESS_USE_UNMAPPED: \"TRANSFORM_ADDRESS_USE_UNMAPPED\",\n /** The message's trigger event has no IG *message* map, so its resource graph was assembled from\n * the reusable IG *segment* maps rather than a message map. The graph is best-effort and flagged\n * as such — never a fabricated message map. */\n TRANSFORM_SEGMENT_ASSEMBLED: \"TRANSFORM_SEGMENT_ASSEMBLED\",\n /** A produced FHIR resource failed `@cosyte/fhir` R4 structural validation and was **withheld**\n * from the bundle rather than emitted as a silently-invalid resource — the conservative-emit gate. */\n TRANSFORM_RESOURCE_INVALID: \"TRANSFORM_RESOURCE_INVALID\",\n /** A FHIR-required element's value could not be faithfully derived from the source, so it was\n * emitted with a `data-absent-reason` extension (value `unknown`) rather than fabricated — e.g.\n * `MessageHeader.source.endpoint` from an MSH-3 application namespace that is not a URL. */\n TRANSFORM_REQUIRED_ELEMENT_UNKNOWN: \"TRANSFORM_REQUIRED_ELEMENT_UNKNOWN\",\n} as const;\n\n/** A value from {@link ISSUE_CODES} — the type consumers narrow `issue.code` against. */\nexport type IssueCode = (typeof ISSUE_CODES)[keyof typeof ISSUE_CODES];\n\n/**\n * Stable **fatal codes** — the reserved names for unrecoverable input conditions. **Nothing in this\n * library throws one today**; every path, datatype and message level alike, fails safe to a\n * value-free issue instead. They are declared so that a future one is an addition rather than a\n * rename.\n *\n * @example\n * ```ts\n * import { FATAL_CODES } from \"@cosyte/transform\";\n * void FATAL_CODES.EMPTY_INPUT;\n * ```\n */\nexport const FATAL_CODES = {\n /** The input carried nothing to transform. */\n EMPTY_INPUT: \"EMPTY_INPUT\",\n /** The input was not a shape this transform accepts. */\n TRANSFORM_UNSUPPORTED_INPUT: \"TRANSFORM_UNSUPPORTED_INPUT\",\n} as const;\n\n/** A value from {@link FATAL_CODES} — the type carried by a thrown fatal error. */\nexport type FatalCode = (typeof FATAL_CODES)[keyof typeof FATAL_CODES];\n","/**\n * The value-free {@link TransformIssue} — the single diagnostic shape the whole library emits.\n *\n * Every issue is **`OperationOutcome`-shaped and PHI-safe by construction**: it carries the *v2\n * location* (segment / field / component index — never a value) and the *FHIR path* it concerns,\n * plus a **static, per-code** severity and human-readable message drawn from {@link ISSUE_REGISTRY}.\n * Nothing in an issue is interpolated from patient data — the factory takes only positional metadata,\n * so there is no code path by which a name, DOB, MRN, or result value can reach a log line (the\n * discipline `@cosyte/fhir` already proved with its value-free `OperationOutcome`).\n *\n * @packageDocumentation\n */\n\nimport { ISSUE_CODES, type IssueCode } from \"./codes.js\";\n\n/** The severity a {@link TransformIssue} carries — an `OperationOutcome.issue.severity` value. */\nexport type TransformSeverity = \"error\" | \"warning\" | \"information\";\n\n/**\n * A single value-free diagnostic.\n *\n * @example\n * ```ts\n * import { ISSUE_CODES } from \"@cosyte/transform\";\n * // issue.code === ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE\n * // issue.v2Location === \"TS.1\"; issue.fhirPath === \"dateTime\"\n * ```\n */\nexport interface TransformIssue {\n /** The stable code. One of {@link ISSUE_CODES}. */\n readonly code: IssueCode;\n /** The `OperationOutcome`-style severity, fixed per code. */\n readonly severity: TransformSeverity;\n /** The v2 source location — a segment / field / component **index**, never a value. */\n readonly v2Location: string;\n /** The FHIR path this issue concerns (e.g. `Identifier.system`), when applicable. */\n readonly fhirPath?: string;\n /** A static, value-free description drawn from {@link ISSUE_REGISTRY}. */\n readonly message: string;\n}\n\n/** The fixed metadata for a code: its severity, its FHIR `issue-type` code, and a static message. */\ninterface IssueMeta {\n readonly severity: TransformSeverity;\n /** The FHIR `OperationOutcome.issue.code` (R4 `issue-type` value set) this maps to. */\n readonly fhirIssueType: string;\n /** A static, value-free message. Contains no interpolated data — safe to log verbatim. */\n readonly message: string;\n}\n\n/**\n * The per-code registry: severity, FHIR `issue-type`, and a static message. Frozen and exhaustive\n * over {@link ISSUE_CODES} (enforced by the `Record<IssueCode, …>` type — a new code will not\n * compile until it has an entry).\n */\nexport const ISSUE_REGISTRY: Readonly<Record<IssueCode, IssueMeta>> = Object.freeze({\n [ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"v2 timestamp carried a time-of-day but no timezone offset; reduced to date precision (FHIR forbids time without a zone).\",\n },\n [ISSUE_CODES.TRANSFORM_TIMESTAMP_INVALID]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message: \"v2 timestamp could not be parsed into a valid FHIR date/time; no value emitted.\",\n },\n [ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED]: {\n severity: \"warning\",\n fhirIssueType: \"not-found\",\n message:\n \"assigning authority could not be resolved to an Identifier.system; identifier emitted with value and no system (never synthesized from a bare namespace).\",\n },\n [ISSUE_CODES.TRANSFORM_CODE_UNMAPPED]: {\n severity: \"warning\",\n fhirIssueType: \"code-invalid\",\n message:\n \"coded value could not be mapped to a FHIR concept (no coding system, or no target in the IG ConceptMap); original code preserved / FHIR value left absent, never coerced or guessed.\",\n },\n [ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED]: {\n severity: \"warning\",\n fhirIssueType: \"code-invalid\",\n message: \"coding-system mnemonic not recognized; code preserved, no system URI invented.\",\n },\n [ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"unit is not a valid UCUM code; preserved verbatim in Quantity.unit, code/system absent, magnitude never converted.\",\n },\n [ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"numeric value is not a valid FHIR decimal literal (e.g. leading sign/zero or trailing dot); no Quantity value emitted rather than altering the magnitude.\",\n },\n [ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"populated source element was not carried to its FHIR target (no target in this map, or its conversion is not implemented); dropped.\",\n },\n [ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED]: {\n severity: \"information\",\n fhirIssueType: \"value\",\n message: \"name-type code has no equivalent in the HL70200 to name-use map; use left absent.\",\n },\n [ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED]: {\n severity: \"information\",\n fhirIssueType: \"value\",\n message:\n \"address-type code has no equivalent in the HL70190 to address-use/type maps; use/type left absent.\",\n },\n [ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"message trigger has no IG message map; resource graph assembled from IG segment maps, best-effort.\",\n },\n [ISSUE_CODES.TRANSFORM_RESOURCE_INVALID]: {\n severity: \"error\",\n fhirIssueType: \"structure\",\n message:\n \"produced resource failed FHIR R4 structural validation; withheld from the bundle rather than emitted invalid.\",\n },\n [ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"required FHIR element could not be derived from the source; emitted with a data-absent-reason extension, never fabricated.\",\n },\n});\n\n/**\n * Construct a value-free {@link TransformIssue}. The severity and message come from\n * {@link ISSUE_REGISTRY}; the caller supplies only positional metadata, so an issue can carry no PHI.\n *\n * @param code - The stable {@link IssueCode}.\n * @param v2Location - The v2 source location (segment / field / component index) — never a value.\n * @param fhirPath - The FHIR path the issue concerns, when applicable.\n * @example\n * ```ts\n * import { issue, ISSUE_CODES } from \"@cosyte/transform\";\n * const i = issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE, \"TS.1\", \"dateTime\");\n * void i.severity; // \"warning\"\n * ```\n */\nexport function issue(code: IssueCode, v2Location: string, fhirPath?: string): TransformIssue {\n const meta = ISSUE_REGISTRY[code];\n const base = {\n code,\n severity: meta.severity,\n v2Location,\n message: meta.message,\n };\n return fhirPath === undefined ? base : { ...base, fhirPath };\n}\n\n/**\n * The FHIR `issue-type` code for an {@link IssueCode} — used by the `OperationOutcome` renderer.\n *\n * @param code - The stable {@link IssueCode}.\n * @example\n * ```ts\n * import { fhirIssueTypeFor, ISSUE_CODES } from \"@cosyte/transform\";\n * fhirIssueTypeFor(ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED); // \"not-found\"\n * ```\n */\nexport function fhirIssueTypeFor(code: IssueCode): string {\n return ISSUE_REGISTRY[code].fhirIssueType;\n}\n","/**\n * Render a list of {@link TransformIssue}s as a FHIR `OperationOutcome` resource model.\n *\n * The transform's diagnostic channel is `OperationOutcome`-shaped by design; this is the adapter that\n * materializes it as an actual `@cosyte/fhir` resource node a consumer can serialize, validate, or\n * return alongside a bundle. It is **value-free**: every field is drawn from the issue's static\n * metadata (code, severity, message) and its positional locations (v2 location → `diagnostics`, FHIR\n * path → `expression`) — no patient data is reachable here.\n *\n * @packageDocumentation\n */\n\nimport { complex, list, primitive, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { fhirIssueTypeFor, type TransformIssue } from \"./issue.js\";\n\n/** The code system under which the transform's stable issue codes are carried in `details.coding`. */\nexport const TRANSFORM_ISSUE_SYSTEM = \"https://cosyte.com/fhir/CodeSystem/transform-issue-codes\";\n\nfunction prop(name: string, value: FhirNode): { name: string; value: FhirNode } {\n return { name, value };\n}\n\nfunction renderIssue(i: TransformIssue): FhirComplex {\n const details = complex([\n prop(\n \"coding\",\n list([\n complex([\n prop(\"system\", primitive(TRANSFORM_ISSUE_SYSTEM)),\n prop(\"code\", primitive(i.code)),\n ]),\n ]),\n ),\n prop(\"text\", primitive(i.message)),\n ]);\n\n const props = [\n prop(\"severity\", primitive(i.severity)),\n prop(\"code\", primitive(fhirIssueTypeFor(i.code))),\n prop(\"details\", details),\n // `diagnostics` carries the v2 source location — positional metadata, never a value.\n prop(\"diagnostics\", primitive(i.v2Location)),\n ];\n if (i.fhirPath !== undefined) {\n props.push(prop(\"expression\", list([primitive(i.fhirPath)])));\n }\n return complex(props);\n}\n\n/**\n * Build a FHIR `OperationOutcome` {@link FhirComplex} from the given issues. An empty list still\n * produces a structurally-valid `OperationOutcome` with a single `information` \"all clear\" issue\n * (FHIR requires `OperationOutcome.issue` to be non-empty).\n *\n * @param issues - The value-free diagnostics to render.\n * @example\n * ```ts\n * import { toOperationOutcome } from \"@cosyte/transform\";\n * const oo = toOperationOutcome([]);\n * // oo is a FhirComplex resource node with resourceType \"OperationOutcome\"\n * void oo;\n * ```\n */\nexport function toOperationOutcome(issues: readonly TransformIssue[]): FhirComplex {\n const rendered =\n issues.length > 0\n ? issues.map(renderIssue)\n : [\n complex([\n prop(\"severity\", primitive(\"information\")),\n prop(\"code\", primitive(\"informational\")),\n prop(\"details\", complex([prop(\"text\", primitive(\"No transform issues.\"))])),\n ]),\n ];\n return complex([\n prop(\"resourceType\", primitive(\"OperationOutcome\")),\n prop(\"issue\", list(rendered)),\n ]);\n}\n","/**\n * The NamingSystem registry — how an HL7 v2 identity/coding namespace becomes a FHIR canonical URI.\n *\n * Two resolutions live here, and both are **fail-safe by refusal**:\n *\n * 1. **Assigning authority (HD) → `Identifier.system`.** The IG's CX→Identifier map says CX.4 maps to\n * `Identifier.system` *only when the authority is in an identifier registry* — the URI comes from a\n * NamingSystem lookup, **not** string concatenation. There is no deterministic algorithm from an\n * HD to a URI, so this resolver **never synthesizes a system from HD.1 (the bare namespace\n * mnemonic) alone** — doing so would let two hospitals reusing \"MR\"/\"HOSPMRN\" collide and merge two\n * patients. The *only* auto-derivations are the unambiguous ones: `urn:oid:<oid>` when HD.2 is a\n * valid OID with HD.3 = `ISO`, and `urn:uuid:<uuid>` when HD.3 = `UUID`. Everything else must be an\n * explicit, caller-seeded registry entry, or it resolves to `undefined` and the caller emits a\n * typed issue.\n *\n * 2. **v2 coding-system mnemonic → canonical URI.** CWE.3/CWE.6 carry a v2 Table 0396 mnemonic\n * (`LN`, `SCT`, …); FHIR needs the canonical URI (`http://loinc.org`, …). {@link DEFAULT_V2_CODE_SYSTEMS}\n * seeds a small, license-clean set of the universally-fixed FHIR-core systems; an unrecognized\n * mnemonic resolves to `undefined` (the caller preserves the raw code and flags it — a URI is\n * never invented). The full HL7 THO crosswalk is not bundled.\n *\n * @packageDocumentation\n */\n\nimport type { HD } from \"@cosyte/hl7\";\n\n/**\n * The HL7 v2 Table 0203 identifier-type code system canonical URI — used to build `Identifier.type`.\n * (FHIR R4 terminologies-systems.html)\n */\nexport const V2_0203_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0203\";\n\n/**\n * A small, license-clean seed of v2 Table 0396 coding-system mnemonic → canonical URI, for the\n * FHIR-core-fixed systems whose URIs are universally cited (FHIR R4 terminologies-systems.html).\n * The full HL7 THO NamingSystem crosswalk is not bundled; callers extend this via\n * {@link createNamingSystem}. **No terminology *content* is bundled — only identity URIs.**\n */\nexport const DEFAULT_V2_CODE_SYSTEMS: Readonly<Record<string, string>> = Object.freeze({\n LN: \"http://loinc.org\",\n SCT: \"http://snomed.info/sct\",\n RXNORM: \"http://www.nlm.nih.gov/research/umls/rxnorm\",\n CVX: \"http://hl7.org/fhir/sid/cvx\",\n UCUM: \"http://unitsofmeasure.org\",\n});\n\n/** A seed for {@link createNamingSystem}: extra coding systems and explicit assigning authorities. */\nexport interface NamingSystemSeed {\n /** Extra v2 coding-system mnemonic → canonical URI entries (merged over the defaults). */\n readonly codeSystems?: Readonly<Record<string, string>>;\n /**\n * Explicit assigning-authority entries, keyed by **HD.1 namespace mnemonic** and/or **HD.2\n * universal ID (OID)** → the `Identifier.system` URI. This is the safe, caller-vetted path the IG\n * calls for; the registry never derives a system from a mnemonic on its own.\n */\n readonly authorities?: Readonly<Record<string, string>>;\n}\n\n/** The resolver consulted by the identity- and code-conversion paths. */\nexport interface NamingSystemRegistry {\n /**\n * Resolve an assigning authority (HD) to a FHIR `Identifier.system` URI, or `undefined` when it\n * cannot be resolved safely. **Never** synthesizes a URI from HD.1 alone.\n */\n readonly resolveAssigningAuthority: (hd: HD) => string | undefined;\n /** Resolve a v2 coding-system mnemonic to a canonical URI, or `undefined` when unrecognized. */\n readonly resolveCodeSystem: (mnemonic: string) => string | undefined;\n}\n\n/** A syntactically-valid ISO OID: dot-separated arcs, first arc 0–2, no leading zeros on multi-digit arcs. */\nfunction isOid(value: string): boolean {\n return /^[0-2](\\.(0|[1-9]\\d*))+$/.test(value);\n}\n\n/** A syntactically-valid UUID (any case). */\nfunction isUuid(value: string): boolean {\n return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(\n value,\n );\n}\n\n/**\n * Create a {@link NamingSystemRegistry}. With no seed it resolves the built-in FHIR-core code systems\n * and the two unambiguous HD auto-derivations (OID/UUID); a seed adds caller-vetted code systems and\n * explicit assigning-authority URIs.\n *\n * @example\n * ```ts\n * import { createNamingSystem } from \"@cosyte/transform\";\n * const registry = createNamingSystem({\n * authorities: { HOSPMRN: \"urn:oid:1.2.840.114350.1.13.1\" },\n * });\n * registry.resolveCodeSystem(\"LN\"); // => \"http://loinc.org\"\n * ```\n */\nexport function createNamingSystem(seed: NamingSystemSeed = {}): NamingSystemRegistry {\n const codeSystems: Record<string, string> = { ...DEFAULT_V2_CODE_SYSTEMS, ...seed.codeSystems };\n const authorities: Record<string, string> = { ...seed.authorities };\n\n return Object.freeze({\n resolveCodeSystem(mnemonic: string): string | undefined {\n if (mnemonic === \"\") return undefined;\n return Object.hasOwn(codeSystems, mnemonic) ? codeSystems[mnemonic] : undefined;\n },\n\n resolveAssigningAuthority(hd: HD): string | undefined {\n // 1. Explicit, caller-vetted registry entries win (by OID first, then by namespace mnemonic).\n if (hd.universalId !== undefined && Object.hasOwn(authorities, hd.universalId)) {\n return authorities[hd.universalId];\n }\n if (hd.namespaceId !== undefined && Object.hasOwn(authorities, hd.namespaceId)) {\n return authorities[hd.namespaceId];\n }\n // 2. The only safe auto-derivations — from the *universal* ID, never from HD.1.\n if (hd.universalId !== undefined && hd.universalId !== \"\") {\n if (hd.universalIdType === \"ISO\" && isOid(hd.universalId)) {\n return `urn:oid:${hd.universalId}`;\n }\n if (hd.universalIdType === \"UUID\" && isUuid(hd.universalId)) {\n return `urn:uuid:${hd.universalId.toLowerCase()}`;\n }\n }\n // 3. HD.1-only, or an unrecognized/unsafe universal ID → unresolved. Never synthesized.\n return undefined;\n },\n });\n}\n","/**\n * DTM / TS → FHIR `dateTime` — the single most dangerous conversion.\n *\n * Grounded on the IG datatype ConceptMap **DTM → dateTime** (`DTM.1` *is equivalent to* the FHIR\n * `dateTime.$value`, with the instruction to \"convert v2 date time format to FHIR date time format\")\n * and the **FHIR core datatype rule** it defers to: *\"if hours and minutes are specified, a timezone\n * offset SHALL be populated\"*, and the R4 `dateTime` grammar requires **full `hh:mm:ss` with an\n * offset** whenever a time is present. Two fail-safe consequences follow:\n *\n * - **Naked timestamp (no offset).** A `20260721143000` cannot become a valid zoned FHIR `dateTime`\n * without inventing an offset — assuming UTC would silently shift the clinical instant by hours. So\n * the value is **reduced to date precision** (`2026-07-21`) and {@link ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE}\n * is raised — unless the caller asserts the sender's offset via `options.assumeTimezoneOffsetMinutes`.\n * - **Partial-precision time (hour/minute only).** FHIR cannot represent `hh` or `hh:mm` without\n * seconds, and padding `:00` would fabricate precision, so such a value is likewise reduced to date\n * precision and flagged — never padded.\n *\n * Date-only precisions (`2026`, `2026-07`, `2026-07-21`) are preserved exactly — never zero-filled —\n * and need no offset (FHIR permits a bare date).\n *\n * @packageDocumentation\n */\n\nimport type { TS } from \"@cosyte/hl7\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformOptions } from \"../terminology/context.js\";\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, \"0\");\n}\n\n/** The signed FHIR offset suffix for a number of minutes east of UTC (e.g. `-300` → `-05:00`). */\nfunction formatOffset(offsetMinutes: number): string {\n const sign = offsetMinutes < 0 ? \"-\" : \"+\";\n const abs = Math.abs(offsetMinutes);\n return `${sign}${pad(Math.floor(abs / 60), 2)}:${pad(abs % 60, 2)}`;\n}\n\n/** The `YYYY[-MM[-DD]]` date portion of a parsed TS, at its stated precision. */\nfunction datePart(ts: TS): string {\n let out = pad(ts.year ?? 0, 4);\n if (ts.month !== undefined) out += `-${pad(ts.month, 2)}`;\n if (ts.day !== undefined) out += `-${pad(ts.day, 2)}`;\n return out;\n}\n\n/**\n * Convert a parsed HL7 v2 timestamp to a FHIR `dateTime` lexical string, fail-safe on timezone and\n * precision. Returns `{ value: undefined }` only when the timestamp is unparseable.\n *\n * @param ts - A parsed `@cosyte/hl7` `TS` (`DtmParts`).\n * @param options - Conversion policy; `assumeTimezoneOffsetMinutes` supplies a sender-asserted offset.\n * @example\n * ```ts\n * import { parseDtm } from \"@cosyte/hl7\";\n * import { toFhirDateTime } from \"@cosyte/transform\";\n * const { value } = toFhirDateTime(parseDtm(\"20260721\"));\n * // value === \"2026-07-21\"\n * void value;\n * ```\n */\nexport function toFhirDateTime(ts: TS, options: TransformOptions = {}): ConvertResult<string> {\n if (!ts.valid || ts.precision === undefined || ts.year === undefined) {\n return {\n value: undefined,\n issues: [issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_INVALID, \"TS.1\", \"dateTime\")],\n };\n }\n\n const date = datePart(ts);\n\n // No time-of-day → a bare date is a valid FHIR dateTime; preserve precision exactly.\n if (ts.hour === undefined) {\n return { value: date, issues: [] };\n }\n\n // Time-of-day present. FHIR requires full hh:mm:ss + an offset; anything less cannot be emitted.\n const hasFullTime = ts.precision === \"second\" || ts.precision === \"fraction\";\n const offset = ts.hasTimezone ? ts.offsetMinutes : options.assumeTimezoneOffsetMinutes;\n\n if (hasFullTime && offset !== undefined) {\n const frac =\n ts.precision === \"fraction\" && ts.fractionalSeconds !== undefined\n ? `.${ts.fractionalSeconds}`\n : \"\";\n const value = `${date}T${pad(ts.hour, 2)}:${pad(ts.minute ?? 0, 2)}:${pad(ts.second ?? 0, 2)}${frac}${formatOffset(offset)}`;\n // If the offset was asserted by the caller rather than present on the wire, say so (value-free).\n const issues = ts.hasTimezone\n ? []\n : [issue(ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE, \"TS.1\", \"dateTime\")];\n return { value, issues };\n }\n\n // Cannot emit a valid zoned/full-precision time → reduce to date precision, never pad, never assume UTC.\n const code =\n !ts.hasTimezone && offset === undefined\n ? ISSUE_CODES.TRANSFORM_TIMESTAMP_NO_TIMEZONE\n : ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED;\n return { value: date, issues: [issue(code, \"TS.1\", \"dateTime\")] };\n}\n","/**\n * Small builders over the `@cosyte/fhir` generic element model, so each converter reads as the\n * datatype it produces rather than as node plumbing. All of them **omit absent/empty parts** — a\n * FHIR datatype node never carries an empty-string leaf or an empty list.\n *\n * @packageDocumentation\n */\n\nimport { complex, list, primitive, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\n/** A `(name, value)` pair for {@link object}; a `undefined` value is dropped. */\nexport type Field = readonly [name: string, value: FhirNode | undefined];\n\n/**\n * A FHIR string/code/uri primitive, or `undefined` for an absent/empty source value.\n *\n * @param value - The source string.\n * @example\n * ```ts\n * // text(\"MA\") -> a FHIR primitive; text(\"\") and text(undefined) -> undefined\n * ```\n */\nexport function text(value: string | undefined): FhirNode | undefined {\n return value === undefined || value === \"\" ? undefined : primitive(value);\n}\n\n/**\n * A FHIR list of the present items, or `undefined` when none are present.\n *\n * @param items - The candidate items; `undefined` entries are dropped.\n * @example\n * ```ts\n * // arr([text(\"Jane\"), text(undefined)]) -> a list of one item\n * ```\n */\nexport function arr(items: readonly (FhirNode | undefined)[]): FhirNode | undefined {\n const present = items.filter((i): i is FhirNode => i !== undefined);\n return present.length === 0 ? undefined : list(present);\n}\n\n/**\n * A FHIR complex node from the present fields, or `undefined` when every field is absent (so an\n * all-empty datatype collapses to \"nothing to emit\" rather than an empty object).\n *\n * @param fields - The candidate `(name, value)` pairs; pairs with a `undefined` value are dropped.\n * @example\n * ```ts\n * // object([[\"city\", text(\"Boston\")], [\"state\", text(undefined)]]) -> a complex with one property\n * ```\n */\nexport function object(fields: readonly Field[]): FhirComplex | undefined {\n const props = fields\n .filter((f): f is readonly [string, FhirNode] => f[1] !== undefined)\n .map(([name, value]) => ({ name, value }));\n return props.length === 0 ? undefined : complex(props);\n}\n","/**\n * CX → FHIR `Identifier` — the patient-identity-integrity path.\n *\n * Grounded on the IG datatype ConceptMap **CX → Identifier**: `CX.1` → `Identifier.value`, `CX.4`\n * (assigning authority HD) → `Identifier.system` *when the authority resolves in a registry* (else\n * the IG maps it to `Identifier.assigner` — a message-level Organization reference this library does\n * not build), and `CX.5` (Table 0203) → `Identifier.type`.\n *\n * The load-bearing fail-safe: the assigning authority is resolved through the\n * {@link NamingSystemRegistry}, which **never synthesizes a system URI from HD.1 (the bare namespace)\n * alone** — two hospitals reusing \"MR\"/\"HOSPMRN\" would otherwise collide and merge two patients. On\n * an unresolved authority the identifier is emitted with its **value and no system**, plus a typed\n * {@link ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED} issue — never a guessed system.\n *\n * @packageDocumentation\n */\n\nimport type { CX } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/** Build `Identifier.type` (a CodeableConcept over v2-0203) from CX.5, or `undefined` when absent. */\nfunction buildType(typeCode: string | undefined): FhirComplex | undefined {\n if (typeCode === undefined || typeCode === \"\") return undefined;\n const coding = object([\n [\"system\", text(V2_0203_SYSTEM)],\n [\"code\", text(typeCode)],\n ]);\n return object([[\"coding\", arr([coding])]]);\n}\n\n/**\n * Convert a parsed HL7 v2 CX to a FHIR `Identifier` node, fail-safe on the assigning authority.\n * Returns `{ value: undefined }` when the CX carries no identifier value at all.\n *\n * @param cx - A parsed `@cosyte/hl7` `CX`.\n * @param ctx - The transform context; `ctx.namingSystem` resolves the assigning authority (HD).\n * @example\n * ```ts\n * import { toFhirIdentifier, createNamingSystem } from \"@cosyte/transform\";\n * const { value, issues } = toFhirIdentifier(\n * { idNumber: \"12345\", assigningAuthority: { namespaceId: \"HOSPMRN\" } },\n * { namingSystem: createNamingSystem() },\n * );\n * // no registry entry for a bare \"HOSPMRN\" namespace → value emitted, system absent, one issue\n * void value;\n * void issues;\n * ```\n */\nexport function toFhirIdentifier(cx: CX, ctx: TransformContext = {}): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // Nothing to key an identifier on → emit nothing (an empty CX is not an error).\n if (cx.idNumber === undefined || cx.idNumber === \"\") {\n return { value: undefined, issues };\n }\n\n // CX.4 (HD) → Identifier.system, never synthesized from HD.1 alone.\n let system: string | undefined;\n const hd = cx.assigningAuthority;\n const hasAuthority =\n hd !== undefined &&\n (hd.namespaceId !== undefined ||\n hd.universalId !== undefined ||\n hd.universalIdType !== undefined);\n if (hd !== undefined && hasAuthority) {\n system = ctx.namingSystem?.resolveAssigningAuthority(hd);\n if (system === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_IDENTIFIER_SYSTEM_UNRESOLVED, \"CX.4\", \"Identifier.system\"),\n );\n }\n }\n\n // Identifier element order (FHIR): use, type, system, value, period, assigner.\n const identifier = object([\n [\"type\", buildType(cx.identifierTypeCode)],\n [\"system\", text(system)],\n [\"value\", text(cx.idNumber)],\n ]);\n\n // CX.7 / CX.8 (effective / expiration date) map to Identifier.period in the IG, but a faithful\n // period needs the dateTime timezone policy — deferred to a later phase and flagged, not silent.\n if (cx.effectiveDate !== undefined && cx.effectiveDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.7\", \"Identifier.period\"));\n }\n if (cx.expirationDate !== undefined && cx.expirationDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.8\", \"Identifier.period\"));\n }\n // CX.9 / CX.10 (jurisdiction / agency) have no place on Identifier — flag the loss (§2 non-goals).\n if (cx.assigningJurisdiction !== undefined && cx.assigningJurisdiction !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.9\"));\n }\n if (cx.assigningAgencyOrDepartment !== undefined && cx.assigningAgencyOrDepartment !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"CX.10\"));\n }\n\n return { value: identifier, issues };\n}\n","/**\n * CWE / CE → FHIR `CodeableConcept` — the code-fidelity path.\n *\n * Grounded on the IG datatype ConceptMap **CWE → CodeableConcept**: `CWE.1`→`coding[0].code`,\n * `CWE.2`→`coding[0].display`, `CWE.3`→`coding[0].system` **(indirect — the vocabulary table gives\n * the actual URI)**, `CWE.7`→`coding[0].version`, the alternate triplet `CWE.4/5/6`→`coding[1]` (+\n * `CWE.8`→`coding[1].version`), and `CWE.9`→`text`. `CE` is the 6-component subset of `CWE` and maps\n * through the same shape.\n *\n * Two fail-safes, neither of which ever fabricates a code:\n * - **Unrecognized coding-system mnemonic** (CWE.3/CWE.6) → the code is preserved with **no system**,\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED}. A canonical URI is never invented.\n * - **A bare code with no coding system at all** (CWE.1 present, CWE.3 absent) → preserved verbatim,\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}. Never coerced to a plausible neighbor.\n *\n * This converter does **no ConceptMap value translation** (that is\n * `toFhirCodeableConceptVia`); it recognizes systems and preserves codes.\n *\n * @packageDocumentation\n */\n\nimport type { CWE } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/** The subset of CWE fields a CE also provides — so `toFhirCodeableConcept` accepts both. */\nexport type CodedElement = Pick<\n CWE,\n | \"identifier\"\n | \"text\"\n | \"nameOfCodingSystem\"\n | \"alternateIdentifier\"\n | \"alternateText\"\n | \"nameOfAlternateCodingSystem\"\n | \"codingSystemVersionId\"\n | \"alternateCodingSystemVersionId\"\n | \"originalText\"\n>;\n\n/** The four inputs to {@link buildCoding} — one CWE/CE coding triplet (code, display, system, version). */\nexport interface CodingParts {\n readonly code: string | undefined;\n readonly display: string | undefined;\n readonly mnemonic: string | undefined;\n readonly version: string | undefined;\n}\n\n/**\n * Build one `Coding` and accumulate any system/unmapped issue against it. Returns `undefined` when\n * the triplet carries no code and no display (nothing to emit). Exported so the value-translation\n * engine ({@link ../terminology/concept-map.js}) can reuse the exact same alternate-triplet\n * (`CWE.4/5/6`) resolution + fail-safe flagging when it builds an additively-translated concept.\n *\n * @param parts - The one coding triplet's code/display/system-mnemonic/version.\n * @param ctx - The transform context (its `namingSystem` resolves the mnemonic to a canonical URI).\n * @param codeLocation - The v2 location of the code component (e.g. `\"CWE.4\"`), for a value-free issue.\n * @param systemLocation - The v2 location of the coding-system component (e.g. `\"CWE.6\"`).\n * @param issues - The issue sink this call appends any system/unmapped diagnostic to.\n * @example\n * ```ts\n * // Internal helper (re-used by the terminology engine):\n * // const issues = [];\n * // const coding = buildCoding(\n * // { code: \"789-8\", display: \"Hgb\", mnemonic: \"LN\", version: undefined },\n * // { namingSystem: createNamingSystem() }, \"CWE.1\", \"CWE.3\", issues,\n * // );\n * ```\n */\nexport function buildCoding(\n parts: CodingParts,\n ctx: TransformContext,\n codeLocation: string,\n systemLocation: string,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (\n (parts.code === undefined || parts.code === \"\") &&\n (parts.display === undefined || parts.display === \"\")\n ) {\n return undefined;\n }\n\n let system: string | undefined;\n if (parts.mnemonic !== undefined && parts.mnemonic !== \"\") {\n system = ctx.namingSystem?.resolveCodeSystem(parts.mnemonic);\n if (system === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_SYSTEM_UNRESOLVED, systemLocation, \"Coding.system\"),\n );\n }\n } else if (parts.code !== undefined && parts.code !== \"\") {\n // A code with no coding-system context at all — preserved, but unmapped to any FHIR system.\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, codeLocation, \"Coding.code\"));\n }\n\n return object([\n [\"system\", text(system)],\n [\"version\", text(parts.version)],\n [\"code\", text(parts.code)],\n [\"display\", text(parts.display)],\n ]);\n}\n\n/**\n * Convert a parsed HL7 v2 CWE (or CE) to a FHIR `CodeableConcept` node, fail-safe on the coding\n * system and on unmapped codes. Returns `{ value: undefined }` when the element is empty.\n *\n * @param cwe - A parsed `@cosyte/hl7` `CWE` (a `CE` is accepted as its subset).\n * @param ctx - The transform context; `ctx.namingSystem` resolves the coding-system mnemonic.\n * @example\n * ```ts\n * import { toFhirCodeableConcept, createNamingSystem } from \"@cosyte/transform\";\n * const { value } = toFhirCodeableConcept(\n * { identifier: \"789-8\", text: \"Hemoglobin\", nameOfCodingSystem: \"LN\" },\n * { namingSystem: createNamingSystem() },\n * );\n * // coding[0] === { system: \"http://loinc.org\", code: \"789-8\", display: \"Hemoglobin\" }\n * void value;\n * ```\n */\nexport function toFhirCodeableConcept(\n cwe: CodedElement,\n ctx: TransformContext = {},\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n const primary = buildCoding(\n {\n code: cwe.identifier,\n display: cwe.text,\n mnemonic: cwe.nameOfCodingSystem,\n version: cwe.codingSystemVersionId,\n },\n ctx,\n \"CWE.1\",\n \"CWE.3\",\n issues,\n );\n const alternate = buildCoding(\n {\n code: cwe.alternateIdentifier,\n display: cwe.alternateText,\n mnemonic: cwe.nameOfAlternateCodingSystem,\n version: cwe.alternateCodingSystemVersionId,\n },\n ctx,\n \"CWE.4\",\n \"CWE.6\",\n issues,\n );\n\n const value = object([\n [\"coding\", arr([primary, alternate])],\n [\"text\", text(cwe.originalText)],\n ]);\n\n return { value, issues };\n}\n","/**\n * XPN → FHIR `HumanName`.\n *\n * Grounded on the IG datatype ConceptMap **XPN → HumanName**: `XPN.1`→`family`, `XPN.2`→`given[0]`,\n * `XPN.3`→`given[1]`, `XPN.4`→`suffix`, `XPN.5`→`prefix`, `XPN.6` (degree)→`suffix`,\n * `XPN.7`→`use` (via the IG **HL70200 → name-use** ConceptMap), `XPN.14` (professional suffix)→`suffix`.\n *\n * `XPN.7`→`use` is a **lossy code translation**: only the codes the IG's HL70200→name-use map covers\n * are translated; any other name-type code leaves `use` **absent** and raises\n * {@link ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED} — never guessed. Not converted, and flagged:\n * the name-validity period (`XPN.12`/`XPN.13`), whose FHIR `period` needs the timezone policy of the\n * dateTime path.\n *\n * @packageDocumentation\n */\n\nimport type { XPN } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/**\n * HL7 v2 Table 0200 name-type code → FHIR `name-use`, exactly per the IG **HL70200 → name-use**\n * ConceptMap (every row is \"is equivalent to\"). Codes absent here (A, B, C, F, I, K, NB, NOUSE, P,\n * REL, S, T, U, …) have **no FHIR equivalent** and are surfaced, never guessed.\n */\nexport const NAME_USE_MAP: Readonly<Record<string, string>> = Object.freeze({\n BAD: \"old\",\n D: \"usual\",\n L: \"official\",\n M: \"maiden\",\n MSK: \"anonymous\",\n N: \"nickname\",\n NAV: \"temp\",\n R: \"official\",\n TEMP: \"temp\",\n});\n\n/**\n * Convert a parsed HL7 v2 XPN to a FHIR `HumanName` node. Returns `{ value: undefined }` when the\n * name carries no emittable part.\n *\n * @param xpn - A parsed `@cosyte/hl7` `XPN`.\n * @example\n * ```ts\n * import { toFhirHumanName } from \"@cosyte/transform\";\n * const { value } = toFhirHumanName({ familyName: \"Public\", givenName: \"Jane\", nameTypeCode: \"L\" });\n * // value === HumanName { use: \"official\", family: \"Public\", given: [\"Jane\"] }\n * void value;\n * ```\n */\nexport function toFhirHumanName(xpn: XPN): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // XPN.7 → use, via the HL70200 → name-use map; unmapped → absent + flagged.\n let use: string | undefined;\n if (xpn.nameTypeCode !== undefined && xpn.nameTypeCode !== \"\") {\n use = Object.hasOwn(NAME_USE_MAP, xpn.nameTypeCode)\n ? NAME_USE_MAP[xpn.nameTypeCode]\n : undefined;\n if (use === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_NAME_USE_UNMAPPED, \"XPN.7\", \"HumanName.use\"));\n }\n }\n\n // XPN.12 / XPN.13 name-validity period is deferred (needs the dateTime timezone policy) — flagged.\n if (xpn.effectiveDate !== undefined && xpn.effectiveDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"XPN.12\", \"HumanName.period\"));\n }\n if (xpn.expirationDate !== undefined && xpn.expirationDate !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"XPN.13\", \"HumanName.period\"));\n }\n\n const value = object([\n [\"use\", text(use)],\n [\"family\", text(xpn.familyName)],\n [\"given\", arr([text(xpn.givenName), text(xpn.secondName)])],\n [\"prefix\", arr([text(xpn.prefix)])],\n // XPN.4 (suffix), XPN.6 (degree), XPN.14 (professional suffix) all land in HumanName.suffix.\n [\"suffix\", arr([text(xpn.suffix), text(xpn.degree), text(xpn.professionalSuffix)])],\n ]);\n\n return { value, issues };\n}\n","/**\n * XAD → FHIR `Address`.\n *\n * Grounded on the IG datatype ConceptMap **XAD → Address**: `XAD.1`/`XAD.2`→`line`, `XAD.3`→`city`,\n * `XAD.4`→`state`, `XAD.5`→`postalCode`, `XAD.6`→`country`, `XAD.9` (county/parish)→`district`, and\n * the **value-conditional `XAD.7`** split across two independent FHIR axes:\n * - `XAD.7 IN {BA, BI, C, B, H, O}` → `Address.use` (via the IG **HL70190 → address-use** map);\n * - `XAD.7 IN {M, SH}` → `Address.type` (via the IG **HL70190 → address-type** map);\n * - a vacation address (`V` in Table 0190; the datatype map references `HV`) → an ISO-21090 extension\n * the IG defines — **not emitted**, and flagged rather than invented;\n * - any other code → `use`/`type` left absent, flagged {@link ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED}.\n *\n * FHIR deliberately separates `use` (home/work/temp) from `type` (postal/physical), so one v2 code\n * cannot always populate both axes — round-trip is not stable, and the drop is surfaced, never hidden.\n * `XAD.8` (other geographic designation) has no FHIR target and is flagged dropped.\n *\n * @packageDocumentation\n */\n\nimport type { XAD } from \"@cosyte/hl7\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport { arr, object, text } from \"./build.js\";\n\n/** HL7 v2 Table 0190 address-type code → FHIR `address-use`, exactly per the IG HL70190→address-use map. */\nexport const ADDRESS_USE_MAP: Readonly<Record<string, string>> = Object.freeze({\n BA: \"old\",\n BI: \"billing\",\n C: \"temp\",\n B: \"work\",\n H: \"home\",\n O: \"work\",\n});\n\n/** HL7 v2 Table 0190 address-type code → FHIR `address-type`, exactly per the IG HL70190→address-type map. */\nexport const ADDRESS_TYPE_MAP: Readonly<Record<string, string>> = Object.freeze({\n M: \"postal\",\n SH: \"postal\",\n});\n\n/**\n * Convert a parsed HL7 v2 XAD to a FHIR `Address` node. Returns `{ value: undefined }` when the\n * address carries no emittable part.\n *\n * @param xad - A parsed `@cosyte/hl7` `XAD`.\n * @example\n * ```ts\n * import { toFhirAddress } from \"@cosyte/transform\";\n * const { value } = toFhirAddress({ street: \"1 Main St\", city: \"Boston\", stateOrProvince: \"MA\", addressType: \"H\" });\n * // value === Address { use: \"home\", line: [\"1 Main St\"], city: \"Boston\", state: \"MA\" }\n * void value;\n * ```\n */\nexport function toFhirAddress(xad: XAD): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // XAD.7 → use and/or type across the two independent axes; unmapped (incl. HV) → flagged, absent.\n let use: string | undefined;\n let type: string | undefined;\n if (xad.addressType !== undefined && xad.addressType !== \"\") {\n use = Object.hasOwn(ADDRESS_USE_MAP, xad.addressType)\n ? ADDRESS_USE_MAP[xad.addressType]\n : undefined;\n type = Object.hasOwn(ADDRESS_TYPE_MAP, xad.addressType)\n ? ADDRESS_TYPE_MAP[xad.addressType]\n : undefined;\n if (use === undefined && type === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ADDRESS_USE_UNMAPPED, \"XAD.7\", \"Address.use\"));\n }\n }\n\n // XAD.8 (other geographic designation) has no FHIR target — flag the drop.\n if (xad.otherGeographicDesignation !== undefined && xad.otherGeographicDesignation !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"XAD.8\"));\n }\n\n const value = object([\n [\"use\", text(use)],\n [\"type\", text(type)],\n [\"line\", arr([text(xad.street), text(xad.otherDesignation)])],\n [\"city\", text(xad.city)],\n [\"district\", text(xad.countyParishCode)],\n [\"state\", text(xad.stateOrProvince)],\n [\"postalCode\", text(xad.zipOrPostalCode)],\n [\"country\", text(xad.country)],\n ]);\n\n return { value, issues };\n}\n","/**\n * NM + units (CWE) → FHIR `Quantity`.\n *\n * Grounded on the IG datatype maps for OBX-5 (NM)→`Quantity.value` and OBX-6 (CWE units)→\n * `Quantity.unit`/`.code`/`.system`. Two hard fail-safes:\n *\n * - **Never convert magnitudes.** The numeric value is carried through **precision-exact** via\n * `@cosyte/fhir`'s string-backed `decimal` (a dose or lab value is never routed through a JS\n * `number`). UCUM magnitude conversion (mg/dL ↔ mmol/L) is analyte-dependent and a\n * clinical-safety footgun — an explicit non-goal, never a transform side effect.\n * - **Never fabricate a UCUM code.** A unit is emitted into `Quantity.code`/`.system` **only** when\n * it is declared UCUM and passes `@cosyte/fhir`'s UCUM shape check. Any other unit is preserved\n * verbatim in `Quantity.unit` with `code`/`system` absent, flagged\n * {@link ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM}.\n *\n * @packageDocumentation\n */\n\nimport type { CWE, NM } from \"@cosyte/hl7\";\nimport {\n decimal,\n primitive,\n UCUM_SYSTEM,\n validateUcumShape,\n type FhirComplex,\n type FhirNode,\n} from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { object, text } from \"./build.js\";\n\n/**\n * Convert a parsed HL7 v2 numeric value plus its units to a FHIR `Quantity` node, fail-safe on the\n * unit. Returns `{ value: undefined }` when the numeric magnitude is absent or non-numeric (a\n * Quantity without a value cannot be safely emitted).\n *\n * @param value - A parsed `@cosyte/hl7` `NM` (its `.raw` carries the exact lexical value).\n * @param units - The units component (an OBX-6 `CWE`); its CWE.1 is the candidate UCUM code.\n * @param ctx - The transform context; used to recognize the UCUM coding system.\n * @example\n * ```ts\n * import { toFhirQuantity } from \"@cosyte/transform\";\n * const { value } = toFhirQuantity(\n * { raw: \"5.4\", value: 5.4 },\n * { identifier: \"mg/dL\", nameOfCodingSystem: \"UCUM\" },\n * );\n * // value === Quantity { value: 5.4, unit: \"mg/dL\", system: \"http://unitsofmeasure.org\", code: \"mg/dL\" }\n * void value;\n * ```\n */\nexport function toFhirQuantity(\n value: NM,\n units: CWE,\n ctx: TransformContext = {},\n): ConvertResult<FhirComplex> {\n // No numeric magnitude → nothing safe to emit as a Quantity (never guess a value).\n if (value.value === undefined || value.raw === \"\") {\n return { value: undefined, issues: [] };\n }\n return quantityFromRawMagnitude(value.raw, units, ctx);\n}\n\n/**\n * Build a FHIR `Quantity` from a **raw lexical magnitude string** plus its units, fail-safe on both\n * the magnitude and the unit, with an optional `Quantity.comparator`. This is the shared core behind\n * {@link toFhirQuantity} (NM) and the SN → `valueQuantity`/`valueRange`/`valueRatio` observation path.\n * Both must carry the magnitude through **precision-exact** as a string-backed `decimal` and\n * apply the identical no-fabricated-UCUM unit gate — so they share one implementation rather than two\n * that could drift.\n *\n * Returns `{ value: undefined }` (+ a {@link ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID} issue) when\n * the raw magnitude is not a faithful FHIR `decimal` literal — never a canonicalized (altered) value.\n *\n * @param raw - The magnitude's exact lexical form (e.g. OBX-5 NM `.raw`, or an SN component string).\n * @param units - The units component (a CWE); its CWE.1 is the candidate UCUM code.\n * @param ctx - The transform context; used to recognize the UCUM coding system.\n * @param comparator - An optional FHIR `Quantity.comparator` (`<` `<=` `>=` `>`), from an SN comparator.\n * @param valueLocation - The v2 location of the magnitude, for the invalid-value issue (default `OBX.5`).\n * @param unitLocation - The v2 location of the units, for the not-UCUM issue (default `OBX.6`).\n * @example\n * ```ts\n * // internal shared core (used by toFhirQuantity for NM and the observation SN path):\n * // const { value } = quantityFromRawMagnitude(\"90\", { identifier: \"mg/dL\", nameOfCodingSystem: \"UCUM\" }, {}, \">\");\n * // value === Quantity { comparator: \">\", value: 90, unit: \"mg/dL\", system: UCUM, code: \"mg/dL\" }\n * ```\n */\nexport function quantityFromRawMagnitude(\n raw: string,\n units: CWE,\n ctx: TransformContext = {},\n comparator?: string,\n valueLocation = \"OBX.5\",\n unitLocation = \"OBX.6\",\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n if (raw === \"\") {\n return { value: undefined, issues };\n }\n // A raw magnitude keeps its v2 lexical form (v2 allows a leading `+`, leading zeros, a trailing dot),\n // but the FHIR `decimal` literal forbids those. Rather than canonicalize — which would ALTER the\n // magnitude's lexical form — fail safe: if a faithful decimal can't be built, emit a typed issue and\n // no value. (`decimal` throws on a non-conforming literal; catch it so this never throws — §4.6.)\n let valueNode: FhirNode;\n try {\n valueNode = primitive(decimal(raw));\n } catch {\n return {\n value: undefined,\n issues: [\n issue(ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID, valueLocation, \"Quantity.value\"),\n ],\n };\n }\n\n const unitCode = units.identifier; // CWE.1 — the candidate coded (UCUM) unit\n const unitDisplay = units.text; // CWE.2 — the human display unit\n const hasUnit =\n (unitCode !== undefined && unitCode !== \"\") ||\n (unitDisplay !== undefined && unitDisplay !== \"\");\n\n let ucumCode: string | undefined;\n let system: string | undefined;\n let unitStr: string | undefined = unitDisplay ?? unitCode;\n\n if (hasUnit) {\n const mnemonic = units.nameOfCodingSystem;\n const declaredUcum =\n mnemonic === \"UCUM\" ||\n (mnemonic !== undefined && ctx.namingSystem?.resolveCodeSystem(mnemonic) === UCUM_SYSTEM);\n if (\n declaredUcum &&\n unitCode !== undefined &&\n unitCode !== \"\" &&\n validateUcumShape(unitCode) === \"ok\"\n ) {\n ucumCode = unitCode;\n system = UCUM_SYSTEM;\n unitStr = unitDisplay ?? unitCode;\n } else {\n // Non-UCUM or unvalidatable → preserve verbatim, no code/system, magnitude untouched.\n issues.push(issue(ISSUE_CODES.TRANSFORM_UNIT_NOT_UCUM, unitLocation, \"Quantity.code\"));\n }\n }\n\n const quantity = object([\n [\"comparator\", text(comparator)],\n [\"value\", valueNode],\n [\"unit\", text(unitStr)],\n [\"system\", text(system)],\n [\"code\", text(ucumCode)],\n ]);\n\n return { value: quantity, issues };\n}\n","/**\n * The `$translate`-shaped ConceptMap-application engine + the **license-clean** v2-table → FHIR\n * value maps it applies. This is the layer that value-**translates** a coded v2\n * field — not merely carrying its code structurally, but mapping the source table code to the FHIR\n * target coding the IG's segment-map `mappedVia` ConceptMap prescribes.\n *\n * **Grounded firsthand on the raw published IG ConceptMaps** (`hl7.fhir.uv.v2mappings`, STU1 —\n * `ConceptMap-table-*.json`). Each shipped map below cites the exact IG ConceptMap it transcribes and\n * was verified against that resource's JSON (its `group.element[].target[]` rows and its `unmatched`\n * `(unmapped)` group). The engine is **fail-safe by refusal**: a source code the IG map has **no\n * target** for (its `(unmapped)` group) is never coerced to a plausible neighbor — the caller flags it\n * and preserves the raw coding, or withholds the value, but a target is **never fabricated**.\n *\n * **License posture.** Only maps whose target CodeSystem is **freely redistributable** are\n * shipped here: the HL7 THO v2 tables (`v2-0162`, `v2-0550`, `v2-0277`, `v2-0161`) and HL7 v3\n * (`v3-RouteOfAdministration`) are HL7's own, license-clean. The IG's `*-to-sct` value maps —\n * **RXR-4 method** (`table-hl70165-to-sct`) and **SCH-7 reason** (`table-hl70276-to-sct`) — translate\n * **into SNOMED CT**, which is **license-encumbered and is NOT bundled**; those fields stay\n * structurally carried (BYO ConceptMap), never value-translated here (see their message modules).\n *\n * **Additive, never mutating.** A successful translation preserves the raw source coding\n * (its code, display, version, and any `CWE.4/5/6` alternate triplet) and *adds* the derived target\n * coding — recognition never overwrites or discards what the message said; it augments it with the\n * IG-mapped equivalent. And it only fires when the field's primary coding is genuinely from the map's\n * **bound source table** (CWE.3 absent, or naming that table): a field that declares a *foreign*\n * coding system (a local `99…`, SNOMED, …) is carried structurally and flagged — its code is **never**\n * asserted to be the standard concept just because the string happens to collide with a table code.\n *\n * @packageDocumentation\n */\n\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport {\n buildCoding,\n toFhirCodeableConcept,\n type CodedElement,\n} from \"../datatypes/codeable-concept.js\";\nimport type { TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"./context.js\";\n\n// ── Target CodeSystem canonical URIs (all license-clean HL7 THO / v3) ────────────────────────────\n\n/** HL7 v2 Table 0162 (Route of Administration) THO CodeSystem URI. */\nexport const V2_0162_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0162\";\n/** HL7 v3 RouteOfAdministration CodeSystem URI (the IG's remap target for the six common routes). */\nexport const V3_ROUTE_OF_ADMINISTRATION_SYSTEM =\n \"http://terminology.hl7.org/CodeSystem/v3-RouteOfAdministration\";\n/** HL7 v2 Table 0550 (Body Parts) THO CodeSystem URI. */\nexport const V2_0550_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0550\";\n/** HL7 v2 Table 0277 (Appointment Type Codes) THO CodeSystem URI. */\nexport const V2_0277_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0277\";\n/** HL7 v2 Table 0161 (Allow Substitution) THO CodeSystem URI. */\nexport const V2_0161_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0161\";\n\n/** A translated FHIR target coding: the target CodeSystem URI + code, and the IG's target display. */\nexport interface CodedTarget {\n /** The FHIR target CodeSystem canonical URI. */\n readonly system: string;\n /** The FHIR target code. */\n readonly code: string;\n /** The IG map's target display, when it carries one (absent for the identity table maps). */\n readonly display?: string;\n}\n\n/**\n * A license-clean v2-table → FHIR value ConceptMap: it translates a **source table code** to its\n * {@link CodedTarget}, or `undefined` when the code is not in the map's *mapped* group (the IG's\n * `(unmapped)` group). Never fabricates a target.\n */\nexport interface CodedValueMap {\n /** The IG ConceptMap id this map transcribes (its citation). */\n readonly name: string;\n /** The source table's canonical CodeSystem URI (what the raw v2 code is a member of when mapped). */\n readonly sourceSystem: string;\n /**\n * The CWE.3 (`nameOfCodingSystem`) mnemonics that denote this map's **bound source table** — the\n * HL7 forms (`\"HL70162\"`, `\"0162\"`, …). Translation applies **only** when the field's primary\n * coding is from the bound table: CWE.3 absent/empty (a positionally-bound bare code) **or** CWE.3 ∈\n * this set. A CWE that declares a **different** coding system (a local `99…`, or SNOMED) is not a\n * source-table code, so the map is not applied to it — the raw coding is carried structurally + its\n * system flagged, never asserted as the standard concept.\n */\n readonly sourceMnemonics: ReadonlySet<string>;\n /** Translate a source table code to its FHIR target, or `undefined` when the IG map has no target. */\n readonly translate: (code: string) => CodedTarget | undefined;\n}\n\n/** Build a {@link CodedValueMap} from an explicit source-code → target table + its bound mnemonics. */\nfunction valueMap(\n name: string,\n sourceSystem: string,\n sourceMnemonics: readonly string[],\n targets: Readonly<Record<string, CodedTarget>>,\n): CodedValueMap {\n return Object.freeze({\n name,\n sourceSystem,\n sourceMnemonics: new Set(sourceMnemonics),\n translate: (code: string): CodedTarget | undefined =>\n Object.hasOwn(targets, code) ? targets[code] : undefined,\n });\n}\n\n/** Build an identity target table (each code maps to itself in `system`) from a code list. */\nfunction identityTargets(system: string, codes: readonly string[]): Record<string, CodedTarget> {\n const t: Record<string, CodedTarget> = {};\n for (const code of codes) t[code] = { system, code };\n return t;\n}\n\n// ── The shipped, license-clean value maps (each verified firsthand against its IG ConceptMap) ────\n\n/**\n * **RXR-1 Route** — IG `ConceptMap/table-hl70162-to-v2-0162`. Two IG groups, transcribed verbatim:\n * a 41-code **identity** group (source `v2-0162` → target `v2-0162`, each `equivalent`) and a 6-code\n * **remap** group into `v3-RouteOfAdministration` (`ID→IDINJ`, `IM→IM`, `IV→IVINJ`, `PO→PO`, `SC→SQ`,\n * `TD→TRNSDERM`, each `equivalent`, with the IG target displays). The two source-code sets are\n * disjoint. Any other v2-0162 code (or a non-table code) is unmapped → the raw coding is preserved\n * and flagged, never coerced.\n */\nexport const ROUTE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70162-to-v2-0162\",\n V2_0162_SYSTEM,\n [\"HL70162\", \"0162\"],\n {\n ...identityTargets(V2_0162_SYSTEM, [\n \"AP\",\n \"B\",\n \"DT\",\n \"EP\",\n \"ET\",\n \"GTT\",\n \"GU\",\n \"IMR\",\n \"IA\",\n \"IB\",\n \"IC\",\n \"ICV\",\n \"IH\",\n \"IHA\",\n \"IN\",\n \"IO\",\n \"IP\",\n \"IS\",\n \"IT\",\n \"IU\",\n \"MTH\",\n \"MM\",\n \"NS\",\n \"NG\",\n \"NP\",\n \"NT\",\n \"OP\",\n \"OT\",\n \"OTH\",\n \"PF\",\n \"PR\",\n \"RM\",\n \"SD\",\n \"SL\",\n \"TP\",\n \"TRA\",\n \"TL\",\n \"UR\",\n \"VG\",\n \"VM\",\n \"WND\",\n ]),\n ID: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"IDINJ\",\n display: \"Injection, intradermal\",\n },\n IM: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"IM\",\n display: \"Injection, intramuscular\",\n },\n IV: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"IVINJ\",\n display: \"Injection, intravenous\",\n },\n PO: { system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM, code: \"PO\", display: \"Swallow, oral\" },\n SC: {\n system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n code: \"SQ\",\n display: \"Injection, subcutaneous\",\n },\n TD: { system: V3_ROUTE_OF_ADMINISTRATION_SYSTEM, code: \"TRNSDERM\", display: \"Transdermal\" },\n },\n);\n\n/**\n * **RXR-2 Administration Site** — IG `ConceptMap/table-hl70550-to-v2-0550`. A single **identity**\n * group of 443 body-part codes (source `v2-0550` → target `v2-0550`, each `equivalent`), transcribed\n * verbatim from the published STU1 ConceptMap — **including** its as-published data-quality artifacts\n * (`CHESTÂ`, a lone `Â`, `KIDNÂ`, where a stray U+00C2 leaked from the IG's source\n * encoding). They are preserved for source-fidelity; they are inert (a clean `CHEST`/`KIDN` simply\n * falls through to unmapped). A code not in the table is unmapped → raw coding preserved + flagged.\n */\nexport const SITE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70550-to-v2-0550\",\n V2_0550_SYSTEM,\n [\"HL70550\", \"0550\"],\n identityTargets(V2_0550_SYSTEM, [\n \"JUGE\",\n \"ADB\",\n \"ACET\",\n \"ACHIL\",\n \"ADE\",\n \"ADR\",\n \"AMN\",\n \"AMS\",\n \"ANAL\",\n \"ANKL\",\n \"ANTEC\",\n \"ANTECF\",\n \"ANTR\",\n \"ANUS\",\n \"AORTA\",\n \"AR\",\n \"AV\",\n \"APDX\",\n \"AREO\",\n \"ARM\",\n \"ARTE\",\n \"ASCIT\",\n \"ASCT\",\n \"ATR\",\n \"AURI\",\n \"AXI\",\n \"BACK\",\n \"BARTD\",\n \"BARTG\",\n \"BRTGF\",\n \"BPH\",\n \"BID\",\n \"BIFL\",\n \"BLAD\",\n \"BLOOD\",\n \"BLDA\",\n \"BLDC\",\n \"BLDV\",\n \"CBLD\",\n \"BLD\",\n \"BDY\",\n \"BON\",\n \"BMAR\",\n \"BOWEL\",\n \"BOWLA\",\n \"BOWSM\",\n \"BRA\",\n \"BRAIN\",\n \"BCYS\",\n \"BRST\",\n \"BRSTFL\",\n \"BRO\",\n \"BROCH\",\n \"BRONC\",\n \"BRV\",\n \"BUCCA\",\n \"BURSA\",\n \"BURSF\",\n \"BUTT\",\n \"CALF\",\n \"CANAL\",\n \"CANLI\",\n \"CNL\",\n \"CANTH\",\n \"CDM\",\n \"CARO\",\n \"CARP\",\n \"CAVIT\",\n \"CHE\",\n \"CECUM\",\n \"CSF\",\n \"CVX\",\n \"CERVUT\",\n \"CHEEK\",\n \"CHES\",\n \"CHESTÂ\",\n \"CHIN\",\n \"CIRCU\",\n \"CLAVI\",\n \"CLITO\",\n \"CLIT\",\n \"COCCG\",\n \"COCCY\",\n \"COLON\",\n \"COLOS\",\n \"COS\",\n \"CDUCT\",\n \"CONJ\",\n \"CORAL\",\n \"COR\",\n \"CORD\",\n \"CORN\",\n \"CRANE\",\n \"CRANF\",\n \"CRANO\",\n \"CRANP\",\n \"CRANS\",\n \"CRANT\",\n \"CUBIT\",\n \"CUFF\",\n \"CULD\",\n \"CULDO\",\n \"DELT\",\n \"DENTA\",\n \"DEN\",\n \"DIAF\",\n \"DPH\",\n \"DIGIT\",\n \"DISC\",\n \"DORS\",\n \"DUFL\",\n \"DUODE\",\n \"DUR\",\n \"EAR\",\n \"EARBI\",\n \"EARBM\",\n \"EARBS\",\n \"EARLO\",\n \"ELBOW\",\n \"ELBOWJ\",\n \"ENDC\",\n \"EC\",\n \"EOLPH\",\n \"ENDM\",\n \"ET\",\n \"EUR\",\n \"EOS\",\n \"EPICA\",\n \"EPICM\",\n \"EPD\",\n \"EPIDU\",\n \"EPIGL\",\n \"ESOPG\",\n \"ESO\",\n \"ETHMO\",\n \"Â\",\n \"EYE\",\n \"BROW\",\n \"EYELI\",\n \"FACE\",\n \"FBINC\",\n \"FBLAC\",\n \"FBMAX\",\n \"FBNAS\",\n \"FBPAL\",\n \"FBVOM\",\n \"FBZYG\",\n \"FALLT\",\n \"FEMOR\",\n \"FMH\",\n \"FEMUR\",\n \"FET\",\n \"FIBU\",\n \"FING\",\n \"FINGN\",\n \"FOL\",\n \"FOOT\",\n \"FOREA\",\n \"FOREH\",\n \"FORES\",\n \"FOURC\",\n \"GB\",\n \"GEN\",\n \"GVU\",\n \"GENC\",\n \"GL\",\n \"GENL\",\n \"GLAND\",\n \"GLANS\",\n \"GLUTE\",\n \"GLUT\",\n \"GLUTM\",\n \"GROIN\",\n \"GUM\",\n \"HAR\",\n \"HAL\",\n \"HAND\",\n \"HEAD\",\n \"HART\",\n \"HV\",\n \"HVB\",\n \"HVT\",\n \"HEEL\",\n \"HEM\",\n \"HIP\",\n \"HIPJ\",\n \"HUMER\",\n \"HYMEN\",\n \"ILC\",\n \"ILE\",\n \"ILEOS\",\n \"ILEUM\",\n \"ILIAC\",\n \"ILCR\",\n \"ILCON\",\n \"INGUI\",\n \"JUGI\",\n \"INT\",\n \"ICX\",\n \"INASA\",\n \"INTRU\",\n \"INTRO\",\n \"ISCHI\",\n \"JAW\",\n \"KIDNÂ\",\n \"KNEE\",\n \"KNEEF\",\n \"KNEEJ\",\n \"LABIA\",\n \"LABMA\",\n \"LABMI\",\n \"LACRI\",\n \"LAM\",\n \"INSTL\",\n \"LARYN\",\n \"LEG\",\n \"LENS\",\n \"WBC\",\n \"LING\",\n \"LINGU\",\n \"LIP\",\n \"STOOLL\",\n \"LIVER\",\n \"LOBE\",\n \"LOCH\",\n \"ISH\",\n \"LUMBA\",\n \"LMN\",\n \"LUNG\",\n \"LN\",\n \"LNG\",\n \"LYM\",\n \"MAC\",\n \"MALLE\",\n \"MANDI\",\n \"MAR\",\n \"MAST\",\n \"MAXIL\",\n \"MAXS\",\n \"MEATU\",\n \"MEC\",\n \"MEDST\",\n \"MEDU\",\n \"MOU\",\n \"MPB\",\n \"METAC\",\n \"METAT\",\n \"MILK\",\n \"MITRL\",\n \"MOLAR\",\n \"MP\",\n \"MONSU\",\n \"MONSV\",\n \"MOUTH\",\n \"MRSA2\",\n \"MYO\",\n \"NAIL\",\n \"NAILB\",\n \"NAILF\",\n \"NAILT\",\n \"NARES\",\n \"NASL\",\n \"NSS\",\n \"NLACR\",\n \"NP\",\n \"NTRAC\",\n \"NAVEL\",\n \"NECK\",\n \"NERVE\",\n \"NIPPL\",\n \"NOS\",\n \"NOSE\",\n \"NOSTR\",\n \"OCCIP\",\n \"OLECR\",\n \"OMEN\",\n \"ORBIT\",\n \"ORO\",\n \"OSCOX\",\n \"OVARY\",\n \"PALAT\",\n \"PLATH\",\n \"PLATS\",\n \"PALM\",\n \"PANCR\",\n \"PAFL\",\n \"PAS\",\n \"PARAT\",\n \"PARIE\",\n \"PARON\",\n \"PAROT\",\n \"PATEL\",\n \"PELV\",\n \"PENSH\",\n \"PENIS\",\n \"PANAL\",\n \"PERI\",\n \"PCARD\",\n \"PCLIT\",\n \"PERIH\",\n \"PNEAL\",\n \"PERIN\",\n \"PNEPH\",\n \"PNM\",\n \"PORBI\",\n \"PERRA\",\n \"PERIS\",\n \"PER\",\n \"PERT\",\n \"PERIT\",\n \"PTONS\",\n \"PERIU\",\n \"PERIV\",\n \"PHALA\",\n \"PILO\",\n \"PINNA\",\n \"PLC\",\n \"PLACF\",\n \"PLACM\",\n \"PLANT\",\n \"PLEUR\",\n \"PLEU\",\n \"PLR\",\n \"POPLI\",\n \"PREAU\",\n \"PRERE\",\n \"PRST\",\n \"PROS\",\n \"PUBIC\",\n \"PUL\",\n \"RADI\",\n \"RADIUS\",\n \"RECTL\",\n \"RECTU\",\n \"RBC\",\n \"RENL\",\n \"RNP\",\n \"RPERI\",\n \"RIB\",\n \"SACRA\",\n \"SACRO\",\n \"SACIL\",\n \"SACRU\",\n \"SALGL\",\n \"SCALP\",\n \"SCAPU\",\n \"SCLER\",\n \"SCROT\",\n \"SEMN\",\n \"SEM\",\n \"SEPTU\",\n \"SEROM\",\n \"SHIN\",\n \"SHOLJ\",\n \"SHOL\",\n \"SIGMO\",\n \"SINUS\",\n \"SKM\",\n \"SKENE\",\n \"SKULL\",\n \"INSTS\",\n \"SOLE\",\n \"SPRM\",\n \"SPHEN\",\n \"SPCOR\",\n \"SPLN\",\n \"STER\",\n \"STOM\",\n \"USTOM\",\n \"STOMA\",\n \"STUMP\",\n \"SCLV\",\n \"SDP\",\n \"SUB\",\n \"SUBD\",\n \"SGF\",\n \"SUBM\",\n \"SUBX\",\n \"SUBME\",\n \"SUBPH\",\n \"SPX\",\n \"SCLAV\",\n \"SUPRA\",\n \"SUPB\",\n \"SWT\",\n \"SWTG\",\n \"SYNOL\",\n \"SYN\",\n \"SYNOV\",\n \"TARS\",\n \"TDUCT\",\n \"TEAR\",\n \"TEMPL\",\n \"TEMPO\",\n \"TML\",\n \"TESTI\",\n \"THIGH\",\n \"THORA\",\n \"THRB\",\n \"THUMB\",\n \"TNL\",\n \"THM\",\n \"THYRD\",\n \"TIBIA\",\n \"TOE\",\n \"TOEN\",\n \"TONG\",\n \"TONS\",\n \"TOOTH\",\n \"TSK\",\n \"TRCHE\",\n \"TBRON\",\n \"TCN\",\n \"ULNA\",\n \"UMB\",\n \"UMBL\",\n \"URET\",\n \"URTH\",\n \"UTERI\",\n \"SAC\",\n \"UTER\",\n \"VAGIN\",\n \"VCUFF\",\n \"VGV\",\n \"VAL\",\n \"VAS\",\n \"VASTL\",\n \"VAULT\",\n \"VEIN\",\n \"VENTG\",\n \"VCSF\",\n \"VERMI\",\n \"VERTC\",\n \"VERTL\",\n \"VERTT\",\n \"VESI\",\n \"VESCL\",\n \"VESFLD\",\n \"VESTI\",\n \"VITR\",\n \"VOC\",\n \"VULVA\",\n \"WRIST\",\n ]),\n);\n\n/**\n * **SCH-8 Appointment Type** — IG `ConceptMap/table-hl70277-to-v2-0277`. A single **identity** group\n * of the three v2-0277 codes (`Normal`, `Tentative`, `Complete` → themselves, each `equivalent`,\n * source and target both `v2-0277`). Any other code is unmapped → raw coding preserved + flagged.\n */\nexport const APPOINTMENT_TYPE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70277-to-v2-0277\",\n V2_0277_SYSTEM,\n [\"HL70277\", \"0277\"],\n identityTargets(V2_0277_SYSTEM, [\"Normal\", \"Tentative\", \"Complete\"]),\n);\n\n/**\n * **RXO-9 Allow Substitutions** — IG `ConceptMap/table-hl70161-to-v2-0161`. A single **identity**\n * group of the three v2-0161 codes (`N` NOT authorized, `G` generic, `T` therapeutic → themselves,\n * each `equivalent`, source and target both `v2-0161`), the target for\n * `MedicationRequest.substitution.allowedCodeableConcept`. Any other code is unmapped → the\n * substitution is withheld + flagged, never a fabricated substitution permission.\n */\nexport const SUBSTITUTION_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70161-to-v2-0161\",\n V2_0161_SYSTEM,\n [\"HL70161\", \"0161\"],\n identityTargets(V2_0161_SYSTEM, [\"N\", \"G\", \"T\"]),\n);\n\n// ── Application: the $translate-shaped, additive, fail-safe engine ────────────────────────────────\n\n/** Build a FHIR `Coding` node (system, optional version, code, optional display). */\nfunction codingFrom(\n system: string,\n code: string,\n display: string | undefined,\n version?: string,\n): FhirComplex {\n const props: { name: string; value: FhirNode }[] = [{ name: \"system\", value: primitive(system) }];\n if (version !== undefined && version !== \"\")\n props.push({ name: \"version\", value: primitive(version) });\n props.push({ name: \"code\", value: primitive(code) });\n if (display !== undefined && display !== \"\")\n props.push({ name: \"display\", value: primitive(display) });\n return complex(props);\n}\n\n/**\n * The bound-table target for a coded element's **primary** coding, or `undefined` when the map does\n * not faithfully apply — i.e. the primary declares a coding system that is **not** this map's bound\n * table (CWE.3 present and not in {@link CodedValueMap.sourceMnemonics}), the primary code is empty, or\n * the code is in the IG map's `(unmapped)` group. Never asserts a standard translation for a foreign\n * coding system, and never fabricates a target.\n *\n * @param cwe - The parsed coded element (its `identifier` is the candidate source-table code).\n * @param map - The license-clean value map to consider applying.\n * @example\n * ```ts\n * import { translateBound, ROUTE_VALUE_MAP } from \"@cosyte/transform\";\n * translateBound({ identifier: \"IM\" }, ROUTE_VALUE_MAP)?.code; // \"IM\" (v3 route)\n * translateBound({ identifier: \"IM\", nameOfCodingSystem: \"99LOCAL\" }, ROUTE_VALUE_MAP); // undefined\n * ```\n */\nexport function translateBound(cwe: CodedElement, map: CodedValueMap): CodedTarget | undefined {\n const mnemonic = cwe.nameOfCodingSystem;\n const fromBoundTable =\n mnemonic === undefined || mnemonic === \"\" || map.sourceMnemonics.has(mnemonic);\n if (!fromBoundTable) return undefined;\n const code = cwe.identifier;\n return code === undefined || code === \"\" ? undefined : map.translate(code);\n}\n\n/**\n * Build a FHIR `CodeableConcept` node for a {@link CodedTarget} — the single translated coding, with\n * an optional free-`text`. Used by translate-or-withhold callers (e.g. substitution) that build the\n * CodeableConcept only on a successful translation.\n *\n * @param target - The translated target coding.\n * @param text - The original free text (`CWE.9`) to carry as `CodeableConcept.text`, if any.\n * @example\n * ```ts\n * import { codeableConceptFromTarget, V2_0161_SYSTEM } from \"@cosyte/transform\";\n * const cc = codeableConceptFromTarget({ system: V2_0161_SYSTEM, code: \"G\" });\n * void cc;\n * ```\n */\nexport function codeableConceptFromTarget(target: CodedTarget, text?: string): FhirComplex {\n const props: { name: string; value: FhirNode }[] = [\n { name: \"coding\", value: list([codingFrom(target.system, target.code, target.display)]) },\n ];\n if (text !== undefined && text !== \"\") props.push({ name: \"text\", value: primitive(text) });\n return complex(props);\n}\n\n/**\n * Value-translate a coded v2 element to a FHIR `CodeableConcept` **via** a license-clean\n * {@link CodedValueMap}, **additively** and fail-safe — never mutating or discarding what the message\n * said:\n *\n * - **Primary code recognized as a bound-table code** ({@link translateBound} — CWE.3 absent or names\n * the bound table, and the code is in the IG map's mapped group) → the **primary** coding is emitted\n * in the recognized source-table system (`map.sourceSystem`, carrying `CWE.7` version) and the\n * **derived** target coding is *appended* when it differs (a remap such as `SC→SQ`); the **alternate\n * triplet** (`CWE.4/5/6`, via {@link buildCoding}, with its own system resolution + flags) and the\n * original `CWE.9` text are preserved. No primary unmapped flag — the value was faithfully recognized.\n * - **Otherwise** — the primary declares a **foreign** coding system (not the bound table), the code is\n * empty, or it is in the IG's `(unmapped)` group → this defers entirely to the **structural**\n * {@link toFhirCodeableConcept}, which preserves the raw coding (and its `CWE.4/5/6` alternate and\n * `CWE.7` version) and flags it ({@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} /\n * `TRANSFORM_CODE_SYSTEM_UNRESOLVED`). A target is **never** fabricated, and a code that declares a\n * foreign system is **never** asserted to be the standard concept.\n *\n * @param cwe - The parsed `@cosyte/hl7` coded element (its `identifier` is the candidate table code).\n * @param map - The license-clean value map to apply (e.g. {@link ROUTE_VALUE_MAP}).\n * @param ctx - The transform context (threaded to the structural path + the alternate-triplet resolver).\n * @example\n * ```ts\n * import { toFhirCodeableConceptVia, ROUTE_VALUE_MAP } from \"@cosyte/transform\";\n * const { value } = toFhirCodeableConceptVia({ identifier: \"IM\" }, ROUTE_VALUE_MAP);\n * // coding === [{ system: \".../v2-0162\", code: \"IM\" },\n * // { system: \".../v3-RouteOfAdministration\", code: \"IM\", display: \"Injection, intramuscular\" }]\n * void value;\n * ```\n */\nexport function toFhirCodeableConceptVia(\n cwe: CodedElement,\n map: CodedValueMap,\n ctx: TransformContext = {},\n): ConvertResult<FhirComplex> {\n const target = translateBound(cwe, map);\n\n if (target === undefined) {\n // Foreign coding system, empty code, or IG-unmapped → structural carry (raw preserved + flagged).\n return toFhirCodeableConcept(cwe, ctx);\n }\n\n const issues: TransformIssue[] = [];\n const codings: FhirComplex[] = [];\n\n // Primary coding — recognized as a bound-table code: emitted in the source-table system (no flag),\n // carrying the CWE.2 display and CWE.7 version.\n codings.push(\n codingFrom(map.sourceSystem, cwe.identifier as string, cwe.text, cwe.codingSystemVersionId),\n );\n\n // Derived (translated) target coding — appended only for a remap (target ≠ the primary coding);\n // for an identity map the primary already IS the target, so no duplicate is added.\n const isIdentity = target.system === map.sourceSystem && target.code === cwe.identifier;\n if (!isIdentity) codings.push(codingFrom(target.system, target.code, target.display));\n\n // Alternate triplet (CWE.4/5/6 + CWE.8 version) — preserved via the same structural builder the\n // datatype path uses, so its system resolution and fail-safe flags are identical, never dropped.\n const alternate = buildCoding(\n {\n code: cwe.alternateIdentifier,\n display: cwe.alternateText,\n mnemonic: cwe.nameOfAlternateCodingSystem,\n version: cwe.alternateCodingSystemVersionId,\n },\n ctx,\n \"CWE.4\",\n \"CWE.6\",\n issues,\n );\n if (alternate !== undefined) codings.push(alternate);\n\n const props: { name: string; value: FhirNode }[] = [{ name: \"coding\", value: list(codings) }];\n if (cwe.originalText !== undefined && cwe.originalText !== \"\") {\n props.push({ name: \"text\", value: primitive(cwe.originalText) });\n }\n return { value: complex(props), issues };\n}\n","/**\n * Bundle-assembly primitives shared by the segment→resource builders: fresh `urn:uuid:` identities,\n * FHIR `Reference` nodes, and the small coding/data-absent helpers the message maps need.\n *\n * The identities are the wiring of the resource graph — a produced resource is registered under a\n * `urn:uuid:` `fullUrl`, and every intra-bundle reference (Encounter→subject→Patient,\n * RelatedPerson→patient→Patient, MessageHeader→focus→…) points at that same `fullUrl` so references\n * always resolve **within** the bundle. Identities come from {@link TransformOptions.generateId}\n * (default `crypto.randomUUID`) so output can be made reproducible for golden fixtures.\n *\n * @packageDocumentation\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { complex, primitive, list, type FhirComplex } from \"@cosyte/fhir\";\n\nimport type { TransformOptions } from \"../terminology/context.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\n\n/** The FHIR `data-absent-reason` extension canonical URL. */\nconst DATA_ABSENT_REASON_URL = \"http://hl7.org/fhir/StructureDefinition/data-absent-reason\";\n\n/**\n * Allocates `urn:uuid:` identities for the resources of one bundle, from the caller's\n * {@link TransformOptions.generateId} (default `crypto.randomUUID`).\n *\n * @example\n * ```ts\n * // const ids = new IdAllocator({ generateId: () => \"1-2-3\" });\n * // ids.next(); // \"urn:uuid:1-2-3\"\n * ```\n */\nexport class IdAllocator {\n private readonly gen: () => string;\n\n /**\n * @param options - The transform options; `options.generateId` overrides the default UUID source.\n */\n constructor(options: TransformOptions | undefined) {\n this.gen = options?.generateId ?? (() => randomUUID());\n }\n\n /** Mint one fresh `urn:uuid:<id>` fullUrl. */\n next(): string {\n return `urn:uuid:${this.gen()}`;\n }\n}\n\n/**\n * A FHIR `Reference` node pointing at a bundle `fullUrl`.\n *\n * @param fullUrl - The `urn:uuid:` fullUrl of the referenced entry.\n * @example\n * ```ts\n * // reference(\"urn:uuid:1-2-3\") -> { reference: \"urn:uuid:1-2-3\" }\n * ```\n */\nexport function reference(fullUrl: string): FhirComplex {\n return complex([{ name: \"reference\", value: primitive(fullUrl) }]);\n}\n\n/**\n * A single FHIR `Coding` node (`system` + `code`, optional `display`), or `undefined` when no code\n * is present.\n *\n * @param system - The canonical system URI.\n * @param code - The code.\n * @param display - The optional display.\n * @example\n * ```ts\n * // coding(\"http://terminology.hl7.org/CodeSystem/v3-ActCode\", \"IMP\", \"inpatient encounter\")\n * ```\n */\nexport function coding(\n system: string,\n code: string | undefined,\n display?: string,\n): FhirComplex | undefined {\n if (code === undefined || code === \"\") return undefined;\n const props = [\n { name: \"system\", value: primitive(system) },\n { name: \"code\", value: primitive(code) },\n ];\n if (display !== undefined && display !== \"\") {\n props.push({ name: \"display\", value: primitive(display) });\n }\n return complex(props);\n}\n\n/**\n * Build one order `identifier` (an EI's EI.1 → `Identifier.value`) with a v2-0203 identifier-type\n * coding, or `undefined` when the value is empty. Shared by the order/result-anchoring resources\n * whose IG maps route the placer/filler order numbers (OBR-2/ORC-2 `PLAC`, OBR-3/ORC-3 `FILL`) to\n * `Identifier` with a `type` from HL7 Table 0203 — `DiagnosticReport` and `ServiceRequest`\n * both use it, so the shape lives here rather than being duplicated per builder.\n *\n * @param value - The order number (EI.1); an empty string yields `undefined`.\n * @param typeCode - The v2-0203 identifier-type code (`PLAC` placer, `FILL` filler).\n * @example\n * ```ts\n * // orderIdentifier(\"PLACER123\", \"PLAC\") -> { type: { coding: [{ system: v2-0203, code: \"PLAC\" }] }, value: \"PLACER123\" }\n * ```\n */\nexport function orderIdentifier(value: string, typeCode: string): FhirComplex | undefined {\n if (value === \"\") return undefined;\n return complex([\n {\n name: \"type\",\n value: complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V2_0203_SYSTEM) },\n { name: \"code\", value: primitive(typeCode) },\n ]),\n ]),\n },\n ]),\n },\n { name: \"value\", value: primitive(value) },\n ]);\n}\n\n/**\n * A value-absent FHIR primitive carrying only a `data-absent-reason` extension — the spec-clean way\n * to satisfy a required primitive whose value is genuinely unknown, **without fabricating one**.\n *\n * @param reasonCode - The `data-absent-reason` code (e.g. `\"unknown\"`).\n * @example\n * ```ts\n * // used for MessageHeader.source.endpoint when MSH-3 is an app name, not a URL\n * ```\n */\nexport function dataAbsent(reasonCode: string): ReturnType<typeof primitive> {\n const ext = complex([\n { name: \"url\", value: primitive(DATA_ABSENT_REASON_URL) },\n { name: \"valueCode\", value: primitive(reasonCode) },\n ]);\n return primitive(undefined, { extension: [ext] });\n}\n","/**\n * SIU_S12 → FHIR `Appointment` — the thin IG single for scheduling, grounded\n * firsthand on the IG **SIU_S12 message map**, the **SCH/AIS/PID → Appointment** segment maps, the\n * **Table HL70278 → AppointmentStatus** ConceptMap, and the **TQ → Appointment** datatype map\n * (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-message-siu-s12-to-bundle.json`,\n * `ConceptMap-segment-sch-to-appointment.json`, `ConceptMap-segment-ais-to-appointment.json`,\n * `ConceptMap-segment-pid-to-appointment.json`, `ConceptMap-table-hl70278-to-appointmentstatus.json`,\n * `ConceptMap-datatype-tq-to-appointment.json`). Per the message map an SIU message yields **one**\n * `Appointment` created from the `SCH` segment; `PID` contributes the patient participant and `AIS`\n * the service type.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | SCH-25 Filler Status Code | `status` (required 1..1) | {@link APPOINTMENT_STATUS_MAP} (HL70278) |\n * | SCH-1 Placer / SCH-2 Filler Appointment ID | `identifier` | EI.1 → `Identifier.value` |\n * | SCH-7 Appointment Reason (CWE) | `reasonCode` | {@link toFhirCodeableConcept} (structural — SNOMED target, BYO) |\n * | SCH-8 Appointment Type (CWE) | `appointmentType` | {@link APPOINTMENT_TYPE_VALUE_MAP} (HL70277, value-translated) |\n * | SCH-9 Duration + SCH-10 Units | `minutesDuration` | integer, only when SCH-10 is minutes |\n * | SCH-11 Appointment Timing Quantity (TQ) | `start` / `end` (instant) | TQ.4/TQ.5 → {@link toFhirDateTime} |\n * | AIS-3 Universal Service Identifier (CWE) | `serviceType` | {@link toFhirCodeableConcept} |\n * | PID (bundle Patient) | `participant.actor` (required 1..*) | reference wiring |\n *\n * **Fail-safes (never a confident wrong appointment).**\n * - **`status` (required 1..1).** SCH-25 → {@link APPOINTMENT_STATUS_MAP} (HL70278). The three HL70278\n * codes the IG leaves unmatched (`Discontinued`, `Blocked`, `Overbook`) and an absent SCH-25 leave\n * `status` absent + flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}; the required-`status` emit gate\n * then **withholds** the Appointment — never guessed.\n * - **`participant` (required 1..*).** The bundle Patient is emitted as the required participant. Its\n * `participant.status` (a required-bound `code` the IG supplies no source for) is emitted as a\n * `data-absent-reason` primitive (value `unknown`) + flagged {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}\n * — the spec-clean way to satisfy a required code whose value is genuinely unknown, never fabricated. An\n * Appointment with no resolvable Patient (and no other groundable actor this library builds) has no\n * participant and is withheld.\n * - **`start`/`end` (instant).** SCH-11's TQ.4/TQ.5 become `start`/`end` only when they are fully-zoned\n * instants; a naked (unzoned) timing is dropped + flagged rather than assigned a fabricated UTC offset,\n * mirroring `Bundle.timestamp`.\n * - **`appointmentType` value translation.** SCH-8 → {@link APPOINTMENT_TYPE_VALUE_MAP}\n * (HL70277 `Normal`/`Tentative`/`Complete` identity into `v2-0277`); a code outside the table is\n * preserved + flagged, never coerced. **`reasonCode` is NOT value-translated:** SCH-7's IG map target\n * is SNOMED CT (`table-hl70276-to-sct`) — encumbered, **not bundled** — so the reason is carried\n * structurally (BYO ConceptMap), never SNOMED-translated here. (The IG's SCH→Appointment map *also*\n * carries a redundant SCH-7 → `appointmentType[1]` row via `table-hl70277-to-v2-0277`; it is not\n * applied — SCH-7 carries HL70276 *reason* codes, not HL70277 *type* codes, so translating them through\n * the type table would only ever produce spurious unmapped flags. `appointmentType` comes from SCH-8,\n * the appointment-*type* field, per that same map's SCH-8 → `appointmentType[1]` row.)\n *\n * Deferred and flagged elsewhere, not silently mapped: SCH-12/16/20 contact participants and AIP/AIL/AIG\n * actors (need Practitioner/Location resources), SCH-26/27 `basedOn` ServiceRequest, AIS participant periods.\n *\n * @packageDocumentation\n */\n\nimport { parseDtm, type Hl7Message, type Segment, type TS } from \"@cosyte/hl7\";\nimport { complex, decimal, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport {\n toFhirCodeableConceptVia,\n APPOINTMENT_TYPE_VALUE_MAP,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { dataAbsent, reference } from \"./reference.js\";\n\n/**\n * HL7 v2 Table 0278 (Filler Status Code) → FHIR `appointmentstatus` (`Appointment.status`), per the IG\n * **Table HL70278 to AppointmentStatus** ConceptMap (each `is equivalent to`). The three source codes\n * the IG leaves **unmatched** (`Discontinued`, `Blocked`, `Overbook`) are absent here on purpose — an\n * SCH-25 carrying one of them (or any local code) leaves `Appointment.status` absent + flagged and the\n * required-`status` emit gate withholds the Appointment.\n */\nexport const APPOINTMENT_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n Pending: \"pending\",\n Waitlist: \"waitlist\",\n Booked: \"booked\",\n Started: \"checked-in\",\n Complete: \"fulfilled\",\n Cancelled: \"cancelled\",\n Deleted: \"entered-in-error\",\n Noshow: \"noshow\",\n});\n\n/** The `data-absent-reason` code for the patient participant's unknown required `status`. */\nconst PARTICIPANT_STATUS_UNKNOWN = \"unknown\";\n/** UCUM / HL7 unit codes SCH-10 uses to declare that SCH-9 is expressed in minutes. */\nconst MINUTE_UNITS: ReadonlySet<string> = new Set([\"min\", \"MIN\", \"minutes\", \"m\"]);\n/** A FHIR `positiveInt` lexical form (a leading-non-zero positive integer, no sign, no leading zero). */\nconst POSITIVE_INT = /^[1-9][0-9]*$/;\n\n/** Convert an SCH-11 TQ timing component (a raw v2 timestamp) to a fully-zoned FHIR `instant`, or drop. */\nfunction tqInstant(\n raw: string | undefined,\n ctx: TransformContext,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): string | undefined {\n if (raw === undefined || raw === \"\") return undefined;\n const ts: TS = parseDtm(raw);\n const dt = toFhirDateTime(ts, ctx.options);\n issues.push(...dt.issues);\n if (dt.value === undefined) return undefined;\n // Appointment.start/.end are `instant`: only a fully-zoned datetime qualifies, else drop + flag.\n if (\n dt.value.includes(\"T\") &&\n (dt.value.includes(\"+\") || dt.value.endsWith(\"Z\") || /-\\d{2}:\\d{2}$/.test(dt.value))\n ) {\n return dt.value;\n }\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, fhirPath));\n return undefined;\n}\n\n/** The raw first-subcomponent of a field's component at 0-based `index`, or `undefined` when empty. */\nfunction rawComponent(seg: Segment, field: number, index: number): string | undefined {\n const c = seg.field(field).repetitions[0]?.components[index]?.subcomponents[0];\n return c === undefined || c === \"\" ? undefined : c;\n}\n\n/** Build the required patient `participant` (actor → Patient, status data-absent), or `undefined`. */\nfunction patientParticipant(\n patientFullUrl: string | undefined,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (patientFullUrl === undefined) return undefined;\n // participant.status is a required-bound code with no IG source for the patient participant → the\n // spec-clean data-absent-reason primitive, flagged, rather than a fabricated ParticipationStatus.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"SIU\", \"Appointment.participant.status\"),\n );\n return complex([\n { name: \"actor\", value: reference(patientFullUrl) },\n { name: \"status\", value: dataAbsent(PARTICIPANT_STATUS_UNKNOWN) },\n ]);\n}\n\n/**\n * Build a FHIR `Appointment` resource node from an SIU message's `SCH` segment (+ the first `AIS`), with\n * the bundle Patient wired as the required participant. Returns `{ value: undefined }` when there is no\n * `SCH`. `Appointment.status` is left absent (and the resource withheld by the emit gate) when SCH-25\n * cannot be grounded via HL70278 — never guessed.\n *\n * @param sch - The `SCH` `@cosyte/hl7` `Segment` (the schedule anchor).\n * @param ais - The first `AIS` service segment, when present (supplies `serviceType`).\n * @param patientFullUrl - The bundle's Patient fullUrl → the required `participant.actor` (Patient).\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const sch = parseHL7(raw).segments(\"SCH\")[0];\n * // const { value } = buildAppointment(sch!, undefined, \"urn:uuid:pat\", {});\n * ```\n */\nexport function buildAppointment(\n sch: Segment,\n ais: Segment | undefined,\n patientFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Appointment\") },\n ];\n\n // SCH-25 → status (HL70278, required 1..1). Absent/unmapped → left absent (emit gate withholds).\n const fillerStatus = sch.field(25).value;\n if (fillerStatus !== \"\") {\n const status = Object.hasOwn(APPOINTMENT_STATUS_MAP, fillerStatus)\n ? APPOINTMENT_STATUS_MAP[fillerStatus]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"SCH.25\", \"Appointment.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // SCH-1 / SCH-2 → identifier (placer / filler appointment id; EI.1 → Identifier.value).\n const identifiers = [sch.field(1).value, sch.field(2).value]\n .filter((v) => v !== \"\")\n .map((v) => complex([{ name: \"value\", value: primitive(v) }]));\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n // SCH-8 → appointmentType (HL70277 → v2-0277; value-translated via the license-clean identity map).\n if (sch.field(8).value !== \"\") {\n const appointmentType = toFhirCodeableConceptVia(\n sch.field(8).asCwe(),\n APPOINTMENT_TYPE_VALUE_MAP,\n ctx,\n );\n issues.push(...appointmentType.issues);\n if (appointmentType.value !== undefined)\n props.push({ name: \"appointmentType\", value: appointmentType.value });\n }\n\n // AIS-3 → serviceType.\n if (ais !== undefined && ais.field(3).value !== \"\") {\n const serviceType = toFhirCodeableConcept(ais.field(3).asCwe(), ctx);\n issues.push(...serviceType.issues);\n if (serviceType.value !== undefined)\n props.push({ name: \"serviceType\", value: list([serviceType.value]) });\n }\n\n // SCH-7 → reasonCode (default table HL70276).\n if (sch.field(7).value !== \"\") {\n const reason = toFhirCodeableConcept(sch.field(7).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"reasonCode\", value: list([reason.value]) });\n }\n\n // SCH-9 + SCH-10 → minutesDuration, only when SCH-10 declares units of minutes (per the IG condition).\n const duration = sch.field(9).value;\n if (\n duration !== \"\" &&\n POSITIVE_INT.test(duration) &&\n MINUTE_UNITS.has(rawComponent(sch, 10, 0) ?? \"\")\n ) {\n props.push({ name: \"minutesDuration\", value: primitive(decimal(duration)) });\n }\n\n // SCH-11 (TQ) → start / end via TQ.4 / TQ.5 (instant; naked timing dropped + flagged).\n const start = tqInstant(rawComponent(sch, 11, 3), ctx, \"SCH.11\", \"Appointment.start\", issues);\n if (start !== undefined) props.push({ name: \"start\", value: primitive(start) });\n const end = tqInstant(rawComponent(sch, 11, 4), ctx, \"SCH.11\", \"Appointment.end\", issues);\n if (end !== undefined) props.push({ name: \"end\", value: primitive(end) });\n\n // participant (required 1..*): the bundle Patient (participant.status data-absent + flagged).\n const participant = patientParticipant(patientFullUrl, issues);\n if (participant !== undefined) props.push({ name: \"participant\", value: list([participant]) });\n\n return { value: complex(props), issues };\n}\n\n/**\n * The first `SCH` and first `AIS` of an SIU message, for the single-Appointment build.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { sch, ais } = collectAppointment(parseHL7(raw));\n * ```\n */\nexport function collectAppointment(msg: Hl7Message): {\n sch: Segment | undefined;\n ais: Segment | undefined;\n} {\n let sch: Segment | undefined;\n let ais: Segment | undefined;\n for (const seg of msg.allSegments()) {\n if (seg.type === \"SCH\" && sch === undefined) sch = seg;\n else if (seg.type === \"AIS\" && ais === undefined) ais = seg;\n }\n return { sch, ais };\n}\n","/**\n * OBR → FHIR `DiagnosticReport` — the ORU results-report anchor, grounded firsthand\n * on the IG **Segment OBR to DiagnosticReport** ConceptMap and its **Table HL70123 to Diagnostic Report\n * Status** ConceptMap (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-obr-to-diagnosticreport.html`,\n * `ConceptMap-table-hl70123-queries-to-diagnostic-report-status.html`):\n *\n * | OBR field | FHIR target | via |\n * |---|---|---|\n * | OBR-2 Placer Order Number | `identifier` (type `PLAC`) | EI.1 → `Identifier.value`, v2-0203 type |\n * | OBR-3 Filler Order Number | `identifier` (type `FILL`) | EI.1 → `Identifier.value`, v2-0203 type |\n * | OBR-4 Universal Service Identifier (CWE) | `DiagnosticReport.code` | {@link toFhirCodeableConcept} |\n * | OBR-7 Observation Date/Time | `effectiveDateTime` / `effectivePeriod.start` | {@link toFhirDateTime} |\n * | OBR-8 Observation End Date/Time | `effectivePeriod.end` (start moves to the period when valued) | — |\n * | OBR-22 Results Rpt/Status Chng Date/Time | `DiagnosticReport.issued` (an `instant`) | {@link toFhirDateTime} |\n * | OBR-24 Diagnostic Serv Sect ID | `DiagnosticReport.category` | v2-0074 coding |\n * | OBR-25 Result Status | `DiagnosticReport.status` | {@link DIAGNOSTIC_REPORT_STATUS_MAP} (HL70123) |\n * | (OBX children) | `DiagnosticReport.result` | reference wiring from the assembler |\n *\n * **Fail-safes.** `DiagnosticReport.status` is required (R4 1..1) and the IG itself notes an unvalued\n * OBR-25 is an error; so an absent OBR-25 — or an OBR-25 code the HL70123 map does not carry (`A`, `M`,\n * `N`, `Y`, `Z`) — leaves `status` absent + flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, and the\n * required-`status` emit gate withholds the report rather than emitting an invalid one or guessing\n * `final`. `OBR-25 = C`→`corrected` / `X`→`cancelled` are modelled exactly. OBR-22 becomes `issued`\n * only when it is a fully-zoned instant; a date-only/naked OBR-22 is dropped + flagged (never a\n * fabricated UTC), mirroring `Bundle.timestamp`. Deferred and flagged elsewhere, not silently mapped:\n * OBR-32/34/35 performers (need PractitionerRole resources), specimen, and `basedOn` ServiceRequest.\n *\n * @packageDocumentation\n */\n\nimport type { Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { orderIdentifier, reference } from \"./reference.js\";\n\n/** The HL7 v2 Table 0074 (Diagnostic Service Section ID) canonical system — `DiagnosticReport.category`. */\nconst V2_0074_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0074\";\n\n/**\n * HL7 v2 Table 0123 (Result Status) → FHIR `diagnostic-report-status` (`DiagnosticReport.status`), per\n * the IG **Table HL70123 [Queries] to Diagnostic Report Status** ConceptMap (each `is equivalent to`).\n * Only these **eight** source codes carry a target; the IG leaves `A`, `M`, `N`, `Y`, `Z` unmapped\n * (verified firsthand against the published v1.0.0 ConceptMap — `N` \"Procedure completed, results\n * pending\" is in the `(not mapped)` group, and the map declares no `unmapped` default), so an OBR-25\n * with one of them leaves `status` absent + flagged and the report is withheld. In particular a\n * results-**pending** `N` is **never** emitted as the post-final `appended`. **`C`→`corrected` and\n * `X`→`cancelled` guarantee a corrected/cancelled report never emits as `final`.**\n */\nexport const DIAGNOSTIC_REPORT_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n O: \"registered\",\n I: \"registered\",\n S: \"registered\",\n P: \"preliminary\",\n R: \"partial\",\n C: \"corrected\",\n F: \"final\",\n X: \"cancelled\",\n});\n\n/**\n * Build a FHIR `DiagnosticReport` resource node from one parsed HL7 v2 OBR segment and the fullUrls of\n * the `Observation`s produced under it. Returns `{ value: undefined }` when OBR-4 (the report `code`,\n * required 1..1) is absent. `DiagnosticReport.status` is left absent (and the report withheld by the\n * emit gate) when OBR-25 is missing or has no HL70123 target — never guessed.\n *\n * @param obr - The OBR `@cosyte/hl7` `Segment`.\n * @param resultFullUrls - The `urn:uuid:` fullUrls of this report's emitted `Observation`s → `.result`.\n * @param subjectFullUrl - The bundle's Patient fullUrl → `DiagnosticReport.subject`.\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `DiagnosticReport.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const obr = parseHL7(raw).segments(\"OBR\")[0];\n * // const { value } = buildDiagnosticReport(obr!, [\"urn:uuid:obs1\"], \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildDiagnosticReport(\n obr: Segment,\n resultFullUrls: readonly string[],\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"DiagnosticReport\") },\n ];\n\n // OBR-2 / OBR-3 → DiagnosticReport.identifier (PLAC / FILL, v2-0203 types).\n const identifiers = [\n orderIdentifier(obr.field(2).value, \"PLAC\"),\n orderIdentifier(obr.field(3).value, \"FILL\"),\n ].filter((i): i is FhirComplex => i !== undefined);\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n // OBR-25 → DiagnosticReport.status (HL70123). Absent/unmapped → left absent (emit gate withholds),\n // never guessed; a corrected/cancelled result is modelled exactly, never emitted as `final`.\n const statusCode = obr.field(25).value;\n if (statusCode !== \"\") {\n const status = Object.hasOwn(DIAGNOSTIC_REPORT_STATUS_MAP, statusCode)\n ? DIAGNOSTIC_REPORT_STATUS_MAP[statusCode]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBR.25\", \"DiagnosticReport.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // OBR-24 → DiagnosticReport.category (v2-0074 diagnostic service section).\n const section = obr.field(24).value;\n if (section !== \"\") {\n props.push({\n name: \"category\",\n value: list([\n complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V2_0074_SYSTEM) },\n { name: \"code\", value: primitive(section) },\n ]),\n ]),\n },\n ]),\n ]),\n });\n }\n\n // OBR-4 → DiagnosticReport.code (required 1..1). Absent → nothing emittable.\n const code = toFhirCodeableConcept(obr.field(4).asCwe(), ctx);\n issues.push(...code.issues);\n if (code.value === undefined) return { value: undefined, issues };\n props.push({ name: \"code\", value: code.value });\n\n // subject / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined) {\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n }\n\n // OBR-7 / OBR-8 → effectiveDateTime, or effectivePeriod when an end (OBR-8) is valued.\n const hasEnd = obr.field(8).value !== \"\";\n if (obr.field(7).value !== \"\") {\n const start = toFhirDateTime(obr.field(7).asTs(), ctx.options);\n issues.push(...start.issues);\n if (start.value !== undefined && !hasEnd) {\n props.push({ name: \"effectiveDateTime\", value: primitive(start.value) });\n } else if (start.value !== undefined) {\n const end = toFhirDateTime(obr.field(8).asTs(), ctx.options);\n issues.push(...end.issues);\n const periodProps: { name: string; value: FhirNode }[] = [\n { name: \"start\", value: primitive(start.value) },\n ];\n if (end.value !== undefined) periodProps.push({ name: \"end\", value: primitive(end.value) });\n props.push({ name: \"effectivePeriod\", value: complex(periodProps) });\n }\n }\n\n // OBR-22 → DiagnosticReport.issued (an `instant`): only a fully-zoned datetime qualifies; a\n // date-only/naked OBR-22 is dropped + flagged rather than emitted as an invalid or fabricated instant.\n if (obr.field(22).value !== \"\") {\n const issued = toFhirDateTime(obr.field(22).asTs(), ctx.options);\n issues.push(...issued.issues);\n if (issued.value !== undefined && issued.value.includes(\"T\")) {\n props.push({ name: \"issued\", value: primitive(issued.value) });\n } else if (issued.value !== undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBR.22\", \"DiagnosticReport.issued\"),\n );\n }\n }\n\n // DiagnosticReport.result → the emitted Observations under this OBR.\n if (resultFullUrls.length > 0) {\n props.push({ name: \"result\", value: list(resultFullUrls.map((u) => reference(u))) });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * MDM_T02 → FHIR `DocumentReference` — the thin IG single for clinical documents,\n * grounded firsthand on the IG **MDM_T02 message map** and the **TXA/OBX → DocumentReference** segment\n * maps (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-message-mdm-t02-to-bundle.json`,\n * `ConceptMap-segment-txa-to-documentreference.json`, `ConceptMap-segment-obx-to-documentreference.json`).\n * Per the message map an MDM message yields **one** `DocumentReference` created from the `TXA` segment,\n * with the document body carried by the `OBX` segments.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | TXA-19 Document Availability Status | `status` (required 1..1) | `AV` → `current` only (see below) |\n * | TXA-2 Document Type (CWE) | `type` | {@link toFhirCodeableConcept} (structural — no IG value map) |\n * | TXA-6 Origination Date/Time (DTM) | `date` (an `instant`) | {@link toFhirDateTime}, fully-zoned only |\n * | TXA-12 Unique Document Number | `masterIdentifier` | EI.1 → `Identifier.value` |\n * | TXA-16 Unique Document File Name | `identifier` | ST → `Identifier.value` |\n * | TXA-25 Document Title | `description` | verbatim |\n * | OBX-5 (per OBX-2) | `content.attachment` (required 1..*) | {@link buildContent} |\n * | (message-map wiring) | `subject` | the bundle's Patient |\n *\n * **Fail-safes (never a confident wrong document record).**\n * - **`status` (required 1..1) — grounded only for `AV`.** The IG conditions TXA-19 → `status` on\n * `IF TXA-19 = \"AV\"` and ships **no** value ConceptMap (there is no HL70273 → document-reference-status\n * table in the IG). \"AV\" (Available) has exactly one faithful target in the required\n * `document-reference-status` binding (`current` | `superseded` | `entered-in-error`): **`current`**, so\n * `AV → current` is emitted. Every other TXA-19 value — `CA`/`OB`/`UN` (whose IG target is a\n * `status.extension` construct that is not valid R4) and any local code — is **unmapped**\n * ({@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}); `status` is left absent and the required-`status` emit\n * gate **withholds** the DocumentReference. Never guessed.\n * - **`content` (required 1..*).** Built from the `OBX` document body via {@link buildContent}. When no\n * OBX yields a groundable attachment the DocumentReference has no content and is withheld + flagged —\n * a document reference that references nothing is never emitted.\n * - **`docStatus` — unmapped, left absent.** TXA-17 → `docStatus` has **no** IG value ConceptMap\n * (HL70271 → composition-status is genuinely ambiguous), so a valued TXA-17 is flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} and `docStatus` (0..1) is left absent — never guessed.\n * - **`content.attachment.contentType`.** Taken from the IG's OBX-2 assignment (`application/text` for\n * TX, `text/hl7v2` for FT — see {@link BODY_CONTENT_TYPE}), **not** from TXA-3 — the TXA-3 → contentType\n * row carries HL70191 codes that are not MIME types, so TXA-3 is flagged dropped rather than emitted as\n * an invalid `contentType`. The document body itself is **carried, never interpreted** (TX/FT text is\n * base64-encoded verbatim into `content.attachment.data`).\n *\n * Deferred and flagged elsewhere, not silently mapped: TXA-9/10 author/authenticator (Practitioner),\n * TXA-18 securityLabel, the ED-encapsulated OBX body, and the COMMON_ORDER ORC → ServiceRequest graph.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/** The only faithful `document-reference-status` target for TXA-19 = \"AV\" (Document is Available). */\nconst STATUS_AVAILABLE_TARGET = \"current\";\n/**\n * The `content.attachment.contentType` the IG assigns per OBX-2 body type (verified firsthand against\n * `ConceptMap-segment-obx-to-documentreference.json`: `content[4].contentType` = `\"application/text\"`\n * for `IF OBX-2=\"TX\"`, `content[2].contentType` = `\"text/hl7v2\"` for `IF OBX-2=\"FT\"`).\n */\nconst BODY_CONTENT_TYPE: Readonly<Record<string, string>> = Object.freeze({\n TX: \"application/text\",\n FT: \"text/hl7v2\",\n});\n\n/**\n * Build one `DocumentReference.content` entry from a body `OBX`, discriminated by OBX-2 per the IG\n * **OBX → DocumentReference** map: `TX` → `content.attachment.data` (the text base64-encoded) + the\n * IG-assigned `application/text` contentType; `FT` → the same, with `text/hl7v2`; `RP` →\n * `content.attachment.url` (the reference pointer). The IG also maps `ED` → `content.attachment`, but\n * that requires decoding the ED encapsulated-data composite (a later concern), so `ED` — and any\n * non-document OBX-2 — is flagged {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} and deferred, never\n * fabricated. The document body itself is carried verbatim, never interpreted.\n */\nfunction buildContent(\n obx: Segment,\n index: number,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const valueType = obx.field(2).value.toUpperCase();\n const raw = obx.field(5).value;\n if (raw === \"\") return undefined;\n\n if (Object.hasOwn(BODY_CONTENT_TYPE, valueType)) {\n // The document body is carried, never interpreted: the verbatim text is base64-encoded into\n // Attachment.data (a base64Binary), with the IG-assigned contentType for this body type.\n const data = Buffer.from(raw, \"utf8\").toString(\"base64\");\n return complex([\n {\n name: \"attachment\",\n value: complex([\n { name: \"contentType\", value: primitive(BODY_CONTENT_TYPE[valueType]) },\n { name: \"data\", value: primitive(data) },\n ]),\n },\n ]);\n }\n\n if (valueType === \"RP\") {\n // RP (reference pointer): the first component is the pointer/URL to the document body.\n return complex([\n {\n name: \"attachment\",\n value: complex([{ name: \"url\", value: primitive(raw) }]),\n },\n ]);\n }\n\n // ED-encapsulated (deferred) and non-document OBX-2 bodies are flagged and dropped, never fabricated.\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n `OBX[${String(index)}].5`,\n \"DocumentReference.content\",\n ),\n );\n return undefined;\n}\n\n/**\n * Build a FHIR `DocumentReference` resource node from an MDM message's `TXA` segment and its body `OBX`\n * segments. Returns `{ value: undefined }` when there is no `TXA`. `status` (from TXA-19 = \"AV\") and\n * `content` (from the OBX body) are both required 1..1 / 1..*; when either cannot be grounded the\n * resource is left incomplete and later **withheld** by the conservative-emit gate — never guessed.\n *\n * @param txa - The `TXA` `@cosyte/hl7` `Segment` (the document metadata anchor).\n * @param obxs - The document-body `OBX` segments, in document order.\n * @param subjectFullUrl - The bundle's Patient fullUrl → `DocumentReference.subject`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const txa = parseHL7(raw).segments(\"TXA\")[0];\n * // const obxs = parseHL7(raw).segments(\"OBX\");\n * // const { value } = buildDocumentReference(txa!, obxs, \"urn:uuid:pat\", {});\n * ```\n */\nexport function buildDocumentReference(\n txa: Segment,\n obxs: readonly Segment[],\n subjectFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"DocumentReference\") },\n ];\n\n // TXA-19 → status (required 1..1). Grounded only for \"AV\" → \"current\"; anything else is unmapped and\n // the required-status emit gate withholds the resource.\n const availability = txa.field(19).value;\n if (availability === \"AV\") {\n props.push({ name: \"status\", value: primitive(STATUS_AVAILABLE_TARGET) });\n } else if (availability !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TXA.19\", \"DocumentReference.status\"));\n }\n\n // TXA-17 → docStatus: no IG value map exists → flag when valued, leave docStatus (0..1) absent.\n if (txa.field(17).value !== \"\") {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TXA.17\", \"DocumentReference.docStatus\"),\n );\n }\n\n // TXA-2 → type: carried **structurally** (system recognized, value preserved). The IG's\n // TXA→DocumentReference segment map ships **no** `mappedVia` value ConceptMap for TXA-2 (verified\n // firsthand — only TXA-18 securityLabel carries one), so a value translation is never invented for it\n // (ADR 0018 applied to mappings); the document-type code (typically LOINC) is emitted as-is.\n if (txa.field(2).value !== \"\") {\n const type = toFhirCodeableConcept(txa.field(2).asCwe(), ctx);\n issues.push(...type.issues);\n if (type.value !== undefined) props.push({ name: \"type\", value: type.value });\n }\n\n // TXA-12 → masterIdentifier; TXA-16 → identifier[1] (both EI/ST → Identifier.value).\n if (txa.field(12).value !== \"\") {\n props.push({\n name: \"masterIdentifier\",\n value: complex([{ name: \"value\", value: primitive(txa.field(12).value) }]),\n });\n }\n if (txa.field(16).value !== \"\") {\n props.push({\n name: \"identifier\",\n value: list([complex([{ name: \"value\", value: primitive(txa.field(16).value) }])]),\n });\n }\n\n // subject → the bundle's Patient (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n\n // TXA-6 → date (an `instant`): only a fully-zoned datetime qualifies (the IG's \"IF time is included\"\n // condition), else dropped + flagged rather than emitted as an invalid or fabricated instant.\n if (txa.field(6).value !== \"\") {\n const date = toFhirDateTime(txa.field(6).asTs(), ctx.options);\n issues.push(...date.issues);\n if (date.value !== undefined && date.value.includes(\"T\")) {\n props.push({ name: \"date\", value: primitive(date.value) });\n } else if (date.value !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TXA.6\", \"DocumentReference.date\"));\n }\n }\n\n // TXA-3 → content.attachment.contentType: HL70191 codes are not MIME types, so a valued TXA-3 is\n // flagged dropped rather than emitted as an invalid contentType (the body type drives it instead).\n if (txa.field(3).value !== \"\") {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"TXA.3\",\n \"DocumentReference.content.attachment.contentType\",\n ),\n );\n }\n\n // TXA-25 → description.\n if (txa.field(25).value !== \"\")\n props.push({ name: \"description\", value: primitive(txa.field(25).value) });\n\n // OBX body → content (required 1..*). No groundable content → resource withheld by the emit gate.\n const contents: FhirComplex[] = [];\n for (let i = 0; i < obxs.length; i++) {\n const obx = obxs[i];\n if (obx === undefined) continue;\n const content = buildContent(obx, i, issues);\n if (content !== undefined) contents.push(content);\n }\n if (contents.length > 0) props.push({ name: \"content\", value: list(contents) });\n\n return { value: complex(props), issues };\n}\n\n/**\n * The first `TXA` and all body `OBX` segments of an MDM message, for the single-DocumentReference build.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { txa, obxs } = collectDocument(parseHL7(raw));\n * ```\n */\nexport function collectDocument(msg: Hl7Message): {\n txa: Segment | undefined;\n obxs: readonly Segment[];\n} {\n let txa: Segment | undefined;\n const obxs: Segment[] = [];\n for (const seg of msg.allSegments()) {\n if (seg.type === \"TXA\" && txa === undefined) txa = seg;\n else if (seg.type === \"OBX\") obxs.push(seg);\n }\n return { txa, obxs };\n}\n","/**\n * PV1 → FHIR `Encounter` — grounded on the IG **Segment PV1 to Encounter** ConceptMap plus the two\n * **Table HL70004** ConceptMaps (to V3 ActCode, and to Encounter Status), all verified firsthand\n * against the published `hl7.fhir.uv.v2mappings` STU1 maps:\n *\n * | PV1 field | FHIR target | condition / via |\n * |---|---|---|\n * | PV1-2 Patient Class | `Encounter.class` (Coding) | Table 0004 → V3 ActCode ({@link ENCOUNTER_CLASS_V3_MAP}); the self-mapped classes stay in v2-0004 |\n * | PV1-2 Patient Class | `Encounter.status` (code) | Table 0004 → Encounter Status ({@link ENCOUNTER_STATUS_MAP}), *only IF PV1-45 not valued* |\n * | PV1-19 Visit Number | `Encounter.identifier` (type `VN`) | v2-0203 identifier-type system |\n * | PV1-44 Admit Date/Time | `Encounter.period.start` | {@link toFhirDateTime} |\n * | PV1-45 Discharge Date/Time | `Encounter.period.end` + `status = finished` | {@link toFhirDateTime} |\n *\n * Fail-safe: an unmapped patient class leaves `Encounter.class` absent and flags\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} (never coerced); `Encounter.subject` is wired to the\n * bundle's Patient (the identity anchor) and omitted only when no valid Patient was produced.\n * Deferred and flagged, not silently mapped: PV1-3 location (Reference(Location), no Location resource\n * is built), PV1-7/8 attending/referring doctor (Reference(Practitioner), no Practitioner resource\n * is built).\n *\n * @packageDocumentation\n */\n\nimport type { Visit } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\nimport { coding, reference } from \"./reference.js\";\n\n/** The v3 ActCode canonical system (FHIR `Encounter.class` binding). */\nconst V3_ACTCODE_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v3-ActCode\";\n/** The HL7 v2 Table 0004 (Patient Class) canonical system — for classes with no v3 ActCode row. */\nconst V2_0004_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0004\";\n\n/**\n * HL7 v2 Table 0004 (Patient Class) → FHIR v3 ActCode (`Encounter.class`), per the IG **Table HL70004\n * to V3 ActCode** ConceptMap (each \"is equivalent to\"). Only these four v2 classes have a v3 ActCode\n * equivalent; the remaining classes (R/B/C/N/U) map to themselves and stay in the v2-0004 system\n * ({@link V2_0004_SYSTEM}) per the same map's V2→V2 rows.\n */\nexport const ENCOUNTER_CLASS_V3_MAP: Readonly<Record<string, { code: string; display: string }>> =\n Object.freeze({\n E: { code: \"EMER\", display: \"emergency\" },\n I: { code: \"IMP\", display: \"inpatient encounter\" },\n O: { code: \"AMB\", display: \"ambulatory\" },\n P: { code: \"PRENC\", display: \"pre-admission\" },\n });\n\n/** The v2-0004 classes the IG maps to themselves (no v3 ActCode equivalent). */\nconst V2_SELF_CLASSES: ReadonlySet<string> = new Set([\"R\", \"B\", \"C\", \"N\", \"U\"]);\n\n/**\n * HL7 v2 Table 0004 (Patient Class) → FHIR `Encounter.status`, per the IG **Table HL70004 to\n * Encounter Status** ConceptMap. Applied only when PV1-45 (discharge date) is *not* valued — a valued\n * discharge sets `status = finished` per the PV1→Encounter map.\n */\nexport const ENCOUNTER_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n E: \"in-progress\",\n I: \"in-progress\",\n O: \"in-progress\",\n R: \"in-progress\",\n B: \"in-progress\",\n C: \"in-progress\",\n N: \"in-progress\",\n P: \"planned\",\n U: \"unknown\",\n});\n\n/** Build `Encounter.class` from PV1-2, or `undefined` (+ push an issue) when it cannot be mapped. */\nfunction buildClass(\n patientClass: string | undefined,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (patientClass === undefined || patientClass === \"\") return undefined;\n const v3 = ENCOUNTER_CLASS_V3_MAP[patientClass];\n if (v3 !== undefined) return coding(V3_ACTCODE_SYSTEM, v3.code, v3.display);\n if (V2_SELF_CLASSES.has(patientClass)) return coding(V2_0004_SYSTEM, patientClass);\n // Unknown patient-class code — never coerced to a neighbor; class left absent and flagged.\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"PV1.2\", \"Encounter.class\"));\n return undefined;\n}\n\n/**\n * Build a FHIR `Encounter` resource node from a parsed HL7 v2 PV1 view.\n *\n * @param visit - The `@cosyte/hl7` `Visit` view (PV1-derived).\n * @param subjectFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient, or `undefined` when none\n * was produced (then `Encounter.subject` is omitted and flagged).\n * @param ctx - The transform context (carries the timezone policy for the period).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildEncounter(parseHL7(raw).visit!, \"urn:uuid:1-2-3\", {});\n * ```\n */\nexport function buildEncounter(\n visit: Visit,\n subjectFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Encounter\") },\n ];\n\n // PV1-19 → Encounter.identifier (type VN, v2-0203).\n if (visit.visitNumber !== undefined && visit.visitNumber !== \"\") {\n const vnCoding = complex([\n { name: \"system\", value: primitive(V2_0203_SYSTEM) },\n { name: \"code\", value: primitive(\"VN\") },\n ]);\n const identifier = complex([\n { name: \"type\", value: complex([{ name: \"coding\", value: list([vnCoding]) }]) },\n { name: \"value\", value: primitive(visit.visitNumber) },\n ]);\n props.push({ name: \"identifier\", value: list([identifier]) });\n }\n\n // PV1-2 / PV1-45 → Encounter.status. A valued discharge means \"finished\"; else Table 0004 status.\n const discharged = visit.dischargeDateTime !== undefined;\n let status: string | undefined;\n if (discharged) {\n status = \"finished\";\n } else if (visit.patientClass !== undefined && visit.patientClass !== \"\") {\n status = Object.hasOwn(ENCOUNTER_STATUS_MAP, visit.patientClass)\n ? ENCOUNTER_STATUS_MAP[visit.patientClass]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"PV1.2\", \"Encounter.status\"));\n }\n }\n if (status !== undefined) props.push({ name: \"status\", value: primitive(status) });\n\n // PV1-2 → Encounter.class (Table 0004 → V3 ActCode; self-mapped classes stay in v2-0004).\n const encounterClass = buildClass(visit.patientClass, issues);\n if (encounterClass !== undefined) props.push({ name: \"class\", value: encounterClass });\n\n // Encounter.subject → the bundle's Patient (the message map's reference wiring).\n if (subjectFullUrl !== undefined) {\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n } else {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PID\", \"Encounter.subject\"));\n }\n\n // PV1-44 / PV1-45 → Encounter.period.start / .end.\n const periodProps: { name: string; value: FhirNode }[] = [];\n if (visit.admitDateTime !== undefined) {\n const start = toFhirDateTime(visit.admitDateTime, ctx.options);\n issues.push(...start.issues);\n if (start.value !== undefined)\n periodProps.push({ name: \"start\", value: primitive(start.value) });\n }\n if (visit.dischargeDateTime !== undefined) {\n const end = toFhirDateTime(visit.dischargeDateTime, ctx.options);\n issues.push(...end.issues);\n if (end.value !== undefined) periodProps.push({ name: \"end\", value: primitive(end.value) });\n }\n if (periodProps.length > 0) props.push({ name: \"period\", value: complex(periodProps) });\n\n // Deferred, flagged: PV1-3 location, PV1-7/8 doctors need Location/Practitioner resources.\n if (visit.location !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.3\", \"Encounter.location\"));\n }\n if (visit.attendingDoctor !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.7\", \"Encounter.participant\"));\n }\n if (visit.referringDoctor !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.8\", \"Encounter.participant\"));\n }\n\n if (props.length === 1) return { value: undefined, issues };\n return { value: complex(props), issues };\n}\n","/**\n * Minimal R4 **required-cardinality** schemas for the resource types this library emits, so the\n * conservative-emit gate ({@link ../messages/to-fhir.js}) actually catches a structurally-invalid\n * resource rather than waving it through.\n *\n * `@cosyte/fhir.validateResource` models only `Patient` out of the box; every other resource type\n * degrades to a base-elements schema and validates as `valid` regardless of its own required\n * elements. These schemas restore the R4 required (`min: 1`) elements for the types we produce, and\n * the gate applies them in **lenient** mode — so a *missing required* element is an error (the\n * resource is withheld), while the resource's other (unmodeled-here) elements are warnings, never a\n * false rejection. Grounded on the FHIR R4 resource definitions:\n *\n * - **Encounter**: `status` (1..1 code) and `class` (1..1 Coding) are both required.\n * - **MessageHeader**: `event[x]` (1..1) is required; we only ever emit the `eventCoding` form, so a\n * header with no `eventCoding` (MSH-9 without a trigger event) is withheld rather than shipped\n * without its mandatory event.\n * - **RelatedPerson**: `patient` (1..1 Reference) is required (defence-in-depth; the assembler only\n * builds a RelatedPerson when a Patient exists to anchor it).\n * - **DiagnosticReport**: `status` (1..1 code) and `code` (1..1 CodeableConcept) are both required — so\n * a report from an unmapped/absent OBR-25 result status (no `status`) is withheld, never guessed.\n * - **Observation**: `status` (1..1 code) and `code` (1..1 CodeableConcept) are both required — so a\n * result from an unmapped/absent OBX-11 status (no `status`) is withheld, never emitted as `final`.\n * - **ServiceRequest**: `status` (1..1 code), `intent` (1..1 code), and `subject` (1..1 Reference) are\n * all required — so an order whose `status` could not be grounded via HL70119 (or whose Patient was\n * withheld) is withheld, never emitted with a guessed status or a dangling subject.\n * - **MedicationRequest**: `status` (1..1 code), `intent` (1..1 code), `subject` (1..1 Reference), and\n * `medication[x]` (1..1) are all required; the assembler only ever emits the `medicationCodeableConcept`\n * form, so it is required here — a pharmacy order with no give code (no `medication[x]`) is withheld.\n *\n * @packageDocumentation\n */\n\nimport { UNBOUNDED, type ResourceSchema } from \"@cosyte/fhir\";\n\n/** The required-cardinality schemas the emit gate applies (lenient) to the non-`Patient` resources. */\nexport const EMIT_SCHEMAS: readonly ResourceSchema[] = Object.freeze([\n {\n type: \"Encounter\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n class: { min: 1, max: 1, types: [\"Coding\"] },\n },\n },\n {\n type: \"MessageHeader\",\n elements: {\n eventCoding: { min: 1, max: 1, types: [\"Coding\"] },\n },\n },\n {\n type: \"RelatedPerson\",\n elements: {\n patient: { min: 1, max: 1, types: [\"Reference\"] },\n },\n },\n {\n type: \"DiagnosticReport\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n code: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n },\n },\n {\n type: \"Observation\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n code: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n },\n },\n {\n type: \"ServiceRequest\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n intent: { min: 1, max: 1, types: [\"code\"] },\n subject: { min: 1, max: 1, types: [\"Reference\"] },\n },\n },\n {\n type: \"MedicationRequest\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n intent: { min: 1, max: 1, types: [\"code\"] },\n subject: { min: 1, max: 1, types: [\"Reference\"] },\n medicationCodeableConcept: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n },\n },\n {\n // Immunization: status (1..1 code), vaccineCode (1..1 CodeableConcept), patient (1..1 Reference), and\n // occurrence[x] (1..1) are all required — the assembler only ever emits the occurrenceDateTime form, so\n // it is required here. An RXA with no groundable status/vaccine/occurrence, or no bundle Patient, is\n // withheld rather than emitted incomplete.\n type: \"Immunization\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n vaccineCode: { min: 1, max: 1, types: [\"CodeableConcept\"] },\n patient: { min: 1, max: 1, types: [\"Reference\"] },\n occurrenceDateTime: { min: 1, max: 1, types: [\"dateTime\"] },\n },\n },\n {\n // Appointment: status (1..1 code) and participant (1..* BackboneElement) are both required — an\n // Appointment whose SCH-25 status could not be grounded via HL70278, or that has no resolvable Patient\n // participant, is withheld rather than emitted with a guessed status or no participant.\n type: \"Appointment\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n participant: { min: 1, max: UNBOUNDED, types: [\"BackboneElement\"] },\n },\n },\n {\n // DocumentReference: status (1..1 code) and content (1..* BackboneElement) are both required — a\n // reference whose TXA-19 is not \"AV\" (no groundable status), or that carries no document body from its\n // OBX segments, is withheld rather than emitted with a guessed status or referencing nothing.\n type: \"DocumentReference\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n content: { min: 1, max: UNBOUNDED, types: [\"BackboneElement\"] },\n },\n },\n]);\n","/**\n * VXU_V04 → FHIR `Immunization` — the thin IG single for immunization administration,\n * grounded firsthand on the IG **VXU_V04 message map** and the **RXA/RXR/ORC → Immunization**\n * segment maps (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-message-vxu-v04-to-bundle.json`,\n * `ConceptMap-segment-rxa-to-immunization.json`, `ConceptMap-segment-rxr-to-immunization.json`,\n * `ConceptMap-segment-orc-to-immunization.json`). Per the VXU message map, **each `ORC` creates an\n * `Immunization`** and the `RXA` (+ `RXR` route) in the same order group are *incorporated into it*, so\n * one builder consumes all three; the order-group `OBX`s become standalone patient `Observation`s\n * (`Observation[2]` in the IG bundle), handled by the assembler.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | RXA-5 Administered Code (CE) | `vaccineCode` (required 1..1) | {@link toFhirCodeableConcept} (structural — no IG value map) |\n * | RXA-3 Date/Time Start of Administration (DTM) | `occurrenceDateTime` (required, occurrence[x]) | {@link toFhirDateTime} |\n * | RXA-20 Completion Status + RXA-21 Action Code | `status` (required 1..1) | {@link buildStatus} (HL70322 + IG assignments) |\n * | RXA-6 Administered Amount + RXA-7 Units | `doseQuantity` | {@link quantityFromRawMagnitude} |\n * | RXA-15 Substance Lot Number (ST) | `lotNumber` | verbatim |\n * | RXA-16 Substance Expiration Date (DT) | `expirationDate` (a `date`) | {@link toFhirDateTime}, date-only |\n * | RXA-18 Substance/Treatment Refusal Reason (CWE) | `statusReason` | {@link toFhirCodeableConcept} |\n * | RXA-19 Indication (CWE) | `reasonCode` | {@link toFhirCodeableConcept} |\n * | RXA-22 System Entry Date/Time (DTM) | `recorded` | {@link toFhirDateTime} (ORC-9 fallback) |\n * | RXR-1 Route (CWE) | `route` | {@link ROUTE_VALUE_MAP} (HL70162, value-translated) |\n * | RXR-2 Administration Site (CWE) | `site` | {@link SITE_VALUE_MAP} (HL70550, value-translated) |\n * | ORC-2 / ORC-3 Placer/Filler Order Number | `identifier` (PLAC / FILL) | {@link orderIdentifier} |\n * | ORC-9 Date/Time of Order Event | `recorded` (fallback) | {@link toFhirDateTime} |\n * | (message-map wiring) | `patient` (required 1..1) / `encounter` | the bundle's Patient / Encounter |\n *\n * **Fail-safes (never a confident wrong immunization record).**\n * - **`status` (required 1..1).** The IG ships **three conditioned status rows** (verified firsthand\n * against `ConceptMap-segment-rxa-to-immunization.json`): **RXA-21 = \"D\"** (delete) → the IG-assigned\n * `entered-in-error`; **RXA-20 not valued and RXA-21 ≠ \"D\"** → the IG-assigned `completed`; **RXA-20\n * valued and RXA-21 ≠ \"D\"** → translated via {@link IMMUNIZATION_STATUS_MAP} (the HL70322 →\n * event-status ConceptMap, whose targets `completed`/`not-done` are all valid `immunization-status`\n * members). A **valued** RXA-20 the HL70322 map has no target for is flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, `status` left absent, and the required-`status` emit gate\n * **withholds** the Immunization — never guessed, never coerced.\n * - **`vaccineCode` (required 1..1) + `occurrence[x]` (required 1..1) + `patient` (required 1..1).** An\n * absent RXA-5, RXA-3, or bundle Patient leaves the resource missing a required element, so it is\n * withheld by the emit gate rather than emitted incomplete.\n * - **Dose.** RXA-6/RXA-7 → `doseQuantity` via {@link quantityFromRawMagnitude}: precision-exact magnitude,\n * non-UCUM unit preserved verbatim with `.code`/`.system` absent + flagged — never a fabricated UCUM code.\n * - **Route/site value translation.** RXR-1 route → {@link ROUTE_VALUE_MAP} (HL70162) and\n * RXR-2 site → {@link SITE_VALUE_MAP} (HL70550) are value-translated additively (derived target coding\n * added, raw coding preserved); a code outside the table is preserved + flagged, never coerced.\n * - **`vaccineCode` is NOT value-translated — by grounding, not omission.** RXA-5 has **no** `mappedVia`\n * value ConceptMap in the IG's RXA→Immunization segment map (verified firsthand), so the code (typically\n * CVX) is carried **structurally** (system recognized, value preserved) — a translation is never\n * invented for it.\n *\n * Deferred and flagged elsewhere, not silently mapped: RXA-10 performer, RXA-17 manufacturer, RXA-27/28\n * location, ORC-12 performer (all need Practitioner/Organization/Location resources this library does not\n * build).\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { quantityFromRawMagnitude } from \"../datatypes/quantity.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport {\n toFhirCodeableConceptVia,\n ROUTE_VALUE_MAP,\n SITE_VALUE_MAP,\n type CodedValueMap,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { orderIdentifier, reference } from \"./reference.js\";\n\n/**\n * HL7 v2 Table 0322 (Completion Status) → FHIR `Immunization.status`, per the IG **Table HL70322 to\n * Event Status** ConceptMap (each `is equivalent to`). Table 0322 has exactly these **four** source\n * codes and every one carries a target; the two distinct targets (`completed`, `not-done`) are both\n * valid members of the `immunization-status` required binding, so applying this map to\n * `Immunization.status` is faithful. Consulted only for a **valued** RXA-20 when **RXA-21 ≠ \"D\"** (the\n * IG's `mappedVia` condition on that row); the two other IG status rows assign fixed values directly (a\n * delete → `entered-in-error`, an unvalued RXA-20 → `completed`) and do not consult this map. See\n * {@link buildStatus}.\n */\nexport const IMMUNIZATION_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n CP: \"completed\",\n PA: \"completed\",\n RE: \"not-done\",\n NA: \"not-done\",\n});\n\n/** One VXU order group: an optional `ORC` anchor, its `RXA` administration, and the first `RXR` route. */\nexport interface ImmunizationGroup {\n /** The `ORC` segment that opened the order (supplies identifiers + a fallback `recorded`), if any. */\n readonly orc: Segment | undefined;\n /** The `RXA` administration segment — the Immunization's clinical core (vaccine, dose, status). */\n readonly rxa: Segment;\n /** The first `RXR` route/site segment beneath the administration, when present. */\n readonly rxr: Segment | undefined;\n}\n\ninterface MutableImmGroup {\n orc: Segment | undefined;\n rxa: Segment | undefined;\n rxr: Segment | undefined;\n}\n\n/**\n * Group a VXU message's `ORC`/`RXA`/`RXR` segments into immunization order groups. Per the VXU_V04\n * message map an `ORC` opens the order and the following `RXA` (+ `RXR`) is incorporated; an `RXA`\n * with no preceding open group anchors its own group (a bare administration). Only groups that carry\n * an `RXA` are returned — an `ORC` with no `RXA` has no vaccine to immunize and is dropped.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { groups } = collectImmunizationGroups(parseHL7(raw));\n * // groups[0]?.rxa; groups[0]?.rxr; groups[0]?.orc;\n * ```\n */\nexport function collectImmunizationGroups(msg: Hl7Message): readonly ImmunizationGroup[] {\n const groups: MutableImmGroup[] = [];\n let current: MutableImmGroup | undefined;\n\n const open = (): MutableImmGroup => {\n const g: MutableImmGroup = { orc: undefined, rxa: undefined, rxr: undefined };\n groups.push(g);\n current = g;\n return g;\n };\n\n for (const seg of msg.allSegments()) {\n switch (seg.type) {\n case \"ORC\":\n open().orc = seg;\n break;\n case \"RXA\":\n // Incorporate into the current ORC-opened group when it has no RXA yet; else open a bare group.\n if (current === undefined || current.rxa !== undefined) open();\n (current as MutableImmGroup).rxa = seg;\n break;\n case \"RXR\":\n // First route only (Immunization.route is 0..1); ignored if the group has no administration.\n if (current !== undefined && current.rxa !== undefined && current.rxr === undefined) {\n current.rxr = seg;\n }\n break;\n default:\n break;\n }\n }\n\n return groups\n .filter((g): g is MutableImmGroup & { rxa: Segment } => g.rxa !== undefined)\n .map((g) => ({ orc: g.orc, rxa: g.rxa, rxr: g.rxr }));\n}\n\n/** Build `Immunization.status` from RXA-20/RXA-21 per the IG's three conditioned status rows. */\nfunction buildStatus(rxa: Segment, issues: TransformIssue[]): string | undefined {\n const actionCode = rxa.field(21).value;\n // RXA-21 = \"D\" (delete): the IG assigns `status = \"entered-in-error\"` (the FHIR retraction state).\n if (actionCode === \"D\") return \"entered-in-error\";\n const completion = rxa.field(20).value;\n // RXA-20 not valued (and not a delete): the IG assigns `status = \"completed\"`.\n if (completion === \"\") return \"completed\";\n // RXA-20 valued: translate via HL70322 → event-status; a code with no target is flagged (the\n // resource is then withheld by the required-status emit gate), never guessed.\n const mapped = Object.hasOwn(IMMUNIZATION_STATUS_MAP, completion)\n ? IMMUNIZATION_STATUS_MAP[completion]\n : undefined;\n if (mapped === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"RXA.20\", \"Immunization.status\"));\n }\n return mapped;\n}\n\n/**\n * Value-translate an RXR CWE field (route/site) to a CodeableConcept via a license-clean\n * {@link CodedValueMap} (HL70162 route / HL70550 site), additive and fail-safe; `undefined` when empty.\n */\nfunction translatedFrom(\n seg: Segment,\n index: number,\n map: CodedValueMap,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (seg.field(index).value === \"\") return undefined;\n const cc = toFhirCodeableConceptVia(seg.field(index).asCwe(), map, ctx);\n issues.push(...cc.issues);\n return cc.value;\n}\n\n/**\n * Build a FHIR `Immunization` resource node from a VXU order group's `RXA` (+ `RXR`, `ORC`). Returns\n * `{ value: undefined }` when RXA-5 (the vaccine code, required 1..1) is absent. `status`,\n * `occurrenceDateTime`, and `patient` are all required 1..1; when any cannot be grounded the resource is\n * left incomplete and later **withheld** by the conservative-emit gate — never guessed.\n *\n * @param rxa - The `RXA` `@cosyte/hl7` `Segment` (the administration).\n * @param rxr - The first `RXR` route/site `Segment` beneath the administration, when present.\n * @param orc - The `ORC` `Segment` that opened the order, when present (identifiers + `recorded` fallback).\n * @param patientFullUrl - The bundle's Patient fullUrl → `Immunization.patient` (required 1..1).\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `Immunization.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const rxa = parseHL7(raw).segments(\"RXA\")[0];\n * // const { value } = buildImmunization(rxa!, undefined, undefined, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildImmunization(\n rxa: Segment,\n rxr: Segment | undefined,\n orc: Segment | undefined,\n patientFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // RXA-5 → vaccineCode (required 1..1). Absent → nothing emittable.\n if (rxa.field(5).value === \"\") return { value: undefined, issues };\n const vaccineCode = toFhirCodeableConcept(rxa.field(5).asCwe(), ctx);\n issues.push(...vaccineCode.issues);\n if (vaccineCode.value === undefined) return { value: undefined, issues };\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Immunization\") },\n ];\n\n // ORC-2 / ORC-3 → identifier (PLAC / FILL, v2-0203 types).\n if (orc !== undefined) {\n const identifiers = [\n orderIdentifier(orc.field(2).value, \"PLAC\"),\n orderIdentifier(orc.field(3).value, \"FILL\"),\n ].filter((i): i is FhirComplex => i !== undefined);\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n }\n\n // RXA-20/RXA-21 → status (required 1..1). Absent/unmapped → left absent (emit gate withholds).\n const status = buildStatus(rxa, issues);\n if (status !== undefined) props.push({ name: \"status\", value: primitive(status) });\n\n props.push({ name: \"vaccineCode\", value: vaccineCode.value });\n\n // patient / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (patientFullUrl !== undefined)\n props.push({ name: \"patient\", value: reference(patientFullUrl) });\n if (encounterFullUrl !== undefined)\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n\n // RXA-3 → occurrenceDateTime (required, occurrence[x]). Absent → emit gate withholds.\n if (rxa.field(3).value !== \"\") {\n const occurrence = toFhirDateTime(rxa.field(3).asTs(), ctx.options);\n issues.push(...occurrence.issues);\n if (occurrence.value !== undefined)\n props.push({ name: \"occurrenceDateTime\", value: primitive(occurrence.value) });\n }\n\n // RXA-22 → recorded (a dateTime; date-only ok), falling back to ORC-9 when RXA-22 is unvalued.\n const recordedTs =\n rxa.field(22).value !== \"\"\n ? rxa.field(22).asTs()\n : orc !== undefined && orc.field(9).value !== \"\"\n ? orc.field(9).asTs()\n : undefined;\n if (recordedTs !== undefined) {\n const recorded = toFhirDateTime(recordedTs, ctx.options);\n issues.push(...recorded.issues);\n if (recorded.value !== undefined)\n props.push({ name: \"recorded\", value: primitive(recorded.value) });\n }\n\n // RXA-6 / RXA-7 → doseQuantity (magnitude precision-exact; non-UCUM unit preserved verbatim).\n const doseRaw = rxa.field(6).asNm().raw;\n if (doseRaw !== \"\") {\n const dose = quantityFromRawMagnitude(\n doseRaw,\n rxa.field(7).asCwe(),\n ctx,\n undefined,\n \"RXA.6\",\n \"RXA.7\",\n );\n issues.push(...dose.issues);\n if (dose.value !== undefined) props.push({ name: \"doseQuantity\", value: dose.value });\n }\n\n // RXA-15 → lotNumber (verbatim string).\n if (rxa.field(15).value !== \"\")\n props.push({ name: \"lotNumber\", value: primitive(rxa.field(15).value) });\n\n // RXA-16 → expirationDate (a FHIR `date`): emit only a date-precision value; a value carrying a\n // time-of-day is not a valid `date` and is dropped + flagged rather than truncated silently.\n if (rxa.field(16).value !== \"\") {\n const exp = toFhirDateTime(rxa.field(16).asTs(), ctx.options);\n issues.push(...exp.issues);\n if (exp.value !== undefined && !exp.value.includes(\"T\")) {\n props.push({ name: \"expirationDate\", value: primitive(exp.value) });\n } else if (exp.value !== undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"RXA.16\", \"Immunization.expirationDate\"),\n );\n }\n }\n\n // RXA-18 → statusReason; RXA-19 → reasonCode.\n if (rxa.field(18).value !== \"\") {\n const reason = toFhirCodeableConcept(rxa.field(18).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"statusReason\", value: reason.value });\n }\n if (rxa.field(19).value !== \"\") {\n const indication = toFhirCodeableConcept(rxa.field(19).asCwe(), ctx);\n issues.push(...indication.issues);\n if (indication.value !== undefined)\n props.push({ name: \"reasonCode\", value: list([indication.value]) });\n }\n\n // RXR-1 → route (HL70162); RXR-2 → site (HL70550) — both value-translated via their license-clean maps.\n if (rxr !== undefined) {\n const route = translatedFrom(rxr, 1, ROUTE_VALUE_MAP, ctx, issues);\n if (route !== undefined) props.push({ name: \"route\", value: route });\n const site = translatedFrom(rxr, 2, SITE_VALUE_MAP, ctx, issues);\n if (site !== undefined) props.push({ name: \"site\", value: site });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * RXO (+ RXR route) → FHIR `MedicationRequest` — the pharmacy-order request,\n * grounded firsthand on the IG **Segment RXO to MedicationRequest** and **Segment RXR to\n * MedicationRequest** ConceptMaps (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-rxo-to-medicationrequest.html`, `ConceptMap-segment-rxr-to-medicationrequest.html`).\n * Per the **ORM_O01 message map**, an `RXO` in the order-detail is a `MedicationRequest`; the `ORC`\n * that opened the order supplies `authoredOn`.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | RXO-1 Requested Give Code (CWE) | `medicationCodeableConcept` | {@link toFhirCodeableConcept} |\n * | RXO-2 / RXO-3 Give Amount Min/Max (NM) | `dosageInstruction.doseAndRate.doseRange.low`/`.high` | {@link quantityFromRawMagnitude} + RXO-4 units |\n * | RXO-11 / RXO-12 Requested Dispense Amount / Units | `dispenseRequest.quantity` | {@link quantityFromRawMagnitude} |\n * | RXO-13 Number of Refills (NM) | `dispenseRequest.numberOfRepeatsAllowed` (unsignedInt) | integer-valued `decimal` |\n * | RXR-1 Route (CWE) | `dosageInstruction.route` | {@link ROUTE_VALUE_MAP} (HL70162, value-translated) |\n * | RXR-2 Site (CWE) | `dosageInstruction.site` | {@link SITE_VALUE_MAP} (HL70550, value-translated) |\n * | RXR-4 Method (CWE) | `dosageInstruction.method` | {@link toFhirCodeableConcept} (structural — SNOMED target, BYO) |\n * | RXO-9 Allow Substitutions (CWE) | `substitution.allowedCodeableConcept` | {@link SUBSTITUTION_VALUE_MAP} (HL70161) |\n * | ORC-9 Date/Time of Order Event | `authoredOn` | {@link toFhirDateTime}, *IF ORC-1 = `NW`* |\n * | (order message context) | `intent` = `order` | see below |\n * | (message-map wiring) | `subject` / `encounter` | the bundle's Patient / Encounter |\n *\n * **Fail-safes (never a confident wrong medication order).**\n * - **`medication[x]` (required 1..1).** Emitted as `medicationCodeableConcept` from RXO-1 only; a\n * pharmacy order with no give code has nothing to prescribe and is not built (`{ value: undefined }`).\n * The ingredient/strength paths (RXO-5/18/19/25/26 → a *contained* `Medication` with `ingredient`)\n * and `medicationReference` are deferred, not fabricated.\n * - **`status` (required 1..1) = `unknown` + flag.** Unlike `ServiceRequest`, the IG ships **no**\n * status source for `MedicationRequest` at all — there is no RXO→status row and no orc-to-\n * medicationrequest map, and the `request-status` codes HL70119 yields (`revoked`, …) are **not**\n * valid `medicationrequest-status` codes, so borrowing that table would emit invalid FHIR. Rather\n * than guess a clinical state, `status` is set to the value-set's own `unknown` (an honest\n * \"not known\", asserting nothing) and flagged {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}.\n * - **`intent` (required 1..1) = `order`.** The IG maps RXO → `intent` `equivalent` with no value\n * ConceptMap; the ORM_O01 family is an *order* message, so `intent` is fixed to `order` from that\n * message context — a resource-level constant, not a fabricated per-code row (as for `ServiceRequest`).\n * - **Dose/dispense units.** Carried through {@link quantityFromRawMagnitude}: a magnitude is\n * precision-exact (string-backed `decimal`, never rescaled), and a non-UCUM unit is preserved\n * verbatim in `.unit` with `.code`/`.system` absent + flagged — a UCUM code is never fabricated.\n * - **Route/site value translation.** RXR-1 route → {@link ROUTE_VALUE_MAP} (HL70162: a\n * 41-code identity group into `v2-0162` plus a 6-code remap into `v3-RouteOfAdministration` —\n * `IM→IM`, `SC→SQ`, …) and RXR-2 site → {@link SITE_VALUE_MAP} (HL70550: 443-code identity into\n * `v2-0550`). Both are additive: the derived target coding is added and the raw coding preserved; a\n * code outside the table is preserved + flagged, never coerced. RXR-4 method's IG target is SNOMED CT\n * (encumbered — **not bundled**), so method stays structurally carried (BYO), never SNOMED-translated.\n * - **Substitution.** RXO-9 → `substitution.allowedCodeableConcept` via\n * {@link SUBSTITUTION_VALUE_MAP} (HL70161 `N`/`G`/`T` identity into `v2-0161`). A valued RXO-9 the map\n * has no target for is flagged and the **substitution backbone is withheld** — a substitution\n * permission (whether the pharmacist may swap the drug) is never emitted from an unrecognized code.\n *\n * **`RXE` is out of scope by grounding, not omission.** The STU1 IG ships no `RXE` segment map and no\n * `RDE`/`RGV` message map; the assembler flags any `RXE` rather than mapping it here (an RXE layout is\n * never guessed from the RXO map — the field positions differ).\n *\n * @packageDocumentation\n */\n\nimport type { CWE, Segment } from \"@cosyte/hl7\";\nimport { complex, decimal, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { quantityFromRawMagnitude } from \"../datatypes/quantity.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport {\n codeableConceptFromTarget,\n toFhirCodeableConceptVia,\n translateBound,\n ROUTE_VALUE_MAP,\n SITE_VALUE_MAP,\n SUBSTITUTION_VALUE_MAP,\n type CodedValueMap,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/** The `medicationrequest-status` code emitted when the IG grounds no status (an honest \"not known\"). */\nconst STATUS_UNKNOWN = \"unknown\";\n/** The `medicationrequest Intent` code fixed for order-message requests (see the module fail-safe note). */\nconst ORDER_INTENT = \"order\";\n/** A FHIR `unsignedInt` lexical form: `0` or a leading-non-zero positive integer (no sign, no leading zero). */\nconst UNSIGNED_INT = /^(0|[1-9][0-9]*)$/;\n\n/**\n * Build a `dosageInstruction.method` CodeableConcept from RXR-4 **structurally** (no value translation).\n * The IG maps RXR-4 → method via `table-hl70165-to-sct`, whose target is **SNOMED CT** — license-\n * encumbered and **not bundled**. So the code is carried structurally (system recognized if the\n * CWE declares one, else flagged) and the SNOMED translation is left BYO — never fabricated here.\n */\nfunction codeableFrom(\n seg: Segment,\n index: number,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (seg.field(index).value === \"\") return undefined;\n const cc = toFhirCodeableConcept(seg.field(index).asCwe(), ctx);\n issues.push(...cc.issues);\n return cc.value;\n}\n\n/** Value-translate an RXR CWE field to a CodeableConcept via a license-clean {@link CodedValueMap}. */\nfunction translatedFrom(\n seg: Segment,\n index: number,\n map: CodedValueMap,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (seg.field(index).value === \"\") return undefined;\n const cc = toFhirCodeableConceptVia(seg.field(index).asCwe(), map, ctx);\n issues.push(...cc.issues);\n return cc.value;\n}\n\n/** Build a dose-range endpoint `Quantity` from an RXO amount field (NM) sharing the RXO-4 units. */\nfunction doseEndpoint(\n rxo: Segment,\n amountIndex: number,\n units: CWE,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const raw = rxo.field(amountIndex).asNm().raw;\n if (raw === \"\") return undefined;\n const q = quantityFromRawMagnitude(\n raw,\n units,\n ctx,\n undefined,\n `RXO.${String(amountIndex)}`,\n \"RXO.4\",\n );\n issues.push(...q.issues);\n return q.value;\n}\n\n/** Build the single `dosageInstruction` (route/site/method + dose range), or `undefined` when empty. */\nfunction buildDosageInstruction(\n rxo: Segment | undefined,\n rxr: Segment | undefined,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n\n if (rxr !== undefined) {\n // RXR-1 route / RXR-2 site are value-translated via the license-clean HL70162 / HL70550 maps.\n const route = translatedFrom(rxr, 1, ROUTE_VALUE_MAP, ctx, issues);\n if (route !== undefined) props.push({ name: \"route\", value: route });\n const site = translatedFrom(rxr, 2, SITE_VALUE_MAP, ctx, issues);\n if (site !== undefined) props.push({ name: \"site\", value: site });\n // RXR-4 method stays structural (its IG target is SNOMED CT — encumbered, BYO; see codeableFrom).\n const method = codeableFrom(rxr, 4, ctx, issues);\n if (method !== undefined) props.push({ name: \"method\", value: method });\n }\n\n if (rxo !== undefined) {\n const units = rxo.field(4).asCwe();\n const low = doseEndpoint(rxo, 2, units, ctx, issues);\n const high = doseEndpoint(rxo, 3, units, ctx, issues);\n const rangeProps: { name: string; value: FhirNode }[] = [];\n if (low !== undefined) rangeProps.push({ name: \"low\", value: low });\n if (high !== undefined) rangeProps.push({ name: \"high\", value: high });\n if (rangeProps.length > 0) {\n props.push({\n name: \"doseAndRate\",\n value: list([complex([{ name: \"doseRange\", value: complex(rangeProps) }])]),\n });\n }\n }\n\n return props.length === 0 ? undefined : complex(props);\n}\n\n/** Build `dispenseRequest` (RXO-11/12 quantity + RXO-13 refills), or `undefined` when empty. */\nfunction buildDispenseRequest(\n rxo: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n\n const amount = rxo.field(11).asNm().raw;\n if (amount !== \"\") {\n const q = quantityFromRawMagnitude(\n amount,\n rxo.field(12).asCwe(),\n ctx,\n undefined,\n \"RXO.11\",\n \"RXO.12\",\n );\n issues.push(...q.issues);\n if (q.value !== undefined) props.push({ name: \"quantity\", value: q.value });\n }\n\n const refills = rxo.field(13).value;\n if (refills !== \"\") {\n if (UNSIGNED_INT.test(refills)) {\n props.push({ name: \"numberOfRepeatsAllowed\", value: primitive(decimal(refills)) });\n } else {\n // A non-unsignedInt refill count is dropped rather than emitted as an invalid primitive.\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"RXO.13\",\n \"dispenseRequest.numberOfRepeatsAllowed\",\n ),\n );\n }\n }\n\n return props.length === 0 ? undefined : complex(props);\n}\n\n/**\n * Build a FHIR `MedicationRequest` resource node from an order group's `RXO` and `RXR` segments and\n * its opening `ORC`. Returns `{ value: undefined }` when RXO-1 (the give code) is absent — a\n * medication request with no `medication[x]` cannot be emitted.\n *\n * @param rxo - The `RXO` `@cosyte/hl7` `Segment` (the pharmacy order detail).\n * @param rxr - The first `RXR` route `Segment` beneath the order, when present.\n * @param orc - The `ORC` `Segment` that opened the order, when present (supplies `authoredOn`).\n * @param subjectFullUrl - The bundle's Patient fullUrl → `MedicationRequest.subject` (required 1..1).\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `MedicationRequest.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const rxo = parseHL7(raw).segments(\"RXO\")[0];\n * // const { value } = buildMedicationRequest(rxo, undefined, undefined, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildMedicationRequest(\n rxo: Segment | undefined,\n rxr: Segment | undefined,\n orc: Segment | undefined,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // RXO-1 → medicationCodeableConcept (required 1..1). Absent → nothing emittable.\n if (rxo === undefined || rxo.field(1).value === \"\") return { value: undefined, issues };\n const medication = toFhirCodeableConcept(rxo.field(1).asCwe(), ctx);\n issues.push(...medication.issues);\n if (medication.value === undefined) return { value: undefined, issues };\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"MedicationRequest\") },\n ];\n\n // status (required) = unknown — the IG grounds no MedicationRequest status; an honest \"not known\".\n props.push({ name: \"status\", value: primitive(STATUS_UNKNOWN) });\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"RXO\", \"MedicationRequest.status\"),\n );\n\n // intent (required) = order — the order-message context, not a per-code translation.\n props.push({ name: \"intent\", value: primitive(ORDER_INTENT) });\n\n props.push({ name: \"medicationCodeableConcept\", value: medication.value });\n\n // subject / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined)\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n\n // ORC-9 → authoredOn, only for a new order (ORC-1 = NW). authoredOn is a `dateTime` (date-only ok).\n if (orc !== undefined && orc.field(1).value === \"NW\" && orc.field(9).value !== \"\") {\n const authored = toFhirDateTime(orc.field(9).asTs(), ctx.options);\n issues.push(...authored.issues);\n if (authored.value !== undefined)\n props.push({ name: \"authoredOn\", value: primitive(authored.value) });\n }\n\n const dosage = buildDosageInstruction(rxo, rxr, ctx, issues);\n if (dosage !== undefined) props.push({ name: \"dosageInstruction\", value: list([dosage]) });\n\n const dispense = buildDispenseRequest(rxo, ctx, issues);\n if (dispense !== undefined) props.push({ name: \"dispenseRequest\", value: dispense });\n\n // RXO-9 → substitution.allowedCodeableConcept (HL70161 → v2-0161; value-translated, translate-or-\n // withhold). Only N/G/T carry a target; a valued RXO-9 the map has no target for is flagged and the\n // substitution backbone is withheld rather than emitted with a fabricated substitution permission.\n const cwe9 = rxo.field(9).asCwe();\n if (cwe9.identifier !== undefined && cwe9.identifier !== \"\") {\n // translateBound withholds a translation for a foreign coding system (CWE.3 ≠ HL70161) too, not\n // just an unmapped code — a substitution permission is never asserted from a non-v2-0161 code.\n const target = translateBound(cwe9, SUBSTITUTION_VALUE_MAP);\n if (target === undefined) {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_CODE_UNMAPPED,\n \"RXO.9\",\n \"MedicationRequest.substitution.allowedCodeableConcept\",\n ),\n );\n } else {\n props.push({\n name: \"substitution\",\n value: complex([\n {\n name: \"allowedCodeableConcept\",\n value: codeableConceptFromTarget(target, cwe9.originalText),\n },\n ]),\n });\n }\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * MSH → FHIR `MessageHeader` — grounded on the IG **Segment MSH to MessageHeader** ConceptMap\n * (`hl7.fhir.uv.v2mappings`, STU1), scoped to the R4 elements that can be produced faithfully:\n *\n * | MSH field | FHIR target | note |\n * |---|---|---|\n * | MSH-9 Message Type (trigger event) | `MessageHeader.eventCoding` | v2-0003 event-type system |\n * | MSH-3 Sending Application (HD) | `MessageHeader.source.name` / `.endpoint` | endpoint is a URL; an app namespace is not one |\n *\n * R4 requires `MessageHeader.source.endpoint` (1..1, a URL). An MSH-3 application *namespace* is not a\n * URL, so rather than fabricate one, the endpoint is emitted with a `data-absent-reason` extension\n * (value `unknown`) and flagged {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN} — the\n * spec-clean way to satisfy a required primitive whose value is genuinely unknown. `MessageHeader.focus`\n * wires the header to the message's focal resources (Patient, Encounter). MSH-10 (message control id)\n * is carried on `Bundle.identifier` by the assembler (R4 `MessageHeader` has no identifier element);\n * MSH-4/5/6 sender/destination Organizations and MessageHeader.timestamp (an R5 element) are deferred.\n *\n * @packageDocumentation\n */\n\nimport type { Meta } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport { coding, dataAbsent, reference } from \"./reference.js\";\n\n/** HL7 v2 Table 0003 (Event Type) canonical system — the `MessageHeader.eventCoding` code system. */\nconst V2_0003_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0003\";\n\n/**\n * Build a FHIR `MessageHeader` resource node from the MSH-derived message metadata.\n *\n * @param meta - The `@cosyte/hl7` `Meta` view (MSH-derived).\n * @param focusFullUrls - The `urn:uuid:` fullUrls of the message's focal resources (Patient,\n * Encounter), wired into `MessageHeader.focus`.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildMessageHeader(parseHL7(raw).meta, [\"urn:uuid:1-2-3\"]);\n * ```\n */\nexport function buildMessageHeader(\n meta: Meta,\n focusFullUrls: readonly string[],\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"MessageHeader\") },\n ];\n\n // MSH-9 trigger event → MessageHeader.eventCoding (Table 0003).\n const eventCoding = coding(V2_0003_SYSTEM, meta.triggerEvent);\n if (eventCoding !== undefined) {\n props.push({ name: \"eventCoding\", value: eventCoding });\n } else {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"MSH.9\", \"MessageHeader.eventCoding\"));\n }\n\n // MSH-3 → MessageHeader.source. endpoint (a URL) is required by R4 but an app namespace is not a\n // URL, so it is emitted data-absent (unknown) rather than fabricated.\n const sourceProps: { name: string; value: FhirNode }[] = [];\n if (meta.sendingApp !== undefined && meta.sendingApp !== \"\") {\n sourceProps.push({ name: \"name\", value: primitive(meta.sendingApp) });\n }\n sourceProps.push({ name: \"endpoint\", value: dataAbsent(\"unknown\") });\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"MSH.3\", \"MessageHeader.source.endpoint\"),\n );\n props.push({ name: \"source\", value: complex(sourceProps) });\n\n // MessageHeader.focus → the focal resources of the message.\n if (focusFullUrls.length > 0) {\n props.push({ name: \"focus\", value: list(focusFullUrls.map((url) => reference(url))) });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * OBX → FHIR `Observation` — the highest-clinical-stakes segment map,\n * grounded firsthand on the IG **Segment OBX to Observation** ConceptMap plus its two governing table\n * ConceptMaps (`hl7.fhir.uv.v2mappings`, STU1). The rows used here, verified against the published maps\n * (`ConceptMap-segment-obx-to-observation.html`, `-table-hl70078-to-v3-observationinterpretation.html`,\n * `-table-hl70085-to-observation-status.html`):\n *\n * | OBX field | FHIR target | via |\n * |---|---|---|\n * | OBX-2 Value Type | discriminates OBX-5 → `value[x]` | {@link buildValue} — never assume `Quantity` |\n * | OBX-3 Observation Identifier (CWE) | `Observation.code` | {@link toFhirCodeableConcept} |\n * | OBX-5 Observation Value | `Observation.value[x]` | per OBX-2 |\n * | OBX-6 Units (CWE) | `valueQuantity.unit`/`.code`/`.system` | {@link quantityFromRawMagnitude} |\n * | OBX-7 Reference Range | `Observation.referenceRange.text` | mapped to `.text` (never decomposed) |\n * | OBX-8 Abnormal Flags | `Observation.interpretation` | {@link HL70078_INTERPRETATION_CODES} |\n * | OBX-11 Result Status | `Observation.status` | {@link OBSERVATION_STATUS_MAP} (HL70085) |\n * | OBX-14 Date/Time of Observation | `Observation.effectiveDateTime` | {@link toFhirDateTime} |\n *\n * **The \"never a confident wrong result\" fail-safes:**\n * - **OBX-2 drives `value[x]`.** `NM`→`valueQuantity`, `CWE`/`CE`/`CF`/`CNE`/`IS`→`valueCodeableConcept`,\n * `SN`→structured (`valueQuantity` with a comparator / `valueRange` / `valueRatio`), `ST`/`TX`/`FT`→\n * `valueString`. A value type with no first-class target here (`NA`, `ED`, `DR`, `TM`, `NR`, unknown)\n * preserves the raw value as `valueString` and flags {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED}\n * (the richer FHIR type is deferred) — never a fabricated `Quantity`.\n * - **A corrected/cancelled result never emits as `final`.** OBX-11 `C`→`corrected`, `X`→`cancelled`,\n * `D`/`W`→`entered-in-error` (HL70085). A status code with **no** HL70085 target leaves\n * `Observation.status` absent (flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}); the required-`status`\n * emit gate then **withholds** the Observation rather than shipping it — never coerced to `final`.\n * - **An unrecognized abnormal flag is surfaced, never coerced to normal.** Each OBX-8 flag in\n * {@link HL70078_INTERPRETATION_CODES} becomes an `interpretation` coding (the map is code-preserving);\n * a flag absent from the table is flagged and dropped, never emitted as `N`/normal.\n *\n * Numeric magnitudes (NM, SN) are read from the **raw OBX-5 field** — not the `@cosyte/hl7`\n * `Observation` view's JS `number` — so a reported lab value's exact lexical precision (`120.50`) is\n * carried through the string-backed FHIR `decimal`, never routed through a lossy `number`.\n *\n * @packageDocumentation\n */\n\nimport type { CWE, Field, Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { quantityFromRawMagnitude } from \"../datatypes/quantity.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/** The v3 ObservationInterpretation canonical system (FHIR `Observation.interpretation` binding). */\nconst V3_OBSERVATION_INTERPRETATION_SYSTEM =\n \"http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation\";\n\n/**\n * HL7 v2 Table 0078 (Abnormal Flags) → FHIR v3 ObservationInterpretation (`Observation.interpretation`),\n * per the IG **Table HL70078 to v3 ObservationInterpretation** ConceptMap. Every mapped row is\n * `is equivalent to` an **identically-spelled** v3 code (the map is code-preserving), so this is the set\n * of codes that carry a target — a flag **absent** from this set has no equivalent and is flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, never coerced (the IG leaves `AC`/`HM`/`OBX`/`QCF`/`TOX`\n * and any local flag unmapped, and declares no `unmapped` default).\n */\nexport const HL70078_INTERPRETATION_CODES: ReadonlySet<string> = new Set([\n \"<\",\n \">\",\n \"A\",\n \"AA\",\n \"B\",\n \"CAR\",\n \"D\",\n \"DET\",\n \"E\",\n \"EX\",\n \"EXP\",\n \"H\",\n \"HH\",\n \"HU\",\n \"I\",\n \"IE\",\n \"IND\",\n \"L\",\n \"LL\",\n \"LU\",\n \"MS\",\n \"N\",\n \"NCL\",\n \"ND\",\n \"NEG\",\n \"NR\",\n \"NS\",\n \"POS\",\n \"R\",\n \"RR\",\n \"S\",\n \"SDD\",\n \"SYN-R\",\n \"SYN-S\",\n \"U\",\n \"UNE\",\n \"VS\",\n \"W\",\n \"WR\",\n]);\n\n/**\n * HL7 v2 Table 0085 (Observation Result Status) → FHIR `observation-status` (`Observation.status`),\n * per the IG **Table HL70085 to Observation Status** ConceptMap (each `is equivalent to`). Only these\n * seven source codes carry a target; the codes the IG leaves unmapped (`B`, `I`, `N`, `O`, `R`, `S`,\n * `U`, `V`) are **absent here on purpose** — an OBX-11 with one of them (or any local code) leaves\n * `Observation.status` absent + flagged, and the required-`status` emit gate withholds the Observation.\n * **`C`→`corrected` and `X`→`cancelled` guarantee a corrected/cancelled result never emits as `final`.**\n */\nexport const OBSERVATION_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n A: \"amended\",\n C: \"corrected\",\n D: \"entered-in-error\",\n F: \"final\",\n P: \"preliminary\",\n W: \"entered-in-error\",\n X: \"cancelled\",\n});\n\n/** The FHIR `Quantity.comparator` codes an SN.1 comparator can populate (SN `=`/`<>` do not). */\nconst SN_COMPARATORS: ReadonlySet<string> = new Set([\">\", \"<\", \">=\", \"<=\"]);\n\n/** OBX-2 value types the IG maps to `valueCodeableConcept`. */\nconst CODED_VALUE_TYPES: ReadonlySet<string> = new Set([\"CWE\", \"CE\", \"CF\", \"CNE\", \"IS\"]);\n/** OBX-2 value types the IG maps to `valueDateTime`. */\nconst DATETIME_VALUE_TYPES: ReadonlySet<string> = new Set([\"DT\", \"DTM\", \"TS\"]);\n/** OBX-2 value types the IG maps directly to `valueString`. */\nconst STRING_VALUE_TYPES: ReadonlySet<string> = new Set([\"ST\", \"TX\", \"FT\"]);\n\n/** The decoded first-subcomponent of a field's component at 0-based `index`, or `undefined` when empty. */\nfunction rawComponent(field: Field, index: number): string | undefined {\n const c = field.repetitions[0]?.components[index]?.subcomponents[0];\n return c === undefined || c === \"\" ? undefined : c;\n}\n\n/** Reconstruct an SN's human string (`>90`, `10-20`, `1:2`) from its raw components — for a fallback. */\nfunction snText(field: Field): string {\n return [0, 1, 2, 3].map((i) => rawComponent(field, i) ?? \"\").join(\"\");\n}\n\n/** A `valueString` property carrying the raw OBX-5 text (a faithful, never-fabricated fallback). */\nfunction valueStringProp(raw: string): { name: string; value: FhirNode } {\n return { name: \"valueString\", value: primitive(raw) };\n}\n\n/**\n * Build a FHIR `Quantity` node wrapped as a `valueRange`/`valueRatio` endpoint pair, or `undefined`\n * when either magnitude is not a faithful decimal. Both endpoints share the OBX-6 units.\n */\nfunction endpointPair(\n field: Field,\n units: CWE,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { first: FhirComplex; second: FhirComplex } | undefined {\n const n1 = rawComponent(field, 1);\n const n2 = rawComponent(field, 3);\n if (n1 === undefined || n2 === undefined) return undefined;\n const first = quantityFromRawMagnitude(n1, units, ctx);\n const second = quantityFromRawMagnitude(n2, units, ctx);\n issues.push(...first.issues, ...second.issues);\n if (first.value === undefined || second.value === undefined) return undefined;\n return { first: first.value, second: second.value };\n}\n\n/**\n * SN (structured numeric) → `value[x]`, per the IG's OBX-2 = `SN` conditional: a separator `-` with two\n * numbers is a `valueRange`; a `:`/`/` separator is a `valueRatio`; a comparator with a single number is\n * a `valueQuantity` (comparator carried); anything else preserves the raw SN string as `valueString`.\n */\nfunction buildSnValue(\n field: Field,\n units: CWE,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { name: string; value: FhirNode } {\n const sn = field.asSn();\n const separator = sn?.separatorOrSuffix;\n\n if (separator === \"-\") {\n const pair = endpointPair(field, units, ctx, issues);\n if (pair !== undefined) {\n return {\n name: \"valueRange\",\n value: complex([\n { name: \"low\", value: pair.first },\n { name: \"high\", value: pair.second },\n ]),\n };\n }\n return valueStringProp(snText(field));\n }\n\n if (separator === \":\" || separator === \"/\") {\n const pair = endpointPair(field, units, ctx, issues);\n if (pair !== undefined) {\n return {\n name: \"valueRatio\",\n value: complex([\n { name: \"numerator\", value: pair.first },\n { name: \"denominator\", value: pair.second },\n ]),\n };\n }\n return valueStringProp(snText(field));\n }\n\n // Comparator + single number → valueQuantity. SN `<>` (unequal) has no FHIR comparator → string.\n const comparator = sn?.comparator;\n const num1 = rawComponent(field, 1);\n if (comparator !== \"<>\" && num1 !== undefined) {\n const fhirComparator =\n comparator !== undefined && SN_COMPARATORS.has(comparator) ? comparator : undefined;\n const q = quantityFromRawMagnitude(num1, units, ctx, fhirComparator);\n issues.push(...q.issues);\n if (q.value !== undefined) return { name: \"valueQuantity\", value: q.value };\n }\n return valueStringProp(snText(field));\n}\n\n/**\n * Discriminate OBX-5 by OBX-2 value type into the correct FHIR `Observation.value[x]` property, or\n * `undefined` when OBX-5 is empty. Never assumes `Quantity`; a value type with no first-class target\n * degrades to `valueString` + a {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} flag, never fabricated.\n */\nfunction buildValue(\n obx: Segment,\n valueType: string,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { name: string; value: FhirNode } | undefined {\n const field = obx.field(5);\n const rawValue = field.value;\n const vt = valueType.toUpperCase();\n\n if (vt === \"NM\") {\n const q = quantityFromRawMagnitude(field.asNm().raw, obx.field(6).asCwe(), ctx);\n issues.push(...q.issues);\n if (q.value !== undefined) return { name: \"valueQuantity\", value: q.value };\n // A present-but-non-decimal NM: preserve the raw text rather than drop the result.\n return rawValue === \"\" ? undefined : valueStringProp(rawValue);\n }\n\n if (vt === \"SN\") {\n if (rawValue === \"\" && snText(field) === \"\") return undefined;\n return buildSnValue(field, obx.field(6).asCwe(), ctx, issues);\n }\n\n if (CODED_VALUE_TYPES.has(vt)) {\n const cc = toFhirCodeableConcept(field.asCwe(), ctx);\n issues.push(...cc.issues);\n return cc.value === undefined ? undefined : { name: \"valueCodeableConcept\", value: cc.value };\n }\n\n if (DATETIME_VALUE_TYPES.has(vt)) {\n if (rawValue === \"\") return undefined;\n const dt = toFhirDateTime(field.asTs(), ctx.options);\n issues.push(...dt.issues);\n return dt.value === undefined\n ? undefined\n : { name: \"valueDateTime\", value: primitive(dt.value) };\n }\n\n if (rawValue === \"\") return undefined;\n if (STRING_VALUE_TYPES.has(vt)) return valueStringProp(rawValue);\n\n // A value type with no first-class FHIR value[x] here (NA, ED, RP, DR, TM, NR, ID, unknown): the raw\n // value is preserved as a string and the richer typed mapping is flagged as deferred — never guessed.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBX.5\", \"Observation.value[x]\"));\n return valueStringProp(rawValue);\n}\n\n/** Build `Observation.interpretation` from OBX-8 abnormal flags (HL70078), or `undefined` when none map. */\nfunction buildInterpretation(obx: Segment, issues: TransformIssue[]): FhirNode | undefined {\n const flags = obx\n .field(8)\n .repetitions.map((r) => r.components[0]?.subcomponents[0] ?? \"\")\n .filter((f) => f !== \"\");\n const codings: FhirComplex[] = [];\n for (const flag of flags) {\n if (HL70078_INTERPRETATION_CODES.has(flag)) {\n codings.push(\n complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V3_OBSERVATION_INTERPRETATION_SYSTEM) },\n { name: \"code\", value: primitive(flag) },\n ]),\n ]),\n },\n ]),\n );\n } else {\n // An unrecognized abnormal flag is surfaced and dropped — NEVER coerced to `N`/normal.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBX.8\", \"Observation.interpretation\"),\n );\n }\n }\n return codings.length === 0 ? undefined : list(codings);\n}\n\n/**\n * Build a FHIR `Observation` resource node from one parsed HL7 v2 OBX segment. Returns\n * `{ value: undefined }` when the OBX carries no observation identifier (OBX-3) — an Observation with\n * no `code` cannot be emitted. `Observation.status` is left absent (and the resource later withheld by\n * the emit gate) when OBX-11 is missing or has no HL70085 target — never guessed.\n *\n * @param obx - The OBX `@cosyte/hl7` `Segment`.\n * @param subjectFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient, wired to `Observation.subject`.\n * @param encounterFullUrl - The `urn:uuid:` fullUrl of the bundle's Encounter, wired to `.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const obx = parseHL7(raw).segments(\"OBX\")[0];\n * // const { value } = buildObservation(obx!, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildObservation(\n obx: Segment,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Observation\") },\n ];\n\n // OBX-11 → Observation.status (HL70085). Absent/unmapped → left absent (emit gate withholds), never\n // guessed; a corrected/cancelled status is modelled exactly, never emitted as `final`.\n const statusCode = obx.field(11).value;\n if (statusCode !== \"\") {\n const status = Object.hasOwn(OBSERVATION_STATUS_MAP, statusCode)\n ? OBSERVATION_STATUS_MAP[statusCode]\n : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBX.11\", \"Observation.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // OBX-3 → Observation.code (required 1..1). Absent → nothing emittable.\n const code = toFhirCodeableConcept(obx.field(3).asCwe(), ctx);\n issues.push(...code.issues);\n if (code.value === undefined) return { value: undefined, issues };\n props.push({ name: \"code\", value: code.value });\n\n // Observation.subject / .encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined) {\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n }\n\n // OBX-14 → Observation.effectiveDateTime.\n if (obx.field(14).value !== \"\") {\n const effective = toFhirDateTime(obx.field(14).asTs(), ctx.options);\n issues.push(...effective.issues);\n if (effective.value !== undefined) {\n props.push({ name: \"effectiveDateTime\", value: primitive(effective.value) });\n }\n }\n\n // OBX-2 / OBX-5 → Observation.value[x] (value-type discriminated; never assume Quantity).\n const value = buildValue(obx, obx.field(2).value, ctx, issues);\n if (value !== undefined) props.push(value);\n\n // OBX-8 → Observation.interpretation (HL70078; unrecognized flag surfaced, never coerced to normal).\n const interpretation = buildInterpretation(obx, issues);\n if (interpretation !== undefined) props.push({ name: \"interpretation\", value: interpretation });\n\n // OBX-7 → Observation.referenceRange.text (the IG maps it to `.text`; never decomposed/evaluated).\n const refRange = obx.field(7).value;\n if (refRange !== \"\") {\n props.push({\n name: \"referenceRange\",\n value: list([complex([{ name: \"text\", value: primitive(refRange) }])]),\n });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * Order-message grouping — the message-map structure the ServiceRequest / MedicationRequest graph is\n * assembled over, grounded firsthand on the IG **ORM_O01** and **OML_O21** message\n * maps (`ConceptMap-message-orm-o01-to-bundle.html`, `ConceptMap-message-oml-o21-to-bundle.html`).\n *\n * Both message maps model the ORDER group the same way: **`ORC` creates the request** and the\n * following **ORDER_DETAIL** segment is *incorporated into that same request* — `OBR` →\n * `ServiceRequest`, `RXO` (+ `RXR` route) → `MedicationRequest`. So one order group is an `ORC`\n * anchor plus at most one order-detail segment (an `OBR` for a service order, an `RXO` for a\n * pharmacy order) and the `RXR` route segments beneath a pharmacy order. This walks the segments in\n * document order and buckets each detail segment under the most recent `ORC` — the same positional\n * grouping `@cosyte/hl7`'s `orders()` performs, done here so the raw `ORC`/`OBR`/`RXO`/`RXR`\n * `Segment`s (the request/dose fields the lean `Order` view omits) are available.\n *\n * A detail segment that precedes any `ORC` still anchors its own group (a bare `OBR`/`RXO` order),\n * and any `RXE` — for which the IG ships **no** segment map at all (verified against the STU1\n * artifacts index) — is counted by {@link OrderGrouping.rxeCount} so the assembler can flag it as\n * un-grounded rather than fabricate an RXE→MedicationRequest layout.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\n\n/** One order group: an optional `ORC` request anchor and its incorporated order-detail segments. */\nexport interface OrderGroup {\n /** The `ORC` segment anchoring this order (absent for a bare `OBR`/`RXO` with no preceding `ORC`). */\n readonly orc: Segment | undefined;\n /** The `OBR` order-detail segment → `ServiceRequest`, when this is a service order. */\n readonly obr: Segment | undefined;\n /** The `RXO` order-detail segment → `MedicationRequest`, when this is a pharmacy order. */\n readonly rxo: Segment | undefined;\n /** The `RXR` route segments beneath a pharmacy order (in document order). */\n readonly rxrs: readonly Segment[];\n}\n\n/** The result of grouping an order message: the order groups plus the count of un-mappable `RXE`s. */\nexport interface OrderGrouping {\n /** The order groups, in document order. */\n readonly groups: readonly OrderGroup[];\n /** The count of `RXE` segments — the IG ships no RXE map, so they are flagged, never assembled. */\n readonly rxeCount: number;\n}\n\ninterface MutableGroup {\n orc: Segment | undefined;\n obr: Segment | undefined;\n rxo: Segment | undefined;\n rxrs: Segment[];\n}\n\n/**\n * Group an order message's `ORC`/`OBR`/`RXO`/`RXR` segments into order groups (each `ORC` with the\n * order-detail segment incorporated into it, or a bare detail segment as its own group).\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { groups } = collectOrderGroups(parseHL7(raw));\n * // groups[0]?.orc; groups[0]?.obr; groups[0]?.rxo;\n * ```\n */\nexport function collectOrderGroups(msg: Hl7Message): OrderGrouping {\n const groups: MutableGroup[] = [];\n let current: MutableGroup | undefined;\n let rxeCount = 0;\n\n const open = (): MutableGroup => {\n const g: MutableGroup = { orc: undefined, obr: undefined, rxo: undefined, rxrs: [] };\n groups.push(g);\n current = g;\n return g;\n };\n\n for (const seg of msg.allSegments()) {\n switch (seg.type) {\n case \"ORC\":\n // A new ORC always opens a new order group (ORM/OML: one request per ORC).\n open().orc = seg;\n break;\n case \"OBR\":\n // Incorporate into the current group when it has no detail yet; else open a bare group.\n if (current === undefined || current.obr !== undefined || current.rxo !== undefined) open();\n (current as MutableGroup).obr = seg;\n break;\n case \"RXO\":\n if (current === undefined || current.obr !== undefined || current.rxo !== undefined) open();\n (current as MutableGroup).rxo = seg;\n break;\n case \"RXR\":\n // Route belongs to the current pharmacy order; harmless (unused) if the group has no RXO.\n if (current !== undefined) current.rxrs.push(seg);\n break;\n case \"RXE\":\n // No IG segment map exists for RXE — surfaced for a flag, never assembled.\n rxeCount += 1;\n break;\n default:\n break;\n }\n }\n\n return {\n groups: groups.map((g) => ({ orc: g.orc, obr: g.obr, rxo: g.rxo, rxrs: g.rxrs })),\n rxeCount,\n };\n}\n","/**\n * ORU^R01 order/result grouping — the message-map structure the DiagnosticReport/Observation graph is\n * assembled over, grounded on the IG **ORU_R01 message map**\n * (`ConceptMap-message-oru-r01-to-bundle.html`).\n *\n * An ORU message is a sequence of order groups, each an **OBR** followed by its **OBX** results. This\n * walks the segments in document order and buckets each OBX under the most recent OBR — the same\n * positional grouping `@cosyte/hl7`'s `orders()` performs, done here so the raw OBR/OBX `Segment`s are\n * available (the report/result fields the lean `Order` view omits — OBR-7/22/24/25 — and the exact\n * lexical OBX-5 magnitude the `Observation` view rounds to a JS `number`). An OBX that precedes any OBR\n * has no report to anchor it and is surfaced by {@link ReportGrouping.orphanObxCount} rather than\n * silently dropped.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\n\n/** One ORU report group: an OBR anchor and the OBX result segments beneath it, in document order. */\nexport interface ReportGroup {\n /** The OBR segment anchoring this report. */\n readonly obr: Segment;\n /** The OBX result segments grouped under this OBR (positional grouping). */\n readonly observations: readonly Segment[];\n}\n\n/** The result of grouping an ORU message: the report groups plus any OBX with no preceding OBR. */\nexport interface ReportGrouping {\n /** The OBR-anchored report groups, in document order. */\n readonly groups: readonly ReportGroup[];\n /** The count of OBX segments that appeared before any OBR (no report to anchor them). */\n readonly orphanObxCount: number;\n}\n\n/**\n * Group an ORU message's OBR/OBX segments into report groups (each OBR with its trailing OBX children).\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { groups } = collectReportGroups(parseHL7(raw));\n * // groups[0]?.obr; groups[0]?.observations.length;\n * ```\n */\nexport function collectReportGroups(msg: Hl7Message): ReportGrouping {\n const groups: { obr: Segment; observations: Segment[] }[] = [];\n let current: { obr: Segment; observations: Segment[] } | undefined;\n let orphanObxCount = 0;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"OBR\") {\n current = { obr: seg, observations: [] };\n groups.push(current);\n } else if (seg.type === \"OBX\") {\n if (current === undefined) orphanObxCount += 1;\n else current.observations.push(seg);\n }\n }\n\n return { groups, orphanObxCount };\n}\n","/**\n * PID → FHIR `Patient` — grounded on the IG **Segment PID to Patient** ConceptMap\n * (`hl7.fhir.uv.v2mappings`, STU1). The field→element rows used here, verified firsthand against the\n * published map:\n *\n * | PID field | FHIR target | via |\n * |---|---|---|\n * | PID-3 Patient Identifier List (CX) | `Patient.identifier` | {@link toFhirIdentifier} |\n * | PID-5 Patient Name (XPN) | `Patient.name` | {@link toFhirHumanName} |\n * | PID-7 Date/Time of Birth (DTM) | `Patient.birthDate` | {@link toFhirDateTime} reduced to a `date` |\n * | PID-8 Administrative Sex (CWE) | `Patient.gender` | {@link ADMINISTRATIVE_GENDER_MAP} (Table 0001) |\n * | PID-11 Patient Address (XAD) | `Patient.address` | {@link toFhirAddress} |\n *\n * Fail-safe throughout: each datatype conversion carries its own value-free issues, an unmapped\n * administrative-sex code leaves `gender` absent (never guessed), and a birth *time* (PID-7 with a\n * time-of-day) is dropped to `date` precision with a flag — the US Core `patient-birthTime` extension\n * is a profile concern this library does not cover. Deferred and flagged, not silently mapped:\n * PID-13/14 telecom (no XTN→ContactPoint converter), and PID-10/15/22/29/30 (US Core race/ethnicity\n * extensions, communication language, deceased).\n *\n * @packageDocumentation\n */\n\nimport type { Patient } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirIdentifier } from \"../datatypes/identifier.js\";\nimport { toFhirHumanName } from \"../datatypes/human-name.js\";\nimport { toFhirAddress } from \"../datatypes/address.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\n\n/**\n * HL7 v2 Table 0001 (Administrative Sex) → FHIR `administrative-gender`, exactly per the IG\n * **Table HL70001 to Administrative Gender** ConceptMap (every row \"is equivalent to\"). `A`\n * (Ambiguous) and `N` (Not applicable) both narrow to `other` — the map's stated equivalence, carried\n * as-is. A code absent here (the map defines no `unmapped` default) leaves `gender` absent and is\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED} — never coerced to `unknown`.\n */\nexport const ADMINISTRATIVE_GENDER_MAP: Readonly<Record<string, string>> = Object.freeze({\n F: \"female\",\n M: \"male\",\n O: \"other\",\n U: \"unknown\",\n A: \"other\",\n N: \"other\",\n});\n\n/** Wrap present items as a FHIR list property value, or `undefined` when none are present. */\nfunction listOrUndefined(items: readonly FhirComplex[]): FhirNode | undefined {\n return items.length === 0 ? undefined : list(items);\n}\n\n/**\n * Build a FHIR `Patient` resource node from a parsed HL7 v2 PID view. Returns `{ value: undefined }`\n * only when the PID carried nothing emittable at all.\n *\n * @param patient - The `@cosyte/hl7` `Patient` view (PID-derived).\n * @param ctx - The transform context; `ctx.namingSystem` resolves identifier assigning authorities.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildPatient(parseHL7(raw).patient!, { namingSystem: createNamingSystem() });\n * ```\n */\nexport function buildPatient(patient: Patient, ctx: TransformContext): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Patient\") },\n ];\n\n // PID-3 → Patient.identifier (each CX repetition, fail-safe on the assigning authority).\n const identifiers: FhirComplex[] = [];\n for (const cx of patient.identifiers) {\n const { value, issues: idIssues } = toFhirIdentifier(cx, ctx);\n issues.push(...idIssues);\n if (value !== undefined) identifiers.push(value);\n }\n const identifierList = listOrUndefined(identifiers);\n if (identifierList !== undefined) props.push({ name: \"identifier\", value: identifierList });\n\n // PID-5 → Patient.name (first repetition; additional repetitions are a later-phase concern).\n const name = toFhirHumanName(patient.name);\n issues.push(...name.issues);\n if (name.value !== undefined) props.push({ name: \"name\", value: list([name.value]) });\n\n // PID-8 → Patient.gender via Table 0001; unmapped → absent + flagged (never guessed).\n if (patient.sex !== undefined && patient.sex !== \"\") {\n const gender = Object.hasOwn(ADMINISTRATIVE_GENDER_MAP, patient.sex)\n ? ADMINISTRATIVE_GENDER_MAP[patient.sex]\n : undefined;\n if (gender === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"PID.8\", \"Patient.gender\"));\n } else {\n props.push({ name: \"gender\", value: primitive(gender) });\n }\n }\n\n // PID-7 → Patient.birthDate. FHIR birthDate is a `date`; a birth time-of-day is dropped to date\n // precision (the birthTime extension is a Phase-8 profile concern) with a flag.\n if (patient.dateOfBirth !== undefined) {\n const dob = toFhirDateTime(patient.dateOfBirth, ctx.options);\n issues.push(...dob.issues);\n if (dob.value !== undefined) {\n const tIndex = dob.value.indexOf(\"T\");\n if (tIndex === -1) {\n props.push({ name: \"birthDate\", value: primitive(dob.value) });\n } else {\n props.push({ name: \"birthDate\", value: primitive(dob.value.slice(0, tIndex)) });\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PID.7\", \"Patient.birthDate\"));\n }\n }\n }\n\n // PID-11 → Patient.address (first repetition of the home address view).\n if (patient.address !== undefined) {\n const address = toFhirAddress(patient.address);\n issues.push(...address.issues);\n if (address.value !== undefined) props.push({ name: \"address\", value: list([address.value]) });\n }\n\n // PID-13/14 → Patient.telecom is deferred (no XTN→ContactPoint converter yet); flag the drop.\n if (patient.phoneNumbers.length > 0) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PID.13\", \"Patient.telecom\"));\n }\n\n // Only `resourceType` present → nothing emittable.\n if (props.length === 1) return { value: undefined, issues };\n return { value: complex(props), issues };\n}\n","/**\n * NK1 → FHIR `RelatedPerson` — grounded on the IG **Segment NK1 to RelatedPerson** ConceptMap\n * (`hl7.fhir.uv.v2mappings`, STU1), verified firsthand:\n *\n * | NK1 field | FHIR target | via |\n * |---|---|---|\n * | NK1-2 Name (XPN) | `RelatedPerson.name` | {@link toFhirHumanName} |\n * | NK1-3 Relationship (CWE) | `RelatedPerson.relationship` | {@link toFhirCodeableConcept} |\n * | NK1-4 Address (XAD) | `RelatedPerson.address` | {@link toFhirAddress} |\n *\n * `RelatedPerson.patient` is FHIR-required (1..1); the message structure supplies it — it is wired to\n * the bundle's Patient, so a RelatedPerson is produced only when a Patient was. Deferred and flagged,\n * not silently mapped: NK1-5/6 telecom (no XTN→ContactPoint converter yet), NK1-15 gender, NK1-16\n * birthDate, NK1-20 communication language (not surfaced by the `@cosyte/hl7` next-of-kin view).\n *\n * @packageDocumentation\n */\n\nimport type { NextOfKin } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirHumanName } from \"../datatypes/human-name.js\";\nimport { toFhirAddress } from \"../datatypes/address.js\";\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { reference } from \"./reference.js\";\n\n/**\n * Build a FHIR `RelatedPerson` resource node from a parsed HL7 v2 NK1 view. Always carries the\n * required `patient` reference to the bundle's Patient. Returns `{ value: undefined }` when the NK1\n * carried nothing beyond the patient link.\n *\n * @param nk1 - The `@cosyte/hl7` `NextOfKin` view (NK1-derived).\n * @param patientFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient (required by FHIR).\n * @param ctx - The transform context; `ctx.namingSystem` resolves the relationship coding system.\n * @param setIndex - The 0-based NK1 repetition index, for value-free issue locations.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const { value } = buildRelatedPerson(parseHL7(raw).nextOfKin()[0], \"urn:uuid:1-2-3\", {}, 0);\n * ```\n */\nexport function buildRelatedPerson(\n nk1: NextOfKin,\n patientFullUrl: string,\n ctx: TransformContext,\n setIndex: number,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const loc = `NK1[${String(setIndex)}]`;\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"RelatedPerson\") },\n { name: \"patient\", value: reference(patientFullUrl) },\n ];\n\n let hasContent = false;\n\n // NK1-3 → RelatedPerson.relationship.\n if (nk1.relationship !== undefined) {\n const rel = toFhirCodeableConcept(nk1.relationship, ctx);\n issues.push(...rel.issues);\n if (rel.value !== undefined) {\n props.push({ name: \"relationship\", value: list([rel.value]) });\n hasContent = true;\n }\n }\n\n // NK1-2 → RelatedPerson.name.\n if (nk1.name !== undefined) {\n const name = toFhirHumanName(nk1.name);\n issues.push(...name.issues);\n if (name.value !== undefined) {\n props.push({ name: \"name\", value: list([name.value]) });\n hasContent = true;\n }\n }\n\n // NK1-4 → RelatedPerson.address.\n if (nk1.address !== undefined) {\n const address = toFhirAddress(nk1.address);\n issues.push(...address.issues);\n if (address.value !== undefined) {\n props.push({ name: \"address\", value: list([address.value]) });\n hasContent = true;\n }\n }\n\n // NK1-5/6 → RelatedPerson.telecom is deferred (no XTN→ContactPoint converter yet); flag the drop.\n if (nk1.phone !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `${loc}.5`, \"RelatedPerson.telecom\"));\n }\n\n if (!hasContent) return { value: undefined, issues };\n return { value: complex(props), issues };\n}\n","/**\n * ORC + OBR → FHIR `ServiceRequest` — the order-entry request, grounded firsthand\n * on the IG **Segment ORC to ServiceRequest** and **Segment OBR to ServiceRequest** ConceptMaps and\n * the **Table HL70119 to Request Status** ConceptMap (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-orc-to-servicerequest.html`, `ConceptMap-segment-obr-to-servicerequest.html`,\n * `ConceptMap-table-hl70119-to-request-status.html`). Per the **ORM_O01 / OML_O21 message maps**,\n * `ORC` *creates* the `ServiceRequest` and `OBR` is *incorporated into that same* request, so one\n * builder consumes both:\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | ORC-1 Order Control | `ServiceRequest.status` | {@link REQUEST_STATUS_MAP} (HL70119), *only IF ORC-5 not valued* |\n * | ORC-2 / OBR-2 Placer Order Number | `identifier` (type `PLAC`) | {@link orderIdentifier} (EI.1, v2-0203) |\n * | ORC-3 / OBR-3 Filler Order Number | `identifier` (type `FILL`) | {@link orderIdentifier} |\n * | ORC-9 Date/Time of Order Event | `authoredOn` | {@link toFhirDateTime}, *IF ORC-1 = `NW`* |\n * | OBR-4 Universal Service Identifier (CWE) | `ServiceRequest.code` | {@link toFhirCodeableConcept} |\n * | OBR-5 Priority (v2-0485) | `ServiceRequest.priority` | {@link SERVICE_REQUEST_PRIORITY_MAP} (HL70485) |\n * | OBR-6 Requested Date/Time | `occurrenceDateTime` | {@link toFhirDateTime} |\n * | OBR-31 Reason for Study (CWE) | `reasonCode` | {@link toFhirCodeableConcept} |\n * | (order message context) | `intent` = `order` | see below |\n * | (message-map wiring) | `subject` / `encounter` | the bundle's Patient / Encounter |\n *\n * **Fail-safes (never a confident wrong request).**\n * - **`status` (required 1..1).** ORC-1 → HL70119 carries a target for only the 19 codes in\n * {@link REQUEST_STATUS_MAP}; the many codes the IG leaves in its `(unmapped)` group (CH, CP, PA,\n * RE, RF, RP, SC, the U* \"unable to …\" family, …) have **no** target and leave `status` absent +\n * flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}. When **ORC-5** (Order Status) is valued the\n * IG routes status through ORC-5 via an *unspecified* mapping (no code table) — so we cannot derive\n * it, flag ORC-5 unmapped, and leave `status` absent rather than mis-applying the ORC-1 table\n * against the IG's own condition. The required-`status` emit gate then **withholds** the request —\n * never guessed, never coerced.\n * - **`intent` (required 1..1) = `order`.** The IG maps ORC-1/OBR → `intent` as `equivalent` but ships\n * **no value ConceptMap** for it; the ORM_O01/OML_O21 families are, by definition, *order* messages\n * (their message maps create a `ServiceRequest`/`MedicationRequest` per order), so `intent` is fixed\n * to the `request-intent` code `order` from that message context. This is a resource-level constant\n * grounded in the message family — **not** a fabricated per-code translation row. The finer\n * OBR-11-conditioned intent refinement is deferred.\n * - **`subject` (required 1..1).** Wired to the bundle's Patient; a request with no resolvable Patient\n * is withheld rather than emitted with a dangling/absent subject.\n *\n * - **`priority` (0..1) — value-translated.** OBR-5 → `ServiceRequest.priority` via the IG\n * **Table HL70485 to Request Priority** ConceptMap ({@link SERVICE_REQUEST_PRIORITY_MAP}): only\n * `S→stat`, `A→asap`, `R→routine` carry a target (each `equivalent`, and all three are valid\n * `request-priority` members). Every other v2-0485 code — `P`, `C`, `T`, the `T{S,M,H,D,W,L}<integer>`\n * timing-critical family, `PRN` — sits in the IG map's `(unmapped)` group, so a valued OBR-5 the map\n * has no target for leaves `priority` absent + flagged {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED},\n * never guessed. (`priority` is 0..1, so an unmapped value simply omits it — the request still emits.)\n *\n * Deferred and flagged elsewhere, not silently mapped: ORC-7/OBR-27 timing (`$this`), ORC-12/OBR-16\n * requester + ORC-21..24 ordering facility/provider (need Practitioner/PractitionerRole/Organization\n * resources), OBR-29 basedOn, specimen, and the ORC-1/ORC-9/OBR-13 order-control/supporting-info\n * extensions.\n *\n * @packageDocumentation\n */\n\nimport type { Segment } from \"@cosyte/hl7\";\nimport { complex, primitive, list, type FhirComplex, type FhirNode } from \"@cosyte/fhir\";\n\nimport { toFhirCodeableConcept } from \"../datatypes/codeable-concept.js\";\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport type { ConvertResult } from \"../diagnostics/result.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\nimport { orderIdentifier, reference } from \"./reference.js\";\n\n/**\n * HL7 v2 Table 0119 (Order Control Codes) → FHIR `request-status` (`ServiceRequest.status`), per the\n * IG **Table HL70119 to Request Status** ConceptMap (each `is equivalent to`). Only these **19** source\n * codes carry a target; every other v2-0119 code sits in the IG's explicit `(unmapped)` group\n * (verified firsthand against the published v1.0.0 ConceptMap — CH/CN/CP/DE/LI/NA/OE/OF/OP/OR/PA/RE/\n * RF/RP/RR/RU/SC/SN/SR/SS/UA/UC/UD/UF/UH/UM/UN/UR/UX/XO/XR/XX/MC are all `unmatched`, and the map\n * declares no `unmapped` default), so an ORC-1 with one of them leaves `status` absent + flagged and\n * the request is withheld. `request-status` has no `cancelled`; the cancel/discontinue codes map to\n * `revoked` and the hold codes to `on-hold`, exactly as the IG table specifies.\n */\nexport const REQUEST_STATUS_MAP: Readonly<Record<string, string>> = Object.freeze({\n AF: \"active\",\n CA: \"active\",\n CR: \"revoked\",\n DC: \"revoked\",\n DF: \"revoked\",\n DR: \"revoked\",\n FU: \"completed\",\n HD: \"active\",\n HR: \"on-hold\",\n NW: \"active\",\n OC: \"revoked\",\n OD: \"revoked\",\n OH: \"on-hold\",\n OK: \"active\",\n PR: \"active\",\n PY: \"active\",\n RL: \"active\",\n RO: \"active\",\n RQ: \"active\",\n});\n\n/**\n * HL7 v2 Table 0485 (Extended Priority Codes) → FHIR `request-priority` (`ServiceRequest.priority`),\n * per the IG **Table HL70485 to Request Priority** ConceptMap (each `is equivalent to`; verified\n * firsthand against the published v1.0.0 ConceptMap). Only these **three** source codes carry a\n * target; every other v2-0485 code — `P` (Preop), `C` (Callback), `T` (Timing critical), the\n * `T{S,M,H,D,W,L}<integer>` timing-critical family, and `PRN` (As needed) — sits in the IG's\n * `(unmapped)` group with no target, so an OBR-5 carrying one leaves `priority` absent + flagged.\n * All three targets (`stat`/`asap`/`routine`) are valid `request-priority` members.\n */\nexport const SERVICE_REQUEST_PRIORITY_MAP: Readonly<Record<string, string>> = Object.freeze({\n S: \"stat\",\n A: \"asap\",\n R: \"routine\",\n});\n\n/** The `request-intent` code fixed for order-message requests (see the module fail-safe note). */\nconst ORDER_INTENT = \"order\";\n\n/** The decoded value of a field on an optional segment (empty string when the segment is absent). */\nfunction fieldValue(seg: Segment | undefined, index: number): string {\n return seg === undefined ? \"\" : seg.field(index).value;\n}\n\n/**\n * Build a FHIR `ServiceRequest` resource node from an order group's `ORC` and/or `OBR` segments.\n * Returns `{ value: undefined }` only when both segments are absent (nothing to build).\n * `ServiceRequest.status` is left absent (and the request withheld by the emit gate) when it cannot be\n * grounded via HL70119 — never guessed.\n *\n * @param orc - The `ORC` `@cosyte/hl7` `Segment`, when the order carries one.\n * @param obr - The `OBR` `@cosyte/hl7` `Segment`, when the order carries one.\n * @param subjectFullUrl - The bundle's Patient fullUrl → `ServiceRequest.subject` (required 1..1).\n * @param encounterFullUrl - The bundle's Encounter fullUrl → `ServiceRequest.encounter`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const orc = parseHL7(raw).segments(\"ORC\")[0];\n * // const obr = parseHL7(raw).segments(\"OBR\")[0];\n * // const { value } = buildServiceRequest(orc, obr, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildServiceRequest(\n orc: Segment | undefined,\n obr: Segment | undefined,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n if (orc === undefined && obr === undefined) return { value: undefined, issues };\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"ServiceRequest\") },\n ];\n\n // ORC-1 → status (HL70119), only when ORC-5 is not valued; else the IG routes status through ORC-5\n // via an unspecified mapping (no code table) → cannot derive → flag, leave absent, withhold.\n const orc1 = fieldValue(orc, 1);\n const orc5 = fieldValue(orc, 5);\n if (orc5 !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"ORC.5\", \"ServiceRequest.status\"));\n } else if (orc1 !== \"\") {\n const status = Object.hasOwn(REQUEST_STATUS_MAP, orc1) ? REQUEST_STATUS_MAP[orc1] : undefined;\n if (status === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"ORC.1\", \"ServiceRequest.status\"));\n } else {\n props.push({ name: \"status\", value: primitive(status) });\n }\n }\n\n // intent (required) = order — the order-message context, not a per-code translation (see module note).\n props.push({ name: \"intent\", value: primitive(ORDER_INTENT) });\n\n // ORC-2/OBR-2 (placer) + ORC-3/OBR-3 (filler) → identifier. The IG conditions each on the other\n // (\"OBR-2 IF ORC-2 NOT VALUED\" and vice-versa); prefer OBR, fall back to ORC — either way, one each.\n const placer = fieldValue(obr, 2) !== \"\" ? fieldValue(obr, 2) : fieldValue(orc, 2);\n const filler = fieldValue(obr, 3) !== \"\" ? fieldValue(obr, 3) : fieldValue(orc, 3);\n const identifiers = [orderIdentifier(placer, \"PLAC\"), orderIdentifier(filler, \"FILL\")].filter(\n (i): i is FhirComplex => i !== undefined,\n );\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n // OBR-4 → ServiceRequest.code (0..1).\n if (obr !== undefined && obr.field(4).value !== \"\") {\n const code = toFhirCodeableConcept(obr.field(4).asCwe(), ctx);\n issues.push(...code.issues);\n if (code.value !== undefined) props.push({ name: \"code\", value: code.value });\n }\n\n // OBR-5 → priority (HL70485 → request-priority; value-translated). Applied only when OBR-5 is a\n // v2-0485 code (CWE.3 absent or names HL70485); a code from a foreign coding system, or one the IG\n // leaves in its (unmapped) group, is flagged and priority left absent (0..1) — never guessed.\n const obr5cwe = obr?.field(5).asCwe();\n const obr5 = obr5cwe?.identifier ?? \"\";\n if (obr5 !== \"\") {\n const mnemonic = obr5cwe?.nameOfCodingSystem;\n const fromTable =\n mnemonic === undefined || mnemonic === \"\" || mnemonic === \"HL70485\" || mnemonic === \"0485\";\n const priority =\n fromTable && Object.hasOwn(SERVICE_REQUEST_PRIORITY_MAP, obr5)\n ? SERVICE_REQUEST_PRIORITY_MAP[obr5]\n : undefined;\n if (priority === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBR.5\", \"ServiceRequest.priority\"));\n } else {\n props.push({ name: \"priority\", value: primitive(priority) });\n }\n }\n\n // subject / encounter → the bundle's Patient / Encounter (message-map reference wiring).\n if (subjectFullUrl !== undefined)\n props.push({ name: \"subject\", value: reference(subjectFullUrl) });\n if (encounterFullUrl !== undefined)\n props.push({ name: \"encounter\", value: reference(encounterFullUrl) });\n\n // ORC-9 → authoredOn, only for a new order (ORC-1 = NW), per the IG condition. authoredOn is a\n // `dateTime`, so a date-only value is valid (unlike the `instant` fields) — no timezone gate needed.\n if (orc1 === \"NW\" && fieldValue(orc, 9) !== \"\" && orc !== undefined) {\n const authored = toFhirDateTime(orc.field(9).asTs(), ctx.options);\n issues.push(...authored.issues);\n if (authored.value !== undefined)\n props.push({ name: \"authoredOn\", value: primitive(authored.value) });\n }\n\n // OBR-6 → occurrenceDateTime (Requested Date/Time).\n if (obr !== undefined && obr.field(6).value !== \"\") {\n const occurrence = toFhirDateTime(obr.field(6).asTs(), ctx.options);\n issues.push(...occurrence.issues);\n if (occurrence.value !== undefined)\n props.push({ name: \"occurrenceDateTime\", value: primitive(occurrence.value) });\n }\n\n // OBR-31 → reasonCode (Reason for Study).\n if (obr !== undefined && obr.field(31).value !== \"\") {\n const reason = toFhirCodeableConcept(obr.field(31).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"reasonCode\", value: list([reason.value]) });\n }\n\n return { value: complex(props), issues };\n}\n","/**\n * `toFhir` — the message-level entry point: assemble a parsed HL7 v2 message into a FHIR R4\n * **message Bundle** (a `MessageHeader` first, then the focal resources), grounded on the IG message\n * and segment maps. The **ADT** family becomes **Patient + Encounter** (+ `RelatedPerson`\n * from NK1); the **ORU^R01** results graph becomes `DiagnosticReport` + `Observation`; the\n * order-entry graph — **ORM_O01 / OML_O21** ORC/OBR → `ServiceRequest` and **RXO** (+ RXR) →\n * `MedicationRequest`; and the thin IG singles — **VXU_V04** RXA/RXR/ORC → `Immunization`,\n * **SIU_S12** SCH/AIS/PID → `Appointment`, and **MDM_T02** TXA/OBX → `DocumentReference`.\n *\n * The fail-safe rule holds at the message level. Two message-level fail-safes join the datatype ones:\n *\n * - **Segment-assembled, not fabricated.** For an ADT trigger the IG maps ({@link IG_MAPPED_ADT_TRIGGERS}),\n * the graph is message-map-grounded. For any other trigger there is no IG *message* map, so the\n * graph is assembled from the reusable IG *segment* maps and flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED} — never a fabricated message map.\n * - **Conservative emit gate.** Every produced resource is run through `@cosyte/fhir.validateResource`\n * before it can join the bundle — `Patient` against the built-in schema in `strict` mode, and the\n * other types against the minimal required-cardinality {@link EMIT_SCHEMAS} in `lenient` mode (so a\n * missing required element errors and withholds, while unmodeled sibling elements do not\n * false-reject). A resource with any structural error is **withheld** from the bundle and flagged\n * {@link ISSUE_CODES.TRANSFORM_RESOURCE_INVALID} rather than shipped as silently-invalid FHIR. When\n * the Patient is withheld, the Encounter's `subject` and any RelatedPerson are dropped rather than\n * left dangling — references always resolve within the bundle.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\nimport {\n complex,\n primitive,\n list,\n resourceType,\n validateResource,\n type FhirComplex,\n type FhirNode,\n} from \"@cosyte/fhir\";\n\nimport { toFhirDateTime } from \"../datatypes/datetime.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport { createNamingSystem } from \"../terminology/naming-system.js\";\nimport type { TransformContext, TransformOptions } from \"../terminology/context.js\";\nimport { buildAppointment, collectAppointment } from \"./appointment.js\";\nimport { buildDiagnosticReport } from \"./diagnostic-report.js\";\nimport { buildDocumentReference, collectDocument } from \"./document-reference.js\";\nimport { buildEncounter } from \"./encounter.js\";\nimport { EMIT_SCHEMAS } from \"./emit-schemas.js\";\nimport { buildImmunization, collectImmunizationGroups } from \"./immunization.js\";\nimport { buildMedicationRequest } from \"./medication-request.js\";\nimport { buildMessageHeader } from \"./message-header.js\";\nimport { buildObservation } from \"./observation.js\";\nimport { collectOrderGroups } from \"./orders.js\";\nimport { collectReportGroups } from \"./oru.js\";\nimport { buildPatient } from \"./patient.js\";\nimport { buildRelatedPerson } from \"./related-person.js\";\nimport { IdAllocator } from \"./reference.js\";\nimport { buildServiceRequest } from \"./service-request.js\";\n\n/**\n * The immutable result of a message-level transform: the FHIR `Bundle` model and the value-free\n * diagnostics raised assembling it.\n */\nexport interface TransformResult {\n /** The FHIR R4 `Bundle` resource node (a message Bundle: MessageHeader first, then focal resources). */\n readonly bundle: FhirComplex;\n /** The value-free diagnostics raised during assembly, in emission order. */\n readonly issues: readonly TransformIssue[];\n}\n\n/**\n * The ADT trigger events the IG ships a **message** map for. Other triggers still transform — from the\n * reusable segment maps — but are flagged {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_ADT_TRIGGERS: ReadonlySet<string> = new Set([\n \"A01\",\n \"A02\",\n \"A05\",\n \"A06\",\n \"A09\",\n \"A11\",\n \"A17\",\n]);\n\n/**\n * The ORU trigger events the IG ships a **message** map for. The IG maps only `R01`; other ORU triggers\n * still assemble their results graph from the reusable OBR/OBX segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_ORU_TRIGGERS: ReadonlySet<string> = new Set([\"R01\"]);\n\n/**\n * The order-message trigger events the IG ships a **message** map for, keyed `CODE^TRIGGER`. Only\n * `ORM^O01` and `OML^O21` are message-map-grounded; other order families (`OMP`, `OMG`, `RDE`, …)\n * still assemble their request graph from the reusable ORC/OBR/RXO/RXR segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_ORDER_TRIGGERS: ReadonlySet<string> = new Set([\"ORM^O01\", \"OML^O21\"]);\n\n/**\n * The immunization trigger the IG ships a **message** map for. The IG maps only `VXU^V04`; other VXU\n * triggers still assemble their Immunization graph from the reusable RXA/RXR/ORC segment maps but are\n * flagged {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_IMMUNIZATION_TRIGGERS: ReadonlySet<string> = new Set([\"V04\"]);\n\n/**\n * The scheduling trigger the IG ships a **message** map for. The IG maps only `SIU^S12`; other SIU\n * triggers still assemble their Appointment from the reusable SCH/AIS/PID segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_APPOINTMENT_TRIGGERS: ReadonlySet<string> = new Set([\"S12\"]);\n\n/**\n * The medical-document trigger the IG ships a **message** map for. The IG maps only `MDM^T02`; other MDM\n * triggers still assemble their DocumentReference from the reusable TXA/OBX segment maps but are flagged\n * {@link ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED}.\n */\nexport const IG_MAPPED_DOCUMENT_TRIGGERS: ReadonlySet<string> = new Set([\"T02\"]);\n\ninterface Entry {\n readonly fullUrl: string;\n readonly resource: FhirComplex;\n}\n\n/**\n * The conservative-emit gate: validate a produced resource against `@cosyte/fhir` before it can join\n * the bundle. Returns `true` when it is safe to emit, or pushes a\n * {@link ISSUE_CODES.TRANSFORM_RESOURCE_INVALID} issue and returns `false` when it has any structural\n * error (the resource is then **withheld** — never shipped invalid).\n *\n * `@cosyte/fhir` models only `Patient` natively, so `Patient` is validated `strict` (its value domains\n * and unknown elements both caught). The other emitted types are validated `lenient` against the\n * minimal required-cardinality {@link EMIT_SCHEMAS}: a **missing required** element (e.g. a\n * class-less/status-less Encounter from an unmapped patient class) is an error and withholds the\n * resource, while the resource's other elements degrade to warnings rather than false rejections.\n */\nfunction passesEmitGate(\n resource: FhirComplex,\n v2Location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): boolean {\n const result =\n resourceType(resource) === \"Patient\"\n ? validateResource(resource, { mode: \"strict\" })\n : validateResource(resource, { mode: \"lenient\", schemas: EMIT_SCHEMAS });\n if (result.valid) return true;\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_INVALID, v2Location, fhirPath));\n return false;\n}\n\n/** Assemble the FHIR message `Bundle` envelope from its ordered entries. */\nfunction buildBundle(\n msg: Hl7Message,\n entries: readonly Entry[],\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex {\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Bundle\") },\n ];\n\n // MSH-10 message control id → Bundle.identifier (R4 MessageHeader carries no identifier element).\n const controlId = msg.meta.controlId;\n if (controlId !== undefined && controlId !== \"\") {\n props.push({\n name: \"identifier\",\n value: complex([{ name: \"value\", value: primitive(controlId) }]),\n });\n }\n\n props.push({ name: \"type\", value: primitive(\"message\") });\n\n // MSH-7 → Bundle.timestamp (an `instant`: only a fully-zoned datetime qualifies; else omit + flag).\n if (msg.meta.timestamp !== undefined) {\n const ts = toFhirDateTime(msg.meta.timestamp, ctx.options);\n issues.push(...ts.issues);\n if (ts.value !== undefined && ts.value.includes(\"T\")) {\n props.push({ name: \"timestamp\", value: primitive(ts.value) });\n } else if (ts.value !== undefined) {\n // A date-only or unzoned MSH-7 is not a valid FHIR `instant`; omit rather than emit invalid.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"MSH.7\", \"Bundle.timestamp\"));\n }\n }\n\n const entryNodes = entries.map((e) =>\n complex([\n { name: \"fullUrl\", value: primitive(e.fullUrl) },\n { name: \"resource\", value: e.resource },\n ]),\n );\n if (entryNodes.length > 0) props.push({ name: \"entry\", value: list(entryNodes) });\n\n return complex(props);\n}\n\n/**\n * Transform a parsed HL7 v2 message into a FHIR R4 message `Bundle`. Never throws for a well-formed\n * {@link Hl7Message}; every ambiguity, unmapped code, dropped element, or withheld resource surfaces\n * as a value-free {@link TransformIssue}.\n *\n * @param msg - A parsed `@cosyte/hl7` message.\n * @param opts - Transform options: the {@link TransformOptions.namingSystem} registry, the naked-\n * timestamp {@link TransformOptions.assumeTimezoneOffsetMinutes} policy, and a\n * {@link TransformOptions.generateId} allocator for reproducible fullUrls.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * import { toFhir, createNamingSystem } from \"@cosyte/transform\";\n * const { bundle, issues } = toFhir(parseHL7(raw), { namingSystem: createNamingSystem() });\n * void bundle;\n * void issues;\n * ```\n */\nexport function toFhir(msg: Hl7Message, opts: TransformOptions = {}): TransformResult {\n const issues: TransformIssue[] = [];\n const namingSystem = opts.namingSystem ?? createNamingSystem();\n const ctx: TransformContext = { namingSystem, options: opts };\n const ids = new IdAllocator(opts);\n\n // Dispatch: an IG-mapped ADT or ORU trigger is message-map-grounded; anything else is\n // segment-assembled (best-effort from the reusable IG segment maps, flagged as such).\n const code = msg.meta.messageCode;\n const trigger = msg.meta.triggerEvent;\n const messageMapGrounded =\n trigger !== undefined &&\n ((code === \"ADT\" && IG_MAPPED_ADT_TRIGGERS.has(trigger)) ||\n (code === \"ORU\" && IG_MAPPED_ORU_TRIGGERS.has(trigger)) ||\n (code === \"VXU\" && IG_MAPPED_IMMUNIZATION_TRIGGERS.has(trigger)) ||\n (code === \"SIU\" && IG_MAPPED_APPOINTMENT_TRIGGERS.has(trigger)) ||\n (code === \"MDM\" && IG_MAPPED_DOCUMENT_TRIGGERS.has(trigger)) ||\n IG_MAPPED_ORDER_TRIGGERS.has(`${code ?? \"\"}^${trigger}`));\n if (!messageMapGrounded) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_SEGMENT_ASSEMBLED, \"MSH.9\"));\n }\n\n const focalEntries: Entry[] = [];\n\n // PID → Patient (the identity anchor). Gated before it can anchor references.\n let patientFullUrl: string | undefined;\n const patientView = msg.patient;\n if (patientView !== undefined) {\n const built = buildPatient(patientView, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"PID\", \"Patient\", issues)) {\n patientFullUrl = ids.next();\n focalEntries.push({ fullUrl: patientFullUrl, resource: built.value });\n }\n }\n\n // PV1 → Encounter, subject wired to the Patient (omitted if no valid Patient).\n let encounterFullUrl: string | undefined;\n const visitView = msg.visit;\n if (visitView !== undefined) {\n const built = buildEncounter(visitView, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"PV1\", \"Encounter\", issues)) {\n encounterFullUrl = ids.next();\n focalEntries.push({ fullUrl: encounterFullUrl, resource: built.value });\n }\n }\n\n // NK1 → RelatedPerson, patient wired to the Patient. Requires a Patient (FHIR-required reference).\n const nextOfKin = msg.nextOfKin();\n if (patientFullUrl !== undefined) {\n for (let i = 0; i < nextOfKin.length; i++) {\n const nk1 = nextOfKin[i];\n if (nk1 === undefined) continue;\n const built = buildRelatedPerson(nk1, patientFullUrl, ctx, i);\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, `NK1[${String(i)}]`, \"RelatedPerson\", issues)\n ) {\n focalEntries.push({ fullUrl: ids.next(), resource: built.value });\n }\n }\n } else if (nextOfKin.length > 0) {\n // No Patient to anchor RelatedPerson.patient — dropped rather than emitted with a dangling ref.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"NK1\", \"RelatedPerson.patient\"));\n }\n\n // ORU → the DiagnosticReport + Observation results graph (Phase 3). OBR anchors a DiagnosticReport;\n // its OBX children become Observations, each subject-wired to the Patient. A withheld Observation is\n // simply absent from DiagnosticReport.result (references always resolve within the bundle), and a\n // withheld DiagnosticReport (unmapped/absent OBR-25 status) still leaves its valid Observations.\n const diagnosticReportFullUrls: string[] = [];\n if (code === \"ORU\") {\n const { groups, orphanObxCount } = collectReportGroups(msg);\n if (orphanObxCount > 0) {\n // OBX with no preceding OBR — no report to anchor it; surfaced rather than silently dropped.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBX\", \"DiagnosticReport.result\"));\n }\n for (const group of groups) {\n const resultFullUrls: string[] = [];\n const observationEntries: Entry[] = [];\n for (let i = 0; i < group.observations.length; i++) {\n const obx = group.observations[i];\n if (obx === undefined) continue;\n const built = buildObservation(obx, patientFullUrl, encounterFullUrl, ctx);\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, `OBX[${String(i)}]`, \"Observation\", issues)\n ) {\n const url = ids.next();\n resultFullUrls.push(url);\n observationEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n const report = buildDiagnosticReport(\n group.obr,\n resultFullUrls,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...report.issues);\n if (\n report.value !== undefined &&\n passesEmitGate(report.value, \"OBR\", \"DiagnosticReport\", issues)\n ) {\n const reportUrl = ids.next();\n diagnosticReportFullUrls.push(reportUrl);\n focalEntries.push({ fullUrl: reportUrl, resource: report.value });\n }\n // The Observations follow their report in the bundle (references resolve regardless of order).\n focalEntries.push(...observationEntries);\n }\n }\n\n // Order messages (ORM/OML, and segment-assembled OMP/OMG/RDE/…) → the ServiceRequest /\n // MedicationRequest graph (Phase 4). Each ORC-anchored order becomes one request: an OBR order\n // detail → ServiceRequest, an RXO pharmacy detail → MedicationRequest, both subject-wired to the\n // Patient. ORU is excluded — there its OBR anchors a DiagnosticReport, not a ServiceRequest.\n const orderResourceFullUrls: string[] = [];\n if (code !== \"ORU\" && code !== \"VXU\" && code !== \"SIU\" && code !== \"MDM\") {\n const { groups, rxeCount } = collectOrderGroups(msg);\n if (rxeCount > 0) {\n // RXE has no IG segment map (nor RDE message map) — surfaced, never assembled from a guess.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"RXE\", \"MedicationRequest\"));\n }\n for (const group of groups) {\n // ServiceRequest: an OBR order detail, or an ORC that opened a non-pharmacy order.\n if (group.obr !== undefined || (group.orc !== undefined && group.rxo === undefined)) {\n const built = buildServiceRequest(\n group.orc,\n group.obr,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...built.issues);\n const loc = group.orc !== undefined ? \"ORC\" : \"OBR\";\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, loc, \"ServiceRequest\", issues)\n ) {\n const url = ids.next();\n orderResourceFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n // MedicationRequest: an RXO pharmacy order detail (+ its first RXR route, its opening ORC).\n if (group.rxo !== undefined) {\n const built = buildMedicationRequest(\n group.rxo,\n group.rxrs[0],\n group.orc,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, \"RXO\", \"MedicationRequest\", issues)\n ) {\n const url = ids.next();\n orderResourceFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n }\n }\n\n // VXU → the Immunization graph (Phase 5). Each ORC-anchored order group's RXA (+ RXR route, + ORC\n // identifiers) becomes one Immunization, subject-wired to the Patient; the order-group OBX bodies\n // become standalone patient Observations (the IG's Observation[2]).\n const immunizationFullUrls: string[] = [];\n if (code === \"VXU\") {\n for (const group of collectImmunizationGroups(msg)) {\n const built = buildImmunization(\n group.rxa,\n group.rxr,\n group.orc,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n );\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"RXA\", \"Immunization\", issues)) {\n const url = ids.next();\n immunizationFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n // OBX in a VXU are patient/immunization observations (Observation[1]/[2] in the IG bundle).\n for (const seg of msg.allSegments()) {\n if (seg.type !== \"OBX\") continue;\n const built = buildObservation(seg, patientFullUrl, encounterFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"OBX\", \"Observation\", issues)) {\n focalEntries.push({ fullUrl: ids.next(), resource: built.value });\n }\n }\n }\n\n // SIU → a single Appointment (Phase 5). SCH anchors the Appointment; the bundle Patient is the\n // required participant; AIS supplies the service type.\n const appointmentFullUrls: string[] = [];\n if (code === \"SIU\") {\n const { sch, ais } = collectAppointment(msg);\n if (sch !== undefined) {\n const built = buildAppointment(sch, ais, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value !== undefined && passesEmitGate(built.value, \"SCH\", \"Appointment\", issues)) {\n const url = ids.next();\n appointmentFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n }\n\n // MDM → a single DocumentReference (Phase 5). TXA anchors the document metadata; the OBX segments\n // carry the document body; the reference is subject-wired to the Patient.\n const documentFullUrls: string[] = [];\n if (code === \"MDM\") {\n const { txa, obxs } = collectDocument(msg);\n if (txa !== undefined) {\n const built = buildDocumentReference(txa, obxs, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (\n built.value !== undefined &&\n passesEmitGate(built.value, \"TXA\", \"DocumentReference\", issues)\n ) {\n const url = ids.next();\n documentFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n }\n }\n }\n\n // MSH → MessageHeader (first entry of a message Bundle), focus = the focal resources.\n const focus = [\n patientFullUrl,\n encounterFullUrl,\n ...diagnosticReportFullUrls,\n ...orderResourceFullUrls,\n ...immunizationFullUrls,\n ...appointmentFullUrls,\n ...documentFullUrls,\n ].filter((u): u is string => u !== undefined);\n const header = buildMessageHeader(msg.meta, focus);\n issues.push(...header.issues);\n const entries: Entry[] = [];\n if (header.value !== undefined && passesEmitGate(header.value, \"MSH\", \"MessageHeader\", issues)) {\n entries.push({ fullUrl: ids.next(), resource: header.value });\n }\n entries.push(...focalEntries);\n\n const bundle = buildBundle(msg, entries, ctx, issues);\n return { bundle, issues };\n}\n","/**\n * Public entry point for `@cosyte/transform` — the HL7 v2 → FHIR R4 transformation library.\n *\n * `@cosyte/transform` is **not** a parser; it is a **consumer** one tier above the parser suite. It\n * takes already-parsed `@cosyte/hl7` composites and produces validated `@cosyte/fhir` model nodes,\n * grounded on the official **HL7 Version 2 to FHIR** Implementation Guide (`hl7.fhir.uv.v2mappings`,\n * STU Edition 1). Its whole promise is narrow and honest: **IG-grounded, fail-safe transformation\n * with typed, value-free diagnostics — never a confident wrong FHIR value.**\n *\n * This module ships the six safety-critical datatype converters, the immutable\n * `OperationOutcome`-shaped diagnostic channel and the NamingSystem resolver they consult,\n * the message-level assembly — HL7 v2 **ADT → FHIR Patient + Encounter**, the\n * **ORU^R01 → DiagnosticReport + Observation** results graph, the order-entry graph\n * (**ORM_O01 / OML_O21 → ServiceRequest** and **RXO → MedicationRequest**), and the thin IG\n * singles (**VXU_V04 → Immunization**, **SIU_S12 → Appointment**, **MDM_T02 → DocumentReference**),\n * all through `toFhir(msg)` — and the **terminology value-translation** layer: a\n * `$translate`-shaped {@link toFhirCodeableConceptVia} engine applying the license-clean IG value\n * ConceptMaps to the previously structural-only coded fields (route/site, appointment type, order\n * priority, substitution). Terminology **depth beyond these maps**, profiles, and the reverse\n * FHIR → v2 direction are not implemented.\n *\n * @packageDocumentation\n */\n\n/**\n * Package version marker exported from the `@cosyte/transform` root.\n *\n * Kept in lockstep with `package.json` by `scripts/sync-version.mjs`, which the `version` script\n * runs immediately after `changeset version`. The `: string` annotation is deliberate: without it\n * TypeScript infers the *literal* type (`declare const VERSION = \"0.0.0\"`), which leaks the current\n * release into consumers' types and makes an equality check against any other version a compile\n * error.\n *\n * @example\n * ```typescript\n * import { VERSION } from \"@cosyte/transform\";\n * console.log(VERSION);\n * ```\n */\nexport const VERSION: string = \"0.0.6\";\n\n// ── The diagnostic channel (the fail-safe rule, materialized) ──────────────────────────────────\nexport { ISSUE_CODES, FATAL_CODES } from \"./diagnostics/codes.js\";\nexport type { IssueCode, FatalCode } from \"./diagnostics/codes.js\";\nexport { issue, fhirIssueTypeFor, ISSUE_REGISTRY } from \"./diagnostics/issue.js\";\nexport type { TransformIssue, TransformSeverity } from \"./diagnostics/issue.js\";\nexport type { ConvertResult } from \"./diagnostics/result.js\";\nexport { toOperationOutcome, TRANSFORM_ISSUE_SYSTEM } from \"./diagnostics/operation-outcome.js\";\n\n// ── The transform context + the NamingSystem resolver ──────────────────────────────────────────\nexport type { TransformContext, TransformOptions } from \"./terminology/context.js\";\nexport {\n createNamingSystem,\n DEFAULT_V2_CODE_SYSTEMS,\n V2_0203_SYSTEM,\n} from \"./terminology/naming-system.js\";\nexport type { NamingSystemRegistry, NamingSystemSeed } from \"./terminology/naming-system.js\";\n\n// ── The six safety-critical datatype converters ────────────────────────────────────────────────\nexport { toFhirDateTime } from \"./datatypes/datetime.js\";\nexport { toFhirIdentifier } from \"./datatypes/identifier.js\";\nexport { toFhirCodeableConcept } from \"./datatypes/codeable-concept.js\";\nexport type { CodedElement } from \"./datatypes/codeable-concept.js\";\nexport { toFhirHumanName, NAME_USE_MAP } from \"./datatypes/human-name.js\";\nexport { toFhirAddress, ADDRESS_USE_MAP, ADDRESS_TYPE_MAP } from \"./datatypes/address.js\";\nexport { toFhirQuantity } from \"./datatypes/quantity.js\";\n\n// ── Message-level assembly: HL7 v2 ADT → FHIR Patient + Encounter graph (Phase 2) ────────────────\nexport {\n toFhir,\n IG_MAPPED_ADT_TRIGGERS,\n IG_MAPPED_ORU_TRIGGERS,\n IG_MAPPED_ORDER_TRIGGERS,\n} from \"./messages/to-fhir.js\";\nexport type { TransformResult } from \"./messages/to-fhir.js\";\nexport { ADMINISTRATIVE_GENDER_MAP } from \"./messages/patient.js\";\nexport { ENCOUNTER_CLASS_V3_MAP, ENCOUNTER_STATUS_MAP } from \"./messages/encounter.js\";\n\n// ── Message-level assembly: HL7 v2 ORU^R01 → FHIR DiagnosticReport + Observation graph (Phase 3) ──\nexport { OBSERVATION_STATUS_MAP, HL70078_INTERPRETATION_CODES } from \"./messages/observation.js\";\nexport { DIAGNOSTIC_REPORT_STATUS_MAP } from \"./messages/diagnostic-report.js\";\n\n// ── Message-level assembly: HL7 v2 ORM/OML → ServiceRequest, RXO → MedicationRequest (Phase 4) ────\nexport { REQUEST_STATUS_MAP } from \"./messages/service-request.js\";\n\n// ── Message-level assembly: the thin IG singles — VXU/SIU/MDM (Phase 5) ──────────────────────────\nexport {\n IG_MAPPED_IMMUNIZATION_TRIGGERS,\n IG_MAPPED_APPOINTMENT_TRIGGERS,\n IG_MAPPED_DOCUMENT_TRIGGERS,\n} from \"./messages/to-fhir.js\";\nexport { IMMUNIZATION_STATUS_MAP } from \"./messages/immunization.js\";\nexport { APPOINTMENT_STATUS_MAP } from \"./messages/appointment.js\";\n\n// ── Terminology value translation: the $translate-shaped ConceptMap engine + maps (Phase 6) ──────\nexport {\n toFhirCodeableConceptVia,\n translateBound,\n codeableConceptFromTarget,\n ROUTE_VALUE_MAP,\n SITE_VALUE_MAP,\n APPOINTMENT_TYPE_VALUE_MAP,\n SUBSTITUTION_VALUE_MAP,\n V2_0162_SYSTEM,\n V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n V2_0550_SYSTEM,\n V2_0277_SYSTEM,\n V2_0161_SYSTEM,\n} from \"./terminology/concept-map.js\";\nexport type { CodedTarget, CodedValueMap } from \"./terminology/concept-map.js\";\nexport { SERVICE_REQUEST_PRIORITY_MAP } from \"./messages/service-request.js\";\n"]}
|