@cosyte/transform 0.0.9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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":["complex","list","primitive","coding","decimal","UCUM_SYSTEM","validateUcumShape","text","randomUUID","parseDtm","UNBOUNDED","translatedFrom","rawComponent","ORDER_INTENT","resourceType","validateResource"],"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,EAAkC,kCAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlC,yBAAA,EAA2B,2BAAA;AAAA;AAAA;AAAA,EAG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,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.cjs","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, and 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`), which is encumbered and **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) | {@link toFhirDateTime} |\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, meaning `CA`/`OB`/`UN` (whose IG target is\n * a `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, and 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, and 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, so 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, so 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, and 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 * namely `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*, so `OBR` →\n * `ServiceRequest` and `RXO` (+ `RXR` route) → `MedicationRequest`. 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, namely 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, because the US Core `patient-birthTime`\n * extension 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\n * `T{S,M,H,D,W,L}<integer>` 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, namely `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 gives **ORM_O01 / OML_O21** ORC/OBR → `ServiceRequest` and **RXO** (+ RXR) →\n * `MedicationRequest`; and the thin IG singles give **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.9\";\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/allergy-intolerance.ts","../src/messages/appointment.ts","../src/messages/condition.ts","../src/messages/coverage.ts","../src/messages/diagnostic-report.ts","../src/messages/document-reference.ts","../src/messages/encounter.ts","../src/messages/procedure.ts","../src/messages/emit-schemas.ts","../src/messages/immunization.ts","../src/messages/tq1-timing.ts","../src/messages/medication-request.ts","../src/messages/message-header.ts","../src/messages/note.ts","../src/messages/observation.ts","../src/messages/orders.ts","../src/messages/oru.ts","../src/messages/patient.ts","../src/messages/related-person.ts","../src/messages/ig-segment-maps.ts","../src/messages/segment-completeness.ts","../src/messages/service-request.ts","../src/messages/specimen.ts","../src/messages/to-fhir.ts","../src/reverse/read.ts","../src/reverse/v2.ts","../src/reverse/coding.ts","../src/reverse/message.ts","../src/reverse/patient.ts","../src/reverse/observation.ts","../src/index.ts"],"names":["complex","list","primitive","coding","decimal","UCUM_SYSTEM","validateUcumShape","text","randomUUID","parseDtm","pad","buildCode","UNBOUNDED","component","renderText","datePart","translatedFrom","rawComponent","validatePrimitiveValue","ORDER_INTEN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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 * **The line between the two registries is structural, and it decides where a new code goes.** A\n * `FatalCode` is the type carried by a *thrown* error; a `TransformIssue.code` is typed `IssueCode`\n * and {@link ISSUE_REGISTRY} is exhaustive over {@link ISSUE_CODES} alone. So a condition that is\n * *returned* on the non-throwing `{ value, issues }` channel is an {@link ISSUE_CODES} entry by\n * construction, however severe it is: the missing-trigger refusal on the reverse\n * (FHIR to v2) entry points is returned, never thrown, so it is\n * {@link ISSUE_CODES.TRANSFORM_MISSING_TRIGGER} rather than a fatal code. Adding it to\n * {@link FATAL_CODES} instead would have required widening `TransformIssue.code` to\n * `IssueCode | FatalCode` and blurring exactly that split.\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 /** A reverse (FHIR to v2) conversion was called without the explicit message trigger it requires.\n * No FHIR resource carries a v2 trigger, so it is never inferred from resource content and never\n * defaulted: no message is built and no builder is called. */\n TRANSFORM_MISSING_TRIGGER: \"TRANSFORM_MISSING_TRIGGER\",\n /** A reverse (FHIR to v2) conversion was handed a resource outside the narrow set of shapes it\n * supports. No v2 message is emitted and no segment layout is guessed. */\n TRANSFORM_UNSUPPORTED_RESOURCE: \"TRANSFORM_UNSUPPORTED_RESOURCE\",\n /** A resource handed to a reverse (FHIR to v2) conversion is not structurally a FHIR resource of\n * its expected type (not an object, no `resourceType`, or an element carrying the wrong node\n * kind). Nothing is emitted and nothing is thrown. */\n TRANSFORM_RESOURCE_MALFORMED: \"TRANSFORM_RESOURCE_MALFORMED\",\n /** A populated FHIR element has no v2 field in the narrow reverse map that covers this shape\n * (the IG map defines no source for it, or its inverse is not implemented here). The element is\n * surfaced and left out, never approximated into a neighbouring v2 field. */\n TRANSFORM_NO_V2_TARGET: \"TRANSFORM_NO_V2_TARGET\",\n /** A FHIR value cannot be carried into its v2 target without altering it (a lexical form v2 has\n * no representation for, or content that exceeds the target's component structure). The v2 field\n * is left absent rather than truncated, rounded, or coerced. */\n TRANSFORM_VALUE_NOT_REPRESENTABLE: \"TRANSFORM_VALUE_NOT_REPRESENTABLE\",\n /** A FHIR code has no usable inverse in the IG ConceptMap that governs its field: either several\n * v2 source codes map onto it (so the inverse is ambiguous) or the map has no row for it at all.\n * The v2 field is left absent, never resolved to one arbitrary member of the ambiguous set. */\n TRANSFORM_CODE_NOT_INVERTIBLE: \"TRANSFORM_CODE_NOT_INVERTIBLE\",\n /** A `Coding.system` is not a system this library can name with a v2 coding-system mnemonic, so\n * the coding cannot be written into a v2 coded field. It is flagged rather than emitted with no\n * table context or with a code from an unrelated table. */\n TRANSFORM_CODE_SYSTEM_NOT_V2: \"TRANSFORM_CODE_SYSTEM_NOT_V2\",\n /** A v2 field the segment's own attribute table marks **required** (usage `R`) is absent from an\n * emitted segment, because the FHIR resource carried no source this reverse map could ground it\n * from, or the source it carried had no faithful v2 form. The field is left absent per v2\n * optionality rules and **declared here**: a placeholder is never written to satisfy v2 structure,\n * and the receiver is never left to discover the gap. Distinct from\n * {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}, which is the forward direction's\n * FHIR-required element. */\n TRANSFORM_V2_REQUIRED_FIELD_ABSENT: \"TRANSFORM_V2_REQUIRED_FIELD_ABSENT\",\n /** A reverse (FHIR to v2) conversion produced **no message at all**: nothing in the resource\n * grounded a single field of the target segment, and an empty segment is never emitted. Raised so\n * that an empty-handed conversion is never indistinguishable from a successful one, and separate\n * from the refusals that name their own cause (an absent trigger, an unsupported resource type, a\n * structurally malformed resource). */\n TRANSFORM_NO_V2_MESSAGE_EMITTED: \"TRANSFORM_NO_V2_MESSAGE_EMITTED\",\n /** A segment the message carried did **not** reach any resource in the returned bundle, and the IG\n * *does* publish a segment map for its name: a **library gap**, fixable here. Raised once per\n * occurrence, located `NAME[k]` with `k` counted 1-based among the occurrences of that name\n * (`DG1[1]`, `DG1[2]`), so a consumer can tell how much of the message the bundle represents\n * without diffing the two by hand. The occurrence may have been read and refused rather than never\n * read: being counted, or already named by another issue, is not the same as reaching a resource. */\n TRANSFORM_SEGMENT_NOT_EMITTED: \"TRANSFORM_SEGMENT_NOT_EMITTED\",\n /** A segment the message carried did **not** reach any resource in the returned bundle, and its\n * name is **not** one the IG publishes a segment map for: a **standard gap**, not fixable here.\n * Custom Z-segments and `RXE` land on this code, and so does a name this library could not\n * classify at all, because a damaged segment identifier is never re-derived from the line: an\n * `AL1` whose identifier arrived as `AL11` reads as unclassifiable, not as an IG omission. Such an\n * occurrence is located `[#n]` by its 1-based position among the segments of the message, with no\n * name part at all. */\n TRANSFORM_SEGMENT_NO_IG_MAP: \"TRANSFORM_SEGMENT_NO_IG_MAP\",\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 [ISSUE_CODES.TRANSFORM_MISSING_TRIGGER]: {\n severity: \"error\",\n fhirIssueType: \"required\",\n message:\n \"reverse conversion requires an explicit v2 trigger from the caller; no resource carries one, so none was inferred and no message was built.\",\n },\n [ISSUE_CODES.TRANSFORM_UNSUPPORTED_RESOURCE]: {\n severity: \"error\",\n fhirIssueType: \"not-supported\",\n message:\n \"resource type is outside the reverse converter's supported shapes; no v2 message emitted and no segment layout guessed.\",\n },\n [ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED]: {\n severity: \"error\",\n fhirIssueType: \"structure\",\n message:\n \"input is not a structurally well-shaped FHIR resource for this conversion; nothing emitted, nothing thrown.\",\n },\n [ISSUE_CODES.TRANSFORM_NO_V2_TARGET]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"populated FHIR element has no v2 field in this reverse map; surfaced and left out, never approximated into a neighbouring field.\",\n },\n [ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE]: {\n severity: \"warning\",\n fhirIssueType: \"value\",\n message:\n \"FHIR value cannot be carried into its v2 target without altering it; the v2 field is left absent, never truncated, rounded, or coerced.\",\n },\n [ISSUE_CODES.TRANSFORM_CODE_NOT_INVERTIBLE]: {\n severity: \"warning\",\n fhirIssueType: \"code-invalid\",\n message:\n \"FHIR code has no usable inverse in the governing IG ConceptMap (ambiguous or absent); v2 field left absent, never resolved arbitrarily.\",\n },\n [ISSUE_CODES.TRANSFORM_CODE_SYSTEM_NOT_V2]: {\n severity: \"warning\",\n fhirIssueType: \"code-invalid\",\n message:\n \"coding system has no v2 coding-system mnemonic here; coding flagged rather than written with no table context or from an unrelated table.\",\n },\n [ISSUE_CODES.TRANSFORM_V2_REQUIRED_FIELD_ABSENT]: {\n severity: \"error\",\n fhirIssueType: \"required\",\n message:\n \"a v2-required field is absent from the emitted segment because the resource carried no source this map could ground it from; left absent per v2 optionality rules and declared here, never filled with a placeholder.\",\n },\n [ISSUE_CODES.TRANSFORM_NO_V2_MESSAGE_EMITTED]: {\n severity: \"error\",\n fhirIssueType: \"processing\",\n message:\n \"no v2 message was emitted: nothing in the resource grounded a single field of the target segment, and an empty segment is never emitted.\",\n },\n [ISSUE_CODES.TRANSFORM_SEGMENT_NOT_EMITTED]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"segment occurrence reached no resource in the returned bundle, and the IG publishes a segment map for its name; the bundle does not represent what this segment carried.\",\n },\n [ISSUE_CODES.TRANSFORM_SEGMENT_NO_IG_MAP]: {\n severity: \"information\",\n fhirIssueType: \"informational\",\n message:\n \"segment occurrence reached no resource in the returned bundle, and the IG publishes no segment map for its name, or the name could not be classified at all; the bundle does not represent what this segment carried.\",\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 * Two of the maps below are consumed as **recognizers** rather than as translations, because their\n * IG rows are identity in the source code: {@link isRepeatPatternCode} (RPT.1 → `Timing.code`) and\n * {@link TIMING_EVENT_VALUE_MAP} (RPT.8 → `Timing.repeat.when`). What they decide is whether the\n * published map has a row at all, so the caller can carry the message's own code verbatim or\n * withhold the element; neither one ever rewrites a code into a different one.\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`, `v2-0127`,\n * `v2-0128`, `v2-0335`, `v2-0528`), the FHIR R4 core code systems (`allergy-intolerance-category`,\n * `allergy-intolerance-type`, `allergy-intolerance-criticality`) and HL7 v3\n * (`v3-RouteOfAdministration`, `v3-TimingEvent`) are HL7's own, license-clean. The IG's `*-to-sct`\n * 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, and 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/** HL7 v2 Table 0127 (Allergen Type) THO CodeSystem URI. */\nexport const V2_0127_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0127\";\n/** HL7 v2 Table 0128 (Allergy Severity) THO CodeSystem URI. */\nexport const V2_0128_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0128\";\n/** FHIR R4 `AllergyIntoleranceCategory` CodeSystem URI (the IG's AL1-2 category target). */\nexport const ALLERGY_INTOLERANCE_CATEGORY_SYSTEM =\n \"http://hl7.org/fhir/allergy-intolerance-category\";\n/** FHIR R4 `AllergyIntoleranceType` CodeSystem URI (the IG's AL1-2 type target). */\nexport const ALLERGY_INTOLERANCE_TYPE_SYSTEM = \"http://hl7.org/fhir/allergy-intolerance-type\";\n/** FHIR R4 `AllergyIntoleranceCriticality` CodeSystem URI (the IG's AL1-4 criticality target). */\nexport const ALLERGY_INTOLERANCE_CRITICALITY_SYSTEM =\n \"http://hl7.org/fhir/allergy-intolerance-criticality\";\n/** HL7 v2 Table 0335 (Repeat Pattern) THO CodeSystem URI. */\nexport const V2_0335_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0335\";\n/** HL7 v2 Table 0528 (Event Related Period) THO CodeSystem URI. */\nexport const V2_0528_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v2-0528\";\n/** HL7 v3 TimingEvent CodeSystem URI: the half of FHIR's `EventTiming` value set the IG targets. */\nexport const V3_TIMING_EVENT_SYSTEM = \"http://terminology.hl7.org/CodeSystem/v3-TimingEvent\";\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/**\n * The published version of the HL7 Version 2 to FHIR Implementation Guide the five **AL1 allergy**\n * value maps below were transcribed from.\n *\n * Recorded per map family rather than once for the file, because the earlier value maps here were\n * transcribed on their own date and this constant must not backdate or forward-date them.\n *\n * @example\n * ```ts\n * import { IG_ALLERGY_VALUE_MAPS_VERSION } from \"@cosyte/transform\";\n * IG_ALLERGY_VALUE_MAPS_VERSION; // \"1.0.0\"\n * ```\n */\nexport const IG_ALLERGY_VALUE_MAPS_VERSION = \"1.0.0\";\n\n/**\n * The publication date of {@link IG_ALLERGY_VALUE_MAPS_VERSION}, so a later release of the guide can\n * be told apart from a defect in this library.\n *\n * @example\n * ```ts\n * import { IG_ALLERGY_VALUE_MAPS_PUBLISHED } from \"@cosyte/transform\";\n * IG_ALLERGY_VALUE_MAPS_PUBLISHED; // \"2025-10-07\"\n * ```\n */\nexport const IG_ALLERGY_VALUE_MAPS_PUBLISHED = \"2025-10-07\";\n\n/**\n * The date the five AL1 allergy ConceptMaps were retrieved and transcribed into the maps below. A\n * target that surprises a reader is answered by re-reading the guide at this date: each map is a\n * transcription of a published document at a moment, not a live query.\n *\n * @example\n * ```ts\n * import { IG_ALLERGY_VALUE_MAPS_RETRIEVED } from \"@cosyte/transform\";\n * IG_ALLERGY_VALUE_MAPS_RETRIEVED; // \"2026-08-28\"\n * ```\n */\nexport const IG_ALLERGY_VALUE_MAPS_RETRIEVED = \"2026-08-28\";\n\n/**\n * The IG segment map the five AL1 allergy value maps hang off, so a reader can audit any row: it is\n * the page that names which vocabulary map applies to which AL1 field.\n *\n * @example\n * ```ts\n * import { IG_ALLERGY_VALUE_MAPS_SOURCE } from \"@cosyte/transform\";\n * IG_ALLERGY_VALUE_MAPS_SOURCE.startsWith(\"https://\"); // true\n * ```\n */\nexport const IG_ALLERGY_VALUE_MAPS_SOURCE =\n \"https://hl7.org/fhir/uv/v2mappings/ConceptMap-segment-al1-to-allergyintolerance.html\";\n\n/**\n * **AL1-2 Allergen Type to category**: IG `ConceptMap/table-hl70127-to-allergy-intolerance-category`.\n * One **mapped** group of six rows into the FHIR R4 `AllergyIntoleranceCategory` code system (`DA`\n * drug to `medication`, `FA` food to `food`, `EA` environmental to `environment`, `AA` animal to\n * `biologic`, `PA` plant to `environment`, `LA` pollen to `environment`, each `equivalent`, with the\n * IG target displays), and an `(unmapped)` group of two: **`MA` and `MC` have no category target**.\n *\n * The IG applies this map to `AllergyIntolerance.category` **only**; `AllergyIntolerance.type` has\n * its own map ({@link ALLERGY_TYPE_VALUE_MAP}) over the same source table, and the two are resolved\n * independently. `MA` therefore yields a type and no category, which is the guide's answer and not a\n * gap to be filled: a category is never borrowed from the type map or from a neighbouring code.\n */\nexport const ALLERGY_CATEGORY_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70127-to-allergy-intolerance-category\",\n V2_0127_SYSTEM,\n [\"HL70127\", \"0127\"],\n {\n DA: { system: ALLERGY_INTOLERANCE_CATEGORY_SYSTEM, code: \"medication\", display: \"Medication\" },\n FA: { system: ALLERGY_INTOLERANCE_CATEGORY_SYSTEM, code: \"food\", display: \"Food\" },\n EA: {\n system: ALLERGY_INTOLERANCE_CATEGORY_SYSTEM,\n code: \"environment\",\n display: \"Environment\",\n },\n AA: { system: ALLERGY_INTOLERANCE_CATEGORY_SYSTEM, code: \"biologic\", display: \"Biologic\" },\n PA: {\n system: ALLERGY_INTOLERANCE_CATEGORY_SYSTEM,\n code: \"environment\",\n display: \"Environment\",\n },\n LA: {\n system: ALLERGY_INTOLERANCE_CATEGORY_SYSTEM,\n code: \"environment\",\n display: \"Environment\",\n },\n },\n);\n\n/**\n * **AL1-2 Allergen Type to type**: IG `ConceptMap/table-hl70127-to-allergy-intolerance-type`. One\n * **mapped** group of seven rows into the FHIR R4 `AllergyIntoleranceType` code system (`DA`, `FA`,\n * `MA`, `EA`, `AA`, `PA`, `LA` all to `allergy`, each `equivalent`, display `Allergy`), and an\n * `(unmapped)` group of one: **`MC` miscellaneous contraindication has no type target**.\n *\n * Read beside {@link ALLERGY_CATEGORY_VALUE_MAP}: the guide publishes two maps over Table 0127 with\n * different unmapped sets, so a code can be mapped by one and not the other. `MC` is the only code\n * neither map carries.\n */\nexport const ALLERGY_TYPE_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70127-to-allergy-intolerance-type\",\n V2_0127_SYSTEM,\n [\"HL70127\", \"0127\"],\n {\n DA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n FA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n MA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n EA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n AA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n PA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n LA: { system: ALLERGY_INTOLERANCE_TYPE_SYSTEM, code: \"allergy\", display: \"Allergy\" },\n },\n);\n\n/**\n * **AL1-4 Allergy Severity to criticality**: IG\n * `ConceptMap/table-hl70128-to-allergy-intolerance-criticality`. One **mapped** group of two rows\n * into the FHIR R4 `AllergyIntoleranceCriticality` code system (`SV` severe to `high`, `MI` mild to\n * `low`, both `equivalent`, with the IG target displays), and an `(unmapped)` group of two: **`MO`\n * moderate and `U` unknown have no criticality target**.\n *\n * The unmapped pair is the whole reason this field fails safe. `criticality` is an overall risk\n * assessment a prescriber acts on, so a moderate severity is left absent and flagged rather than\n * rounded to `low` or `high`, and `AllergyIntolerance.reaction.severity` is never populated from the\n * same component instead: the IG offers that only as a local variation, conditioned on a severity\n * that was **not** used equivalently to criticality, which no v2 message states.\n */\nexport const ALLERGY_CRITICALITY_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70128-to-allergy-intolerance-criticality\",\n V2_0128_SYSTEM,\n [\"HL70128\", \"0128\"],\n {\n SV: { system: ALLERGY_INTOLERANCE_CRITICALITY_SYSTEM, code: \"high\", display: \"High Risk\" },\n MI: { system: ALLERGY_INTOLERANCE_CRITICALITY_SYSTEM, code: \"low\", display: \"Low Risk\" },\n },\n);\n\n/**\n * **AL1-2 original code**: IG `ConceptMap/table-hl70127-to-v2-0127`. A single **identity** group of\n * all eight Table 0127 codes (`DA`, `FA`, `MA`, `MC`, `EA`, `AA`, `PA`, `LA` to themselves, each\n * `equivalent`, source and target both `v2-0127`).\n *\n * This is the map behind the `alternate-codes` extension the IG puts on `category`: whatever the\n * category map does or does not translate, the code the sender actually wrote survives on the\n * resource in its own code system, so a consumer can always see what the message said.\n */\nexport const ALLERGY_ORIGINAL_CATEGORY_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70127-to-v2-0127\",\n V2_0127_SYSTEM,\n [\"HL70127\", \"0127\"],\n identityTargets(V2_0127_SYSTEM, [\"DA\", \"FA\", \"MA\", \"MC\", \"EA\", \"AA\", \"PA\", \"LA\"]),\n);\n\n/**\n * **AL1-4 original code**: IG `ConceptMap/table-hl70128-original-to-v2-0128`. A single **identity**\n * group of all four Table 0128 codes (`SV`, `MO`, `MI`, `U` to themselves, each `equivalent`, source\n * and target both `v2-0128`), the map behind the `alternate-codes` extension on `criticality`.\n *\n * Its four codes are a superset of the two {@link ALLERGY_CRITICALITY_VALUE_MAP} translates, which\n * is the point: a `MO` that yields no criticality still yields the original severity code here.\n */\nexport const ALLERGY_ORIGINAL_CRITICALITY_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70128-original-to-v2-0128\",\n V2_0128_SYSTEM,\n [\"HL70128\", \"0128\"],\n identityTargets(V2_0128_SYSTEM, [\"SV\", \"MO\", \"MI\", \"U\"]),\n);\n\n/**\n * **RPT.8 Event**: IG `ConceptMap/table-hl70528-to-v3-timingevent`, **Group 1 only**. The published\n * map has two groups and only the first targets `v3-TimingEvent`: nine codes (`HS`, `AC`, `PC`,\n * `ACM`, `ACD`, `ACV`, `PCM`, `PCD`, `PCV`, each `equivalent`, each keeping its own spelling). The\n * second group (`IC`, `ICM`, `ICD`, `ICV`) targets `v2-0528` **back onto itself**, which is the map's\n * own way of saying those four have no `v3-TimingEvent` equivalent, and `v3-TimingEvent` is the half\n * of FHIR's required-bound `EventTiming` value set that a v2 event code can reach. So a Group 2 code\n * carries **no target here**: writing one into a required-bound `code` element would emit invalid\n * R4, and this library flags rather than emits. Any other code is unmapped and likewise flagged.\n *\n * @example\n * ```ts\n * // translateBound({ identifier: \"ACM\" }, TIMING_EVENT_VALUE_MAP)?.code; // \"ACM\"\n * // translateBound({ identifier: \"IC\" }, TIMING_EVENT_VALUE_MAP); // undefined (no v3 target)\n * ```\n */\nexport const TIMING_EVENT_VALUE_MAP: CodedValueMap = valueMap(\n \"table-hl70528-to-v3-timingevent\",\n V2_0528_SYSTEM,\n [\"HL70528\", \"0528\"],\n identityTargets(V3_TIMING_EVENT_SYSTEM, [\n \"HS\",\n \"AC\",\n \"PC\",\n \"ACM\",\n \"ACD\",\n \"ACV\",\n \"PCM\",\n \"PCD\",\n \"PCV\",\n ]),\n);\n\n/**\n * The **literal** source codes of IG `ConceptMap/table-hl70335-to-v2-0335` (RPT.1 Repeat Pattern):\n * the rows whose source code is a fixed token rather than a parameterized shape. Group 1 (identity\n * into `v2-0335`) contributes `QAM`, `QSHIFT`, `QHS`, `QPM`, `C`, `PRN`, `Once` and the six\n * meal-related building blocks `A`, `P`, `I`, `M`, `D`, `V`; Group 2 (into `v3-GTSAbbreviation`)\n * contributes `BID`, `TID`, `QID`, `QOD`. Both groups are recognized here because\n * {@link isRepeatPatternCode} answers *\"does this code have a row\"*, not *\"which system does its\n * target live in\"*.\n */\nconst REPEAT_PATTERN_LITERALS: ReadonlySet<string> = Object.freeze(\n new Set([\n \"QAM\",\n \"QSHIFT\",\n \"QHS\",\n \"QPM\",\n \"C\",\n \"PRN\",\n \"Once\",\n \"A\",\n \"P\",\n \"I\",\n \"M\",\n \"D\",\n \"V\",\n \"BID\",\n \"TID\",\n \"QID\",\n \"QOD\",\n ]),\n);\n\n/**\n * The **parameterized** source rows of the same map, each transcribed as the shape its published\n * placeholder text defines, so an instantiation of the row is recognized as the row it instantiates:\n *\n * - `Q<integer>S|M|H|D|W|L` (every `<integer>` seconds / minutes / hours / days / weeks / lunar months)\n * - `Q<integer>J<day#>` (repeats on a particular day of the week)\n * - `xID` (\"X\" times per day at institution-specified times, **where X is a numeral 5 or greater**)\n * - `U <spec>` (an interval specification in the UNIX cron form the row names)\n * - `<timing>C<meal>`, the row published as *Meal Related Timings*, composed from the `A`/`P`/`I`\n * timing letters and the `M`/`D`/`V` meal letters the map lists as its own rows.\n *\n * `PRNxxx` (\"where xxx is some frequency code\") is not here: it is a prefix over another row, and is\n * resolved recursively by {@link isRepeatPatternCode} so that the suffix must itself be a row.\n */\nconst REPEAT_PATTERN_SHAPES: readonly RegExp[] = Object.freeze([\n /^Q[0-9]+[SMHDWL]$/,\n /^Q[0-9]+J[1-7]$/,\n /^(?:[5-9]|[1-9][0-9]+)ID$/,\n /^U .+$/,\n /^[API]C[MDV]$/,\n]);\n\n/** Whether `code` matches a literal row or a parameterized row shape (the non-recursive rows). */\nfunction isRepeatPatternRow(code: string): boolean {\n return REPEAT_PATTERN_LITERALS.has(code) || REPEAT_PATTERN_SHAPES.some((s) => s.test(code));\n}\n\n/**\n * Whether the IG **Table HL70335 to v2-0335** ConceptMap publishes a row for this repeat-pattern\n * code, transcribed firsthand from the published STU1 map and applied as a **positive** test: a code\n * this returns `false` for has no row, and the caller withholds the schedule rather than asserting an\n * unpublished concept. Nothing is translated here: the map's mapped rows are all identity in the\n * source code, so the code a caller emits is the code the message sent, verbatim.\n *\n * @param code - The RPT.1 code exactly as the message sent it (case-sensitive, as the table is).\n * @example\n * ```ts\n * // isRepeatPatternCode(\"Q4H\"); // true (the Q<integer>H row)\n * // isRepeatPatternCode(\"BID\"); // true (a literal row)\n * // isRepeatPatternCode(\"PRNQ4H\"); // true (the PRNxxx row over the Q<integer>H row)\n * // isRepeatPatternCode(\"ZZZ\"); // false (no row: never asserted as a v2-0335 concept)\n * ```\n */\nexport function isRepeatPatternCode(code: string): boolean {\n if (isRepeatPatternRow(code)) return true;\n // PRNxxx: the PRN row taken over another frequency row, so the suffix must itself be a row.\n return code.startsWith(\"PRN\") && code.length > 3 && isRepeatPatternRow(code.slice(3));\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 type { Field } from \"@cosyte/hl7\";\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/** The raw first-subcomponent of a field's component at 0-based `index`, or `\"\"` when empty. */\nfunction component(field: Field, index: number): string {\n return field.repetitions[0]?.components[index]?.subcomponents[0] ?? \"\";\n}\n\n/** One EI field read as a FHIR `Identifier`: the value, and whether an authority went unused. */\nexport interface EntityIdentifier {\n /** The `Identifier` node built from EI.1, or `undefined` when EI.1 carries nothing. */\n readonly identifier: FhirComplex | undefined;\n /** Whether EI.2, EI.3 or EI.4 carried an assigning authority this library did not resolve. */\n readonly authorityValued: boolean;\n}\n\n/**\n * Read one EI (Entity Identifier) field as a FHIR `Identifier`, carrying EI.1 as\n * `Identifier.value` and nothing else. The same reading {@link orderIdentifier} applies to the\n * placer/filler order numbers, without the v2-0203 identifier type those rows assign.\n *\n * `Identifier.system` is deliberately left absent even when EI.2 to EI.4 name an assigning\n * authority: a system URI is never synthesized from a bare namespace, because two senders reusing\n * one namespace would otherwise collide. The caller is told the authority went unused through\n * {@link EntityIdentifier.authorityValued} so it can raise its own value-free diagnostic.\n *\n * @param field - The `EI` field, exactly as the parser published it.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const dg1 = parseHL7(raw).segments(\"DG1\")[0];\n * // toFhirEntityIdentifier(dg1!.field(20)).identifier; // { value: \"<EI.1>\" } or undefined\n * ```\n */\nexport function toFhirEntityIdentifier(field: Field): EntityIdentifier {\n const entityId = component(field, 0);\n const authorityValued =\n component(field, 1) !== \"\" || component(field, 2) !== \"\" || component(field, 3) !== \"\";\n return {\n identifier:\n entityId === \"\" ? undefined : complex([{ name: \"value\", value: primitive(entityId) }]),\n authorityValued,\n };\n}\n\n/**\n * The same `CodeableConcept` with its `text` replaced by `textValue`, so a segment row that targets\n * `code.text` directly can override the original text the datatype map read out of the coded field.\n *\n * @param concept - The `CodeableConcept` node the datatype converter produced.\n * @param textValue - The text the segment map's own row assigns.\n * @example\n * ```ts\n * // withCodeableText(concept, \"Diabetes mellitus\") -> the same codings, that text\n * ```\n */\nexport function withCodeableText(concept: FhirComplex, textValue: string): FhirComplex {\n return complex([\n ...concept.properties.filter((p) => p.name !== \"text\"),\n { name: \"text\", value: primitive(textValue) },\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 return primitive(undefined, { extension: [dataAbsentReason(reasonCode)] });\n}\n\n/** The `data-absent-reason` extension node itself, shared by the primitive and complex forms. */\nfunction dataAbsentReason(reasonCode: string): FhirComplex {\n return complex([\n { name: \"url\", value: primitive(DATA_ABSENT_REASON_URL) },\n { name: \"valueCode\", value: primitive(reasonCode) },\n ]);\n}\n\n/**\n * A value-absent FHIR **complex** element carrying only a `data-absent-reason` extension: the\n * counterpart of {@link dataAbsent} for a required element whose type is a datatype rather than a\n * primitive, so the cardinality is satisfied **without fabricating any part of the value**.\n *\n * @param reasonCode - The `data-absent-reason` code (e.g. `\"unknown\"`).\n * @example\n * ```ts\n * // used for SampledData.origin, which R4 requires and the IG's NA map has no source row for\n * // dataAbsentComplex(\"unknown\"); // { extension: [{ url: …/data-absent-reason, valueCode: \"unknown\" }] }\n * ```\n */\nexport function dataAbsentComplex(reasonCode: string): FhirComplex {\n return complex([{ name: \"extension\", value: list([dataAbsentReason(reasonCode)]) }]);\n}\n","/**\n * AL1 to FHIR `AllergyIntolerance`: the allergy an ADT states, carried into the bundle instead of\n * lost between the v2 feed and the FHIR record. Grounded firsthand on the IG **AL1 to\n * AllergyIntolerance** segment map and the **ADT_A01 to Bundle** message map\n * (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-segment-al1-to-allergyintolerance.html`,\n * `ConceptMap-message-adt-a01-to-bundle.html`), which wires\n * `AllergyIntolerance.patient.reference` to the bundle's Patient and creates one resource per AL1.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | AL1 (fixed) | `clinicalStatus` (`active`) | the IG's own assignment for constraint ait-1 |\n * | AL1-2 Allergen Type Code (CWE) | `category` (0..*) | {@link ALLERGY_CATEGORY_VALUE_MAP} (HL70127) |\n * | AL1-2 Allergen Type Code (CWE) | `category.extension` alternate-codes | {@link ALLERGY_ORIGINAL_CATEGORY_VALUE_MAP} (v2-0127 identity) |\n * | AL1-2 Allergen Type Code (CWE) | `type` (0..1) | {@link ALLERGY_TYPE_VALUE_MAP} (HL70127) |\n * | AL1-3 Allergen Code (CWE) | `code` | {@link toFhirCodeableConcept} (structural, no IG value map) |\n * | AL1-4 Allergy Severity Code (CWE) | `criticality` (0..1) | {@link ALLERGY_CRITICALITY_VALUE_MAP} (HL70128) |\n * | AL1-4 Allergy Severity Code (CWE) | `criticality.extension` alternate-codes | {@link ALLERGY_ORIGINAL_CRITICALITY_VALUE_MAP} (v2-0128 identity) |\n * | AL1-5 Allergy Reaction Code (ST) | `reaction.manifestation.text` | verbatim, one manifestation per repetition |\n * | AL1-6 Identification Date (DT) | `onsetDateTime` | {@link toFhirDateTime}, legacy versions only |\n * | (message-map wiring) | `patient` (required 1..1) | the bundle's Patient |\n *\n * **Fail-safes (never a confident wrong allergy).**\n * - **Two maps over one component, resolved independently.** The guide publishes a separate Table\n * 0127 map for `category` and for `type`, with different unmapped sets, so `MA` yields a type and\n * **no category**. Neither answer is ever borrowed from the other map or from a neighbouring code:\n * the element the map has no target for is omitted and flagged\n * {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}.\n * - **The original code survives whatever the map does.** The IG makes the `alternate-codes`\n * extension `1..1` wherever AL1-2 or AL1-4 is valued, so the code the sender wrote is carried in\n * its own v2 code system even when the translating map had no target for it. An unmapped category\n * is therefore a `category` element with the extension and no code value, not an absent one.\n * - **`criticality` is the only severity target.** `AllergyIntolerance.reaction.severity` is a LOCAL\n * VARIATION in the guide, conditioned on a severity that was not used equivalently to criticality,\n * which no message states. It is never populated here, so a `MO` or `U` severity leaves criticality\n * absent and flagged rather than reappearing as a reaction grading the source never asserted.\n * - **An allergy names what it is to.** AL1-3 is the allergen. An AL1 that grounds no allergen code\n * and no allergen text asserts an allergy without saying to what, so the resource is withheld and\n * flagged {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} rather than emitted naming nothing.\n * - **AL1-6 is legacy input, never a live element.** The IG's own comment on that row reads\n * \"Withdrawn as of 2.7\", so `onsetDateTime` is carried only for a message whose MSH-12 is readable\n * and earlier than 2.7. A valued AL1-6 on any later, absent or unreadable version is dropped and\n * flagged, never read as an onset the sender may not have meant.\n * - **A rejected extension costs the extension, not the allergy.** If the alternate-codes extension\n * would make the resource fail the conservative-emit gate, the same resource is emitted without it\n * and the drop is flagged, so a consumer keeps the allergy rather than losing it to a detail.\n *\n * Deferred and flagged elsewhere, not silently mapped: `IAM` (the guide's other allergy segment),\n * AL1-1 (the guide states it does not warrant mapping), and `verificationStatus`, which no AL1\n * component grounds.\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 {\n toFhirCodeableConceptVia,\n translateBound,\n ALLERGY_CATEGORY_VALUE_MAP,\n ALLERGY_CRITICALITY_VALUE_MAP,\n ALLERGY_ORIGINAL_CATEGORY_VALUE_MAP,\n ALLERGY_ORIGINAL_CRITICALITY_VALUE_MAP,\n ALLERGY_TYPE_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/**\n * The code system of the fixed `clinicalStatus` the IG assigns to every AllergyIntolerance built\n * from an AL1, transcribed from the segment map's own sort-order 0 row.\n *\n * @example\n * ```ts\n * import { ALLERGY_CLINICAL_STATUS_SYSTEM } from \"@cosyte/transform\";\n * ALLERGY_CLINICAL_STATUS_SYSTEM.endsWith(\"allergyintolerance-clinical\"); // true\n * ```\n */\nexport const ALLERGY_CLINICAL_STATUS_SYSTEM =\n \"http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical\";\n\n/**\n * The fixed `clinicalStatus` code the IG assigns. The guide's own note explains why it is fixed\n * rather than derived: constraint ait-1 requires a clinicalStatus unless the verificationStatus is\n * `entered-in-error`, and no AL1 component can ground that retraction.\n *\n * @example\n * ```ts\n * import { ALLERGY_CLINICAL_STATUS_CODE } from \"@cosyte/transform\";\n * ALLERGY_CLINICAL_STATUS_CODE; // \"active\"\n * ```\n */\nexport const ALLERGY_CLINICAL_STATUS_CODE = \"active\";\n\n/**\n * The canonical URL of the FHIR `alternate-codes` extension, the IG's fixed assignment for the\n * `category.extension.url` and `criticality.extension.url` rows.\n *\n * @example\n * ```ts\n * import { ALTERNATE_CODES_EXTENSION_URL } from \"@cosyte/transform\";\n * ALTERNATE_CODES_EXTENSION_URL; // \"http://hl7.org/fhir/StructureDefinition/alternate-codes\"\n * ```\n */\nexport const ALTERNATE_CODES_EXTENSION_URL =\n \"http://hl7.org/fhir/StructureDefinition/alternate-codes\";\n\n/**\n * The HL7 v2 version at which AL1-6 Identification Date was withdrawn, per the IG map's own comment\n * on that row (\"Withdrawn as of 2.7, Refer to IAM-11 Onset or IAM-13 Reported Date\"). A message at\n * this version or later carries no AL1-6 that this library will read as an onset.\n *\n * @example\n * ```ts\n * import { AL1_ONSET_WITHDRAWN_AT } from \"@cosyte/transform\";\n * AL1_ONSET_WITHDRAWN_AT; // [2, 7]\n * ```\n */\nexport const AL1_ONSET_WITHDRAWN_AT: readonly number[] = Object.freeze([2, 7]);\n\n/** A v2 version identifier this library will compare: dotted, numeric, nothing else. */\nconst READABLE_VERSION = /^\\d+(?:\\.\\d+)*$/;\n\n/**\n * Whether a message's MSH-12 version identifier is readable **and** earlier than the version at\n * which AL1-6 was withdrawn ({@link AL1_ONSET_WITHDRAWN_AT}).\n *\n * Fails closed in both directions a version can be unusable: an absent MSH-12 and one this library\n * cannot compare (a vendor string, an empty component, anything outside the dotted-numeric shape)\n * both answer `false`, so a valued AL1-6 is dropped and flagged rather than read as an onset on a\n * message that may never have meant one.\n *\n * @param version - The MSH-12 version identifier exactly as the parser published it.\n * @example\n * ```ts\n * import { carriesLegacyOnsetDate } from \"@cosyte/transform\";\n * carriesLegacyOnsetDate(\"2.5.1\"); // true\n * carriesLegacyOnsetDate(\"2.7\"); // false\n * carriesLegacyOnsetDate(undefined); // false\n * ```\n */\nexport function carriesLegacyOnsetDate(version: string | undefined): boolean {\n if (version === undefined || !READABLE_VERSION.test(version)) return false;\n const parts = version.split(\".\").map(Number);\n for (let i = 0; i < AL1_ONSET_WITHDRAWN_AT.length; i++) {\n const part = parts[i] ?? 0;\n const bound = AL1_ONSET_WITHDRAWN_AT[i] ?? 0;\n if (part !== bound) return part < bound;\n }\n // Equal on every component of the bound: 2.7 itself, and 2.7.1 with it.\n return false;\n}\n\n/**\n * Every `AL1` occurrence a message carries, in message order. One AllergyIntolerance is created per\n * occurrence, per the IG message map's `0..-1` cardinality on the AL1 row.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // collectAllergies(parseHL7(raw)).length; // one entry per AL1 in the message\n * ```\n */\nexport function collectAllergies(msg: Hl7Message): readonly Segment[] {\n return msg.allSegments().filter((seg) => seg.type === \"AL1\");\n}\n\n/** How much of the IG's AL1 mapping to carry: the alternate-codes extension is the one variable. */\nexport interface AllergyBuildOptions {\n /**\n * Whether to carry the IG's `alternate-codes` extension on `category` / `criticality`. Defaults to\n * `true`; the emit path builds a second draft with it off only when the first draft fails the\n * conservative-emit gate.\n */\n readonly carryAlternateCodes?: boolean;\n}\n\n/**\n * Build the IG's `alternate-codes` extension for a coded AL1 component, carrying the original v2\n * code through its identity ConceptMap, or `undefined` when the component grounds no coding at all.\n */\nfunction alternateCodesExtension(\n seg: Segment,\n field: number,\n map: CodedValueMap,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const original = toFhirCodeableConceptVia(seg.field(field).asCwe(), map, ctx);\n issues.push(...original.issues);\n if (original.value === undefined) return undefined;\n return complex([\n { name: \"url\", value: primitive(ALTERNATE_CODES_EXTENSION_URL) },\n { name: \"valueCodeableConcept\", value: original.value },\n ]);\n}\n\n/**\n * Translate one coded AL1 component to a FHIR `code` primitive, carrying the alternate-codes\n * extension the IG puts beside it. Returns `undefined` only when the component grounds neither a\n * translated code nor an original one; an untranslated code still yields the extension, so what the\n * message said is never lost to a map that had no target for it.\n */\nfunction translatedCodeElement(\n seg: Segment,\n field: number,\n targetMap: CodedValueMap,\n originalMap: CodedValueMap,\n carryAlternateCodes: boolean,\n v2Location: string,\n fhirPath: string,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirNode | undefined {\n const extension = carryAlternateCodes\n ? alternateCodesExtension(seg, field, originalMap, ctx, issues)\n : undefined;\n const target = translateBound(seg.field(field).asCwe(), targetMap);\n if (target === undefined) {\n // No target in the map being applied: this element is omitted and flagged, never coerced to a\n // neighbouring value, and never resolved from the other map over the same source table.\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, v2Location, fhirPath));\n }\n if (target === undefined && extension === undefined) return undefined;\n return extension === undefined\n ? primitive(target?.code)\n : primitive(target?.code, { extension: [extension] });\n}\n\n/** Build `AllergyIntolerance.reaction` from the AL1-5 repetitions, or `undefined` when none. */\nfunction buildReaction(al1: Segment): FhirNode | undefined {\n const manifestations = al1\n .field(5)\n .repetitions.map((rep) => rep.components[0]?.subcomponents[0] ?? \"\")\n .filter((text) => text !== \"\")\n .map((text) => complex([{ name: \"text\", value: primitive(text) }]));\n if (manifestations.length === 0) return undefined;\n return list([complex([{ name: \"manifestation\", value: list(manifestations) }])]);\n}\n\n/** Build `AllergyIntolerance.onsetDateTime` from AL1-6, per the withdrawn-field rule. */\nfunction buildOnset(\n al1: Segment,\n version: string | undefined,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirNode | undefined {\n if (al1.field(6).value === \"\") return undefined;\n if (!carriesLegacyOnsetDate(version)) {\n // Valued on a message at or after the withdrawal, or on one whose version cannot be read: the\n // field is legacy input only, so it is dropped and declared rather than read as an onset.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"AL1.6\", \"AllergyIntolerance.onsetDateTime\"),\n );\n return undefined;\n }\n const onset = toFhirDateTime(al1.field(6).asTs(), ctx.options);\n issues.push(...onset.issues);\n return onset.value === undefined ? undefined : primitive(onset.value);\n}\n\n/**\n * Build a FHIR `AllergyIntolerance` resource node from one `AL1` occurrence, wired to the bundle's\n * Patient. Returns `{ value: undefined }` when AL1-3 grounds no allergen code and no allergen text,\n * because an allergy that names no substance asserts one without saying to what.\n *\n * @param al1 - The `AL1` `@cosyte/hl7` `Segment`.\n * @param patientFullUrl - The bundle's Patient fullUrl, for `patient` (required 1..1).\n * @param version - The message's MSH-12 version identifier, which decides AL1-6 (see\n * {@link carriesLegacyOnsetDate}).\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @param options - Whether to carry the IG's alternate-codes extension (see\n * {@link AllergyBuildOptions}).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const al1 = parseHL7(raw).segments(\"AL1\")[0];\n * // const { value } = buildAllergyIntolerance(al1!, \"urn:uuid:pat\", \"2.5.1\", {});\n * ```\n */\nexport function buildAllergyIntolerance(\n al1: Segment,\n patientFullUrl: string,\n version: string | undefined,\n ctx: TransformContext,\n options: AllergyBuildOptions = {},\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const carryAlternateCodes = options.carryAlternateCodes ?? true;\n\n // AL1-3 → code, the allergen itself. Nothing groundable here means nothing safe to emit.\n const allergen = toFhirCodeableConcept(al1.field(3).asCwe(), ctx);\n if (allergen.value === undefined) {\n return {\n value: undefined,\n issues: [\n ...allergen.issues,\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"AL1.3\", \"AllergyIntolerance.code\"),\n ],\n };\n }\n issues.push(...allergen.issues);\n\n // AL1-2 → type and category, resolved against their two separate IG maps, independently.\n const allergenTypeValued = al1.field(2).value !== \"\";\n const type = allergenTypeValued\n ? translatedCodeElement(\n al1,\n 2,\n ALLERGY_TYPE_VALUE_MAP,\n ALLERGY_ORIGINAL_CATEGORY_VALUE_MAP,\n false,\n \"AL1.2\",\n \"AllergyIntolerance.type\",\n ctx,\n issues,\n )\n : undefined;\n const category = allergenTypeValued\n ? translatedCodeElement(\n al1,\n 2,\n ALLERGY_CATEGORY_VALUE_MAP,\n ALLERGY_ORIGINAL_CATEGORY_VALUE_MAP,\n carryAlternateCodes,\n \"AL1.2\",\n \"AllergyIntolerance.category\",\n ctx,\n issues,\n )\n : undefined;\n\n // AL1-4 → criticality. The reaction.severity local variation is deliberately not populated.\n const criticality =\n al1.field(4).value !== \"\"\n ? translatedCodeElement(\n al1,\n 4,\n ALLERGY_CRITICALITY_VALUE_MAP,\n ALLERGY_ORIGINAL_CRITICALITY_VALUE_MAP,\n carryAlternateCodes,\n \"AL1.4\",\n \"AllergyIntolerance.criticality\",\n ctx,\n issues,\n )\n : undefined;\n\n const onset = buildOnset(al1, version, ctx, issues);\n const reaction = buildReaction(al1);\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"AllergyIntolerance\") },\n // The IG's fixed assignment: not derived from the message, and the reason is on the row itself.\n {\n name: \"clinicalStatus\",\n value: complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(ALLERGY_CLINICAL_STATUS_SYSTEM) },\n { name: \"code\", value: primitive(ALLERGY_CLINICAL_STATUS_CODE) },\n ]),\n ]),\n },\n ]),\n },\n ];\n if (type !== undefined) props.push({ name: \"type\", value: type });\n if (category !== undefined) props.push({ name: \"category\", value: list([category]) });\n if (criticality !== undefined) props.push({ name: \"criticality\", value: criticality });\n props.push({ name: \"code\", value: allergen.value });\n props.push({ name: \"patient\", value: reference(patientFullUrl) });\n if (onset !== undefined) props.push({ name: \"onsetDateTime\", value: onset });\n if (reaction !== undefined) props.push({ name: \"reaction\", value: reaction });\n\n return { value: complex(props), issues };\n}\n\n/**\n * Build one AL1's `AllergyIntolerance` and put it through the conservative-emit `gate`, falling back\n * to the same resource without its alternate-codes extension when the extension is what the gate\n * refuses. Returns `{ value: undefined }` when the allergy is withheld, with the issue saying why\n * already raised: an ungrounded allergen (`TRANSFORM_ELEMENT_DROPPED`) or a draft the gate rejects\n * either way ({@link ISSUE_CODES.TRANSFORM_RESOURCE_INVALID}).\n *\n * The gate is a parameter rather than a call into the assembler, so the fallback is decided by one\n * predicate that a caller (and a test) can supply: what \"the gate rejects this\" means stays in one\n * place, and the branch is reachable without a hand-built invalid resource.\n *\n * @param al1 - The `AL1` `@cosyte/hl7` `Segment`.\n * @param patientFullUrl - The bundle's Patient fullUrl, for `patient` (required 1..1).\n * @param version - The message's MSH-12 version identifier (see {@link carriesLegacyOnsetDate}).\n * @param ctx - The transform context.\n * @param gate - The conservative-emit predicate: `true` when this resource may join the bundle.\n * @param v2Location - The occurrence's v2 location, for the withholding issue (e.g. `AL1[0]`).\n * @example\n * ```ts\n * // const emitted = emitAllergyIntolerance(al1, \"urn:uuid:pat\", \"2.5.1\", {}, () => true, \"AL1[0]\");\n * ```\n */\nexport function emitAllergyIntolerance(\n al1: Segment,\n patientFullUrl: string,\n version: string | undefined,\n ctx: TransformContext,\n gate: (resource: FhirComplex) => boolean,\n v2Location: string,\n): ConvertResult<FhirComplex> {\n const built = buildAllergyIntolerance(al1, patientFullUrl, version, ctx);\n if (built.value === undefined) return built;\n if (gate(built.value)) return built;\n\n const issues = [...built.issues];\n\n // The extension is the one part of this resource the guide adds beside a value rather than as\n // one, so it is the one part that can be dropped without losing what the allergy says. The\n // second draft's own issues are the first draft's, already raised: only the drop is new.\n const withoutExtension = buildAllergyIntolerance(al1, patientFullUrl, version, ctx, {\n carryAlternateCodes: false,\n });\n if (withoutExtension.value !== undefined && gate(withoutExtension.value)) {\n if (al1.field(2).value !== \"\") {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"AL1.2\",\n \"AllergyIntolerance.category.extension\",\n ),\n );\n }\n if (al1.field(4).value !== \"\") {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"AL1.4\",\n \"AllergyIntolerance.criticality.extension\",\n ),\n );\n }\n return { value: withoutExtension.value, issues };\n }\n\n // Rejected with the extension and without it: withheld, never shipped as invalid FHIR.\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_INVALID, v2Location, \"AllergyIntolerance\"));\n return { value: undefined, issues };\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`), which is encumbered and **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 * DG1 to FHIR `Condition`: the diagnoses an admit states, carried into the bundle instead of lost\n * between the v2 feed and the FHIR record. Grounded firsthand on the IG **DG1 to Condition** segment\n * map and the **ADT_A01 to Bundle** message map (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-dg1-to-condition.html`, `ConceptMap-message-adt-a01-to-bundle.html`), which\n * wires `Condition[1].subject.reference` to the bundle's Patient, creates one Condition per DG1, and\n * references it back from `Encounter[1].diagnosis`.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | DG1-3 Diagnosis Code (CWE) | `code` | {@link toFhirCodeableConcept} (structural, no IG value map) |\n * | DG1-4 Diagnosis Description (ST) | `code.text` | verbatim, overriding the coded field's own text |\n * | DG1-5 Diagnosis Date/Time (DTM) | `onsetDateTime` | {@link toFhirDateTime} |\n * | DG1-19 Attestation Date/Time (DTM) | `recordedDate` | {@link toFhirDateTime} |\n * | DG1-20 Diagnosis Identifier (EI) | `identifier` | {@link toFhirEntityIdentifier} |\n * | DG1-21 Diagnosis Action Code (ID) | `verificationStatus` | the map's fixed assignment for `D` |\n * | (message-map wiring) | `subject` (required 1..1) | the bundle's Patient |\n *\n * **Fail-safes (never a confident wrong diagnosis).**\n * - **One action code is mapped, and only one.** The DG1-21 row assigns the fixed value\n * `entered-in-error` and names no source code; its own comment reads \"Other values (A and U) don't\n * map to anything\", and Table 0206 publishes `A`, `D`, `S`, `U` and `X`. `D` (Delete) is therefore\n * the code the assignment covers: every other published action code leaves `verificationStatus`\n * absent and raises {@link ISSUE_CODES.TRANSFORM_CODE_UNMAPPED}, never a neighbouring status.\n * - **A diagnosis with no code and no text is visible, not silent.** Such a DG1 still becomes a\n * Condition (the message stated a diagnosis), and the empty `code` is declared\n * {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} rather than read as an intentionally empty one.\n * - **`clinicalStatus` is absent because no row grounds it.** The map has no `Condition.clinicalStatus`\n * row and no DG1 component states one, so it is never filled. R4's `con-3` invariant expects it\n * wherever `verificationStatus` is not `entered-in-error`, so a Condition built here can fail that\n * invariant under a full profile validator: that is a declared gap, and filling the element from\n * nothing is the fabrication this library refuses.\n *\n * Deferred and flagged, never silently mapped: `DG1-16` (`asserter`, a Practitioner resource this\n * library does not build), `DG1-22` (the `condition-dueTo` extension, whose reference resolves by\n * identifier rather than by bundle position) and the map's `EpisodeOfCare` target, so a diagnosis\n * ties to an Encounter or to nothing.\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, toFhirEntityIdentifier, withCodeableText } from \"./reference.js\";\n\n/**\n * The code system of the `verificationStatus` the DG1-21 row assigns, transcribed from the segment\n * map's own `Condition.verificationStatus.coding.system` assignment.\n *\n * @example\n * ```ts\n * import { CONDITION_VERIFICATION_STATUS_SYSTEM } from \"@cosyte/transform\";\n * CONDITION_VERIFICATION_STATUS_SYSTEM.endsWith(\"condition-ver-status\"); // true\n * ```\n */\nexport const CONDITION_VERIFICATION_STATUS_SYSTEM =\n \"http://terminology.hl7.org/CodeSystem/condition-ver-status\";\n\n/**\n * The `verificationStatus` code the DG1-21 row assigns, transcribed from the segment map's own\n * `Condition.verificationStatus.coding.code` assignment.\n *\n * @example\n * ```ts\n * import { CONDITION_ENTERED_IN_ERROR } from \"@cosyte/transform\";\n * CONDITION_ENTERED_IN_ERROR; // \"entered-in-error\"\n * ```\n */\nexport const CONDITION_ENTERED_IN_ERROR = \"entered-in-error\";\n\n/**\n * The Table 0206 (Segment Action Code) code the DG1-21 assignment covers. The row assigns a\n * retraction and names no source code; `D` is Delete, and the row's own comment excludes the rest.\n *\n * @example\n * ```ts\n * import { DG1_RETRACTION_ACTION_CODE } from \"@cosyte/transform\";\n * DG1_RETRACTION_ACTION_CODE; // \"D\"\n * ```\n */\nexport const DG1_RETRACTION_ACTION_CODE = \"D\";\n\n/**\n * Every `DG1` occurrence a message carries, in message order. One Condition is created per\n * occurrence, per the IG message map's `0..-1` cardinality on the DG1 row.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // collectDiagnoses(parseHL7(raw)).length; // one entry per DG1 in the message\n * ```\n */\nexport function collectDiagnoses(msg: Hl7Message): readonly Segment[] {\n return msg.allSegments().filter((seg) => seg.type === \"DG1\");\n}\n\n/**\n * The value-free diagnostics for the DG1 rows this library reads and deliberately does not build:\n * the diagnosing clinician (a Practitioner resource), and the parent diagnosis (a reference resolved\n * by identifier rather than by bundle position).\n *\n * Raised for the occurrence whether or not the Condition itself is emitted, so a deferred row a\n * message actually valued is in the issues list rather than silently absent.\n *\n * @param dg1 - The `DG1` `@cosyte/hl7` `Segment`.\n * @example\n * ```ts\n * // deferredDiagnosisIssues(dg1).length; // one per valued deferred row\n * ```\n */\nexport function deferredDiagnosisIssues(dg1: Segment): readonly TransformIssue[] {\n const issues: TransformIssue[] = [];\n if (dg1.field(16).value !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"DG1.16\", \"Condition.asserter\"));\n }\n if (dg1.field(22).value !== \"\") {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"DG1.22\",\n \"Condition.extension[condition-dueTo].valueReference\",\n ),\n );\n }\n return issues;\n}\n\n/** Build `Condition.verificationStatus` from DG1-21, or `undefined` when no row covers the code. */\nfunction buildVerificationStatus(dg1: Segment, issues: TransformIssue[]): FhirComplex | undefined {\n const action = dg1.field(21).value;\n if (action === \"\") return undefined;\n if (action !== DG1_RETRACTION_ACTION_CODE) {\n // Every other published action code: the map has no target, so the element stays absent rather\n // than borrowing the retraction the one mapped code assigns.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"DG1.21\", \"Condition.verificationStatus\"),\n );\n return undefined;\n }\n return complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(CONDITION_VERIFICATION_STATUS_SYSTEM) },\n { name: \"code\", value: primitive(CONDITION_ENTERED_IN_ERROR) },\n ]),\n ]),\n },\n ]);\n}\n\n/** Build `Condition.code` from DG1-3, with DG1-4 overriding its text when that row is valued. */\nfunction buildCode(\n dg1: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const description = dg1.field(4).value;\n const coded = toFhirCodeableConcept(dg1.field(3).asCwe(), ctx);\n issues.push(...coded.issues);\n if (coded.value === undefined) {\n // An empty CWE grounds no coding at all, so DG1-4 alone carries the concept, if anything does.\n return description === \"\"\n ? undefined\n : complex([{ name: \"text\", value: primitive(description) }]);\n }\n return description === \"\" ? coded.value : withCodeableText(coded.value, description);\n}\n\n/** Build a `dateTime` element from a DTM field, or `undefined` when the field carries nothing. */\nfunction buildDateTime(\n dg1: Segment,\n field: number,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirNode | undefined {\n if (dg1.field(field).value === \"\") return undefined;\n const converted = toFhirDateTime(dg1.field(field).asTs(), ctx.options);\n issues.push(...converted.issues);\n return converted.value === undefined ? undefined : primitive(converted.value);\n}\n\n/**\n * Build a FHIR `Condition` resource node from one `DG1` occurrence, wired to the bundle's Patient.\n * Always produces a Condition: a DG1 states a diagnosis, so an occurrence that grounds neither a\n * code nor a description is emitted with its empty `code` declared rather than withheld.\n *\n * @param dg1 - The `DG1` `@cosyte/hl7` `Segment`.\n * @param patientFullUrl - The bundle's Patient fullUrl, for `subject` (required 1..1).\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @param v2Location - The occurrence's v2 location, for the codeless diagnostic (e.g. `DG1[0]`).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const dg1 = parseHL7(raw).segments(\"DG1\")[0];\n * // const { value } = buildCondition(dg1!, \"urn:uuid:pat\", {}, \"DG1[0]\");\n * ```\n */\nexport function buildCondition(\n dg1: Segment,\n patientFullUrl: string,\n ctx: TransformContext,\n v2Location: string,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Condition\") },\n ];\n\n // DG1-20 EI -> identifier. The assigning authority is never turned into a system URI.\n const entity = toFhirEntityIdentifier(dg1.field(20));\n if (entity.identifier !== undefined) {\n props.push({ name: \"identifier\", value: list([entity.identifier]) });\n }\n if (entity.authorityValued) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"DG1.20\", \"Condition.identifier.system\"),\n );\n }\n\n // DG1-21 -> verificationStatus, for the one action code the map's assignment covers.\n const verification = buildVerificationStatus(dg1, issues);\n if (verification !== undefined) props.push({ name: \"verificationStatus\", value: verification });\n\n // DG1-3 -> code, DG1-4 -> code.text. Neither valued is a diagnosis that names nothing: declared.\n const code = buildCode(dg1, ctx, issues);\n if (code === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, v2Location, \"Condition.code\"));\n } else {\n props.push({ name: \"code\", value: code });\n }\n\n // The message map's wiring: Condition[1].subject.reference = Patient[1].id.\n props.push({ name: \"subject\", value: reference(patientFullUrl) });\n\n // DG1-5 -> onsetDateTime, DG1-19 -> recordedDate.\n const onset = buildDateTime(dg1, 5, ctx, issues);\n if (onset !== undefined) props.push({ name: \"onsetDateTime\", value: onset });\n const recorded = buildDateTime(dg1, 19, ctx, issues);\n if (recorded !== undefined) props.push({ name: \"recordedDate\", value: recorded });\n\n return { value: complex(props), issues };\n}\n","/**\n * IN1 to FHIR `Coverage`: the insurance an admit states, carried into the bundle instead of lost\n * between the v2 feed and the FHIR record. Grounded firsthand on the IG **IN1 to Coverage** segment\n * map and the **ADT_A01 to Bundle** message map (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-in1-to-coverage.html`, `ConceptMap-message-adt-a01-to-bundle.html`), which\n * wires `Coverage.beneficiary.reference` to the bundle's Patient and creates one Coverage per IN1.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | IN1-2 Health Plan ID (CWE) | `identifier` | CWE.1 as the identifier value |\n * | IN1-4 Insurance Company Name (XON) | `payor` (required 1..*) | a reference carrying the name as `display` only |\n * | IN1-10 Insured's Group Emp ID (CX) | the subscriber-id extension, `IF CX.5 IS \"SN\"` | {@link toFhirIdentifier} |\n * | IN1-12 Plan Effective Date (DT) | `period.start` | {@link toFhirDateTime} |\n * | IN1-13 Plan Expiration Date (DT) | `period.end` | {@link toFhirDateTime} |\n * | IN1-15 Plan Type (CWE) | `type` | {@link toFhirCodeableConcept} |\n * | IN1-49 Insured's ID Number (CX) | the subscriber-id extension | {@link toFhirIdentifier} |\n * | (no row at all) | `status` (required 1..1) | a value-absent element, `data-absent-reason` `unknown` |\n * | (message-map wiring) | `beneficiary` (required 1..1) | the bundle's Patient |\n *\n * **Fail-safes (never a confident wrong coverage).**\n * - **The status is never asserted.** `Coverage.status` occurs nowhere in the segment map, and R4\n * makes the element required under a required binding whose members are all positive claims about\n * a policy. So it ships as a value-absent element carrying `data-absent-reason` `unknown`, plus\n * {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}: a consumer must read the status as\n * unknown, and `active` is never the answer this library gives to a message that did not say so.\n * - **A coverage names who pays.** `payor` is required 1..1 and IN1-4 is the only row that grounds\n * it, so an IN1 whose insurance company name is absent is **withheld** and declared\n * {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} rather than emitted naming no payer.\n * - **The payer is named, not resolved.** No Organization resource is built here, so `payor` carries\n * the company name as a `display` and no literal reference, and the missing resource is declared\n * rather than left to look like a resolvable link.\n * - **A health plan id keeps its value, never a synthesized system.** IN1-2 is a coded element whose\n * coding system is a table mnemonic, not an identifier namespace, so only CWE.1 is carried as\n * `Identifier.value`; a valued CWE.3 is declared dropped rather than turned into an\n * `Identifier.system` this library would be inventing.\n *\n * Deferred and flagged, never silently mapped: `IN1-5` (the payer address, an Organization this\n * library does not build), `IN1-10` and `IN1-11` (`policyHolder`, likewise an Organization),\n * `IN1-16` (`subscriber`, a Patient or RelatedPerson reference the guide conditions on IN1-17) and\n * `IN1-17` (`relationship`, whose value translation needs a Table 0063 to v3 RoleCode ConceptMap\n * this library does not carry).\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 { toFhirIdentifier } from \"../datatypes/identifier.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 { dataAbsent, reference } from \"./reference.js\";\n\n/**\n * The canonical URL of the subscriber-id extension the IN1-10 and IN1-49 rows assign, transcribed\n * from the segment map's own `Coverage.extension.url` assignment.\n *\n * @example\n * ```ts\n * import { COVERAGE_SUBSCRIBER_ID_EXTENSION_URL } from \"@cosyte/transform\";\n * COVERAGE_SUBSCRIBER_ID_EXTENSION_URL.endsWith(\"extension-subscriberId\"); // true\n * ```\n */\nexport const COVERAGE_SUBSCRIBER_ID_EXTENSION_URL =\n \"http://hl7.org/fhir/5.0/StructureDefinition/extension-subscriberId\";\n\n/**\n * The `data-absent-reason` code carried by `Coverage.status`, the one FHIR-required element of this\n * resource that no published row of the segment map grounds.\n *\n * @example\n * ```ts\n * import { COVERAGE_STATUS_UNKNOWN } from \"@cosyte/transform\";\n * COVERAGE_STATUS_UNKNOWN; // \"unknown\"\n * ```\n */\nexport const COVERAGE_STATUS_UNKNOWN = \"unknown\";\n\n/**\n * The Table 0203 identifier-type code the IN1-10 row conditions its subscriber-id assignment on\n * (`IF CX.5 IS \"SN\"`, Subscriber Number). Any other identifier type leaves that row unapplied.\n *\n * @example\n * ```ts\n * import { IN1_SUBSCRIBER_NUMBER_TYPE } from \"@cosyte/transform\";\n * IN1_SUBSCRIBER_NUMBER_TYPE; // \"SN\"\n * ```\n */\nexport const IN1_SUBSCRIBER_NUMBER_TYPE = \"SN\";\n\n/**\n * Every `IN1` occurrence a message carries, in message order. One Coverage is created per\n * occurrence, per the IG message map's INSURANCE group.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // collectCoverages(parseHL7(raw)).length; // one entry per IN1 in the message\n * ```\n */\nexport function collectCoverages(msg: Hl7Message): readonly Segment[] {\n return msg.allSegments().filter((seg) => seg.type === \"IN1\");\n}\n\n/**\n * The insurance company name an IN1 carries, read from XON.1 of IN1-4, or `\"\"` when that component\n * carries nothing. The only row of the segment map that grounds the required `payor`.\n *\n * @param in1 - The `IN1` `@cosyte/hl7` `Segment`.\n * @example\n * ```ts\n * // insuranceCompanyName(in1); // the XON.1 organization name, verbatim\n * ```\n */\nexport function insuranceCompanyName(in1: Segment): string {\n return in1.field(4).repetitions[0]?.components[0]?.subcomponents[0] ?? \"\";\n}\n\n/**\n * The value-free diagnostics for the IN1 rows this library reads and deliberately does not build:\n * the payer address and the two policy-holder rows (each an Organization resource), the subscriber\n * (a Patient or RelatedPerson reference), and the relationship, whose value translation needs a\n * table this library does not carry.\n *\n * Raised for the occurrence whether or not the Coverage itself is emitted, so a deferred row a\n * message actually valued is in the issues list rather than silently absent.\n *\n * @param in1 - The `IN1` `@cosyte/hl7` `Segment`.\n * @example\n * ```ts\n * // deferredCoverageIssues(in1).length; // one per valued deferred row\n * ```\n */\nexport function deferredCoverageIssues(in1: Segment): readonly TransformIssue[] {\n const deferred: readonly (readonly [number, string])[] = [\n [5, \"Coverage.payer\"],\n [10, \"Coverage.policyHolder\"],\n [11, \"Coverage.policyHolder\"],\n [16, \"Coverage.subscriber\"],\n [17, \"Coverage.relationship\"],\n ];\n const issues: TransformIssue[] = [];\n for (const [field, path] of deferred) {\n if (in1.field(field).value !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `IN1.${String(field)}`, path));\n }\n }\n return issues;\n}\n\n/** Build `Coverage.identifier` from IN1-2, carrying CWE.1 and declaring a coding system it drops. */\nfunction buildIdentifier(in1: Segment, issues: TransformIssue[]): FhirComplex | undefined {\n const cwe = in1.field(2).asCwe();\n const planId = cwe.identifier;\n if (planId === undefined || planId === \"\") return undefined;\n if (cwe.nameOfCodingSystem !== undefined && cwe.nameOfCodingSystem !== \"\") {\n // A coding-system mnemonic names a table, not an identifier namespace: never an Identifier.system.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"IN1.2\", \"Coverage.identifier.system\"),\n );\n }\n return complex([{ name: \"value\", value: primitive(planId) }]);\n}\n\n/** One subscriber-id extension carrying a CX field as its `valueIdentifier`, or `undefined`. */\nfunction subscriberIdExtension(\n in1: Segment,\n field: number,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const identifier = toFhirIdentifier(in1.field(field).asCx(), ctx);\n issues.push(...identifier.issues);\n if (identifier.value === undefined) return undefined;\n return complex([\n { name: \"url\", value: primitive(COVERAGE_SUBSCRIBER_ID_EXTENSION_URL) },\n { name: \"valueIdentifier\", value: identifier.value },\n ]);\n}\n\n/** Build `Coverage.period` from IN1-12 / IN1-13, or `undefined` when neither is valued. */\nfunction buildPeriod(\n in1: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n for (const [field, name] of [\n [12, \"start\"],\n [13, \"end\"],\n ] as const) {\n if (in1.field(field).value === \"\") continue;\n const converted = toFhirDateTime(in1.field(field).asTs(), ctx.options);\n issues.push(...converted.issues);\n if (converted.value !== undefined) props.push({ name, value: primitive(converted.value) });\n }\n return props.length === 0 ? undefined : complex(props);\n}\n\n/**\n * Build a FHIR `Coverage` resource node from one `IN1` occurrence, wired to the bundle's Patient.\n * Returns `{ value: undefined }` when IN1-4 names no insurance company, because `payor` is required\n * by R4 and no other row of the segment map grounds it.\n *\n * @param in1 - The `IN1` `@cosyte/hl7` `Segment`.\n * @param patientFullUrl - The bundle's Patient fullUrl, for `beneficiary` (required 1..1).\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @param v2Location - The occurrence's v2 location, for the withholding diagnostic (e.g. `IN1[0]`).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const in1 = parseHL7(raw).segments(\"IN1\")[0];\n * // const { value } = buildCoverage(in1!, \"urn:uuid:pat\", {}, \"IN1[0]\");\n * ```\n */\nexport function buildCoverage(\n in1: Segment,\n patientFullUrl: string,\n ctx: TransformContext,\n v2Location: string,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // payor is required 1..1 and IN1-4 is its only source: no name, no coverage.\n const payerName = insuranceCompanyName(in1);\n if (payerName === \"\") {\n return {\n value: undefined,\n issues: [issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, v2Location, \"Coverage.payor\")],\n };\n }\n\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Coverage\") },\n ];\n\n // IN1-10 (IF CX.5 IS \"SN\") and IN1-49 -> the subscriber-id extension, in map sort order.\n const extensions: FhirComplex[] = [];\n if (in1.field(10).asCx().identifierTypeCode === IN1_SUBSCRIBER_NUMBER_TYPE) {\n const groupId = subscriberIdExtension(in1, 10, ctx, issues);\n if (groupId !== undefined) extensions.push(groupId);\n }\n if (in1.field(49).value !== \"\") {\n const insuredId = subscriberIdExtension(in1, 49, ctx, issues);\n if (insuredId !== undefined) extensions.push(insuredId);\n }\n if (extensions.length > 0) props.push({ name: \"extension\", value: list(extensions) });\n\n // IN1-2 -> identifier.\n const identifier = buildIdentifier(in1, issues);\n if (identifier !== undefined) props.push({ name: \"identifier\", value: list([identifier]) });\n\n // No row grounds a coverage status: value-absent, declared, never asserted.\n issues.push(issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, v2Location, \"Coverage.status\"));\n props.push({ name: \"status\", value: dataAbsent(COVERAGE_STATUS_UNKNOWN) });\n\n // IN1-15 -> type.\n const type = toFhirCodeableConcept(in1.field(15).asCwe(), ctx);\n issues.push(...type.issues);\n if (type.value !== undefined) props.push({ name: \"type\", value: type.value });\n\n // The message map's wiring: Coverage.beneficiary.reference = Patient[1].id.\n props.push({ name: \"beneficiary\", value: reference(patientFullUrl) });\n\n // IN1-12 / IN1-13 -> period.\n const period = buildPeriod(in1, ctx, issues);\n if (period !== undefined) props.push({ name: \"period\", value: period });\n\n // IN1-4 -> payor. The insurer is named, and the Organization it would resolve to is declared.\n props.push({\n name: \"payor\",\n value: list([complex([{ name: \"display\", value: primitive(payerName) }])]),\n });\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"IN1.4\", \"Coverage.payor\"));\n\n return { value: complex(props), issues };\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) | {@link toFhirDateTime} |\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 * | (SPM children) | `DiagnosticReport.specimen` | reference wiring from the assembler |\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`. `.specimen` carries only the Specimens the\n * assembler has already emitted into this bundle, so the reference never resolves to nothing.\n * Deferred and flagged elsewhere, not silently mapped: OBR-32/34/35 performers (need\n * PractitionerRole resources), the ORU map's own OBR-to-Specimen row (4.2.2, distinct from the SPM\n * one), 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 * @param specimenFullUrls - The `urn:uuid:` fullUrls of this group's emitted `Specimen`s → `.specimen`.\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 specimenFullUrls: readonly string[] = [],\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.specimen → the emitted Specimens of this group (ORU map row 4.2.7.1's own\n // assignment, `DiagnosticReport[1].specimen.reference = Specimen[n].id`).\n if (specimenFullUrls.length > 0) {\n props.push({ name: \"specimen\", value: list(specimenFullUrls.map((u) => reference(u))) });\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, meaning `CA`/`OB`/`UN` (whose IG target is\n * a `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/**\n * The same Encounter carrying one `diagnosis` entry per Condition the bundle holds, per the ADT_A01\n * message map's `Encounter[1].diagnosis.reference = Condition[1].id` row. Each entry's `condition`\n * points at that Condition's `fullUrl`, so the link resolves inside the bundle.\n *\n * Applied after the diagnoses are built, because the Encounter joins the bundle before them and the\n * produced nodes are immutable: this returns a new node rather than mutating the emitted one.\n *\n * @param encounter - The Encounter node already in the bundle.\n * @param conditionFullUrls - The fullUrls of the Conditions emitted for the same message, in order.\n * @example\n * ```ts\n * // withEncounterDiagnosis(encounter, [\"urn:uuid:cond-1\"]); // adds one diagnosis entry\n * ```\n */\nexport function withEncounterDiagnosis(\n encounter: FhirComplex,\n conditionFullUrls: readonly string[],\n): FhirComplex {\n if (conditionFullUrls.length === 0) return encounter;\n const entries = conditionFullUrls.map((url) =>\n complex([{ name: \"condition\", value: reference(url) }]),\n );\n return complex([\n ...encounter.properties.filter((p) => p.name !== \"diagnosis\"),\n { name: \"diagnosis\", value: list(entries) },\n ]);\n}\n\n/**\n * The Encounter that should replace the emitted one once the message's diagnoses exist: the same\n * resource carrying the back-references, put through the conservative-emit gate first. When the\n * gate refuses the linked draft the ORIGINAL Encounter is returned unchanged and the link is\n * declared {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED}, so a detail never costs the visit.\n *\n * The gate is a parameter rather than a call into the assembler, so what \"the gate refuses this\"\n * means stays in one place and the refusal branch is reachable from a test without a hand-built\n * invalid resource: the same shape the allergy emit path uses.\n *\n * @param encounter - The Encounter node already in the bundle.\n * @param conditionFullUrls - The fullUrls of the Conditions emitted for the same message, in order.\n * @param gate - The conservative-emit predicate: `true` when the linked Encounter may replace it.\n * @example\n * ```ts\n * // emitEncounterDiagnosis(encounter, [\"urn:uuid:cond-1\"], () => true).value; // the linked one\n * ```\n */\nexport function emitEncounterDiagnosis(\n encounter: FhirComplex,\n conditionFullUrls: readonly string[],\n gate: (resource: FhirComplex) => boolean,\n): ConvertResult<FhirComplex> {\n const linked = withEncounterDiagnosis(encounter, conditionFullUrls);\n if (linked === encounter || gate(linked)) return { value: linked, issues: [] };\n return {\n value: encounter,\n issues: [issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"DG1\", \"Encounter.diagnosis\")],\n };\n}\n","/**\n * PR1 to FHIR `Procedure`: the procedures an admit states, carried into the bundle instead of lost\n * between the v2 feed and the FHIR record. Grounded firsthand on the IG **PR1 to Procedure** segment\n * map and the **ADT_A01 to Bundle** message map (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-pr1-to-procedure.html`, `ConceptMap-message-adt-a01-to-bundle.html`), which\n * wires `Procedure.subject.reference` to the bundle's Patient and creates one Procedure per PR1.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | PR1 (narrative row) | `status` (required 1..1) | the row's own `unknown`, the value it directs when the message context does not determine one |\n * | PR1-3 Procedure Code (CNE) | `code` | {@link toFhirCodeableConcept} (structural, no IG value map) |\n * | PR1-4 Procedure Description (ST) | `code.text` | verbatim, only `IF PR1-3.9 NOT VALUED` |\n * | PR1-5 Procedure Date/Time (DTM) | `performedDateTime` / `performedPeriod.start` | {@link toFhirDateTime}, branched on PR1-7 |\n * | PR1-6 Procedure Functional Type (CWE) | `category` | {@link toFhirCodeableConcept} |\n * | PR1-7 Procedure Minutes (NM) | `performedPeriod.end` | the period start plus that many minutes |\n * | PR1-15 Associated Diagnosis Code (CWE) | `reasonCode` | {@link toFhirCodeableConcept} |\n * | PR1-19 Procedure Identifier (EI) | `identifier` | {@link toFhirEntityIdentifier} |\n * | (message-map wiring) | `subject` (required 1..1) | the bundle's Patient |\n *\n * **Fail-safes (never a confident wrong procedure).**\n * - **The status is the one the map directs, never one the message did not state.** The map's own\n * sort-order 0 row reads \"The value mapping depends on the message context where the PR1 is used\n * and to be determined by the implementer. If not clear, use `unknown`\". No PR1 component states a\n * procedure status, so `unknown` is the answer, and `completed` or `in-progress` is never selected\n * from a message that did not say so.\n * - **A period needs a start precise enough to add minutes to.** PR1-7 is minutes, and the map's own\n * comment requires PR1-5 to reach at least minute granularity before a `performedPeriod` is built\n * from the pair. This library goes by what the conversion could actually carry: a PR1-5 that\n * reduces to date precision (a naked or partial-precision timestamp, per {@link toFhirDateTime})\n * is not a start a duration can be added to, so the value stays `performedDateTime` and the end is\n * declared {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} rather than computed from a date.\n * - **The description defers to the coded field's own text.** The PR1-4 row is conditioned\n * `IF PR1-3.9 NOT VALUED`, so an original text the sender put in the coded field wins and PR1-4 is\n * dropped and declared rather than overwriting it.\n *\n * Deferred and flagged, never silently mapped: `PR1-8`, `PR1-11` and `PR1-12` (`performer.actor`, a\n * Practitioner resource this library does not build), `PR1-23` (`location`, likewise a Location),\n * `PR1-25` (`partOf`, a reference resolved by identifier rather than by bundle position) and\n * `PR1-16`, whose target `Procedure.code.value` is not an element of R4's `Procedure.code`.\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, toFhirEntityIdentifier, withCodeableText } from \"./reference.js\";\n\n/**\n * The `Procedure.status` the PR1 map's own narrative row directs when the message context does not\n * determine one. No PR1 component carries a procedure status, so this is the value every Procedure\n * built from a PR1 carries.\n *\n * @example\n * ```ts\n * import { PROCEDURE_STATUS_UNKNOWN } from \"@cosyte/transform\";\n * PROCEDURE_STATUS_UNKNOWN; // \"unknown\"\n * ```\n */\nexport const PROCEDURE_STATUS_UNKNOWN = \"unknown\";\n\n/** A v2 procedure-minutes value this library will add to a start: a plain non-negative integer. */\nconst WHOLE_MINUTES = /^\\d+$/;\n\n/** A FHIR `dateTime` carrying a time of day, captured so minutes can be added to it faithfully. */\nconst ZONED_DATE_TIME =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\n\n/**\n * Every `PR1` occurrence a message carries, in message order. One Procedure is created per\n * occurrence, per the IG message map's `0..-1` cardinality on the PROCEDURE group.\n *\n * @param msg - The parsed `@cosyte/hl7` message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // collectProcedures(parseHL7(raw)).length; // one entry per PR1 in the message\n * ```\n */\nexport function collectProcedures(msg: Hl7Message): readonly Segment[] {\n return msg.allSegments().filter((seg) => seg.type === \"PR1\");\n}\n\n/**\n * Add whole minutes to a FHIR `dateTime` that carries a time of day, preserving its stated offset and\n * its fractional seconds exactly. Returns `undefined` when the value is not a full zoned timestamp,\n * because a date is not a start a duration can be added to.\n *\n * @param start - The FHIR `dateTime` lexical value the conversion produced.\n * @param minutes - The number of minutes to add.\n * @example\n * ```ts\n * import { addMinutes } from \"@cosyte/transform\";\n * addMinutes(\"2026-01-15T10:30:00-05:00\", 45); // \"2026-01-15T11:15:00-05:00\"\n * addMinutes(\"2026-01-15\", 45); // undefined\n * ```\n */\nexport function addMinutes(start: string, minutes: number): string | undefined {\n const parts = ZONED_DATE_TIME.exec(start);\n if (parts === null) return undefined;\n const [, year, month, day, hour, minute, second, fraction, zone] = parts;\n // Wall-clock arithmetic in a fixed offset: the parts are placed as if they were UTC and read back\n // the same way, so the stated offset is carried through untouched rather than re-derived.\n const wall = new Date(0);\n // Never NaN: the pattern above admits only four-digit years and two-digit parts, and every\n // out-of-range part rolls over. The one way out of range is the SHIFT, which is guarded below.\n wall.setUTCFullYear(Number(year), Number(month) - 1, Number(day));\n wall.setUTCHours(Number(hour), Number(minute), Number(second), 0);\n const shifted = new Date(wall.getTime() + minutes * 60_000);\n if (Number.isNaN(shifted.getTime())) return undefined;\n const pad = (value: number, width: number): string => String(value).padStart(width, \"0\");\n const rendered =\n `${pad(shifted.getUTCFullYear(), 4)}-${pad(shifted.getUTCMonth() + 1, 2)}` +\n `-${pad(shifted.getUTCDate(), 2)}T${pad(shifted.getUTCHours(), 2)}` +\n `:${pad(shifted.getUTCMinutes(), 2)}:${pad(shifted.getUTCSeconds(), 2)}`;\n return `${rendered}${fraction ?? \"\"}${zone ?? \"\"}`;\n}\n\n/**\n * The value-free diagnostics for the PR1 rows this library reads and deliberately does not build:\n * the three practitioner roles, the treating organizational unit, the parent procedure, and the code\n * modifier whose target is not an R4 element.\n *\n * Raised for the occurrence whether or not the Procedure itself is emitted, so a deferred row a\n * message actually valued is in the issues list rather than silently absent.\n *\n * @param pr1 - The `PR1` `@cosyte/hl7` `Segment`.\n * @example\n * ```ts\n * // deferredProcedureIssues(pr1).length; // one per valued deferred row\n * ```\n */\nexport function deferredProcedureIssues(pr1: Segment): readonly TransformIssue[] {\n const deferred: readonly (readonly [number, string])[] = [\n [8, \"Procedure.performer.actor\"],\n [11, \"Procedure.performer.actor\"],\n [12, \"Procedure.performer.actor\"],\n [16, \"Procedure.code.value\"],\n [23, \"Procedure.location\"],\n [25, \"Procedure.partOf\"],\n ];\n const issues: TransformIssue[] = [];\n for (const [field, path] of deferred) {\n if (pr1.field(field).value !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `PR1.${String(field)}`, path));\n }\n }\n return issues;\n}\n\n/** Build `Procedure.code` from PR1-3, with PR1-4 supplying text only where PR1-3.9 is not valued. */\nfunction buildCode(\n pr1: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const cne = pr1.field(3).asCwe();\n const description = pr1.field(4).value;\n const originalTextValued = cne.originalText !== undefined && cne.originalText !== \"\";\n const coded = toFhirCodeableConcept(cne, ctx);\n issues.push(...coded.issues);\n\n if (description !== \"\" && originalTextValued) {\n // The row's own condition: an original text in the coded field wins, so PR1-4 is not carried.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PR1.4\", \"Procedure.code.text\"));\n return coded.value;\n }\n if (coded.value === undefined) {\n return description === \"\"\n ? undefined\n : complex([{ name: \"text\", value: primitive(description) }]);\n }\n return description === \"\" ? coded.value : withCodeableText(coded.value, description);\n}\n\n/** Build `Procedure.performed[x]` from PR1-5 and PR1-7, per the map's three conditioned rows. */\nfunction buildPerformed(\n pr1: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { name: string; value: FhirNode } | undefined {\n if (pr1.field(5).value === \"\") return undefined;\n const converted = toFhirDateTime(pr1.field(5).asTs(), ctx.options);\n issues.push(...converted.issues);\n if (converted.value === undefined) return undefined;\n\n const minutesRaw = pr1.field(7).value;\n if (minutesRaw === \"\") {\n return { name: \"performedDateTime\", value: primitive(converted.value) };\n }\n\n const end = WHOLE_MINUTES.test(minutesRaw)\n ? addMinutes(converted.value, Number(minutesRaw))\n : undefined;\n if (end === undefined) {\n // Either PR1-5 did not reach a time this conversion could carry, or PR1-7 is not a number of\n // minutes: no end is computed from a start that is not one, and the loss is declared.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PR1.7\", \"Procedure.performedPeriod.end\"),\n );\n return { name: \"performedDateTime\", value: primitive(converted.value) };\n }\n return {\n name: \"performedPeriod\",\n value: complex([\n { name: \"start\", value: primitive(converted.value) },\n { name: \"end\", value: primitive(end) },\n ]),\n };\n}\n\n/**\n * Build a FHIR `Procedure` resource node from one `PR1` occurrence, wired to the bundle's Patient.\n * Always produces a Procedure: a PR1 states that a procedure happened, and `status` is grounded on\n * the map's own row rather than on the message, so nothing here can fail to be groundable.\n *\n * @param pr1 - The `PR1` `@cosyte/hl7` `Segment`.\n * @param patientFullUrl - The bundle's Patient fullUrl, for `subject` (required 1..1).\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const pr1 = parseHL7(raw).segments(\"PR1\")[0];\n * // const { value } = buildProcedure(pr1!, \"urn:uuid:pat\", {});\n * ```\n */\nexport function buildProcedure(\n pr1: Segment,\n patientFullUrl: string,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n const props: { name: string; value: FhirNode }[] = [\n { name: \"resourceType\", value: primitive(\"Procedure\") },\n ];\n\n // PR1-19 EI -> identifier. The assigning authority is never turned into a system URI.\n const entity = toFhirEntityIdentifier(pr1.field(19));\n if (entity.identifier !== undefined) {\n props.push({ name: \"identifier\", value: list([entity.identifier]) });\n }\n if (entity.authorityValued) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PR1.19\", \"Procedure.identifier.system\"),\n );\n }\n\n // The map's own narrative row: the status a PR1 grounds when the message context states none.\n props.push({ name: \"status\", value: primitive(PROCEDURE_STATUS_UNKNOWN) });\n\n // PR1-6 -> category.\n const category = toFhirCodeableConcept(pr1.field(6).asCwe(), ctx);\n issues.push(...category.issues);\n if (category.value !== undefined) props.push({ name: \"category\", value: category.value });\n\n // PR1-3 -> code, PR1-4 -> code.text (only where the coded field carries no original text).\n const code = buildCode(pr1, ctx, issues);\n if (code !== undefined) props.push({ name: \"code\", value: code });\n\n // The message map's wiring: Procedure.subject.reference = Patient[1].id.\n props.push({ name: \"subject\", value: reference(patientFullUrl) });\n\n // PR1-5 (+ PR1-7) -> performedDateTime or performedPeriod.\n const performed = buildPerformed(pr1, ctx, issues);\n if (performed !== undefined) props.push(performed);\n\n // PR1-15 -> reasonCode.\n const reason = toFhirCodeableConcept(pr1.field(15).asCwe(), ctx);\n issues.push(...reason.issues);\n if (reason.value !== undefined) props.push({ name: \"reasonCode\", value: list([reason.value]) });\n\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, and a pharmacy order with no give code (no `medication[x]`) is withheld.\n * - **Condition**: `subject` (1..1 Reference) is required, so a diagnosis whose Patient was withheld\n * is withheld too rather than emitted with a subject that resolves to nothing in the bundle.\n * - **Procedure**: `status` (1..1 code) and `subject` (1..1 Reference) are both required. The status\n * carries its R4 required binding, so the fixed value the segment map directs is checked against the\n * event-status value set rather than trusted.\n * - **Coverage**: `status` (1..1 code), `beneficiary` (1..1 Reference) and `payor` (1..* Reference)\n * are all required. No published row grounds the status, so it ships as a value-absent element\n * carrying `data-absent-reason`, which satisfies the cardinality without asserting a code; a\n * coverage that lost its beneficiary or its payer is withheld.\n * - **AllergyIntolerance**: `patient` (1..1 Reference) is required, and the three coded elements the IG\n * value maps target (`type`, `category`, `criticality`) carry their R4 **required** bindings, so a map\n * row that ever produced a non-member code would withhold the resource rather than ship an allergy a\n * consumer's value set does not admit. `clinicalStatus` is modelled so the element the guide fixes is\n * not read as unknown; its presence is separately enforced by `@cosyte/fhir`'s own ait-1 check.\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, and 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 // Condition: subject (1..1 Reference) is required. A DG1 with no bundle Patient to anchor never\n // reaches this gate (the assembly withholds it first); the entry is the defence behind that.\n type: \"Condition\",\n elements: {\n subject: { min: 1, max: 1, types: [\"Reference\"] },\n },\n },\n {\n // Procedure: status (1..1 code) and subject (1..1 Reference) are both required. The status\n // binding is R4's required EventStatus set, so the value the PR1 map's own row directs is\n // checked rather than trusted, and a Procedure carrying anything else is withheld.\n type: \"Procedure\",\n elements: {\n status: {\n min: 1,\n max: 1,\n types: [\"code\"],\n binding: {\n strength: \"required\",\n codes: [\n \"preparation\",\n \"in-progress\",\n \"not-done\",\n \"on-hold\",\n \"stopped\",\n \"completed\",\n \"entered-in-error\",\n \"unknown\",\n ],\n },\n },\n subject: { min: 1, max: 1, types: [\"Reference\"] },\n },\n },\n {\n // Coverage: status (1..1 code), beneficiary (1..1 Reference) and payor (1..* Reference) are all\n // required. The status is modelled WITHOUT its required binding on purpose: no published row\n // grounds a coverage status, so the element ships value-absent with a data-absent-reason\n // extension, which satisfies the cardinality while asserting no member of the value set.\n type: \"Coverage\",\n elements: {\n status: { min: 1, max: 1, types: [\"code\"] },\n beneficiary: { min: 1, max: 1, types: [\"Reference\"] },\n payor: { min: 1, max: UNBOUNDED, types: [\"Reference\"] },\n },\n },\n {\n // AllergyIntolerance: patient (1..1 Reference) is required, so an AL1 with no bundle Patient to\n // anchor is withheld rather than emitted with a dangling reference. The three coded elements carry\n // their R4 required bindings: an unmapped code leaves its element absent (never a neighbour), and a\n // value-absent element carrying only the IG's alternate-codes extension is not a code to check.\n type: \"AllergyIntolerance\",\n elements: {\n clinicalStatus: { min: 0, max: 1, types: [\"CodeableConcept\"] },\n type: {\n min: 0,\n max: 1,\n types: [\"code\"],\n binding: { strength: \"required\", codes: [\"allergy\", \"intolerance\"] },\n },\n category: {\n min: 0,\n max: UNBOUNDED,\n types: [\"code\"],\n binding: {\n strength: \"required\",\n codes: [\"food\", \"medication\", \"environment\", \"biologic\"],\n },\n },\n criticality: {\n min: 0,\n max: 1,\n types: [\"code\"],\n binding: { strength: \"required\", codes: [\"low\", \"high\", \"unable-to-assess\"] },\n },\n code: { min: 0, max: 1, types: [\"CodeableConcept\"] },\n patient: { min: 1, max: 1, types: [\"Reference\"] },\n onsetDateTime: { min: 0, max: 1, types: [\"dateTime\"] },\n reaction: { min: 0, max: UNBOUNDED, types: [\"BackboneElement\"] },\n },\n },\n {\n // Appointment: status (1..1 code) and participant (1..* BackboneElement) are both required, so 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, so 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 * TQ1 (Timing/Quantity) → the FHIR `Timing` an order's request carries, grounded firsthand on the IG\n * **Segment TQ1 to MedicationRequest** and **Segment TQ1 to ServiceRequest** ConceptMaps and the\n * **Datatype RPT to Timing** ConceptMap it delegates to (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-tq1-to-medicationrequest.html`, `ConceptMap-segment-tq1-to-servicerequest.html`,\n * `ConceptMap-datatype-rpt-to-timing.html`).\n *\n * A pharmacy order that reaches this library as `RXO` + `TQ1` used to produce a `MedicationRequest`\n * with a drug, a dose and a route and **no schedule at all**, so \"give 5 mg every 4 hours for 3 days\"\n * and \"give 5 mg once\" were the same resource. This module is the schedule: what the TQ1 grounds, and\n * an explicit refusal for everything it does not.\n *\n * | v2 field | FHIR target | via |\n * |---|---|---|\n * | TQ1-3 Repeat Pattern (RPT) | `dosageInstruction.timing` / `occurrenceTiming` | the RPT rows below |\n * | TQ1-7 Start date/time (DTM) | that Timing's `repeat.boundsPeriod.start` | {@link toFhirDateTime} |\n * | TQ1-8 End date/time (DTM) | that Timing's `repeat.boundsPeriod.end` | {@link toFhirDateTime} |\n * | TQ1-10 Condition text (TX) | `dosageInstruction.additionalInstruction.text` | whole field, verbatim |\n * | TQ1-11 Text instruction (TX) | `MedicationRequest.text` (a `Narrative`) | whole field, XML-escaped |\n *\n * and inside TQ1-3, the **expressible RPT components and only those**:\n *\n * | RPT component | FHIR target | via |\n * |---|---|---|\n * | RPT.1 Repeat Pattern Code | `Timing.code` (system `v2-0335`, code verbatim) | {@link isRepeatPatternCode} |\n * | RPT.5 Period Quantity | `Timing.repeat.period` (decimal) | precision-exact, never rescaled |\n * | RPT.6 Period Units | `Timing.repeat.periodUnit` (code) | {@link UNITS_OF_TIME} membership |\n * | RPT.8 Event | `Timing.repeat.when` (code) | {@link TIMING_EVENT_VALUE_MAP} |\n *\n * **RPT.5 and RPT.6 are a pair, not two independent rows**, because R4 constrains `Timing.repeat`\n * beyond its element types: `tim-2` requires period units wherever a period exists, and `tim-5`\n * requires the period to be non-negative. So a period with no units, a unit with no period, and a\n * negative period are each refused whole rather than emitted, for the reason below.\n *\n * **A schedule is fully grounded or absent and flagged.** Everything here is all-or-nothing, because\n * a half-built timing reads to the receiving system as a complete instruction: an order whose TQ1\n * says \"every 4 hours, but only between meals\" must not arrive as \"every 4 hours\". So **any** of the\n * conditions below withholds the whole `Timing` (no partial repeat, no lone `boundsPeriod`) and\n * raises a value-free issue naming the offending component:\n *\n * - An RPT component **outside** the four expressible rows is valued, at **any** position the wire\n * carried, not just at one of the seven remaining published ones (see\n * {@link EXPRESSIBLE_RPT_COMPONENTS}). `RPT.2` Calendar Alignment, `RPT.7` Institution Specified\n * Time and `RPT.11` General Timing Specification have **no FHIR target row at all** in the\n * published map; `RPT.3`/`RPT.4` (the two ends of the day-of-week range) carry the narrative\n * `/translate number to day/` with no published table behind it; `RPT.9`/`RPT.10` Event Offset\n * carry `/convert to minutes based on RPT.10/`, a rescale this library never performs.\n * - An `RPT.1` with no HL70335 row, an `RPT.8` with no HL70528 row targeting `v3-TimingEvent`, an\n * `RPT.5` that is not a faithful FHIR `decimal`, or an `RPT.6` outside FHIR's required-bound\n * `UnitsOfTime`. Each would need a value invented to be carried.\n * - An `RPT.1`, `RPT.6` or `RPT.8` the message declared under a **foreign coding system**. All three\n * are read against a bound table, and a site's local `AC` need not mean the published\n * `v3-TimingEvent` concept that shares its spelling; asserting it would be exactly the confident\n * wrong value this library exists to refuse.\n * - An `RPT.5` **without** an `RPT.6`, an `RPT.6` **without** an `RPT.5`, or a **negative** `RPT.5`.\n * The two are `0..1` each on the wire, so all three shapes arrive in real traffic, and every one of\n * them produces a `Timing.repeat` that **fails a published R4 invariant**: `tim-2`\n * (`period.empty() or periodUnit.exists()`) and `tim-5` (\"period SHALL be a non-negative value\").\n * `@cosyte/fhir` models no `Timing` constraint, so the conservative-emit gate cannot catch any of\n * them and a receiving system would be handed `{\"period\": 6}` or `{\"period\": -6}` as a grounded\n * repeat to compute against. \"Every minus six hours\" is not a schedule.\n * - A **schedule-narrowing** field is valued: TQ1-4 Explicit Time, TQ1-5 Relative Time and Units,\n * TQ1-6 Service Duration, TQ1-12 Conjunction, TQ1-13 Occurrence duration, TQ1-14 Total\n * occurrences. Each one *narrows* the schedule, so a Timing built without it is not a subset of\n * what the sender said, it is a different and larger instruction.\n * - A valued TQ1-7/TQ1-8 that yields no FHIR dateTime, or a TQ1-8 that precedes TQ1-7.\n * - More than one TQ1 on the order, or more than one **valued** repetition of TQ1-3: mapping one and\n * discarding the rest would silently drop half a regimen. A repetition that carries no value is\n * not one of them: `Q4H~`, `~Q4H` and `Q4H~\"\"` each send exactly one repeat pattern, and the\n * single valued repetition is the one every component is read from, wherever on the wire it sat.\n *\n * **TQ1-2 Quantity and TQ1-9 Priority are different**, and do *not* withhold the timing: the IG maps\n * them to the dose and the priority, both of which the RXO/OBR path already grounds. They are flagged\n * dropped and neither field is touched, so a TQ1 that carries them still contributes its schedule.\n *\n * **Only a valued field is read, and \"valued\" is one question asked in the shape of the datatype it\n * is asked about.** An absent field and the HL7 explicit null (the two-character literal `\"\"`, the\n * wire saying this position carries no value) are both read as carrying nothing, at every\n * granularity: no FHIR element is written from either, no diagnostic is raised about either, and a\n * TQ1 whose only content was a null contributed nothing and is reported as unreached. The null\n * marker is *text* to a projection that reads a field whole, so reading one as a value would put two\n * quotation marks into a dosing narrative as though a clinician wrote them.\n *\n * A **composite** field (every TQ1 field but the two `TX` rows) is valued when some subcomponent\n * carries a value, which is also how a repetition and a component are decided, so a structural empty\n * is never read as content anywhere in the composite path. A **primitive** `TX` row is valued when\n * the wire put any character in the field at all, because that datatype has no positions to be empty\n * (see {@link freeText}); asking it the composite question dropped a row of nothing but raw\n * delimiters, which this module's own rule calls content.\n *\n * **A valued free-text row that cannot be placed is flagged, never dropped in silence**, which is\n * the difference between it and the two states above. Two shapes reach that arm: content the display\n * projection resolves away entirely (a `\\H\\`/`\\N\\` highlight pair with nothing between it), and a\n * TQ1-11 of nothing but whitespace, which R4's `txt-2` (\"the narrative SHALL have some\n * non-whitespace content\") forbids as a `Narrative`. Each raises a value-free\n * `TRANSFORM_ELEMENT_DROPPED` naming its own row and writes no element. TQ1-10 is not whitespace\n * tested: its target is a plain `string`, which R4 constrains no further, so a whitespace-only one\n * is carried exactly as sent.\n *\n * @packageDocumentation\n */\n\nimport { renderText, type EncodingCharacters, type RawRepetition, type Segment } from \"@cosyte/hl7\";\nimport { complex, decimal, list, primitive, 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 {\n isRepeatPatternCode,\n translateBound,\n TIMING_EVENT_VALUE_MAP,\n V2_0335_SYSTEM,\n} from \"../terminology/concept-map.js\";\nimport type { TransformContext } from \"../terminology/context.js\";\n\n/**\n * FHIR R4's `UnitsOfTime` value set: the **required** binding on `Timing.repeat.periodUnit`. RPT.6\n * carries a v2 period unit and the IG publishes no ConceptMap for that row, so the only faithful\n * carry is a code that is already a member; anything else would be an invented translation and is\n * refused instead.\n *\n * @example\n * ```ts\n * // UNITS_OF_TIME.has(\"h\"); // true -> RPT.6 \"h\" reaches Timing.repeat.periodUnit\n * // UNITS_OF_TIME.has(\"hr\"); // false -> refused, never translated to \"h\"\n * ```\n */\nexport const UNITS_OF_TIME: ReadonlySet<string> = Object.freeze(\n new Set([\"s\", \"min\", \"h\", \"d\", \"wk\", \"mo\", \"a\"]),\n);\n\n/** The UCUM coding-system mnemonics RPT.6 may declare and still be read as a `UnitsOfTime` code. */\nconst UCUM_MNEMONICS: ReadonlySet<string> = Object.freeze(new Set([\"UCUM\", \"ISO+\"]));\n\n/** The HL70335 coding-system mnemonics RPT.1 may declare and still be read as a table code. */\nconst HL70335_MNEMONICS: ReadonlySet<string> = Object.freeze(new Set([\"HL70335\", \"0335\"]));\n\n/**\n * Which request the TQ1 is read for. It selects the FHIR paths the diagnostics name and whether the\n * TQ1-10 / TQ1-11 free-text rows have a target at all (the IG's ServiceRequest map sends them\n * elsewhere, and the service path carries only the timing here).\n *\n * @example\n * ```ts\n * // const reading = readTq1(group.tq1s, \"MedicationRequest\", ctx);\n * ```\n */\nexport type Tq1Target = \"MedicationRequest\" | \"ServiceRequest\";\n\n/**\n * What one order group's TQ1 occurrences ground, ready for a request builder to place: the `Timing`\n * (or `undefined` when it was absent or refused), the two free-text rows, the value-free diagnostics\n * raised reading them, and whether anything at all reached the request.\n *\n * @example\n * ```ts\n * // const { timing, issues, contributes } = readTq1(tq1s, \"ServiceRequest\", ctx);\n * ```\n */\nexport interface Tq1Reading {\n /** The FHIR `Timing` node, or `undefined` when the TQ1 grounded none or the schedule was refused. */\n readonly timing: FhirComplex | undefined;\n /** TQ1-10 Condition text, verbatim, for `dosageInstruction.additionalInstruction.text`. */\n readonly conditionText: string | undefined;\n /** TQ1-11 Text instruction, verbatim, for the `MedicationRequest.text` narrative. */\n readonly instructionText: string | undefined;\n /** The value-free diagnostics this reading raised, in emission order. */\n readonly issues: readonly TransformIssue[];\n /** Whether the TQ1 contributed anything to the request (what the completeness ledger marks on). */\n readonly contributes: boolean;\n}\n\n/** The R4 element TQ1-10 reaches on the medication path, for the diagnostics that name it. */\nconst CONDITION_TEXT_PATH = \"MedicationRequest.dosageInstruction.additionalInstruction.text\";\n\n/** The R4 element TQ1-11 reaches on the medication path, for the diagnostics that name it. */\nconst INSTRUCTION_TEXT_PATH = \"MedicationRequest.text\";\n\n/** The FHIR path of the timing element on each target: the `occurrence[x]`/`timing` choice differs. */\nfunction timingPath(target: Tq1Target): string {\n return target === \"MedicationRequest\"\n ? \"MedicationRequest.dosageInstruction.timing\"\n : \"ServiceRequest.occurrenceTiming\";\n}\n\n/**\n * The HL7 explicit null: the two literal quotation marks a sender writes to say \"this position\n * carries no value\". The parser already answers it at FIELD granularity, collapsing a field written\n * that way to zero repetitions; below that it survives as these two characters, so a repetition or a\n * component written as one is decided here.\n */\nconst EXPLICIT_NULL = '\"\"';\n\n/**\n * Whether one subcomponent carries a value. This is the module's single answer to \"did the wire say\n * anything at this position\", and every composite question below is built from it, so an explicit\n * null reads the same way wherever it sits rather than only where the parser happened to fold it.\n */\nfunction carriesValue(sub: string): boolean {\n return sub !== \"\" && sub !== EXPLICIT_NULL;\n}\n\n/** Whether one repetition of a composite field carries a value anywhere inside it. */\nfunction repetitionValued(rep: RawRepetition): boolean {\n return rep.components.some((c) => c.subcomponents.some(carriesValue));\n}\n\n/** Whether a composite field carries a value at all: one valued subcomponent in any repetition. */\nfunction isValued(seg: Segment, index: number): boolean {\n return seg.field(index).repetitions.some(repetitionValued);\n}\n\n/** The subcomponents of a 1-based component of one composite repetition. */\nfunction subcomponents(rep: RawRepetition, component: number): readonly string[] {\n return rep.components[component - 1]?.subcomponents ?? [];\n}\n\n/** Whether a 1-based component of one composite repetition carries a value. */\nfunction componentValued(rep: RawRepetition, component: number): boolean {\n return subcomponents(rep, component).some(carriesValue);\n}\n\n/** A 1-based subcomponent of a 1-based component, or `\"\"` when absent (a composite-encoded CWE part). */\nfunction subcomponent(rep: RawRepetition, component: number, sub: number): string {\n return subcomponents(rep, component)[sub - 1] ?? \"\";\n}\n\n/**\n * A field's wire text with the **structural empties** its canonical form drops put back, so a `TX`\n * primitive that ends in (or contains) a raw delimiter arrives with every character the sender sent.\n *\n * `Field.text` is byte-verbatim for content but structurally canonical: it strips each component's\n * trailing empty subcomponents and each repetition's trailing empty components (the parser's D-02),\n * so the wire `2 tabs^` projects as `2 tabs` and `a&^b` as `a^b`. On a composite field those empties\n * are absent positions and dropping them is right; on a `TX` primitive they are the last characters\n * of a clinical instruction. This walks the field's own repetition tree, which still records every\n * empty, and pads each surviving component back to the subcomponent count the wire carried and each\n * repetition back to its component count. **Only delimiter characters are ever added**: content is\n * copied across untouched, so every escape keeps the exact bytes the sender wrote, and a tree that\n * does not line up with the text (nothing observed produces one) leaves that stretch exactly as it\n * was rather than dropping any of it.\n *\n * @param text - The field's canonical wire text (`Field.text`).\n * @param repetitions - That same field's repetition tree (`Field.repetitions`).\n * @param enc - The message's encoding characters.\n * @example\n * ```ts\n * // restoreStructuralEmpties(\"2 tabs\", field.repetitions, enc); // \"2 tabs^\"\n * ```\n */\nexport function restoreStructuralEmpties(\n text: string,\n repetitions: readonly RawRepetition[],\n enc: EncodingCharacters,\n): string {\n const padded = (part: string, count: number): string => {\n const subs = part.split(enc.subcomponent);\n if (subs.length >= count) return part;\n return [...subs, ...Array.from({ length: count - subs.length }, () => \"\")].join(\n enc.subcomponent,\n );\n };\n return text\n .split(enc.repetition)\n .map((repetition, r) => {\n const components = repetitions[r]?.components ?? [];\n const parts = repetition.split(enc.component);\n const restored = parts.map((part, c) =>\n padded(part, components[c]?.subcomponents.length ?? 0),\n );\n // Components the canonicalization dropped whole: each contributes its own separator, plus the\n // separators between the empty subcomponents it carried.\n for (const dropped of components.slice(parts.length))\n restored.push(padded(\"\", dropped.subcomponents.length));\n return restored.join(enc.component);\n })\n .join(enc.repetition);\n}\n\n/**\n * What a `TX` free-text row projects to. Three outcomes, and the third is the one a boolean\n * `string | undefined` could not tell apart from the first: a field the wire **valued** whose whole\n * content the display projection resolves away (a lone `\\H\\`/`\\N\\` highlight pair, say). That is not\n * an absent field, it is content that arrived and cannot be placed, so it is flagged rather than\n * dropped in silence.\n */\ntype FreeTextReading =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"unplaceable\" }\n | { readonly kind: \"text\"; readonly text: string };\n\n/**\n * The **whole** content of a `TX` free-text field as display text.\n *\n * TQ1-10 and TQ1-11 are `TX`: a v2 **primitive**, with no component or subcomponent structure at\n * all, so a raw `^`, `&` or `~` inside one is *content* by definition. `Field.value` is documented\n * as the \"first-repetition, first-component, first-subcomponent value\" and would therefore truncate\n * `2 tabs^then 1 tab` to `2 tabs`, delivering a dosing instruction that lost its taper with nothing\n * to say so. So the whole field is read, through the parser's own renderer for a clinical narrative:\n * a read projection over byte-verbatim wire text that resolves the v2 escape sequences (`\\T\\` to a\n * literal `&`, `\\.br\\` to a line break) and **never fabricates**, preserving any sequence it cannot\n * render rather than guessing at it, over the text {@link restoreStructuralEmpties} repairs.\n *\n * **\"Valued\" is the PRIMITIVE's own question here, not the composite one.** A composite field is\n * valued when some subcomponent carries content, and asking that of a `TX` row contradicts the\n * paragraph above: a field of nothing but raw delimiters (`^`, `&`, `~`, `^&~`) produces only empty\n * positions, so the composite test calls it absent and drops the very characters this datatype\n * defines as content. The question a primitive asks is \"did the wire put anything in this field\",\n * and it is answered off the field's own repetition tree, which the parser leaves EMPTY for an\n * absent field and for the HL7 explicit null alike.\n *\n * **An HL7 explicit null is not a value.** The two-character literal `\"\"` is the wire's way of\n * saying this field carries nothing, and it projects as text as the two characters it is. The\n * parser folds a field written that way to zero repetitions, so it arrives here already\n * indistinguishable from an absent field: nothing to carry, and nothing dropped to flag.\n *\n * **A field that projects to nothing is not the same as either.** Display markup alone is still\n * content the sender put on the wire, so it yields `unplaceable` and its caller raises a value-free\n * diagnostic: silence there would be indistinguishable from a field that was never sent.\n */\nfunction freeText(seg: Segment, field: number): FreeTextReading {\n const f = seg.field(field);\n if (f.repetitions.length === 0) return { kind: \"absent\" };\n // The message's OWN delimiters, off the segment, never the defaults: a sender declares them in\n // MSH-2, and a repair that assumed \"^~&\" would put a character into a narrative that the message\n // never used as a separator.\n const rendered = renderText(\n restoreStructuralEmpties(f.text, f.repetitions, seg.enc),\n seg.enc,\n ).text;\n return rendered === \"\" ? { kind: \"unplaceable\" } : { kind: \"text\", text: rendered };\n}\n\n/**\n * Whether a `TX` free-text row carries content, decided by the same read that places it, so the\n * `ServiceRequest` arm (which has no target for either row and only flags them) and the\n * `MedicationRequest` arm (which places them) never disagree about whether one arrived.\n */\nfunction txValued(seg: Segment, field: number): boolean {\n return freeText(seg, field).kind !== \"absent\";\n}\n\n/**\n * The six TQ1 fields that each **narrow** a schedule, paired with the IG target they would have\n * reached. A valued one withholds the whole timing (see the module note), because a Timing built\n * without it would read as a complete instruction that is strictly wider than the one sent.\n */\nconst SCHEDULE_NARROWING: readonly (readonly [field: number, path: string])[] = Object.freeze([\n [4, \".event\"],\n [5, \".repeat.offset\"],\n // R4 places every `bounds[x]` on `Timing.repeat`, not on `Timing`, so the element the IG's\n // TQ1-6 rows would have reached is `...timing.repeat.boundsDuration`: a consumer routing on\n // `fhirPath` must not be handed a path that resolves to nothing.\n [6, \".repeat.boundsDuration\"],\n [12, \"\"],\n [13, \".repeat.duration\"],\n [14, \".repeat.countMax\"],\n]);\n\n/**\n * The RPT components this library can ground, by 1-based position: `RPT.1` Repeat Pattern Code,\n * `RPT.5` Period Quantity, `RPT.6` Period Units and `RPT.8` Event. The refusal is written as the\n * **complement** of this set rather than as a list of the components to refuse, so it is closed over\n * whatever the wire actually carries: the published RPT datatype defines eleven components, and a\n * message that values a twelfth is non-conformant content the transform must still not drop in\n * silence. Refusing by enumeration would have read that twelfth as absent.\n *\n * Why each of the other published components is not here, on the IG's own rows: `RPT.2` Calendar\n * Alignment, `RPT.7` Institution Specified Time and `RPT.11` General Timing Specification have no\n * FHIR target row at all; `RPT.3`/`RPT.4`, the two ends of the day-of-week range, carry the\n * narrative `/translate number to day/` with no published table behind it; `RPT.9`/`RPT.10` Event\n * Offset carry `/convert to minutes based on RPT.10/`, a rescale this library never performs.\n */\nconst EXPRESSIBLE_RPT_COMPONENTS: ReadonlySet<number> = Object.freeze(new Set([1, 5, 6, 8]));\n\n/**\n * Whether the instant `end` denotes precedes the instant `start` denotes, decided only where the\n * two FHIR dateTime values are unambiguously comparable, so an inverted period is caught without a\n * date-precision value ever being read as an instant it does not carry:\n *\n * - Two fully-zoned datetimes are compared as the absolute instants they are.\n * - Otherwise both are reduced to the calendar date each states and compared at day granularity,\n * with a partial date (`2026`, `2026-07`) widened to the whole span it covers, so a comparison\n * only fires when *every* day the end could mean is before *every* day the start could mean.\n *\n * @param start - The FHIR dateTime the boundsPeriod would start at.\n * @param end - The FHIR dateTime the boundsPeriod would end at.\n * @example\n * ```ts\n * // endPrecedesStart(\"2026-07-22\", \"2026-07-21\"); // true\n * // endPrecedesStart(\"2026-07-21T10:00:00-05:00\", \"2026-07-21T09:00:00-05:00\"); // true\n * // endPrecedesStart(\"2026-07-21T10:00:00-05:00\", \"2026-07-21\"); // false (same day)\n * ```\n */\nexport function endPrecedesStart(start: string, end: string): boolean {\n const zoned = (v: string): number | undefined => {\n if (!v.includes(\"T\")) return undefined;\n const ms = Date.parse(v);\n return Number.isNaN(ms) ? undefined : ms;\n };\n const startMs = zoned(start);\n const endMs = zoned(end);\n if (startMs !== undefined && endMs !== undefined) return endMs < startMs;\n // Day granularity: the earliest day the start could mean vs the latest day the end could mean.\n const datePart = (v: string): string => v.split(\"T\")[0] ?? v;\n const widen = (v: string, high: boolean): string => {\n const d = datePart(v);\n if (d.length === 4) return high ? `${d}-12-31` : `${d}-01-01`;\n if (d.length === 7) return high ? `${d}-31` : `${d}-01`;\n return d;\n };\n return widen(end, true) < widen(start, false);\n}\n\n/**\n * Build the `Timing.code` CodeableConcept from RPT.1: the message's own code, **verbatim**, under the\n * `v2-0335` CodeSystem. The IG map's rows are identity in the source code, so nothing is translated\n * and no second, derived coding is asserted; a code the map has no row for never reaches here.\n */\nfunction timingCode(code: string): FhirComplex {\n return complex([\n {\n name: \"coding\",\n value: list([\n complex([\n { name: \"system\", value: primitive(V2_0335_SYSTEM) },\n { name: \"code\", value: primitive(code) },\n ]),\n ]),\n },\n ]);\n}\n\n/** The accumulating state of one TQ1 read: the timing parts so far, plus whether it has been refused. */\ninterface Draft {\n refused: boolean;\n code: FhirComplex | undefined;\n period: FhirNode | undefined;\n periodUnit: string | undefined;\n when: string | undefined;\n boundsStart: string | undefined;\n boundsEnd: string | undefined;\n}\n\n/** Read TQ1-3's RPT components into `draft`, refusing on anything outside the expressible set. */\nfunction readRepeatPattern(\n tq1: Segment,\n base: string,\n draft: Draft,\n issues: TransformIssue[],\n): void {\n // The repetitions that carry a VALUE, never the raw ones the separators delimit. `Q4H~`, `~Q4H`\n // and `Q4H~\"\"` each send exactly one repeat pattern, so counting `~` characters instead of\n // content refused a schedule the message had grounded completely, and it did so at the one place\n // in this module that read a structural empty as content: every other emptiness question here is\n // {@link carriesValue}. The valued one is the repetition every component below is read from, so a\n // pattern that arrived second on the wire is read exactly as one that arrived first.\n const valued = tq1.field(3).repetitions.filter(repetitionValued);\n const rpt = valued[0];\n if (rpt === undefined) return;\n if (valued.length > 1) {\n // Timing.code is 0..1 and Timing carries one repeat: a second pattern cannot be placed, and\n // taking the first would emit a schedule the message did not send.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.3\", base));\n draft.refused = true;\n return;\n }\n\n // Every component position the wire actually carried, not a fixed list of the seven published\n // ones: a valued component past RPT.11 is content the sender sent and this library cannot ground,\n // so it withholds the schedule exactly as RPT.2 does rather than being read as absent.\n const carried = rpt.components.length;\n for (let component = 1; component <= carried; component += 1) {\n if (EXPRESSIBLE_RPT_COMPONENTS.has(component)) continue;\n if (!componentValued(rpt, component)) continue;\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `TQ1.3.${String(component)}`, base));\n draft.refused = true;\n }\n\n // RPT.1 → Timing.code. A foreign coding system is never asserted to be the v2-0335 concept, and a\n // code the published map has no row for is never asserted at all.\n if (componentValued(rpt, 1)) {\n const code = subcomponent(rpt, 1, 1);\n const mnemonic = subcomponent(rpt, 1, 3);\n const fromTable = mnemonic === \"\" || HL70335_MNEMONICS.has(mnemonic);\n if (fromTable && isRepeatPatternCode(code)) {\n draft.code = timingCode(code);\n } else {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TQ1.3.1\", `${base}.code`));\n draft.refused = true;\n }\n }\n\n // RPT.5 → Timing.repeat.period, precision-exact. A magnitude FHIR's decimal cannot hold in the\n // sender's own lexical form is refused, never canonicalized (which would alter it); and so is a\n // negative one, which R4's tim-5 (\"period SHALL be a non-negative value\") forbids on the target\n // element whatever its lexical form. Unsigned zero is not refused: tim-5 admits it and carrying\n // the sender's own magnitude unaltered is this library's standing rule.\n //\n // The sign test is LEXICAL, on the digits the sender wrote, because the emitted value is lexical:\n // `decimal` preserves the sender's form, so the guard has to answer the same question the wire\n // will. `Number(raw) < 0` answers a different one and is false for a whole class of negatives: any\n // magnitude under about 5e-324 underflows to `-0`, so `-1e-400` passed that test and reached the\n // resource as `\"period\":-1e-400`, invisible to a JSON-parsing probe because parsing normalizes the\n // literal to `0`. A minus sign in front of a magnitude is a negative period, at every magnitude.\n if (componentValued(rpt, 5)) {\n const raw = subcomponent(rpt, 5, 1);\n let period: FhirNode | undefined;\n try {\n period = primitive(decimal(raw));\n } catch {\n period = undefined;\n }\n if (period === undefined || raw.startsWith(\"-\")) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID, \"TQ1.3.5\", `${base}.repeat.period`),\n );\n draft.refused = true;\n } else {\n draft.period = period;\n }\n }\n\n // RPT.6 → Timing.repeat.periodUnit, a required-bound code: carried only when it already is one.\n if (componentValued(rpt, 6)) {\n const unit = subcomponent(rpt, 6, 1);\n const mnemonic = subcomponent(rpt, 6, 3);\n const fromUcum = mnemonic === \"\" || UCUM_MNEMONICS.has(mnemonic);\n if (fromUcum && UNITS_OF_TIME.has(unit)) {\n draft.periodUnit = unit;\n } else {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TQ1.3.6\", `${base}.repeat.periodUnit`),\n );\n draft.refused = true;\n }\n }\n\n // RPT.5 and RPT.6 are one carry, not two. R4's tim-2 (\"if there's a period, there needs to be\n // period units\") makes a lone period an INVALID repeat rather than a narrower one, and a lone unit\n // grounds no interval at all; either way the half that did arrive cannot be placed. The one the\n // message valued is named, so the diagnostic points at content the sender actually sent. Skipped\n // when that half was already refused above: its own issue already names the component.\n const periodValued = componentValued(rpt, 5);\n const unitValued = componentValued(rpt, 6);\n if (periodValued && !unitValued && draft.period !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.3.5\", `${base}.repeat.period`));\n draft.refused = true;\n }\n if (unitValued && !periodValued && draft.periodUnit !== undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.3.6\", `${base}.repeat.periodUnit`),\n );\n draft.refused = true;\n }\n\n // RPT.8 → Timing.repeat.when, a required-bound code: only the IG rows that target v3-TimingEvent,\n // and only when the message declared the bound table (or declared nothing). The coding system the\n // sender put in RPT.8's third subcomponent is handed to translateBound, which is the only thing\n // that can enforce TIMING_EVENT_VALUE_MAP's own sourceMnemonics: withhold it and a code sent under\n // a site's local table is asserted to be the published v3-TimingEvent concept that shares its\n // spelling, inside an element whose binding is REQUIRED. `AC` under a local table need not mean\n // \"before meal\". RPT.1 and RPT.6 above apply the same guard through their own mnemonic sets;\n // RPT.8's bound table is a real ConceptMap, so it is guarded by the map's declared mnemonics\n // rather than by a second copy of that list.\n if (componentValued(rpt, 8)) {\n const event = subcomponent(rpt, 8, 1);\n const mnemonic = subcomponent(rpt, 8, 3);\n const target = translateBound(\n { identifier: event, nameOfCodingSystem: mnemonic },\n TIMING_EVENT_VALUE_MAP,\n );\n if (target === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"TQ1.3.8\", `${base}.repeat.when`));\n draft.refused = true;\n } else {\n draft.when = target.code;\n }\n }\n}\n\n/** Read TQ1-7 / TQ1-8 into `draft`'s bounds, refusing an endpoint that is lost or inverted. */\nfunction readBounds(\n tq1: Segment,\n base: string,\n ctx: TransformContext,\n draft: Draft,\n issues: TransformIssue[],\n): void {\n const endpoint = (field: number, name: \"start\" | \"end\"): string | undefined => {\n if (!isValued(tq1, field)) return undefined;\n const converted = toFhirDateTime(tq1.field(field).asTs(), ctx.options);\n issues.push(...converted.issues);\n if (converted.value === undefined) {\n // A valued endpoint that yields no dateTime cannot be silently omitted: the remaining bound\n // would read as an open-ended regimen the message never authorized.\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n `TQ1.${String(field)}`,\n `${base}.repeat.boundsPeriod.${name}`,\n ),\n );\n draft.refused = true;\n }\n return converted.value;\n };\n\n draft.boundsStart = endpoint(7, \"start\");\n draft.boundsEnd = endpoint(8, \"end\");\n\n if (\n draft.boundsStart !== undefined &&\n draft.boundsEnd !== undefined &&\n endPrecedesStart(draft.boundsStart, draft.boundsEnd)\n ) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.8\", `${base}.repeat.boundsPeriod.end`),\n );\n draft.refused = true;\n }\n}\n\n/** Assemble the `Timing` node from a draft that was not refused, or `undefined` when it grounds none. */\nfunction assembleTiming(draft: Draft): FhirComplex | undefined {\n if (draft.refused) return undefined;\n\n const bounds: { name: string; value: FhirNode }[] = [];\n if (draft.boundsStart !== undefined)\n bounds.push({ name: \"start\", value: primitive(draft.boundsStart) });\n if (draft.boundsEnd !== undefined)\n bounds.push({ name: \"end\", value: primitive(draft.boundsEnd) });\n\n const repeat: { name: string; value: FhirNode }[] = [];\n if (bounds.length > 0) repeat.push({ name: \"boundsPeriod\", value: complex(bounds) });\n if (draft.period !== undefined) repeat.push({ name: \"period\", value: draft.period });\n if (draft.periodUnit !== undefined)\n repeat.push({ name: \"periodUnit\", value: primitive(draft.periodUnit) });\n if (draft.when !== undefined) repeat.push({ name: \"when\", value: list([primitive(draft.when)]) });\n\n const timing: { name: string; value: FhirNode }[] = [];\n if (repeat.length > 0) timing.push({ name: \"repeat\", value: complex(repeat) });\n if (draft.code !== undefined) timing.push({ name: \"code\", value: draft.code });\n\n return timing.length === 0 ? undefined : complex(timing);\n}\n\n/** The reading an order group with no usable TQ1 yields: nothing placed, nothing claimed reached. */\nfunction nothing(issues: readonly TransformIssue[]): Tq1Reading {\n return {\n timing: undefined,\n conditionText: undefined,\n instructionText: undefined,\n issues,\n contributes: false,\n };\n}\n\n/**\n * Read an order group's TQ1 occurrences into the parts its request builder places. Never throws;\n * every refusal is a value-free {@link TransformIssue} naming the TQ1 field or component that caused\n * it, and a refused schedule leaves `timing` `undefined` rather than partially built.\n *\n * @param tq1s - The group's `TQ1` segments, in document order (usually zero or one).\n * @param target - Which request is being built; selects the FHIR paths and the free-text rows.\n * @param ctx - The transform context (its options carry the naked-timestamp policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const tq1s = parseHL7(raw).allSegments().filter((s) => s.type === \"TQ1\");\n * // const { timing, issues } = readTq1(tq1s, \"MedicationRequest\", {});\n * ```\n */\nexport function readTq1(\n tq1s: readonly Segment[],\n target: Tq1Target,\n ctx: TransformContext,\n): Tq1Reading {\n const issues: TransformIssue[] = [];\n const base = timingPath(target);\n\n if (tq1s.length === 0) return nothing(issues);\n if (tq1s.length > 1) {\n // Two timings on one order is a regimen this library cannot express as one request. Mapping the\n // first and discarding the rest would emit half a schedule as if it were the whole one, so\n // nothing from any occurrence is carried and every one of them stays unreached.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1\", base));\n return nothing(issues);\n }\n const tq1 = tq1s[0];\n if (tq1 === undefined) return nothing(issues);\n\n // TQ1-2 / TQ1-9: the IG maps these to the dose and the priority, which the RXO/OBR path already\n // grounds. Flagged dropped, neither field touched, and the schedule is unaffected.\n if (isValued(tq1, 2)) {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED,\n \"TQ1.2\",\n target === \"MedicationRequest\"\n ? \"MedicationRequest.dosageInstruction.doseAndRate.doseQuantity\"\n : \"ServiceRequest.quantityQuantity\",\n ),\n );\n }\n if (isValued(tq1, 9)) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.9\", `${target}.priority`));\n }\n\n const draft: Draft = {\n refused: false,\n code: undefined,\n period: undefined,\n periodUnit: undefined,\n when: undefined,\n boundsStart: undefined,\n boundsEnd: undefined,\n };\n\n for (const [field, suffix] of SCHEDULE_NARROWING) {\n if (!isValued(tq1, field)) continue;\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `TQ1.${String(field)}`, `${base}${suffix}`),\n );\n draft.refused = true;\n }\n\n readRepeatPattern(tq1, base, draft, issues);\n readBounds(tq1, base, ctx, draft, issues);\n\n const timing = assembleTiming(draft);\n\n // TQ1-10 / TQ1-11 reach two DIFFERENT MedicationRequest targets, and the IG names no target on the\n // service path for either (TQ1-10 is a proposed extension there, TQ1-11 an Annotation this library\n // does not build), so on that path they are flagged dropped rather than silently discarded.\n let conditionText: string | undefined;\n let instructionText: string | undefined;\n if (target === \"MedicationRequest\") {\n // Read whole, never truncated at the first raw delimiter, and read only where the field is\n // valued by the same test the service path applies: see freeText. \"Verbatim\" is the claim these\n // two rows make, and a TX field's delimiters are content, not structure.\n const condition = freeText(tq1, 10);\n if (condition.kind === \"text\") conditionText = condition.text;\n else if (condition.kind === \"unplaceable\")\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.10\", CONDITION_TEXT_PATH));\n\n const instruction = freeText(tq1, 11);\n if (instruction.kind === \"unplaceable\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.11\", INSTRUCTION_TEXT_PATH));\n } else if (instruction.kind === \"text\") {\n // R4's `txt-2` on Narrative: \"The narrative SHALL have some non-whitespace content\". A TQ1-11\n // of nothing but spaces projects faithfully and still cannot be placed, because the div it\n // would fill is invalid. @cosyte/fhir models no Narrative constraint, so the conservative-emit\n // gate cannot catch it and the resource would ship: the refusal happens here or nowhere. Only\n // this row is tested, because only this row targets a Narrative; TQ1-10 reaches a plain\n // `string`, which R4 constrains no further, so a whitespace-only one is carried as sent.\n if (instruction.text.trim() === \"\")\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.11\", INSTRUCTION_TEXT_PATH));\n else instructionText = instruction.text;\n }\n } else {\n if (txValued(tq1, 10))\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.10\", \"ServiceRequest\"));\n if (txValued(tq1, 11))\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"TQ1.11\", \"ServiceRequest.note\"));\n }\n\n return {\n timing,\n conditionText,\n instructionText,\n issues,\n contributes:\n timing !== undefined || conditionText !== undefined || instructionText !== undefined,\n };\n}\n\n/**\n * Escape the five XML predefined entities in a v2 free-text instruction so it can sit inside an\n * XHTML `div` without altering anything else about it. Nothing is trimmed, collapsed, wrapped or\n * re-cased: unescaping the result returns the sender's text character for character.\n *\n * @param value - The decoded v2 text.\n * @example\n * ```ts\n * // escapeXml('take <2 & \"rest\"'); // 'take &lt;2 &amp; &quot;rest&quot;'\n * ```\n */\nexport function escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n}\n\n/**\n * Build the `MedicationRequest.text` `Narrative` for a TQ1-11 free-text instruction: `status`\n * `additional` (the resource's structured elements do not contain this text, so it is genuinely\n * additional, never `generated`), and a `div` carrying the sender's text XML-escaped and otherwise\n * untouched.\n *\n * @param value - The TQ1-11 text, decoded.\n * @example\n * ```ts\n * // narrative(\"with food\"); // Narrative { status: \"additional\", div: \"<div ...>with food</div>\" }\n * ```\n */\nexport function narrative(value: string): FhirComplex {\n return complex([\n { name: \"status\", value: primitive(\"additional\") },\n {\n name: \"div\",\n value: primitive(`<div xmlns=\"http://www.w3.org/1999/xhtml\">${escapeXml(value)}</div>`),\n },\n ]);\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 * | TQ1-3 Repeat Pattern (RPT) | `dosageInstruction.timing` | {@link readTq1} (RPT[Timing], all-or-nothing) |\n * | TQ1-7 / TQ1-8 Start / End date-time | `dosageInstruction.timing.repeat.boundsPeriod.start`/`.end` | {@link readTq1} |\n * | TQ1-10 Condition text (TX) | `dosageInstruction.additionalInstruction.text` | verbatim |\n * | TQ1-11 Text instruction (TX) | `text` (a `Narrative`, `status` `additional`) | verbatim, XML-escaped |\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, and 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 * namely `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 * - **The schedule is fully grounded or absent and flagged.** TQ1-3 becomes at most **one**\n * `dosageInstruction.timing`, and only over the RPT components {@link readTq1} can ground; any\n * component, schedule-narrowing TQ1 field, unresolvable bound, inverted period, or second TQ1\n * withholds the whole `Timing` and raises a value-free issue naming what caused it. A partially\n * built timing is the one failure mode that matters here: it reads to the receiving system as a\n * complete dosing instruction, and a wrong frequency is a dosing error no re-run undoes.\n * - **The two free-text rows go to two different places, and neither is `dosageInstruction.text`.**\n * The IG maps TQ1-10 to `dosageInstruction.additionalInstruction.text` and TQ1-11 to the\n * resource's own `text` narrative; it targets `dosageInstruction.text` from nothing at all, so\n * nothing is written there. Both carry the sender's words verbatim and both survive a refused\n * timing: a \"with food\" that arrived is still true when the frequency could not be grounded.\n * Verbatim is the whole field including a trailing delimiter, and **only a valued field is\n * written**: a row the wire says carries nothing (absent, or the HL7 explicit null `\"\"`) puts no\n * text on the resource and no marker in its place.\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\";\nimport { narrative, type Tq1Reading } from \"./tq1-timing.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/**\n * Build the single `dosageInstruction` (TQ1 additional instruction + timing, then route/site/method\n * and the dose range), or `undefined` when nothing grounds one. The TQ1 parts lead because that is\n * the R4 `Dosage` element order; when the order carries no TQ1 they are simply absent and the\n * remaining elements keep exactly the shape and order the RXO/RXR path has always produced.\n */\nfunction buildDosageInstruction(\n rxo: Segment | undefined,\n rxr: Segment | undefined,\n tq1: Tq1Reading | undefined,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n\n if (tq1?.conditionText !== undefined) {\n // TQ1-10 → additionalInstruction[0].text, verbatim. Emitted whether or not a timing was.\n props.push({\n name: \"additionalInstruction\",\n value: list([complex([{ name: \"text\", value: primitive(tq1.conditionText) }])]),\n });\n }\n if (tq1?.timing !== undefined) {\n props.push({ name: \"timing\", value: tq1.timing });\n }\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 tq1 - What the order's `TQ1` occurrences grounded ({@link readTq1}), when it carries any.\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, undefined, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildMedicationRequest(\n rxo: Segment | undefined,\n rxr: Segment | undefined,\n orc: Segment | undefined,\n tq1: Tq1Reading | undefined,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // The TQ1 diagnostics are raised whatever becomes of the request: a refused schedule is news even\n // when the order turns out to have no give code to prescribe.\n if (tq1 !== undefined) issues.push(...tq1.issues);\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 // TQ1-11 → text (DomainResource.text, which precedes the resource's own elements in R4). The\n // sender's instruction verbatim inside an XHTML div, never placed in dosageInstruction.text.\n if (tq1?.instructionText !== undefined) {\n props.push({ name: \"text\", value: narrative(tq1.instructionText) });\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, tq1, 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 * NTE → a FHIR `Annotation`, grounded firsthand on the IG **Segment NTE to ServiceRequest**\n * ConceptMap (`hl7.fhir.uv.v2mappings`, STU1; `ConceptMap-segment-nte-to-servicerequest.html`),\n * which is the map the ORU_R01 message map files its `Observation.note` row against.\n *\n * | NTE field | FHIR target | via |\n * |---|---|---|\n * | NTE-3 Comment (FT, `0..-1`) | `Annotation.text` (`markdown`) | one annotation per repetition |\n * | NTE-6 Entered Date/Time (DTM) | `Annotation.time` | {@link toFhirDateTime} |\n *\n * `NTE-1`, `NTE-2`, `NTE-7`, `NTE-8` and `NTE-9` carry no target in the map at all. Two rows do\n * carry one and are deliberately **declared rather than built**: `NTE-5 Entered By` targets\n * `note.authorReference(Practitioner)`, and this library builds no Practitioner, so an author would\n * be a reference resolving to nothing; and `NTE-4 Comment Type` targets a **proposed** extension\n * the guide has not named yet (its own cell reads `extension??-noteType`), so there is no canonical\n * URL to write and one is never invented.\n *\n * **A note is text the sender wrote, so it is read as text.** `NTE-3` is `FT`: a v2 primitive with\n * no component structure, where a raw `^` or `&` is content. Each repetition is rendered through\n * the parser's own display projection, which resolves the v2 escape sequences (`\\T\\` to `&`,\n * `\\.br\\` to a line break) and preserves verbatim any sequence it cannot render. The repetitions\n * are **not** joined: a separator between them would be a character the wire never carried, and\n * `Observation.note` is `0..*` precisely so each can stand on its own.\n *\n * @packageDocumentation\n */\n\nimport { renderText, type Segment } 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 { TransformContext } from \"../terminology/context.js\";\n\n/**\n * The NTE rows the map gives a target this library does not build, paired with that target. Each is\n * declared for an occurrence that valued it, so a deferred row is in the issues list rather than\n * silently absent.\n */\nconst DEFERRED_NOTE_ROWS: readonly (readonly [field: number, path: string])[] = Object.freeze([\n [4, \"Annotation.extension\"],\n [5, \"Annotation.authorReference\"],\n]);\n\n/** `Annotation.time` from NTE-6, or `undefined` when the segment values no entry timestamp. */\nfunction annotationTime(\n nte: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirNode | undefined {\n if (nte.field(6).value === \"\") return undefined;\n const entered = toFhirDateTime(nte.field(6).asTs(), ctx.options);\n issues.push(...entered.issues);\n return entered.value === undefined ? undefined : primitive(entered.value);\n}\n\n/**\n * Every FHIR `Annotation` a run of `NTE` segments contributes, in message order: one per valued\n * `NTE-3` repetition, each carrying that repetition's rendered text and the segment's `NTE-6` time.\n *\n * Returns `undefined` when the segments carry no comment text at all, so a caller adds no empty\n * `note` element. The diagnostics raised are value-free: no byte of a note ever reaches one.\n *\n * @param notes - The `NTE` segments to read, in message order.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @param issues - The issue sink for the deferred-row and timestamp diagnostics.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const nte = parseHL7(raw).segments(\"NTE\");\n * // buildAnnotations(nte, {}, []); // a FHIR list of Annotation nodes, or undefined\n * ```\n */\nexport function buildAnnotations(\n notes: readonly Segment[],\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirNode | undefined {\n const annotations: FhirComplex[] = [];\n\n for (const nte of notes) {\n for (const [field, path] of DEFERRED_NOTE_ROWS) {\n if (nte.field(field).value !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `NTE.${String(field)}`, path));\n }\n }\n\n const comment = nte.field(3);\n if (comment.repetitions.length === 0) continue;\n const time = annotationTime(nte, ctx, issues);\n // The field's own delimiters, off the segment: a sender declares them in MSH-2, and splitting\n // on an assumed `~` would cut a note at a character the message never used as a separator.\n for (const repetition of comment.text.split(nte.enc.repetition)) {\n const rendered = renderText(repetition, nte.enc).text;\n if (rendered === \"\") continue;\n const props: { name: string; value: FhirNode }[] = [];\n if (time !== undefined) props.push({ name: \"time\", value: time });\n props.push({ name: \"text\", value: primitive(rendered) });\n annotations.push(complex(props));\n }\n }\n\n return annotations.length === 0 ? undefined : list(annotations);\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 * | (OBSERVATION-group NTE) | `Observation.note` | {@link buildAnnotations} (`NTE[ServiceRequest]`) |\n *\n * **What OBX-2 selects, row by row** (`ConceptMap-segment-obx-to-observation.html`, the OBX-5 rows):\n *\n * | OBX-2 | FHIR target | datatype map |\n * |---|---|---|\n * | `NM` | `valueQuantity` | `NM[Quantity]` |\n * | `SN` | `valueQuantity` (with a comparator) / `valueRange` / `valueRatio` | the row's own conditions |\n * | `CWE`/`CE`/`CF`/`CNE`/`IS` | `valueCodeableConcept` | `CWE[CodeableConcept]` |\n * | `DT`/`DTM`/`TS` | `valueDateTime` | `DTM[DateTime]` |\n * | `ST`/`TX`/`FT` | `valueString` | (direct) |\n * | `DR` | `valuePeriod` | `DR[Period]` |\n * | `NR` | `valueRange` | `NR[Range]` |\n * | `TM` | `valueTime` | (direct, an R4 `time`) |\n * | `NA` | `valueSampledData` | `NA[SampledData]` |\n * | `ED` **and** OBX-5.4 = `Base64` | the {@link OBSERVATION_VALUE_ATTACHMENT_EXTENSION_URL} extension | `ED[Attachment]` |\n * | `RP`, `ID`, anything else | `valueString` + flagged | (no settled target) |\n *\n * **The \"never a confident wrong result\" fail-safes:**\n * - **OBX-2 drives `value[x]`**, per the table above, and every row of it degrades to the raw OBX-5\n * text as `valueString` + {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED} rather than emit a value\n * the map cannot ground: a `DR` neither of whose bounds is a dateTime this library will emit, an\n * `NR` neither of whose bounds is a faithful `decimal`, a `TM` carrying a UTC offset (an R4 `time`\n * admits none, and discarding one would move the instant), an `NA` carrying a magnitude `decimal`\n * cannot hold unaltered, an `ED` whose OBX-5.4 is not `Base64` (both ED rows are conditioned on\n * it), and `RP`, whose extension target the guide's own comment marks unsettled.\n * - **The published NA row spells its attribute `Observation.valueSampedData`.** That is a typo in\n * the guide; the R4 element is `valueSampledData` and that is what is emitted.\n * - **A SampledData asserts no origin and no period.** R4 makes both `1..1` and the NA map has no\n * source row for either, so they ship value-absent with a `data-absent-reason` and\n * {@link ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN}: an `origin` of 0 or a `period` of 1\n * would be a magnitude this message never sent, on a waveform.\n * - **An ED payload is carried, never read.** OBX-5.5 reaches `Attachment.data` byte-for-byte: no\n * decode, no re-encode, no normalization, no validation, no truncation.\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 { parseDtm, type CWE, type Field, type Segment } from \"@cosyte/hl7\";\nimport {\n complex,\n decimal,\n primitive,\n list,\n validatePrimitiveValue,\n type FhirComplex,\n type FhirNode,\n} 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 { ALTERNATE_CODES_EXTENSION_URL } from \"./allergy-intolerance.js\";\nimport { buildAnnotations } from \"./note.js\";\nimport { dataAbsent, dataAbsentComplex, reference } from \"./reference.js\";\n\n/**\n * The v3 ObservationInterpretation canonical system (FHIR `Observation.interpretation` binding).\n *\n * @example\n * ```ts\n * import { V3_OBSERVATION_INTERPRETATION_SYSTEM } from \"@cosyte/transform\";\n * V3_OBSERVATION_INTERPRETATION_SYSTEM.endsWith(\"v3-ObservationInterpretation\"); // => true\n * ```\n */\nexport const 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/**\n * The extension URL the OBX map **fixes** on the `IF OBX-2 EQUALS \"ED\" AND IF OBX-5.4 EQUALS\n * \"Base64\"` rows, transcribed from the map's own `Observation.extension.url` assignment. R4 has no\n * `Observation.valueAttachment`, so the guide carries the R5 element as this named extension.\n *\n * @example\n * ```ts\n * import { OBSERVATION_VALUE_ATTACHMENT_EXTENSION_URL } from \"@cosyte/transform\";\n * OBSERVATION_VALUE_ATTACHMENT_EXTENSION_URL.endsWith(\"extension-Observation.valueAttachment\"); // true\n * ```\n */\nexport const OBSERVATION_VALUE_ATTACHMENT_EXTENSION_URL =\n \"https://hl7.org/fhir/5.0/StructureDefinition/extension-Observation.valueAttachment\";\n\n/**\n * The OBX-5.4 encoding the OBX map conditions **both** of its `ED` rows on. Any other encoding\n * (`A`, `Hex`, `Ascii`, a local token) leaves those rows unapplied, so no attachment is built.\n *\n * @example\n * ```ts\n * import { ED_BASE64_ENCODING } from \"@cosyte/transform\";\n * ED_BASE64_ENCODING; // \"Base64\"\n * ```\n */\nexport const ED_BASE64_ENCODING = \"Base64\";\n\n/**\n * The `SampledData.data` token the Implementation Considerations chapter's own worked example\n * directs for a data point a repetition did not carry (`\"set .dimensions to 4 and use E for the\n * data points not present\"`). It is the FHIR-defined \"error\" token, and it is written **only** for\n * an absent position, never for a value that arrived and could not be converted.\n *\n * @example\n * ```ts\n * import { SAMPLED_DATA_ABSENT_POINT } from \"@cosyte/transform\";\n * SAMPLED_DATA_ABSENT_POINT; // \"E\"\n * ```\n */\nexport const SAMPLED_DATA_ABSENT_POINT = \"E\";\n\n/**\n * The `data-absent-reason` code carried by `SampledData.origin` and `SampledData.period`, the two\n * R4-required elements of that datatype that **no row of the IG's NA map, and no line of the\n * Implementation Considerations chapter it points at, supplies a source for**.\n *\n * @example\n * ```ts\n * import { SAMPLED_DATA_UNGROUNDED } from \"@cosyte/transform\";\n * SAMPLED_DATA_UNGROUNDED; // \"unknown\"\n * ```\n */\nexport const SAMPLED_DATA_UNGROUNDED = \"unknown\";\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/**\n * Whether a field carries nothing at all, asked of its **whole** repetition tree rather than of\n * `Field.value` (the first subcomponent of the first component of the first repetition). An OBX-5\n * of `^20260722` is empty by the latter question and is plainly not empty: a composite value type\n * has to be asked the composite question or the emptiness test silently drops content.\n */\nfunction fieldEmpty(field: Field): boolean {\n return field.repetitions.every((r) =>\n r.components.every((c) => c.subcomponents.every((s) => s === \"\")),\n );\n}\n\n/**\n * `DR` → `Period` per the IG **DR to Period** datatype map: `DR.1` to `Period.start` and `DR.2` to\n * `Period.end`, both `0..1`, both through the `DTM[DateTime]` map. Nothing else is mapped, so a\n * missing bound stays missing: the observation time, the message time and the other bound are all\n * refused as substitutes. Returns `undefined` when neither component yields a dateTime.\n */\nfunction buildPeriodValue(\n field: Field,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n for (const [index, name] of [\n [0, \"start\"],\n [1, \"end\"],\n ] as const) {\n const raw = rawComponent(field, index);\n if (raw === undefined) continue;\n const converted = toFhirDateTime(parseDtm(raw), ctx.options);\n issues.push(...converted.issues);\n if (converted.value !== undefined) props.push({ name, value: primitive(converted.value) });\n }\n return props.length === 0 ? undefined : complex(props);\n}\n\n/**\n * One `Range` bound: a `SimpleQuantity` carrying the magnitude and **nothing else**. The NR map\n * grounds `Range.low.value` and `Range.high.value` and no unit, code or system anywhere, so none is\n * written, and OBX-6 is deliberately not borrowed for it. The magnitude keeps its exact lexical\n * form through the string-backed FHIR `decimal`; a form `decimal` cannot carry faithfully yields no\n * bound and a value-free {@link ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID}, never a rescaled one.\n */\nfunction rangeBound(\n raw: string | undefined,\n fhirPath: string,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (raw === undefined) return undefined;\n try {\n return complex([{ name: \"value\", value: primitive(decimal(raw)) }]);\n } catch {\n issues.push(issue(ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID, \"OBX.5\", fhirPath));\n return undefined;\n }\n}\n\n/** `NR` → `Range` per the IG **NR to Range** map, or `undefined` when neither bound converts. */\nfunction buildRangeValue(field: Field, issues: TransformIssue[]): FhirComplex | undefined {\n const low = rangeBound(rawComponent(field, 0), \"Range.low.value\", issues);\n const high = rangeBound(rawComponent(field, 1), \"Range.high.value\", issues);\n const props: { name: string; value: FhirNode }[] = [];\n if (low !== undefined) props.push({ name: \"low\", value: low });\n if (high !== undefined) props.push({ name: \"high\", value: high });\n return props.length === 0 ? undefined : complex(props);\n}\n\n/**\n * A v2 `TM` read as a FHIR `time`, or `undefined` when it is not one this library will emit.\n *\n * The OBX map routes `TM` straight to `Observation.valueTime` with no datatype map, so the R4\n * `time` value domain is the whole contract, and it admits **no timezone offset and no partial\n * precision**. A v2 TM may carry both. Discarding a `+0530` would move the clinical instant by\n * hours with nothing said, and padding `1430` to `14:30:00` would fabricate a precision the sender\n * did not send: both are refused here, and the caller falls back to the raw text. The candidate is\n * checked against `@cosyte/fhir`'s own `time` domain rather than trusted to this shape test alone.\n */\nfunction timeValue(raw: string): string | undefined {\n const parts = /^(\\d{2})(\\d{2})(\\d{2})(\\.\\d{1,4})?$/.exec(raw);\n if (parts === null) return undefined;\n const candidate = `${parts[1] ?? \"\"}:${parts[2] ?? \"\"}:${parts[3] ?? \"\"}${parts[4] ?? \"\"}`;\n return validatePrimitiveValue(candidate, \"time\") === \"ok\" ? candidate : undefined;\n}\n\n/**\n * `NA` → `SampledData` per the IG **NA to SampledData** map and the \"Numeric Array to Sampled Data\n * Mapping\" section of the Implementation Considerations chapter its comment points at.\n *\n * `.dimensions` is \"the number of values present within each repeat separated by the component\n * delimiter\", read off the widest repetition so a short or absent row does not shrink the array's\n * declared width. A field carrying **one** repetition is the chapter's own vector case (its 8-value\n * example sets `.dimensions` to `1`): with no second repetition there is no second dimension to\n * count, and each value is its own time point. `.data` is the values in row-major order, space\n * separated, with {@link SAMPLED_DATA_ABSENT_POINT} for every position a repetition did not carry,\n * which is exactly the set of positions the chapter's sparse example enumerates as not present.\n *\n * Returns `undefined` when any value that DID arrive is not a magnitude FHIR `decimal` carries\n * faithfully: the caller then falls back to the raw text rather than shipping a rewritten waveform.\n */\nfunction buildSampledData(field: Field, issues: TransformIssue[]): FhirComplex | undefined {\n const rows = field.repetitions.map((r) => r.components.map((c) => c.subcomponents[0] ?? \"\"));\n if (rows.length === 0) return undefined;\n const width = Math.max(...rows.map((r) => r.length));\n const dimensions = rows.length === 1 ? 1 : width;\n\n const points: string[] = [];\n for (const row of rows) {\n for (let i = 0; i < width; i++) {\n const cell = row[i] ?? \"\";\n if (cell === \"\") {\n points.push(SAMPLED_DATA_ABSENT_POINT);\n continue;\n }\n try {\n // `decimal` throws on a lexical form FHIR's decimal cannot carry unaltered (a leading `+`,\n // a leading zero, a trailing dot): the whole array is refused rather than canonicalized.\n // The wire text itself is what is written, so the magnitude keeps its exact precision.\n decimal(cell);\n points.push(cell);\n } catch {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_QUANTITY_VALUE_INVALID, \"OBX.5\", \"SampledData.data\"),\n );\n return undefined;\n }\n }\n }\n\n // R4 makes `origin` and `period` required, and the map grounds neither: they ship value-absent\n // with a data-absent-reason, which satisfies the cardinality while asserting no magnitude.\n for (const path of [\"SampledData.origin\", \"SampledData.period\"]) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_REQUIRED_ELEMENT_UNKNOWN, \"OBX.5\", path));\n }\n return complex([\n { name: \"origin\", value: dataAbsentComplex(SAMPLED_DATA_UNGROUNDED) },\n { name: \"period\", value: dataAbsent(SAMPLED_DATA_UNGROUNDED) },\n { name: \"dimensions\", value: primitive(decimal(String(dimensions))) },\n { name: \"data\", value: primitive(points.join(\" \")) },\n ]);\n}\n\n/**\n * `ED` (encoded data) → the IG-named `valueAttachment` extension, per the OBX map's two\n * `IF OBX-2 EQUALS \"ED\" AND IF OBX-5.4 EQUALS \"Base64\"` rows and the **ED to Attachment** datatype\n * map behind the second of them: `ED.3` (OBX-5.3) to `Attachment.contentType`, `ED.5` (OBX-5.5) to\n * `Attachment.data`, and `ED.2` to an `alternate-codes` extension on the Attachment **only** when\n * `ED.3` is unvalued. `ED.1` and `ED.4` have no target.\n *\n * **The payload is carried, never read.** OBX-5.4 already declares it Base64 and the row is\n * conditioned on that, so it is copied into `Attachment.data` exactly as received: not decoded, not\n * re-encoded, not normalized, not length-checked, not truncated. This library has no business\n * deciding a binary is malformed, and a \"repaired\" attachment is the worst kind of confident wrong\n * value. Returns `undefined` when OBX-5.5 carries nothing to attach.\n */\nfunction buildAttachmentExtension(field: Field, issues: TransformIssue[]): FhirNode | undefined {\n const payload = rawComponent(field, 4);\n if (payload === undefined) return undefined;\n\n const attachment: { name: string; value: FhirNode }[] = [];\n const subtype = rawComponent(field, 2);\n const typeOfData = rawComponent(field, 1);\n if (subtype === undefined && typeOfData !== undefined) {\n // The ED map's `IF ED.3 NOT VALUED` row: the type of data is carried as an alternate code\n // rather than guessed into a MIME `contentType` this message never stated.\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_UNMAPPED, \"OBX.5\", \"Attachment.contentType\"));\n attachment.push({\n name: \"extension\",\n value: list([\n complex([\n { name: \"url\", value: primitive(ALTERNATE_CODES_EXTENSION_URL) },\n {\n name: \"valueCodeableConcept\",\n value: complex([\n {\n name: \"coding\",\n value: list([complex([{ name: \"code\", value: primitive(typeOfData) }])]),\n },\n ]),\n },\n ]),\n ]),\n });\n }\n if (subtype !== undefined) attachment.push({ name: \"contentType\", value: primitive(subtype) });\n attachment.push({ name: \"data\", value: primitive(payload) });\n\n return list([\n complex([\n { name: \"url\", value: primitive(OBSERVATION_VALUE_ATTACHMENT_EXTENSION_URL) },\n { name: \"valueAttachment\", value: complex(attachment) },\n ]),\n ]);\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 * The five value types this discrimination maps through a datatype (or extension) target rather\n * than through `Field.value`. Each is a composite whose first component is not the whole value, so\n * emptiness is asked of the whole field and the fallback carries the whole OBX-5 text.\n */\nconst COMPOSITE_VALUE_TYPES: ReadonlySet<string> = new Set([\"DR\", \"NR\", \"TM\", \"NA\", \"ED\"]);\n\n/**\n * The IG-mapped target for one of {@link COMPOSITE_VALUE_TYPES}, or `undefined` when this OBX-5\n * carries nothing that target can be built from faithfully (the caller then falls back).\n */\nfunction buildMappedValue(\n field: Field,\n vt: string,\n ctx: TransformContext,\n issues: TransformIssue[],\n): { name: string; value: FhirNode } | undefined {\n if (vt === \"DR\") {\n const period = buildPeriodValue(field, ctx, issues);\n return period === undefined ? undefined : { name: \"valuePeriod\", value: period };\n }\n if (vt === \"NR\") {\n const range = buildRangeValue(field, issues);\n return range === undefined ? undefined : { name: \"valueRange\", value: range };\n }\n if (vt === \"TM\") {\n // TM is a v2 primitive, so the whole field is the time; a component structure it never had\n // would only be a damaged line, and `timeValue` refuses one.\n const time = timeValue(field.text);\n return time === undefined ? undefined : { name: \"valueTime\", value: primitive(time) };\n }\n if (vt === \"NA\") {\n const sampled = buildSampledData(field, issues);\n // The OBX map's own NA row spells this attribute `valueSampedData`, which is a typo in the\n // published guide: R4 names the element `valueSampledData`, and that is what is emitted.\n return sampled === undefined ? undefined : { name: \"valueSampledData\", value: sampled };\n }\n // ED, and only under the OBX map's `IF OBX-5.4 EQUALS \"Base64\"` condition both its rows carry.\n if (rawComponent(field, 3) !== ED_BASE64_ENCODING) return undefined;\n const extension = buildAttachmentExtension(field, issues);\n return extension === undefined ? undefined : { name: \"extension\", value: extension };\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 (COMPOSITE_VALUE_TYPES.has(vt)) {\n // An empty OBX-5 is nothing to carry and nothing to flag, exactly as every already-mapped\n // value type treats one. The question is asked of the whole field: `Field.value` reads only\n // the first component, and a DR that valued only its end bound is not an empty field.\n if (fieldEmpty(field)) return undefined;\n const mapped = buildMappedValue(field, vt, ctx, issues);\n if (mapped !== undefined) return mapped;\n // The IG-mapped type could not carry this value faithfully: the raw OBX-5 text is preserved in\n // full (never truncated to its first component, which would drop the rest of a composite) and\n // the drop is flagged, which is the same fail-safe floor this library has always had here.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBX.5\", \"Observation.value[x]\"));\n return valueStringProp(field.text);\n }\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 (RP, ID, unknown): the raw value is\n // preserved as a string and the richer typed mapping is flagged as deferred, never guessed. `RP`\n // has a nominal extension target whose own IG comment marks it unsettled (\"To be resolved when we\n // resolve DocumentReference and valueAttachment\"), so it stays here on purpose.\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 * @param notes - The `NTE` segments of this OBX's own OBSERVATION group → `Observation.note`. Only\n * that group's row has a target; a PATIENT-level or ORDER_OBSERVATION-level NTE has none, so the\n * caller passes none here and the occurrence is reported as unread instead.\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 notes: readonly Segment[] = [],\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 // The OBSERVATION group's NTE segments → Observation.note (ORU_R01 row 4.2.4.3.3, via NTE[ServiceRequest]).\n const note = buildAnnotations(notes, ctx, issues);\n if (note !== undefined) props.push({ name: \"note\", value: note });\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*, so `OBR` →\n * `ServiceRequest` and `RXO` (+ `RXR` route) → `MedicationRequest`. 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), the `RXR` route segments beneath a pharmacy order, and the `TQ1` timing segments\n * the order's TIMING group carries. 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`/`TQ1`\n * `Segment`s (the request/dose/schedule fields the lean `Order` view omits) are available.\n *\n * **`TQ1` is bucketed positionally, like `RXR`, and that is the wiring the schedule arrives on.** No\n * published STU1 *message* map wires a `TQ1` into a `MedicationRequest`: the ORM_O01 map carries no\n * `TQ1` row at all and the OML_O21 map's only `TQ1` row targets a `ServiceRequest`. The `RXO`-plus-\n * `TQ1` pairing therefore reaches this library on the segment-assembled path (`OMP_O09` and its\n * relatives, already flagged), so this positional grouping is what pairs a timing with the order it\n * times. Every occurrence is kept, in document order and never collapsed, because a second `TQ1` on\n * one order is a fact the request builder has to refuse rather than a duplicate to discard here.\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 /** The `TQ1` timing segments this order carries (in document order); every occurrence, uncollapsed. */\n readonly tq1s: 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 tq1s: 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 = {\n orc: undefined,\n obr: undefined,\n rxo: undefined,\n rxrs: [],\n tq1s: [],\n };\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 \"TQ1\":\n // The TIMING group's schedule belongs to the order that is open. A TQ1 that precedes every\n // ORC/OBR/RXO has no order to time, reaches no resource, and is reported as such.\n if (current !== undefined) current.tq1s.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) => ({\n orc: g.orc,\n obr: g.obr,\n rxo: g.rxo,\n rxrs: g.rxrs,\n tq1s: g.tq1s,\n })),\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,\n * with the group's specimens (`4.2.7 SPECIMEN`) and per-result notes (`4.2.4.3.3 OBSERVATION.NTE`)\n * beneath it. This walks the segments in document order and buckets each one under the most recent\n * anchor: the same positional grouping `@cosyte/hl7`'s `orders()` performs, done here so the raw\n * OBR/OBX `Segment`s are available (the report/result fields the lean `Order` view omits, namely\n * OBR-7/22/24/25, and the exact lexical OBX-5 magnitude the `Observation` view rounds to a JS\n * `number`). An OBX that precedes any OBR has no report to anchor it and is surfaced by\n * {@link ReportGrouping.orphanObxCount} rather than silently dropped.\n *\n * **Which NTE is which is decided positionally, because the map's three NTE rows differ.** The\n * message map publishes a FHIR target for the OBSERVATION group's NTE (`4.2.4.3.3` →\n * `Observation.note`) and **none at all** for the PATIENT-level (`4.1.4`) or ORDER_OBSERVATION-level\n * (`4.2.3`) rows. In the wire's segment order those are exactly the NTEs that follow an OBX, so an\n * NTE is attached to an observation only while one is open: any other segment closes it, and an NTE\n * before the first OBX of a group, or before any OBR, attaches to nothing. It is then reported by\n * the completeness diagnostic as a segment that reached no resource, which is what the guide's\n * silence about it means.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\n\n/** One OBX result and the OBSERVATION-group NTE segments beneath it, in document order. */\nexport interface ObservationEntry {\n /** The OBX segment carrying the result. */\n readonly obx: Segment;\n /** The NTE segments that followed it with no other segment in between → `Observation.note`. */\n readonly notes: readonly Segment[];\n}\n\n/** One ORU report group: an OBR anchor, the OBX results beneath it, and the group's specimens. */\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), each with its notes. */\n readonly observations: readonly ObservationEntry[];\n /** The SPM segments of this group's SPECIMEN occurrences (message map row 4.2.7.1). */\n readonly specimens: 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\ninterface MutableGroup {\n readonly obr: Segment;\n readonly observations: { obx: Segment; notes: Segment[] }[];\n readonly specimens: Segment[];\n}\n\n/**\n * Group an ORU message's OBR/OBX/SPM/NTE segments into report groups (each OBR with its trailing\n * OBX results and their notes, plus the SPM occurrences of its SPECIMEN group).\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; groups[0]?.specimens.length;\n * ```\n */\nexport function collectReportGroups(msg: Hl7Message): ReportGrouping {\n const groups: MutableGroup[] = [];\n let current: MutableGroup | undefined;\n let openObservation: { obx: Segment; notes: Segment[] } | undefined;\n let orphanObxCount = 0;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"NTE\") {\n // Only an NTE inside an open OBSERVATION group has a published target; every other one is\n // left unattached, and therefore reported by the completeness diagnostic.\n if (openObservation !== undefined) openObservation.notes.push(seg);\n continue;\n }\n if (seg.type === \"OBX\") {\n if (current === undefined) {\n orphanObxCount += 1;\n openObservation = undefined;\n continue;\n }\n openObservation = { obx: seg, notes: [] };\n current.observations.push(openObservation);\n continue;\n }\n\n // Any other segment closes the OBSERVATION group: a note after it belongs to no observation.\n openObservation = undefined;\n if (seg.type === \"OBR\") {\n current = { obr: seg, observations: [], specimens: [] };\n groups.push(current);\n } else if (seg.type === \"SPM\" && current !== undefined) {\n current.specimens.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, because the US Core `patient-birthTime`\n * extension 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 * The set of HL7 v2 segment names the **HL7 Version 2 to FHIR** Implementation Guide publishes a\n * segment-to-resource map for, transcribed by hand from the guide's own Segment Maps index.\n *\n * This is the one fact the completeness diagnostic cannot derive from the message or from this\n * library's own code: whether a segment the transform did not carry into the Bundle is missing\n * because this library has not built the mapping yet, or because the standard publishes no mapping\n * to build. The two answers are different news for a consumer, so the set is recorded here with the\n * guide version and the retrieval date it was read at, and every entry is auditable against the\n * published index a reader can open themselves.\n *\n * **The set is the guide's, not this library's.** It says nothing about which of these segments the\n * transform actually reads: `IAM` is on it and is not transformed, `RXE` is off it and is read and\n * refused. Whether an occurrence is reported at all is decided elsewhere, by whether it reached an\n * emitted resource; this set only chooses which of the two codes the report carries.\n *\n * **Qualified rows collapse onto their segment name.** The index publishes several maps per name and\n * some of them carry a use qualifier (`MSH[Source]`, `PID[Patient]`, `PV1[EncounterHistory]`,\n * `OBX[Component]`, `NTE[Comment]`, `PD1[LivingWill]`, `PRT[Location]`, `ROL[GeneralPractitioner]`\n * and the rest). A qualifier selects a use of the same segment, so every one of them contributes its\n * base name and nothing else: what a message carries is an `MSH`, never an `MSH[Source]`.\n *\n * @packageDocumentation\n */\n\n/**\n * The published version of the HL7 Version 2 to FHIR Implementation Guide this set was read from.\n *\n * @example\n * ```ts\n * import { IG_SEGMENT_MAPS_VERSION } from \"@cosyte/transform\";\n * IG_SEGMENT_MAPS_VERSION; // \"1.0.0\"\n * ```\n */\nexport const IG_SEGMENT_MAPS_VERSION = \"1.0.0\";\n\n/**\n * The publication date of {@link IG_SEGMENT_MAPS_VERSION}, so a later release of the guide can be\n * told apart from a defect in this library.\n *\n * @example\n * ```ts\n * import { IG_SEGMENT_MAPS_PUBLISHED } from \"@cosyte/transform\";\n * IG_SEGMENT_MAPS_PUBLISHED; // \"2025-10-07\"\n * ```\n */\nexport const IG_SEGMENT_MAPS_PUBLISHED = \"2025-10-07\";\n\n/**\n * The date the Segment Maps index was retrieved and transcribed into {@link IG_MAPPED_SEGMENT_NAMES}.\n *\n * A classification that surprises a reader is answered by re-reading the index at this date: the set\n * is a transcription of a published document at a moment, not a live query.\n *\n * @example\n * ```ts\n * import { IG_SEGMENT_MAPS_RETRIEVED } from \"@cosyte/transform\";\n * IG_SEGMENT_MAPS_RETRIEVED; // \"2026-08-22\"\n * ```\n */\nexport const IG_SEGMENT_MAPS_RETRIEVED = \"2026-08-22\";\n\n/**\n * The Segment Maps index this set was transcribed from, so a reader can audit any entry.\n *\n * @example\n * ```ts\n * import { IG_SEGMENT_MAPS_SOURCE } from \"@cosyte/transform\";\n * IG_SEGMENT_MAPS_SOURCE.startsWith(\"https://\"); // true\n * ```\n */\nexport const IG_SEGMENT_MAPS_SOURCE = \"https://hl7.org/fhir/uv/v2mappings/segment_maps.html\";\n\n/**\n * Every v2 segment name the guide publishes at least one segment-to-resource map for, at\n * {@link IG_SEGMENT_MAPS_VERSION}, as of {@link IG_SEGMENT_MAPS_RETRIEVED}.\n *\n * Thirty-three names, transcribed chapter by chapter from {@link IG_SEGMENT_MAPS_SOURCE}: Control\n * (`MSA`, `MSH`, `NTE`, `SFT`), Patient Administration (`AL1`, `EVN`, `IAM`, `MRG`, `NK1`, `PD1`,\n * `PID`, `PV1`, `PV2`), Order Entry (`OBR`, `ORC`, `TQ1`), Pharmacy and Vaccination (`RXA`, `RXO`,\n * `RXR`), Financial Management (`DG1`, `IN1`, `IN3`, `PR1`), Observation Reporting (`OBX`, `PRT`,\n * `SPM`), Medical Records (`TXA`), Scheduling (`AIG`, `AIL`, `AIP`, `AIS`, `SCH`) and Personnel\n * Management (`ROL`).\n *\n * Two absences a reader is most likely to check, because they look like oversights and are not:\n * **`RXE` is not on this set** (the guide publishes no map for it, which is why this library counts\n * an `RXE` and refuses to assemble one), and neither is **`GT1`**.\n *\n * @example\n * ```ts\n * import { IG_MAPPED_SEGMENT_NAMES } from \"@cosyte/transform\";\n * IG_MAPPED_SEGMENT_NAMES.has(\"IAM\"); // true\n * IG_MAPPED_SEGMENT_NAMES.has(\"RXE\"); // false\n * ```\n */\nexport const IG_MAPPED_SEGMENT_NAMES: ReadonlySet<string> = Object.freeze(\n new Set([\n \"AIG\",\n \"AIL\",\n \"AIP\",\n \"AIS\",\n \"AL1\",\n \"DG1\",\n \"EVN\",\n \"IAM\",\n \"IN1\",\n \"IN3\",\n \"MRG\",\n \"MSA\",\n \"MSH\",\n \"NK1\",\n \"NTE\",\n \"OBR\",\n \"OBX\",\n \"ORC\",\n \"PD1\",\n \"PID\",\n \"PR1\",\n \"PRT\",\n \"PV1\",\n \"PV2\",\n \"ROL\",\n \"RXA\",\n \"RXO\",\n \"RXR\",\n \"SCH\",\n \"SFT\",\n \"SPM\",\n \"TQ1\",\n \"TXA\",\n ]),\n);\n\n/**\n * Whether the guide publishes a segment map for `name`, decided against\n * {@link IG_MAPPED_SEGMENT_NAMES} and against nothing else.\n *\n * The comparison is exact: a name this library could not classify is not in the set, and is reported\n * as a standard gap for that reason rather than because the guide was consulted and published\n * nothing. That conflation is deliberate and is documented on the code itself; the alternative would\n * be re-deriving a name the parser refused to vouch for.\n *\n * @param name - A v2 segment name, exactly as the parser published it.\n * @example\n * ```ts\n * import { isIgMappedSegmentName } from \"@cosyte/transform\";\n * isIgMappedSegmentName(\"DG1\"); // true\n * isIgMappedSegmentName(\"ZAL\"); // false\n * ```\n */\nexport function isIgMappedSegmentName(name: string): boolean {\n return IG_MAPPED_SEGMENT_NAMES.has(name);\n}\n","/**\n * The message-level completeness diagnostic: which segment occurrences a message carried, which of\n * them contributed to a resource the returned bundle actually contains, and one value-free issue for\n * each one that did not.\n *\n * The library already refuses to produce a confident wrong FHIR value at the datatype and resource\n * levels. This is the same rule one level up. A message can carry an `IAM`, a `DG1` or an `IN1` that\n * nothing here reads, and until now the consumer got a bundle with nothing in it about the allergy\n * and an issues list with nothing in it about the omission: silence read as completeness, which is a\n * claim this library cannot make. After this, a consumer reads the issues list and learns which\n * segments did not reach the bundle, and whether each one is a **library gap**\n * ({@link ISSUE_CODES.TRANSFORM_SEGMENT_NOT_EMITTED}, the IG publishes a map and this library has\n * not built it) or a **standard gap** ({@link ISSUE_CODES.TRANSFORM_SEGMENT_NO_IG_MAP}, the IG\n * publishes no map, or the name could not be classified at all).\n *\n * Four rules carry the safety of this, and each one is enforced here rather than assumed upstream:\n *\n * - **Contribution, never inspection.** An occurrence \"reached\" a resource only if the assembly took\n * at least one of its values, or its identity, into a resource that is present in the returned\n * bundle. An occurrence that was counted, walked past, or already named by another issue did not\n * reach anything: the `RXE` and the orphan `OBX` this library counts and refuses are exactly the\n * omissions a consumer most needs told, so a \"the walker touched it\" reading would silence the\n * two cases the diagnostic exists for.\n * - **A name is rendered only if it passes the segment-identifier shape**\n * ({@link SEGMENT_IDENTIFIER_SHAPE}), applied by this library to the value the parser published,\n * as a positive test the value must pass. Not by excluding known markers, not by importing a\n * constant from the parser package, not by anything that depends on which parser version a\n * consumer resolved: this library declares a peer range that admits any of them, so a rule keyed\n * on a marker literal fails OPEN the moment that literal changes, promoting an unvouched value\n * into a rendering. A shape test fails CLOSED: whatever it does not recognize is located\n * positionally, and no byte of it is reproduced.\n * - **A position that carries no segment is not an occurrence.** The parser materializes an empty\n * position for a blank line so that ordinals stay stable. It carries no name AND no field content,\n * nothing was sent there, and reporting it would be a false claim of clinical omission at a\n * position the sender left empty. It is excluded wherever it sits, and it still counts toward the\n * `[#n]` ordinal of later occurrences so those keep matching the wire. A line that kept its field\n * separator still carries content and IS reported: the exclusion is for the absence of a segment,\n * never for the absence of a name.\n * - **One issue per occurrence, numbered among all occurrences of its name.** Never collapsed,\n * capped or deduplicated, and `[k]` is the occurrence's position among all occurrences of that\n * name, never among the reported ones: a message with two `NK1` of which only the second is\n * reported yields `NK1[2]`.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } from \"@cosyte/hl7\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport { isIgMappedSegmentName } from \"./ig-segment-maps.js\";\n\n/**\n * The HL7 v2 Chapter 2 segment-identifier shape: three characters, a leading letter, applied to the\n * name value ITSELF as a positive membership test that must pass before any name is rendered.\n *\n * Everything else is a malformed name without exception: the empty string, a withheld marker, a raw\n * pre-delimiter token, a bare numeric like `202`, a four-character `AL11`. A malformed occurrence has\n * no name in this library's vocabulary and is identified by position instead.\n *\n * @example\n * ```ts\n * import { SEGMENT_IDENTIFIER_SHAPE } from \"@cosyte/transform\";\n * SEGMENT_IDENTIFIER_SHAPE.test(\"ZAL\"); // true\n * SEGMENT_IDENTIFIER_SHAPE.test(\"202\"); // false\n * ```\n */\nexport const SEGMENT_IDENTIFIER_SHAPE = /^[A-Z][A-Za-z0-9]{2}$/;\n\n/**\n * Whether a segment name may be rendered: the shape test of {@link SEGMENT_IDENTIFIER_SHAPE} applied\n * to the value itself.\n *\n * Deliberately NOT an exclusion of known-bad literals. An exclusion test admits any value it has not\n * heard of, which is the wrong direction for a rule whose whole job is to keep message bytes out of\n * a diagnostic, and it would silently couple this library to one release of the parser package.\n *\n * @param name - The value the parser published as the occurrence's segment type.\n * @example\n * ```ts\n * import { isWellFormedSegmentName } from \"@cosyte/transform\";\n * isWellFormedSegmentName(\"ZAL\"); // true\n * isWellFormedSegmentName(\"AL11\"); // false\n * ```\n */\nexport function isWellFormedSegmentName(name: string): boolean {\n return SEGMENT_IDENTIFIER_SHAPE.test(name);\n}\n\n/**\n * One segment occurrence of a parsed message: a segment as it appears in the message, in message\n * order, with everything needed to locate it in a value-free way and nothing else.\n */\nexport interface SegmentOccurrence {\n /** The parsed segment this occurrence wraps. */\n readonly segment: Segment;\n /** 1-based position among **all** parsed positions, empty ones included, so it matches the wire. */\n readonly ordinal: number;\n /** The renderable segment name, present only when it passed the shape test. */\n readonly name: string | undefined;\n /** 1-based position among the occurrences of {@link SegmentOccurrence.name}, when there is one. */\n readonly nameIndex: number | undefined;\n}\n\n/**\n * Every segment occurrence of a parsed message, in message order.\n *\n * A position that carries neither a name nor any field content is the parser's ordinal placeholder\n * for a blank line: it is not a segment occurrence, it is left out, and it still advances the\n * ordinal of everything after it. A position that carries field content is an occurrence even when\n * its name is empty.\n *\n * @param msg - The parsed message.\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * import { enumerateSegmentOccurrences } from \"@cosyte/transform\";\n * // enumerateSegmentOccurrences(parseHL7(raw))[0]?.name; // \"MSH\"\n * ```\n */\nexport function enumerateSegmentOccurrences(msg: Hl7Message): readonly SegmentOccurrence[] {\n const occurrences: SegmentOccurrence[] = [];\n const seenPerName = new Map<string, number>();\n\n for (const [i, segment] of msg.allSegments().entries()) {\n // The ordinal placeholder: no name AND no field content. Skipped, but `i` still advances, so a\n // later occurrence's `[#n]` keeps naming the line the sender actually wrote.\n if (segment.type === \"\" && segment.fields.length === 0) continue;\n\n if (isWellFormedSegmentName(segment.type)) {\n const nameIndex = (seenPerName.get(segment.type) ?? 0) + 1;\n seenPerName.set(segment.type, nameIndex);\n occurrences.push({ segment, ordinal: i + 1, name: segment.type, nameIndex });\n } else {\n occurrences.push({ segment, ordinal: i + 1, name: undefined, nameIndex: undefined });\n }\n }\n\n return occurrences;\n}\n\n/**\n * The v2 location of an occurrence: `NAME[k]` for a name that passed the shape test, `[#n]` for one\n * that did not. Those are the only two shapes, and neither carries a field or component index.\n *\n * @param occurrence - The occurrence to locate.\n * @example\n * ```ts\n * import { segmentOccurrenceLocation } from \"@cosyte/transform\";\n * // segmentOccurrenceLocation(occ); // \"DG1[2]\" or \"[#4]\"\n * ```\n */\nexport function segmentOccurrenceLocation(occurrence: SegmentOccurrence): string {\n return occurrence.name !== undefined && occurrence.nameIndex !== undefined\n ? `${occurrence.name}[${String(occurrence.nameIndex)}]`\n : `[#${String(occurrence.ordinal)}]`;\n}\n\n/**\n * Tracks, across one message-level assembly, which segment occurrences CONTRIBUTED to a resource the\n * returned bundle contains, and turns the rest into one value-free issue each.\n *\n * The assembly marks an occurrence only where a resource has just cleared the emit gate and joined\n * the bundle, so \"reached\" means contributed-and-present by construction: an occurrence that was\n * read and refused, or that built a resource the gate withheld, is never marked and is therefore\n * reported.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * import { SegmentReachLedger } from \"@cosyte/transform\";\n * // const ledger = new SegmentReachLedger(parseHL7(raw));\n * // ledger.markFirstOfType(\"MSH\");\n * // ledger.issues(); // one issue per occurrence that reached nothing\n * ```\n */\nexport class SegmentReachLedger {\n private readonly occurrences: readonly SegmentOccurrence[];\n private readonly reached = new Set<Segment>();\n\n /**\n * @param msg - The parsed message whose occurrences are being tracked.\n */\n constructor(msg: Hl7Message) {\n this.occurrences = enumerateSegmentOccurrences(msg);\n }\n\n /**\n * Record that each given segment contributed to a resource now present in the bundle. `undefined`\n * entries are ignored, so a call site can pass an optional part of a group without branching.\n */\n mark(...segments: readonly (Segment | undefined)[]): void {\n for (const segment of segments) {\n if (segment !== undefined) this.reached.add(segment);\n }\n }\n\n /**\n * Record that the FIRST occurrence of `type` contributed. The parser's derived views (`patient`,\n * `visit`, `meta`) are built from the first segment of their type, so this is how a resource built\n * from a view marks the occurrence it came from.\n */\n markFirstOfType(type: string): void {\n const found = this.occurrences.find((o) => o.name === type);\n if (found !== undefined) this.reached.add(found.segment);\n }\n\n /**\n * Record that the `index`-th (0-based) occurrence of `type` contributed: the counterpart of\n * {@link SegmentReachLedger.markFirstOfType} for the repeating views (`nextOfKin()`), whose\n * entries are in document order.\n */\n markNthOfType(type: string, index: number): void {\n const matching = this.occurrences.filter((o) => o.name === type);\n const found = matching[index];\n if (found !== undefined) this.reached.add(found.segment);\n }\n\n /** The occurrences that contributed to no resource present in the bundle, in message order. */\n reportable(): readonly SegmentOccurrence[] {\n return this.occurrences.filter((o) => !this.reached.has(o.segment));\n }\n\n /**\n * One value-free issue per reportable occurrence, in message order: the library-gap code when the\n * IG publishes a segment map for the name, the standard-gap code otherwise, and the standard-gap\n * code for every name that could not be classified at all.\n */\n issues(): readonly TransformIssue[] {\n return this.reportable().map((occurrence) =>\n issue(\n occurrence.name !== undefined && isIgMappedSegmentName(occurrence.name)\n ? ISSUE_CODES.TRANSFORM_SEGMENT_NOT_EMITTED\n : ISSUE_CODES.TRANSFORM_SEGMENT_NO_IG_MAP,\n segmentOccurrenceLocation(occurrence),\n ),\n );\n }\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}, *IF no TQ1 timing* |\n * | OBR-31 Reason for Study (CWE) | `reasonCode` | {@link toFhirCodeableConcept} |\n * | TQ1-3 Repeat Pattern (RPT) | `occurrenceTiming` | {@link readTq1} (RPT[Timing], all-or-nothing) |\n * | TQ1-7 / TQ1-8 Start / End date-time | `occurrenceTiming.repeat.boundsPeriod.start`/`.end` | {@link readTq1} |\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 * - **`occurrence[x]` is a choice, so exactly one member is ever emitted.** OBR-6 grounds an\n * `occurrenceDateTime` and a TQ1 grounds an `occurrenceTiming`; a group that would yield both\n * emits the **timing** (the richer statement, and the one the sender wrote a whole segment for)\n * and flags the dropped OBR-6. Emitting both would be structurally invalid FHIR, and silently\n * preferring the single instant would throw away the schedule. The timing itself is\n * all-or-nothing: see {@link readTq1}, whose every refusal leaves `occurrenceTiming` absent and\n * therefore hands the choice back to OBR-6 with no issue raised about it.\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\n * `T{S,M,H,D,W,L}<integer>` 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\";\nimport type { Tq1Reading } from \"./tq1-timing.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, namely `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 tq1 - What the order's `TQ1` occurrences grounded ({@link readTq1}), when it carries any.\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, undefined, \"urn:uuid:pat\", undefined, {});\n * ```\n */\nexport function buildServiceRequest(\n orc: Segment | undefined,\n obr: Segment | undefined,\n tq1: Tq1Reading | undefined,\n subjectFullUrl: string | undefined,\n encounterFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n // The TQ1 diagnostics are raised whatever becomes of the request (see the MedicationRequest note).\n if (tq1 !== undefined) issues.push(...tq1.issues);\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 // occurrence[x]: the TQ1 timing when the order grounded one, else OBR-6's requested date/time.\n // Never both members of the choice; a dropped OBR-6 is flagged rather than silently overwritten.\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 && tq1?.timing === undefined) {\n props.push({ name: \"occurrenceDateTime\", value: primitive(occurrence.value) });\n } else if (occurrence.value !== undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"OBR.6\", \"ServiceRequest.occurrenceDateTime\"),\n );\n }\n }\n if (tq1?.timing !== undefined) {\n props.push({ name: \"occurrenceTiming\", value: tq1.timing });\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 * SPM → FHIR `Specimen`: the sample a result was taken from, carried into the bundle instead of\n * lost between the lab feed and the FHIR record. Grounded firsthand on the IG **Segment SPM to\n * Specimen** ConceptMap and the **ORU_R01 to Bundle** message map (`hl7.fhir.uv.v2mappings`, STU1;\n * `ConceptMap-segment-spm-to-specimen.html`, `ConceptMap-message-oru-r01-to-bundle.html`), whose\n * row 4.2.7.1 creates one Specimen per SPM of an ORDER_OBSERVATION's SPECIMEN group and wires\n * `DiagnosticReport[1].specimen.reference` to it.\n *\n * | SPM field | FHIR target | via |\n * |---|---|---|\n * | SPM-2 Specimen ID (EIP) | `identifier` (placer, then filler) | EI.1 → `Identifier.value` |\n * | SPM-4 Specimen Type (CWE) | `Specimen.type` | {@link toFhirCodeableConcept} |\n * | SPM-6 Specimen Additives (CWE) | `container.additiveCodeableConcept` | {@link toFhirCodeableConcept} |\n * | SPM-7 Collection Method (CWE) | `collection.method` | {@link toFhirCodeableConcept} |\n * | SPM-8 Source Site (CWE) | `collection.bodySite` | {@link toFhirCodeableConcept} |\n * | SPM-14 Specimen Description (ST) | `note` (`Annotation.text`) | one annotation per repetition |\n * | SPM-17 Collection Date/Time (DR) | `collection.collectedPeriod` / `collectedDateTime` | `IF SPM-17.2 VALUED` |\n * | SPM-18 Received Date/Time (DTM) | `Specimen.receivedTime` | {@link toFhirDateTime} |\n * | SPM-24 Specimen Condition (CWE) | `Specimen.condition` | {@link toFhirCodeableConcept} |\n * | SPM-27 Container Type (CWE) | `container.type` | {@link toFhirCodeableConcept} |\n * | SPM-30 Accession ID (CX) | `Specimen.accessionIdentifier` | {@link toFhirIdentifier} |\n * | SPM-31 Other Specimen ID (CX) | `identifier` | {@link toFhirIdentifier} |\n * | SPM-32 Shipment ID (EI) | `identifier` (type `SHIP`, v2-0203) | the row's own fixed assignment |\n * | (message-map wiring) | referenced from `DiagnosticReport.specimen` | the assembler |\n *\n * **Fail-safes (never a confident wrong specimen).**\n * - **The status is never asserted.** `SPM-20` is the only row that targets `Specimen.status`, and\n * it reaches it through a **Table 0136 to specimen-status** value ConceptMap this library does not\n * carry. R4 binds that element `required`, and every member of the binding is a positive claim\n * about a sample a clinician may act on, so the element stays absent and the row is declared\n * {@link ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED}. Unlike `Coverage.status`, `Specimen.status` is\n * `0..1`, so absence is the spec-clean shape and no `data-absent-reason` is needed to hold a slot.\n * - **A specimen never points at a specimen that is not there.** `SPM-3 Specimen Parent IDs` targets\n * `Specimen.parent`, a reference to another Specimen resource; none is built for a parent, so the\n * row is declared rather than emitted as a link that resolves to nothing.\n * - **A collection amount is not rebuilt from parts.** `SPM-12` reaches `collection.quantity`\n * through the `CQ[Quantity]` datatype map, which this library does not carry; assembling one from\n * CQ.1 and CQ.2 by hand would be a unit gate written twice, so the row is declared instead.\n * - **An unresolvable coding system costs the system URI, never the code**, and every date/time goes\n * through the one timezone-safe converter: the datatype converters own both rules and this module\n * only routes fields to them.\n *\n * @packageDocumentation\n */\n\nimport { parseDtm, 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 { toFhirIdentifier } from \"../datatypes/identifier.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 } from \"./reference.js\";\n\n/**\n * The Table 0203 identifier-type code the SPM-32 row **assigns** to the shipment identifier\n * (`Specimen.identifier[3].type.coding.code = \"SHIP\"`, with the v2-0203 system beside it).\n *\n * @example\n * ```ts\n * import { SPM_SHIPMENT_IDENTIFIER_TYPE } from \"@cosyte/transform\";\n * SPM_SHIPMENT_IDENTIFIER_TYPE; // \"SHIP\"\n * ```\n */\nexport const SPM_SHIPMENT_IDENTIFIER_TYPE = \"SHIP\";\n\n/**\n * The SPM rows this library reads and deliberately does not build, each with the target it would\n * have reached. Raised for the occurrence whether or not the Specimen itself is emitted, so a\n * deferred row a message actually valued is in the issues list rather than silently absent.\n */\nconst DEFERRED_SPECIMEN_ROWS: readonly (readonly [field: number, path: string])[] = Object.freeze([\n [3, \"Specimen.parent\"],\n [12, \"Specimen.collection.quantity\"],\n [20, \"Specimen.status\"],\n]);\n\n/** The 1-based subcomponent of a 1-based component of a field's first repetition, or `\"\"`. */\nfunction subcomponent(spm: Segment, field: number, component: number, sub: number): string {\n return spm.field(field).repetitions[0]?.components[component - 1]?.subcomponents[sub - 1] ?? \"\";\n}\n\n/** A CWE field read as a `CodeableConcept`, or `undefined` when the field carries no coded value. */\nfunction codeable(\n spm: Segment,\n field: number,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const converted = toFhirCodeableConcept(spm.field(field).asCwe(), ctx);\n issues.push(...converted.issues);\n return converted.value;\n}\n\n/** A CX field read as an `Identifier`, or `undefined` when it keys nothing. */\nfunction identifierFrom(\n spm: Segment,\n field: number,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const converted = toFhirIdentifier(spm.field(field).asCx(), ctx);\n issues.push(...converted.issues);\n return converted.value;\n}\n\n/**\n * `Specimen.identifier`: the placer and filler halves of SPM-2's EIP, then SPM-31's other specimen\n * id, then SPM-32's shipment id under the type the row assigns. Each entity identifier carries its\n * EI.1 as `Identifier.value` and **no system**: a namespace is never turned into a system URI,\n * because two senders reusing one namespace would otherwise collide.\n */\nfunction buildIdentifiers(\n spm: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex[] {\n const identifiers: FhirComplex[] = [];\n for (const component of [1, 2]) {\n const entityId = subcomponent(spm, 2, component, 1);\n if (entityId !== \"\") {\n identifiers.push(complex([{ name: \"value\", value: primitive(entityId) }]));\n }\n }\n const other = identifierFrom(spm, 31, ctx, issues);\n if (other !== undefined) identifiers.push(other);\n const shipment = orderIdentifier(spm.field(32).value, SPM_SHIPMENT_IDENTIFIER_TYPE);\n if (shipment !== undefined) identifiers.push(shipment);\n return identifiers;\n}\n\n/**\n * `Specimen.collection`: the method, the body site, and the collection time. SPM-17 is a `DR`, and\n * the map's own condition decides the shape: `IF SPM-17.2 VALUED` it is a `collectedPeriod` (via\n * `DR[Period]`), otherwise the start alone is a `collectedDateTime` (via `DR[dateTime]`). Neither\n * bound is ever substituted for the other.\n */\nfunction buildCollection(\n spm: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n\n const method = codeable(spm, 7, ctx, issues);\n if (method !== undefined) props.push({ name: \"method\", value: method });\n const bodySite = codeable(spm, 8, ctx, issues);\n if (bodySite !== undefined) props.push({ name: \"bodySite\", value: bodySite });\n\n const start = subcomponent(spm, 17, 1, 1);\n const end = subcomponent(spm, 17, 2, 1);\n const bounds: { name: string; value: FhirNode }[] = [];\n for (const [raw, name] of [\n [start, \"start\"],\n [end, \"end\"],\n ] as const) {\n if (raw === \"\") continue;\n const converted = toFhirDateTime(parseDtm(raw), ctx.options);\n issues.push(...converted.issues);\n if (converted.value !== undefined) bounds.push({ name, value: primitive(converted.value) });\n }\n if (end !== \"\" && bounds.length > 0) {\n props.push({ name: \"collectedPeriod\", value: complex(bounds) });\n } else if (bounds[0] !== undefined) {\n props.push({ name: \"collectedDateTime\", value: bounds[0].value });\n }\n\n return props.length === 0 ? undefined : complex(props);\n}\n\n/** `Specimen.container`: the container type and the additive the sample sits in. */\nfunction buildContainer(\n spm: Segment,\n ctx: TransformContext,\n issues: TransformIssue[],\n): FhirNode | undefined {\n const props: { name: string; value: FhirNode }[] = [];\n const type = codeable(spm, 27, ctx, issues);\n if (type !== undefined) props.push({ name: \"type\", value: type });\n const additive = codeable(spm, 6, ctx, issues);\n if (additive !== undefined) props.push({ name: \"additiveCodeableConcept\", value: additive });\n return props.length === 0 ? undefined : list([complex(props)]);\n}\n\n/** `Specimen.note`: one `Annotation` per valued SPM-14 repetition, its text carried verbatim. */\nfunction buildDescriptionNotes(spm: Segment): FhirNode | undefined {\n const annotations: FhirComplex[] = [];\n for (const repetition of spm.field(14).repetitions) {\n const text = repetition.components[0]?.subcomponents[0] ?? \"\";\n if (text === \"\") continue;\n annotations.push(complex([{ name: \"text\", value: primitive(text) }]));\n }\n return annotations.length === 0 ? undefined : list(annotations);\n}\n\n/**\n * Build a FHIR `Specimen` resource node from one parsed HL7 v2 SPM segment. Returns\n * `{ value: undefined }` when the segment grounds no element of the map at all, because an empty\n * `Specimen` in a bundle is a claim that a sample was described when nothing about it was sent.\n *\n * @param spm - The SPM `@cosyte/hl7` `Segment`.\n * @param subjectFullUrl - The `urn:uuid:` fullUrl of the bundle's Patient → `Specimen.subject`.\n * @param ctx - The transform context (naming-system registry + timezone policy).\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * // const spm = parseHL7(raw).segments(\"SPM\")[0];\n * // const { value } = buildSpecimen(spm!, \"urn:uuid:pat\", {});\n * ```\n */\nexport function buildSpecimen(\n spm: Segment,\n subjectFullUrl: string | undefined,\n ctx: TransformContext,\n): ConvertResult<FhirComplex> {\n const issues: TransformIssue[] = [];\n\n // The rows read and not built, declared for the occurrence before anything else is decided.\n for (const [field, path] of DEFERRED_SPECIMEN_ROWS) {\n if (spm.field(field).value !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, `SPM.${String(field)}`, path));\n }\n }\n\n const props: { name: string; value: FhirNode }[] = [];\n\n const identifiers = buildIdentifiers(spm, ctx, issues);\n if (identifiers.length > 0) props.push({ name: \"identifier\", value: list(identifiers) });\n\n const accession = identifierFrom(spm, 30, ctx, issues);\n if (accession !== undefined) props.push({ name: \"accessionIdentifier\", value: accession });\n\n const type = codeable(spm, 4, ctx, issues);\n if (type !== undefined) props.push({ name: \"type\", value: type });\n\n // The message map's wiring: the specimen belongs to the bundle's patient, or to nobody named.\n if (subjectFullUrl !== undefined) {\n props.push({\n name: \"subject\",\n value: complex([{ name: \"reference\", value: primitive(subjectFullUrl) }]),\n });\n }\n\n // SPM-18 → receivedTime.\n if (spm.field(18).value !== \"\") {\n const received = toFhirDateTime(spm.field(18).asTs(), ctx.options);\n issues.push(...received.issues);\n if (received.value !== undefined) {\n props.push({ name: \"receivedTime\", value: primitive(received.value) });\n }\n }\n\n const collection = buildCollection(spm, ctx, issues);\n if (collection !== undefined) props.push({ name: \"collection\", value: collection });\n\n const container = buildContainer(spm, ctx, issues);\n if (container !== undefined) props.push({ name: \"container\", value: container });\n\n const condition = codeable(spm, 24, ctx, issues);\n if (condition !== undefined) props.push({ name: \"condition\", value: list([condition]) });\n\n const note = buildDescriptionNotes(spm);\n if (note !== undefined) props.push({ name: \"note\", value: note });\n\n // Nothing but the wiring: no row of the map was grounded, so there is no specimen to describe.\n if (props.every((p) => p.name === \"subject\")) return { value: undefined, issues };\n\n return {\n value: complex([{ name: \"resourceType\", value: primitive(\"Specimen\") }, ...props]),\n issues,\n };\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, + one `AllergyIntolerance` per AL1, + one `Condition` per DG1, one `Procedure` per PR1\n * and one `Coverage` per IN1); the **ORU^R01** results graph becomes\n * `DiagnosticReport` + `Observation` (+ one `Specimen` per SPM of the report's SPECIMEN group,\n * referenced from the report that scopes it); the\n * order-entry graph gives **ORM_O01 / OML_O21** ORC/OBR → `ServiceRequest` and **RXO** (+ RXR, + the\n * order's **TQ1** schedule) → `MedicationRequest`; and the thin IG singles give **VXU_V04**\n * 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 * - **Segment-level completeness.** Every segment occurrence that contributed nothing to a resource\n * the returned bundle contains raises one value-free issue naming it\n * ({@link SegmentReachLedger}), so silence over an omitted segment can no longer read as\n * completeness. The diagnostic OBSERVES this assembly and never steers it: the occurrences are\n * marked where a resource clears the gate above, the issues are appended after every issue the\n * assembly raised, and no resource, value or existing issue changes because of it.\n *\n * @packageDocumentation\n */\n\nimport type { Hl7Message, Segment } 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 { collectAllergies, emitAllergyIntolerance } from \"./allergy-intolerance.js\";\nimport { buildAppointment, collectAppointment } from \"./appointment.js\";\nimport { buildCondition, collectDiagnoses, deferredDiagnosisIssues } from \"./condition.js\";\nimport { buildCoverage, collectCoverages, deferredCoverageIssues } from \"./coverage.js\";\nimport { buildDiagnosticReport } from \"./diagnostic-report.js\";\nimport { buildDocumentReference, collectDocument } from \"./document-reference.js\";\nimport { buildEncounter, emitEncounterDiagnosis } from \"./encounter.js\";\nimport { buildProcedure, collectProcedures, deferredProcedureIssues } from \"./procedure.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 { SegmentReachLedger } from \"./segment-completeness.js\";\nimport { buildServiceRequest } from \"./service-request.js\";\nimport { buildSpecimen } from \"./specimen.js\";\nimport { readTq1 } from \"./tq1-timing.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 clearsEmitGate(resource: FhirComplex): boolean {\n const result =\n resourceType(resource) === \"Patient\"\n ? validateResource(resource, { mode: \"strict\" })\n : validateResource(resource, { mode: \"lenient\", schemas: EMIT_SCHEMAS });\n return result.valid;\n}\n\nfunction passesEmitGate(\n resource: FhirComplex,\n v2Location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): boolean {\n if (clearsEmitGate(resource)) 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 // The completeness ledger observes the assembly below: an occurrence is marked only where the\n // resource it contributed to has just cleared the emit gate and joined the bundle.\n const reach = new SegmentReachLedger(msg);\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 reach.markFirstOfType(\"PID\");\n }\n }\n\n // PV1 → Encounter, subject wired to the Patient (omitted if no valid Patient).\n let encounterFullUrl: string | undefined;\n let encounterEntryIndex = -1;\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 encounterEntryIndex = focalEntries.length;\n focalEntries.push({ fullUrl: encounterFullUrl, resource: built.value });\n reach.markFirstOfType(\"PV1\");\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 reach.markNthOfType(\"NK1\", i);\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 // AL1 → AllergyIntolerance, one per occurrence, patient wired to the bundle Patient. The IG's\n // ADT_A01 message map fixes that wiring (AllergyIntolerance.patient.reference = Patient[1].id) and\n // the segment map is reusable, so it is applied wherever an AL1 occurs. With no Patient there is\n // nothing to anchor an allergy to: it is withheld and declared per occurrence, never emitted with\n // a dangling reference to a patient the bundle does not carry.\n const allergyFullUrls: string[] = [];\n const allergies = collectAllergies(msg);\n for (let i = 0; i < allergies.length; i++) {\n const al1 = allergies[i];\n if (al1 === undefined) continue;\n const location = `AL1[${String(i)}]`;\n if (patientFullUrl === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, \"AllergyIntolerance.patient\"),\n );\n continue;\n }\n const emitted = emitAllergyIntolerance(\n al1,\n patientFullUrl,\n msg.meta.version,\n ctx,\n clearsEmitGate,\n location,\n );\n issues.push(...emitted.issues);\n if (emitted.value === undefined) continue;\n const url = ids.next();\n allergyFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: emitted.value });\n reach.mark(al1);\n }\n\n // DG1 → Condition, one per occurrence, subject wired to the bundle Patient. The IG's ADT_A01\n // message map fixes that wiring (Condition[1].subject.reference = Patient[1].id) and the segment\n // map is reusable, so it is applied wherever a DG1 occurs. With no Patient there is nothing to\n // anchor a diagnosis to: it is withheld and declared per occurrence, never emitted with a dangling\n // reference. The rows the guide maps to resources this library does not build are declared for the\n // occurrence either way, so a deferred row a message valued is never silently absent.\n const conditionFullUrls: string[] = [];\n const diagnoses = collectDiagnoses(msg);\n for (let i = 0; i < diagnoses.length; i++) {\n const dg1 = diagnoses[i];\n if (dg1 === undefined) continue;\n const location = `DG1[${String(i)}]`;\n issues.push(...deferredDiagnosisIssues(dg1));\n if (patientFullUrl === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, \"Condition.subject\"));\n continue;\n }\n const built = buildCondition(dg1, patientFullUrl, ctx, location);\n issues.push(...built.issues);\n if (built.value === undefined) continue;\n if (!passesEmitGate(built.value, location, \"Condition\", issues)) continue;\n const url = ids.next();\n conditionFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n reach.mark(dg1);\n }\n if (diagnoses.length > 0) {\n // The message map's third DG1 target. No EpisodeOfCare is built here, so a diagnosis ties to an\n // Encounter or to nothing: declared once for the message, the way the other unbuilt targets are.\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"DG1\", \"EpisodeOfCare\"));\n }\n\n // The message map's other DG1 row: Encounter[1].diagnosis.reference = Condition[1].id. The\n // Encounter joined the bundle before its diagnoses existed and the produced nodes are immutable,\n // so the entry is replaced by the same Encounter carrying the back-references, re-gated first.\n if (conditionFullUrls.length > 0 && encounterEntryIndex >= 0) {\n const emitted = focalEntries[encounterEntryIndex];\n if (emitted !== undefined) {\n const linked = emitEncounterDiagnosis(emitted.resource, conditionFullUrls, clearsEmitGate);\n issues.push(...linked.issues);\n if (linked.value !== undefined) {\n focalEntries[encounterEntryIndex] = { fullUrl: emitted.fullUrl, resource: linked.value };\n }\n }\n }\n\n // PR1 → Procedure, one per occurrence, subject wired to the bundle Patient\n // (Procedure.subject.reference = Patient[1].id in the ADT_A01 message map).\n const procedureFullUrls: string[] = [];\n const procedures = collectProcedures(msg);\n for (let i = 0; i < procedures.length; i++) {\n const pr1 = procedures[i];\n if (pr1 === undefined) continue;\n const location = `PR1[${String(i)}]`;\n issues.push(...deferredProcedureIssues(pr1));\n if (patientFullUrl === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, \"Procedure.subject\"));\n continue;\n }\n const built = buildProcedure(pr1, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value === undefined) continue;\n if (!passesEmitGate(built.value, location, \"Procedure\", issues)) continue;\n const url = ids.next();\n procedureFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n reach.mark(pr1);\n }\n\n // IN1 → Coverage, one per occurrence, beneficiary wired to the bundle Patient\n // (Coverage.beneficiary.reference = Patient[1].id in the ADT_A01 message map). Collected before\n // the PV1-20 declaration below, which is scoped to the insurance the message carries.\n const coverages = collectCoverages(msg);\n\n // The PV1-20 financial class also targets Coverage[1] in the message map, the SAME Coverage[1]\n // the IN1 rows create. Its contribution to that resource is not built here, so it is declared for\n // an insured message rather than dropped in silence. A message with no IN1 has no Coverage[1] for\n // the row to contribute to and is left exactly as the reading of IN1 found it: the PV1[Coverage]\n // segment map, which is that message's only route to a Coverage, is not read here at all.\n const visitSegment = msg.allSegments().find((seg) => seg.type === \"PV1\");\n if (coverages.length > 0 && visitSegment !== undefined && visitSegment.field(20).value !== \"\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, \"PV1.20\", \"Coverage\"));\n }\n\n const coverageFullUrls: string[] = [];\n for (let i = 0; i < coverages.length; i++) {\n const in1 = coverages[i];\n if (in1 === undefined) continue;\n const location = `IN1[${String(i)}]`;\n issues.push(...deferredCoverageIssues(in1));\n if (patientFullUrl === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_ELEMENT_DROPPED, location, \"Coverage.beneficiary\"));\n continue;\n }\n const built = buildCoverage(in1, patientFullUrl, ctx, location);\n issues.push(...built.issues);\n if (built.value === undefined) continue;\n if (!passesEmitGate(built.value, location, \"Coverage\", issues)) continue;\n const url = ids.next();\n coverageFullUrls.push(url);\n focalEntries.push({ fullUrl: url, resource: built.value });\n reach.mark(in1);\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 observation = group.observations[i];\n if (observation === undefined) continue;\n const built = buildObservation(\n observation.obx,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n observation.notes,\n );\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 // The OBSERVATION-group NTEs contributed their text to the Observation just emitted.\n reach.mark(observation.obx, ...observation.notes);\n }\n }\n\n // SPM → Specimen, one per SPECIMEN group occurrence. Built here but held back: the map wires\n // the specimen to the report that scopes it, so a report the gate withholds takes its\n // specimens with it rather than leaving entries nothing in the bundle points at.\n const specimenFullUrls: string[] = [];\n const specimenEntries: Entry[] = [];\n const emittedSpecimens: Segment[] = [];\n for (let i = 0; i < group.specimens.length; i++) {\n const spm = group.specimens[i];\n if (spm === undefined) continue;\n const built = buildSpecimen(spm, patientFullUrl, ctx);\n issues.push(...built.issues);\n if (built.value === undefined) continue;\n if (!passesEmitGate(built.value, `SPM[${String(i)}]`, \"Specimen\", issues)) continue;\n const url = ids.next();\n specimenFullUrls.push(url);\n specimenEntries.push({ fullUrl: url, resource: built.value });\n emittedSpecimens.push(spm);\n }\n\n const report = buildDiagnosticReport(\n group.obr,\n resultFullUrls,\n patientFullUrl,\n encounterFullUrl,\n ctx,\n specimenFullUrls,\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 reach.mark(group.obr);\n // The Specimens join only now, with the report that scopes them: withheld together or\n // present together, so neither side of the wiring is ever left pointing at nothing.\n focalEntries.push(...specimenEntries);\n reach.mark(...emittedSpecimens);\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 // The order's TQ1 schedule, read once for this target: a refused one leaves the request's\n // occurrence[x] to OBR-6 and leaves every TQ1 occurrence unreached, which is the point.\n const tq1 = readTq1(group.tq1s, \"ServiceRequest\", ctx);\n const built = buildServiceRequest(\n group.orc,\n group.obr,\n tq1,\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 reach.mark(group.orc, group.obr, tq1.contributes ? group.tq1s[0] : undefined);\n }\n }\n // MedicationRequest: an RXO pharmacy order detail (+ its first RXR route, its opening ORC).\n if (group.rxo !== undefined) {\n const tq1 = readTq1(group.tq1s, \"MedicationRequest\", ctx);\n const built = buildMedicationRequest(\n group.rxo,\n group.rxrs[0],\n group.orc,\n tq1,\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 // Only the FIRST RXR is incorporated into the request; a later one contributed nothing.\n // The TQ1 is marked only when it actually put a timing, an instruction or a narrative in.\n reach.mark(\n group.rxo,\n group.rxrs[0],\n group.orc,\n tq1.contributes ? group.tq1s[0] : undefined,\n );\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 reach.mark(group.rxa, group.rxr, group.orc);\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 reach.mark(seg);\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 reach.mark(sch, ais);\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 reach.mark(txa, ...obxs);\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 ...allergyFullUrls,\n ...conditionFullUrls,\n ...procedureFullUrls,\n ...coverageFullUrls,\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 reach.markFirstOfType(\"MSH\");\n }\n entries.push(...focalEntries);\n\n const bundle = buildBundle(msg, entries, ctx, issues);\n\n // The completeness diagnostic goes last, so every issue the assembly raised keeps its position and\n // its relative order, and a consumer reading the tail reads exactly what did not reach the bundle.\n issues.push(...reach.issues());\n\n return { bundle, issues };\n}\n","/**\n * Reading the `@cosyte/fhir` node model on the way **out** of FHIR, never-throw by construction.\n *\n * The reverse direction is handed nodes it did not build, so every read here answers two questions at\n * once: what the element carries, and whether it is the *kind* of node FHIR says it should be. A node\n * of the wrong kind (a `HumanName` where a string belongs, a string where a list belongs) is not an\n * exception here: it raises {@link ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED} on the caller's issue\n * sink and reads as absent, so the whole-repository never-throw guardrail holds for structurally\n * malformed input exactly as it does for unmappable input.\n *\n * @packageDocumentation\n */\n\nimport {\n getProperty,\n isComplex,\n isList,\n isPrimitive,\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\";\n\n/** The nodes an element carries: a list's items, a lone node as one item, or none when absent. */\nfunction itemsOf(node: FhirNode | undefined): readonly FhirNode[] {\n if (node === undefined) return [];\n return isList(node) ? node.items : [node];\n}\n\n/**\n * The named property of a complex node, or `undefined` when the element is absent.\n *\n * @param node - The complex node to read.\n * @param name - The FHIR element name.\n * @example\n * ```ts\n * // at(patientNode, \"birthDate\") -> the birthDate primitive node, or undefined\n * ```\n */\nexport function at(node: FhirComplex, name: string): FhirNode | undefined {\n return getProperty(node, name);\n}\n\n/**\n * The string a primitive element carries, or `undefined` when it is absent or empty. A node that is\n * not a string primitive is flagged malformed and read as absent.\n *\n * @param node - The element node, or `undefined`.\n * @param location - The v2 target location, for a value-free issue.\n * @param fhirPath - The FHIR path being read.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // readString(at(name, \"family\"), \"PID.5.1\", \"Patient.name.family\", issues) -> \"Public\"\n * ```\n */\nexport function readString(\n node: FhirNode | undefined,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): string | undefined {\n if (node === undefined) return undefined;\n if (!isPrimitive(node) || typeof node.value !== \"string\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED, location, fhirPath));\n return undefined;\n }\n return node.value === \"\" ? undefined : node.value;\n}\n\n/**\n * Every string a repeating primitive element carries, in order; non-string items are flagged\n * malformed and skipped.\n *\n * @param node - The element node, or `undefined`.\n * @param location - The v2 target location, for a value-free issue.\n * @param fhirPath - The FHIR path being read.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // readStrings(at(name, \"given\"), \"PID.5.2\", \"Patient.name.given\", issues) -> [\"Jane\"]\n * ```\n */\nexport function readStrings(\n node: FhirNode | undefined,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): readonly string[] {\n const out: string[] = [];\n for (const item of itemsOf(node)) {\n const value = readString(item, location, fhirPath, issues);\n if (value !== undefined) out.push(value);\n }\n return out;\n}\n\n/**\n * Every complex item a repeating element carries; items of another kind are flagged malformed and\n * skipped.\n *\n * @param node - The element node, or `undefined`.\n * @param location - The v2 target location, for a value-free issue.\n * @param fhirPath - The FHIR path being read.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // readComplexes(at(patient, \"name\"), \"PID.5\", \"Patient.name\", issues) -> [HumanName, ...]\n * ```\n */\nexport function readComplexes(\n node: FhirNode | undefined,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): readonly FhirComplex[] {\n const out: FhirComplex[] = [];\n for (const item of itemsOf(node)) {\n if (isComplex(item)) out.push(item);\n else issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED, location, fhirPath));\n }\n return out;\n}\n\n/**\n * The **exact lexical form** of a numeric element, never routed through a JS `number`: a\n * string-backed `decimal` yields its raw text unchanged. A boolean (or a value-absent) primitive is\n * flagged malformed.\n *\n * @param node - The element node, or `undefined`.\n * @param location - The v2 target location, for a value-free issue.\n * @param fhirPath - The FHIR path being read.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // readNumberText(at(quantity, \"value\"), \"OBX.5\", \"Observation.valueQuantity.value\", issues) -> \"120.50\"\n * ```\n */\nexport function readNumberText(\n node: FhirNode | undefined,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): string | undefined {\n if (node === undefined) return undefined;\n const value = isPrimitive(node) ? node.value : undefined;\n if (value === undefined || typeof value === \"boolean\") {\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED, location, fhirPath));\n return undefined;\n }\n return typeof value === \"string\" ? value : value.raw;\n}\n","/**\n * Writing HL7 v2 field content: the small, safe primitives the reverse (FHIR to v2) maps build on.\n *\n * Two disciplines live here.\n *\n * **Composite content is structured, never concatenated.** A typed composite (XPN, CX, CWE, XAD) is\n * handed to `@cosyte/hl7` as a `RawField` of components, so the serializer owns delimiter escaping:\n * a family name of `Do^e` emits as `Do\\S\\e` and reads back as `Do^e`, where a hand-built `\"Do^e\"`\n * string would have silently become two components. Nothing in this module writes a `^` or a `~`.\n *\n * **A lexical form v2 cannot carry is refused, never trimmed to fit.** {@link v2Timestamp} and\n * {@link v2Number} return `undefined` rather than an approximation, and their callers flag the value\n * and leave the v2 field absent.\n *\n * @packageDocumentation\n */\n\nimport type { RawField } from \"@cosyte/hl7\";\n\n/** One repetition of a field: its components, in order, `undefined` for an absent component. */\nexport type V2Components = readonly (string | undefined)[];\n\n/** A component with a single subcomponent, or an empty component for absent content. */\nfunction component(value: string | undefined): { subcomponents: readonly string[] } {\n return { subcomponents: value === undefined || value === \"\" ? [] : [value] };\n}\n\n/**\n * Build a v2 field from its repetitions, each a list of components, or `undefined` when every\n * repetition is empty (an empty field is left absent, never emitted as structure).\n *\n * @param repetitions - The field's repetitions, outermost first.\n * @example\n * ```ts\n * // v2Field([[\"Public\", \"Jane\"]]) -> a PID-5 field that serializes as `Public^Jane`\n * ```\n */\nexport function v2Field(repetitions: readonly V2Components[]): RawField | undefined {\n const present = repetitions.filter((components) =>\n components.some((value) => value !== undefined && value !== \"\"),\n );\n if (present.length === 0) return undefined;\n return {\n isNull: false,\n repetitions: present.map((components) => {\n // Trailing absent components carry no information on the wire: drop them, keep interior gaps.\n let last = components.length;\n while (last > 0 && (components[last - 1] === undefined || components[last - 1] === \"\"))\n last--;\n return { components: components.slice(0, last).map(component) };\n }),\n };\n}\n\n/**\n * Lay fields out in HL7 1-indexed positional order for `addSegment`, filling unmapped positions with\n * an empty field. Position 1 is the segment's first field (PID-1, OBX-1, ...).\n *\n * @param byPosition - The mapped fields, keyed by their 1-based HL7 field position.\n * @example\n * ```ts\n * // segmentFields(new Map([[3, mrnField], [5, nameField]])) -> [\"\", \"\", mrnField, \"\", nameField]\n * ```\n */\nexport function segmentFields(\n byPosition: ReadonlyMap<number, RawField>,\n): readonly (string | RawField)[] {\n const positions = [...byPosition.keys()];\n const highest = positions.length === 0 ? 0 : Math.max(...positions);\n const out: (string | RawField)[] = [];\n for (let position = 1; position <= highest; position++) {\n out.push(byPosition.get(position) ?? \"\");\n }\n return out;\n}\n\n/** FHIR `date`/`dateTime` lexical forms, at every precision R4 permits. */\nconst FHIR_DATETIME =\n /^(\\d{4})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2}):(\\d{2})(\\.\\d{1,4})?(Z|[+-]\\d{2}:\\d{2}))?)?)?$/;\n\n/**\n * FHIR `date`/`dateTime` to a v2 DTM, precision-preserving, or `undefined` when the value has no\n * faithful v2 form (an unparseable lexical form, or sub-second precision finer than DTM's four\n * digits, which would have to be truncated). `Z` becomes the explicit `+0000` offset v2 writes.\n *\n * @param value - The FHIR lexical date or dateTime.\n * @example\n * ```ts\n * // v2Timestamp(\"2026-01-02\") -> \"20260102\"\n * // v2Timestamp(\"2026-01-02T10:15:00-05:00\") -> \"20260102101500-0500\"\n * ```\n */\nexport function v2Timestamp(value: string): string | undefined {\n const parts = FHIR_DATETIME.exec(value);\n if (parts === null) return undefined;\n const [, year, month, day, hour, minute, second, fraction, zone] = parts;\n let out = year ?? \"\";\n if (month !== undefined) out += month;\n if (day !== undefined) out += day;\n if (hour === undefined) return out;\n out += `${hour}${minute ?? \"\"}${second ?? \"\"}${fraction ?? \"\"}`;\n return out + (zone === \"Z\" ? \"+0000\" : (zone ?? \"\").replace(\":\", \"\"));\n}\n\n/**\n * FHIR `date` to a v2 DTM. A `date` element carrying a time-of-day is outside its own type's value\n * domain, so it is refused (`undefined`) rather than quietly re-read as a `dateTime`: reinterpreting\n * an out-of-domain value is the coercion the fail-safe rule forbids.\n *\n * @param value - The FHIR lexical date.\n * @example\n * ```ts\n * // v2Date(\"1980-01-15\") -> \"19800115\"\n * // v2Date(\"1980-01-15T10:00:00-05:00\") -> undefined\n * ```\n */\nexport function v2Date(value: string): string | undefined {\n return value.includes(\"T\") ? undefined : v2Timestamp(value);\n}\n\n/** The FHIR `decimal` lexical forms a v2 NM can carry verbatim: no exponent, no leading `+`. */\nconst V2_NUMBER = /^-?(0|[1-9]\\d*)(\\.\\d+)?$/;\n\n/**\n * A FHIR decimal's exact lexical form when v2 NM can carry it unchanged, else `undefined`. An\n * exponent form (`1e3`) has no NM representation, and rewriting it would alter the value's lexical\n * precision, so it is refused rather than expanded.\n *\n * @param raw - The decimal's exact lexical text.\n * @example\n * ```ts\n * // v2Number(\"120.50\") -> \"120.50\" (trailing-zero precision preserved)\n * // v2Number(\"1e3\") -> undefined\n * ```\n */\nexport function v2Number(raw: string): string | undefined {\n return V2_NUMBER.test(raw) ? raw : undefined;\n}\n\n/**\n * Invert a forward v2-to-FHIR code map, keeping **only** the targets exactly one v2 code maps to.\n *\n * This is the bijective-subset rule as code. Where several v2 codes are \"equivalent to\" one FHIR\n * concept (Table 0001 `O`/`A`/`N` all map to `other`), the inverse is ambiguous: the target is\n * dropped here, and its caller flags `TRANSFORM_CODE_NOT_INVERTIBLE` rather than picking one member\n * of the set.\n *\n * @param forward - A v2 code to FHIR code map, as published by the IG ConceptMap.\n * @example\n * ```ts\n * import { invertCodeMap } from \"@cosyte/transform\";\n * invertCodeMap({ F: \"female\", O: \"other\", A: \"other\" }); // => { female: \"F\" }\n * ```\n */\nexport function invertCodeMap(\n forward: Readonly<Record<string, string>>,\n): Readonly<Record<string, string>> {\n const sources = new Map<string, string[]>();\n for (const [v2Code, fhirCode] of Object.entries(forward)) {\n const seen = sources.get(fhirCode);\n if (seen === undefined) sources.set(fhirCode, [v2Code]);\n else seen.push(v2Code);\n }\n const inverse: Record<string, string> = {};\n for (const [fhirCode, v2Codes] of sources) {\n const only = v2Codes[0];\n if (v2Codes.length === 1 && only !== undefined) inverse[fhirCode] = only;\n }\n return Object.freeze(inverse);\n}\n","/**\n * Codes and coding systems on the way out to v2, and the caller-supplied context that resolution\n * needs.\n *\n * A v2 coded field names its vocabulary with a Table 0396 mnemonic (`LN`, `SCT`, `UCUM`), so writing\n * a FHIR `Coding` into one means turning a canonical system URI back into that mnemonic. There is no\n * algorithm for that, only a registry, so this module inverts the same seed the forward direction\n * resolves through ({@link DEFAULT_V2_CODE_SYSTEMS} plus whatever the caller adds) and **refuses\n * everything else**: an unrecognized system is flagged, never written into a coded field with no\n * table context and never re-coded into a neighbouring table.\n *\n * The inversion keeps only URIs exactly one mnemonic names, for the same reason the code-map\n * inversion does: two mnemonics for one URI is an ambiguity, not a choice to make silently.\n *\n * @packageDocumentation\n */\n\nimport type { BuildMessageInit } 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 { DEFAULT_V2_CODE_SYSTEMS } from \"../terminology/naming-system.js\";\nimport { at, readComplexes, readString } from \"./read.js\";\nimport { invertCodeMap, type V2Components } from \"./v2.js\";\n\n/**\n * Caller context for a reverse (FHIR to v2) conversion. Every entry is **caller-vetted**: nothing\n * here is derived from resource content, and omitting all of it is safe (the conversion then flags\n * what it cannot resolve rather than guessing it).\n *\n * @example\n * ```ts\n * import { toV2Patient } from \"@cosyte/transform\";\n * const options = {\n * assigningAuthorities: { \"urn:oid:1.2.840.114350\": \"HOSP\" },\n * envelope: { sendingApp: \"EHR\", sendingFacility: \"MAIN\" },\n * };\n * void options;\n * void toV2Patient;\n * ```\n */\nexport interface ReverseOptions {\n /**\n * Extra v2 coding-system mnemonic to canonical URI entries, merged over\n * {@link DEFAULT_V2_CODE_SYSTEMS} and then inverted. Same shape and direction as the forward\n * registry's seed, so one declaration serves both directions.\n */\n readonly codeSystems?: Readonly<Record<string, string>>;\n /**\n * `Identifier.system` URI to the v2 assigning-authority namespace (HD.1) that stands for it. There\n * is no derivation from a URI to a namespace, so an identifier whose system is absent here is\n * emitted with its value and **no** assigning authority, flagged rather than invented.\n */\n readonly assigningAuthorities?: Readonly<Record<string, string>>;\n /**\n * MSH envelope fields for the emitted message (sending/receiving application and facility, control\n * id, timestamp, version, processing id). The message type is never taken from here: it is fixed\n * by the shape plus the caller's trigger argument.\n */\n readonly envelope?: Omit<BuildMessageInit, \"type\">;\n}\n\n/** The resolved, inverted lookups one conversion runs against. */\nexport interface ReverseContext {\n /** The v2 Table 0396 mnemonic for a canonical system URI, or `undefined` when unresolvable. */\n readonly mnemonicFor: (system: string) => string | undefined;\n /** The v2 assigning-authority namespace for an `Identifier.system`, or `undefined`. */\n readonly namespaceFor: (system: string) => string | undefined;\n /** The MSH envelope fields to build the message with. */\n readonly envelope: Omit<BuildMessageInit, \"type\">;\n}\n\n/**\n * Resolve a {@link ReverseOptions} into the lookups a conversion consults.\n *\n * @param options - The caller's reverse options.\n * @example\n * ```ts\n * // reverseContext({ codeSystems: { LOCAL: \"http://example.org/cs\" } }).mnemonicFor(\"http://loinc.org\")\n * // => \"LN\"\n * ```\n */\nexport function reverseContext(options: ReverseOptions = {}): ReverseContext {\n const mnemonics = invertCodeMap({ ...DEFAULT_V2_CODE_SYSTEMS, ...options.codeSystems });\n const authorities = options.assigningAuthorities ?? {};\n return {\n mnemonicFor: (system) => (Object.hasOwn(mnemonics, system) ? mnemonics[system] : undefined),\n namespaceFor: (system) =>\n Object.hasOwn(authorities, system) ? authorities[system] : undefined,\n envelope: options.envelope ?? {},\n };\n}\n\n/** One `Coding`, read into the three v2 components a coded triplet carries. */\ninterface V2Coding {\n readonly code: string | undefined;\n readonly display: string | undefined;\n readonly mnemonic: string;\n}\n\n/**\n * Read one `Coding` into its v2 triplet, or `undefined` when its system has no v2 mnemonic (flagged)\n * or it carries no code at all.\n */\nfunction readCoding(\n coding: FhirComplex,\n ctx: ReverseContext,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): V2Coding | undefined {\n const code = readString(at(coding, \"code\"), location, `${fhirPath}.code`, issues);\n const display = readString(at(coding, \"display\"), location, `${fhirPath}.display`, issues);\n const system = readString(at(coding, \"system\"), location, `${fhirPath}.system`, issues);\n if (code === undefined) return undefined;\n const mnemonic = system === undefined ? undefined : ctx.mnemonicFor(system);\n if (mnemonic === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_SYSTEM_NOT_V2, location, `${fhirPath}.system`));\n return undefined;\n }\n return { code, display, mnemonic };\n}\n\n/**\n * A FHIR `CodeableConcept` as CWE components (CWE.1/2/3 primary triplet, CWE.4/5/6 alternate,\n * CWE.9 original text), or `undefined` when nothing in it can be written to a v2 coded field.\n *\n * Codings whose system has no v2 mnemonic are flagged and left out: the concept degrades to the\n * codings that resolve, and to `CodeableConcept.text` when none do, which is the exact inverse of\n * the CWE to CodeableConcept map's `CWE.9` row.\n *\n * @param concept - The `CodeableConcept` node.\n * @param ctx - The resolved reverse context.\n * @param location - The v2 target location (e.g. `\"OBX.3\"`), for value-free issues.\n * @param fhirPath - The FHIR path being converted.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // codeableToCwe(observationCode, ctx, \"OBX.3\", \"Observation.code\", issues)\n * // => [\"789-8\", \"Hemoglobin\", \"LN\"]\n * ```\n */\nexport function codeableToCwe(\n concept: FhirComplex,\n ctx: ReverseContext,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): V2Components | undefined {\n const codings: V2Coding[] = [];\n for (const coding of readComplexes(\n at(concept, \"coding\"),\n location,\n `${fhirPath}.coding`,\n issues,\n )) {\n const read = readCoding(coding, ctx, location, `${fhirPath}.coding`, issues);\n if (read !== undefined) codings.push(read);\n }\n const text = readString(at(concept, \"text\"), location, `${fhirPath}.text`, issues);\n if (codings.length === 0 && text === undefined) return undefined;\n\n // A third and further coding has no CWE slot: CWE carries a primary and one alternate triplet.\n if (codings.length > 2) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, location, `${fhirPath}.coding`),\n );\n }\n const primary = codings[0];\n const alternate = codings[1];\n return [\n primary?.code,\n primary?.display,\n primary?.mnemonic,\n alternate?.code,\n alternate?.display,\n alternate?.mnemonic,\n undefined,\n undefined,\n text,\n ];\n}\n\n/**\n * The code a concept carries in one specific system, or `undefined` when it carries none there.\n * Used where a v2 field is a bare table code rather than a full CWE (an identifier type, an abnormal\n * flag): a coding from any other system is flagged, never re-read as if it were from this table.\n *\n * @param concept - The `CodeableConcept` node.\n * @param system - The canonical system URI the v2 table corresponds to.\n * @param location - The v2 target location, for value-free issues.\n * @param fhirPath - The FHIR path being converted.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // codeInSystem(identifierType, V2_0203_SYSTEM, \"CX.5\", \"Identifier.type\", issues) -> \"MR\"\n * ```\n */\nexport function codeInSystem(\n concept: FhirComplex,\n system: string,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): string | undefined {\n let found: string | undefined;\n let foreign = false;\n for (const coding of readComplexes(\n at(concept, \"coding\"),\n location,\n `${fhirPath}.coding`,\n issues,\n )) {\n const codingSystem = readString(at(coding, \"system\"), location, `${fhirPath}.system`, issues);\n const code = readString(at(coding, \"code\"), location, `${fhirPath}.code`, issues);\n if (code === undefined) continue;\n if (codingSystem === system) found ??= code;\n else foreign = true;\n }\n if (found === undefined && foreign) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_SYSTEM_NOT_V2, location, `${fhirPath}.system`));\n }\n return found;\n}\n","/**\n * The scaffolding every reverse (FHIR to v2) entry point shares: the required trigger, the resource\n * gate, and the message the mapped segment is carried in.\n *\n * **The trigger is always the caller's.** No FHIR resource carries an HL7 v2 message trigger: not\n * `Patient`, not `Observation`, not `Encounter`. So it is a required argument, and a missing, empty\n * or non-string one stops the conversion **before** any builder call, with\n * {@link ISSUE_CODES.TRANSFORM_MISSING_TRIGGER} on the ordinary `{ value, issues }` channel. It is\n * never defaulted, never derived from resource content, and never substituted with a placeholder.\n *\n * **What is emitted is a message, never a bare segment.** A segment on its own is not parseable HL7\n * (a v2 parser fatally rejects any input whose first segment is not `MSH`), so each shape builds a\n * complete message through `buildMessage` and appends its mapped segment to it. The trigger is used\n * verbatim as the trailing component of the fixed message code the shape itself owns.\n *\n * **What is missing is declared, not merely missing.** A FHIR resource carrying no source for a v2\n * field the segment's own attribute table marks *required* leaves that field absent, because the\n * alternative is inventing content for a clinical reader. Absent is the right wire; **silent** is\n * not, so each shape names its required fields ({@link ReverseShape.required}) and every one of them\n * that ends up unsourced raises {@link ISSUE_CODES.TRANSFORM_V2_REQUIRED_FIELD_ABSENT}. When nothing\n * at all grounded a field, there is no segment to be missing from and no message is built:\n * {@link ISSUE_CODES.TRANSFORM_NO_V2_MESSAGE_EMITTED} declares that outcome on its own, so an\n * empty-handed conversion never looks like a successful one.\n *\n * @packageDocumentation\n */\n\nimport { buildMessage, type Hl7Message, type RawField } from \"@cosyte/hl7\";\nimport { isComplex, resourceType, 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 type { ReverseContext } from \"./coding.js\";\nimport { segmentFields } from \"./v2.js\";\n\n/**\n * What a reverse conversion returns: the complete `@cosyte/hl7` message it could faithfully build\n * (or `undefined` when it could not), plus the value-free diagnostics it raised. The same fail-safe\n * envelope the forward converters return, in the other direction.\n *\n * @example\n * ```ts\n * import { toV2Patient } from \"@cosyte/transform\";\n * // const { value, issues } = toV2Patient(patientNode, \"A28\");\n * // value?.toString() -> \"MSH|^~\\\\&|...|ADT^A28|...\\rPID|||MRN1\\r\"\n * void toV2Patient;\n * ```\n */\nexport type ReverseResult = ConvertResult<Hl7Message>;\n\n/**\n * The resource types this library names in a diagnostic. It is **library-owned vocabulary**: the\n * resource types the forward direction produces, plus the reverse shapes' own inputs. An observed\n * `resourceType` outside it is reported as the generic `Resource`, so no string taken from input\n * content can reach a diagnostic through the unsupported-resource path.\n */\nconst NAMED_RESOURCES: ReadonlySet<string> = new Set([\n \"Appointment\",\n \"Bundle\",\n \"DiagnosticReport\",\n \"DocumentReference\",\n \"Encounter\",\n \"Immunization\",\n \"MedicationRequest\",\n \"MessageHeader\",\n \"Observation\",\n \"OperationOutcome\",\n \"Patient\",\n \"RelatedPerson\",\n \"ServiceRequest\",\n]);\n\n/** Whether a caller actually supplied a trigger at all (the parameter is typed, callers may not be). */\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim() !== \"\";\n}\n\n/** A bare MSH-9.2 trigger: one token, no whitespace and none of the HL7 delimiter characters. */\nconst BARE_TRIGGER = /^[^\\s|^~\\\\&\\r\\n]+$/;\n\n/**\n * Check the caller-supplied trigger. A `false` return means **no builder call may be made**, and one\n * of two value-free issues has been raised:\n *\n * - {@link ISSUE_CODES.TRANSFORM_MISSING_TRIGGER} when it is missing, empty, or not a string. There\n * is nothing to fall back to: no resource carries a trigger, so none is inferred or defaulted.\n * - {@link ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE} when it is a string but not a *bare*\n * trigger. A value carrying a component separator or whitespace cannot be written into MSH-9.2\n * verbatim (`^` would split it into further MSH-9 components, and padding does not survive a\n * parse), so it is refused rather than trimmed or escaped into something the caller did not ask\n * for.\n *\n * @param trigger - The caller's bare v2 trigger (e.g. `\"A28\"`).\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // hasTrigger(\"A28\", issues) -> true; hasTrigger(\"\", issues) -> false + one issue\n * ```\n */\nexport function hasTrigger(trigger: string, issues: TransformIssue[]): boolean {\n if (!isNonEmptyString(trigger)) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_MISSING_TRIGGER, \"MSH.9.2\", \"trigger\"));\n return false;\n }\n if (!BARE_TRIGGER.test(trigger)) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"MSH.9.2\", \"trigger\"));\n return false;\n }\n return true;\n}\n\n/**\n * Gate an input node into the resource a shape accepts: a complex node carrying the expected\n * `resourceType`. Anything else raises {@link ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED} (not a\n * resource) or {@link ISSUE_CODES.TRANSFORM_UNSUPPORTED_RESOURCE} (a resource this converter does\n * not map), and reads as nothing to convert.\n *\n * @param input - The FHIR node handed to the converter.\n * @param expected - The `resourceType` this shape converts.\n * @param location - The v2 target segment, for value-free issues.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // readResource(node, \"Patient\", \"PID\", issues) -> the Patient node, or undefined + one issue\n * ```\n */\nexport function readResource(\n input: FhirNode,\n expected: string,\n location: string,\n issues: TransformIssue[],\n): FhirComplex | undefined {\n if (!isComplex(input)) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED, location, \"Resource\"));\n return undefined;\n }\n const type = resourceType(input);\n if (type === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED, location, \"Resource.resourceType\"));\n return undefined;\n }\n if (type !== expected) {\n const named = NAMED_RESOURCES.has(type) ? type : \"Resource\";\n issues.push(issue(ISSUE_CODES.TRANSFORM_UNSUPPORTED_RESOURCE, location, named));\n return undefined;\n }\n return input;\n}\n\n/**\n * Flag every populated element of a resource that this reverse map does not carry into v2, one\n * value-free issue each. Element **names** are reported only from the supplied table, which is\n * library-owned vocabulary; an element outside it is reported against the resource itself, so no\n * name taken from input content reaches a diagnostic.\n *\n * @param resource - The gated resource node.\n * @param mapped - The element names this shape does convert.\n * @param targets - The known-but-unconverted element names, each with the v2 location it would take.\n * @param resourceName - The resource type, for the FHIR path.\n * @param segment - The v2 segment, used when an element has no location of its own.\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // flagUnmapped(patient, PATIENT_MAPPED, PATIENT_UNMAPPED, \"Patient\", \"PID\", issues)\n * // -> one TRANSFORM_NO_V2_TARGET per populated element outside PATIENT_MAPPED\n * ```\n */\nexport function flagUnmapped(\n resource: FhirComplex,\n mapped: ReadonlySet<string>,\n targets: Readonly<Record<string, string>>,\n resourceName: string,\n segment: string,\n issues: TransformIssue[],\n): void {\n for (const property of resource.properties) {\n if (mapped.has(property.name)) continue;\n const known = Object.hasOwn(targets, property.name);\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_NO_V2_TARGET,\n known ? (targets[property.name] ?? segment) : segment,\n known ? `${resourceName}.${property.name}` : resourceName,\n ),\n );\n }\n}\n\n// ▶ EVERY `RequiredV2Field` ROW A SHAPE DECLARES CLAIMS ONE CELL OF A PUBLISHED HL7\n// v2.5.1 SEGMENT ATTRIBUTE TABLE: the OPT (usage) column reading `R`. The tables\n// are Chapter 3 §3.4.2 (PID) and Chapter 7 §7.4.2 (OBX), the same standard text\n// and the same second, version-pinned publication that `scripts/phi-scan.ts` cites\n// for its field numbers, and the VERSION IS LOAD-BEARING here for the same reason\n// it is there: a later v2 reads some of these cells differently, so grounding\n// against the wrong version's table yields a confident wrong answer, not an error.\n//\n// ▶ AND THE USAGE CELL WAS NOT EXTRACTED BY THE PASS THAT WROTE THESE ROWS, WHICH\n// IS SAID HERE RATHER THAN LEFT TO BE DISCOVERED. That pass ran with no network\n// egress and could not open either publication, so the four rows below are\n// ASSERTED from the attribute tables rather than read out of them. This repository\n// has already measured what that costs once: a `PV1-7` item number written from\n// recall, right by luck, and invisible either way. So the rule that work left\n// behind is kept literally here too: AN ITEM NUMBER IS WRITTEN ONLY WHERE THIS\n// REPOSITORY HAS ALREADY EXTRACTED ONE. `PID-3` (`00106`) and `PID-5` (`00108`)\n// carry theirs, from the Chapter 3 extraction dated 2026-08-08 in\n// `test/scripts/phi-scan.test.ts`; the OBX rows carry NONE, because nothing here\n// has ever extracted one.\n//\n// ▶ RE-EXTRACT BEFORE ADDING A ROW, AND RE-EXTRACT THESE FOUR THE NEXT TIME A\n// READER HAS THE TABLES OPEN. A wrong usage cell is a FALSE DIAGNOSTIC ON A\n// CLINICAL FIELD, the same harm class the field-number corroboration exists for,\n// and unlike a wrong field number it fires on every conversion rather than once.\n\n/**\n * One v2 field the segment's own attribute table marks **required**, paired with the FHIR element\n * this reverse map would have sourced it from. A required field with no source is left absent (v2\n * optionality is a receiver-side contract, and a placeholder would be a fabricated clinical value),\n * and declared: absence is the right wire, silence is not.\n *\n * @example\n * ```ts\n * // { position: 3, location: \"PID.3\", fhirPath: \"Patient.identifier\" }\n * ```\n */\nexport interface RequiredV2Field {\n /** The 1-based HL7 field position within the segment (`3` is the third field). */\n readonly position: number;\n /** The v2 location the issue reports (`\"PID.3\"`), never a value. */\n readonly location: string;\n /** The FHIR path this map sources the field from (`\"Patient.identifier\"`). */\n readonly fhirPath: string;\n}\n\n/**\n * A reverse shape's fixed identity: the message code it emits under, the segment it carries, the\n * resource it converts, and that segment's required fields. All four are library-owned constants;\n * none is derived from input content, so none can carry a value into a diagnostic.\n *\n * @example\n * ```ts\n * // { messageCode: \"ADT\", segment: \"PID\", resourceName: \"Patient\", required: PID_REQUIRED }\n * ```\n */\nexport interface ReverseShape {\n /** The fixed MSH-9.1 message code (`\"ADT\"`, `\"ORU\"`). */\n readonly messageCode: string;\n /** The segment this shape appends (`\"PID\"`, `\"OBX\"`). */\n readonly segment: string;\n /** The resource type this shape converts, for the FHIR path of a whole-message diagnostic. */\n readonly resourceName: string;\n /** The segment's v2-required fields, in field order. */\n readonly required: readonly RequiredV2Field[];\n}\n\n/**\n * Build the complete message for a shape: `buildMessage` with the shape's fixed message code and the\n * caller's trigger, then the mapped segment appended to it, and finally the honest account of what\n * the resource could not supply.\n *\n * Two outcomes, and each is declared:\n *\n * - **Nothing grounded a field.** No message is built (an empty segment is never emitted) and\n * {@link ISSUE_CODES.TRANSFORM_NO_V2_MESSAGE_EMITTED} is raised, so `{ value: undefined }` can\n * never be read as a successful empty conversion. The required-field rows are *not* also raised\n * here: there is no emitted segment for a field to be absent from, and restating it per field\n * would add noise, not information.\n * - **A message is built.** Every one of the shape's required fields that no mapped content reached\n * raises {@link ISSUE_CODES.TRANSFORM_V2_REQUIRED_FIELD_ABSENT}. The wire is untouched by this:\n * the issue reports the field's absence, it never fills it.\n *\n * @param shape - The shape's fixed identity and its segment's required fields.\n * @param trigger - The caller's bare trigger, used verbatim as MSH-9.2.\n * @param byPosition - The mapped fields, keyed by 1-based HL7 field position.\n * @param ctx - The resolved reverse context (its `envelope` supplies the MSH fields).\n * @param issues - The issue sink.\n * @example\n * ```ts\n * // emitMessage(PATIENT_SHAPE, \"A28\", fields, ctx, issues)?.toString()\n * // -> \"MSH|^~\\\\&|...|ADT^A28|...\\rPID|||MRN1||Public^Jane\\r\"\n * ```\n */\nexport function emitMessage(\n shape: ReverseShape,\n trigger: string,\n byPosition: ReadonlyMap<number, RawField>,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): Hl7Message | undefined {\n if (byPosition.size === 0) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_NO_V2_MESSAGE_EMITTED, shape.segment, shape.resourceName),\n );\n return undefined;\n }\n for (const field of shape.required) {\n if (byPosition.has(field.position)) continue;\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_V2_REQUIRED_FIELD_ABSENT, field.location, field.fhirPath),\n );\n }\n return buildMessage({ ...ctx.envelope, type: `${shape.messageCode}^${trigger}` }).addSegment(\n shape.segment,\n segmentFields(byPosition),\n );\n}\n","/**\n * FHIR `Patient` to a v2 message carrying a `PID` segment: the inverse of the IG **Segment PID to\n * Patient** ConceptMap, over the rows whose inverse is defensible.\n *\n * | FHIR element | PID field | inverse |\n * |---|---|---|\n * | `Patient.identifier` | PID-3 (CX) | value to CX.1, caller-vetted authority to CX.4, Table 0203 type to CX.5 |\n * | `Patient.name` | PID-5 (XPN) | family/given/prefix/suffix to XPN.1-XPN.5, `use` to XPN.7 where the HL70200 map inverts |\n * | `Patient.birthDate` | PID-7 (DTM) | lexical date, precision preserved |\n * | `Patient.gender` | PID-8 | Table 0001 where the map inverts (`female`/`male`/`unknown`) |\n * | `Patient.address` | PID-11 (XAD) | line/city/state/postalCode/country/district, `use` to XAD.7 where HL70190 inverts |\n *\n * **This is the lossy direction, and it says so rather than papering over it.** The published map is\n * v2 to FHIR; several of its rows are many-to-one, so the inverse is ambiguous and is refused:\n * `gender` `other` (Table 0001 `O`, `A` and `N` all mean it), name use `official` (`L` and `R`) and\n * `temp` (`NAV` and `TEMP`), address use `work` (`B` and `O`), and every `Address.type`\n * (`M` and `SH` both mean `postal`). Each leaves its v2 field absent and raises\n * {@link ISSUE_CODES.TRANSFORM_CODE_NOT_INVERTIBLE}. Nothing here reconstructs a v2 message that was\n * transformed to FHIR: it writes what the FHIR resource itself supports, and flags the rest.\n *\n * @packageDocumentation\n */\n\nimport type { FhirComplex, FhirNode } from \"@cosyte/fhir\";\nimport type { RawField } from \"@cosyte/hl7\";\n\nimport { ADDRESS_USE_MAP } from \"../datatypes/address.js\";\nimport { NAME_USE_MAP } from \"../datatypes/human-name.js\";\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport { ADMINISTRATIVE_GENDER_MAP } from \"../messages/patient.js\";\nimport { V2_0203_SYSTEM } from \"../terminology/naming-system.js\";\nimport {\n codeInSystem,\n reverseContext,\n type ReverseContext,\n type ReverseOptions,\n} from \"./coding.js\";\nimport {\n emitMessage,\n flagUnmapped,\n hasTrigger,\n readResource,\n type RequiredV2Field,\n type ReverseResult,\n type ReverseShape,\n} from \"./message.js\";\nimport { at, readComplexes, readString, readStrings } from \"./read.js\";\nimport { invertCodeMap, v2Date, v2Field, type V2Components } from \"./v2.js\";\n\n/**\n * FHIR `administrative-gender` to HL7 v2 Table 0001, the invertible rows of the IG's **HL70001 to\n * Administrative Gender** map. `other` is absent on purpose: three source codes carry it.\n *\n * @example\n * ```ts\n * import { GENDER_TO_V2 } from \"@cosyte/transform\";\n * GENDER_TO_V2[\"female\"]; // => \"F\"\n * GENDER_TO_V2[\"other\"]; // => undefined (ambiguous inverse, flagged instead)\n * ```\n */\nexport const GENDER_TO_V2: Readonly<Record<string, string>> =\n invertCodeMap(ADMINISTRATIVE_GENDER_MAP);\n\n/**\n * FHIR `name-use` to HL7 v2 Table 0200, the invertible rows of the IG's **HL70200 to name-use** map.\n * `official` and `temp` are absent on purpose: two source codes each.\n *\n * @example\n * ```ts\n * import { NAME_USE_TO_V2 } from \"@cosyte/transform\";\n * NAME_USE_TO_V2[\"maiden\"]; // => \"M\"\n * ```\n */\nexport const NAME_USE_TO_V2: Readonly<Record<string, string>> = invertCodeMap(NAME_USE_MAP);\n\n/**\n * FHIR `address-use` to HL7 v2 Table 0190, the invertible rows of the IG's **HL70190 to\n * address-use** map. `work` is absent on purpose (`B` and `O`), as is every `Address.type` row.\n *\n * @example\n * ```ts\n * import { ADDRESS_USE_TO_V2 } from \"@cosyte/transform\";\n * ADDRESS_USE_TO_V2[\"home\"]; // => \"H\"\n * ```\n */\nexport const ADDRESS_USE_TO_V2: Readonly<Record<string, string>> = invertCodeMap(ADDRESS_USE_MAP);\n\n/** The `Patient` elements this map carries into PID. */\nconst PATIENT_MAPPED: ReadonlySet<string> = new Set([\n \"resourceType\",\n \"identifier\",\n \"name\",\n \"birthDate\",\n \"gender\",\n \"address\",\n]);\n\n// The PID rows whose v2.5.1 usage is `R`, and ONLY those two. PID-1 is `O`, PID-2\n// and PID-4 are `B` (retained for backward compatibility, not required), and\n// PID-6, PID-7, PID-8 and PID-11 are `O`, so none of them is declared here even\n// though this map writes three of them: declaring an optional field as required\n// would be a false diagnostic on a clinical field. Read the grounding banner above\n// `RequiredV2Field` in `message.ts` before adding a row to this list.\n/** The PID fields v2.5.1 requires, with the `Patient` element this map sources each from. */\nconst PID_REQUIRED: readonly RequiredV2Field[] = [\n // PID-3 Patient Identifier List, v2.5.1 item 00106.\n { position: 3, location: \"PID.3\", fhirPath: \"Patient.identifier\" },\n // PID-5 Patient Name, v2.5.1 item 00108.\n { position: 5, location: \"PID.5\", fhirPath: \"Patient.name\" },\n];\n\n/** What `toV2Patient` emits: an `ADT` message carrying a `PID`, whose required fields are above. */\nconst PATIENT_SHAPE: ReverseShape = {\n messageCode: \"ADT\",\n segment: \"PID\",\n resourceName: \"Patient\",\n required: PID_REQUIRED,\n};\n\n/** `Patient` elements with a known PID home this narrow map does not implement. */\nconst PATIENT_UNMAPPED: Readonly<Record<string, string>> = Object.freeze({\n telecom: \"PID.13\",\n communication: \"PID.15\",\n maritalStatus: \"PID.16\",\n multipleBirthBoolean: \"PID.24\",\n multipleBirthInteger: \"PID.25\",\n deceasedDateTime: \"PID.29\",\n deceasedBoolean: \"PID.30\",\n contact: \"NK1\",\n});\n\n/** A code's inverse, or `undefined` plus a flag when the governing map does not invert it. */\nfunction invertible(\n inverse: Readonly<Record<string, string>>,\n code: string,\n location: string,\n fhirPath: string,\n issues: TransformIssue[],\n): string | undefined {\n if (Object.hasOwn(inverse, code)) return inverse[code];\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_NOT_INVERTIBLE, location, fhirPath));\n return undefined;\n}\n\n/** One `Identifier` as CX components, or `undefined` when it carries no value to key on. */\nfunction identifierComponents(\n identifier: FhirComplex,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): V2Components | undefined {\n const value = readString(at(identifier, \"value\"), \"CX.1\", \"Patient.identifier.value\", issues);\n if (value === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_NO_V2_TARGET, \"CX.1\", \"Patient.identifier\"));\n return undefined;\n }\n // CX.4 is an assigning authority, and no algorithm turns a system URI into one: only a\n // caller-vetted namespace is written, and an unseeded system is flagged, never synthesized.\n const system = readString(at(identifier, \"system\"), \"CX.4\", \"Patient.identifier.system\", issues);\n let namespace: string | undefined;\n if (system !== undefined) {\n namespace = ctx.namespaceFor(system);\n if (namespace === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_NO_V2_TARGET, \"CX.4\", \"Patient.identifier.system\"));\n }\n }\n const typeConcept = readComplexes(\n at(identifier, \"type\"),\n \"CX.5\",\n \"Patient.identifier.type\",\n issues,\n )[0];\n const typeCode =\n typeConcept === undefined\n ? undefined\n : codeInSystem(typeConcept, V2_0203_SYSTEM, \"CX.5\", \"Patient.identifier.type\", issues);\n return [value, undefined, undefined, namespace, typeCode];\n}\n\n/** One `HumanName` as XPN components. */\nfunction nameComponents(name: FhirComplex, issues: TransformIssue[]): V2Components {\n const family = readString(at(name, \"family\"), \"XPN.1\", \"Patient.name.family\", issues);\n const given = readStrings(at(name, \"given\"), \"XPN.2\", \"Patient.name.given\", issues);\n const prefix = readStrings(at(name, \"prefix\"), \"XPN.5\", \"Patient.name.prefix\", issues);\n const suffix = readStrings(at(name, \"suffix\"), \"XPN.4\", \"Patient.name.suffix\", issues);\n const use = readString(at(name, \"use\"), \"XPN.7\", \"Patient.name.use\", issues);\n\n // XPN carries one further-given component, one prefix and one suffix: extras would have to be\n // joined or dropped, and both alter the name, so they are flagged and left out.\n if (given.length > 2) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"XPN.3\", \"Patient.name.given\"),\n );\n }\n if (prefix.length > 1) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"XPN.5\", \"Patient.name.prefix\"),\n );\n }\n if (suffix.length > 1) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"XPN.4\", \"Patient.name.suffix\"),\n );\n }\n const nameType =\n use === undefined\n ? undefined\n : invertible(NAME_USE_TO_V2, use, \"XPN.7\", \"Patient.name.use\", issues);\n return [family, given[0], given[1], suffix[0], prefix[0], undefined, nameType];\n}\n\n/** One `Address` as XAD components. */\nfunction addressComponents(address: FhirComplex, issues: TransformIssue[]): V2Components {\n const line = readStrings(at(address, \"line\"), \"XAD.1\", \"Patient.address.line\", issues);\n const city = readString(at(address, \"city\"), \"XAD.3\", \"Patient.address.city\", issues);\n const state = readString(at(address, \"state\"), \"XAD.4\", \"Patient.address.state\", issues);\n const postal = readString(\n at(address, \"postalCode\"),\n \"XAD.5\",\n \"Patient.address.postalCode\",\n issues,\n );\n const country = readString(at(address, \"country\"), \"XAD.6\", \"Patient.address.country\", issues);\n const district = readString(at(address, \"district\"), \"XAD.9\", \"Patient.address.district\", issues);\n const use = readString(at(address, \"use\"), \"XAD.7\", \"Patient.address.use\", issues);\n const type = readString(at(address, \"type\"), \"XAD.7\", \"Patient.address.type\", issues);\n\n if (line.length > 2) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"XAD.2\", \"Patient.address.line\"),\n );\n }\n const addressType =\n use === undefined\n ? undefined\n : invertible(ADDRESS_USE_TO_V2, use, \"XAD.7\", \"Patient.address.use\", issues);\n // FHIR splits use (home/work) from type (postal/physical); XAD.7 is one code, and the IG's\n // address-type rows are many-to-one, so a type is always flagged rather than merged into XAD.7.\n if (type !== undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_NOT_INVERTIBLE, \"XAD.7\", \"Patient.address.type\"));\n }\n return [line[0], line[1], city, state, postal, country, addressType, undefined, district];\n}\n\n/** Every PID field this map produces, keyed by HL7 field position. */\nfunction pidFields(\n patient: FhirComplex,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): ReadonlyMap<number, RawField> {\n const fields = new Map<number, RawField>();\n\n const identifiers: V2Components[] = [];\n for (const identifier of readComplexes(\n at(patient, \"identifier\"),\n \"PID.3\",\n \"Patient.identifier\",\n issues,\n )) {\n const components = identifierComponents(identifier, ctx, issues);\n if (components !== undefined) identifiers.push(components);\n }\n const pid3 = v2Field(identifiers);\n if (pid3 !== undefined) fields.set(3, pid3);\n\n const names = readComplexes(at(patient, \"name\"), \"PID.5\", \"Patient.name\", issues).map((name) =>\n nameComponents(name, issues),\n );\n const pid5 = v2Field(names);\n if (pid5 !== undefined) fields.set(5, pid5);\n\n const birthDate = readString(at(patient, \"birthDate\"), \"PID.7\", \"Patient.birthDate\", issues);\n if (birthDate !== undefined) {\n const dtm = v2Date(birthDate);\n if (dtm === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"PID.7\", \"Patient.birthDate\"),\n );\n } else {\n const pid7 = v2Field([[dtm]]);\n if (pid7 !== undefined) fields.set(7, pid7);\n }\n }\n\n const gender = readString(at(patient, \"gender\"), \"PID.8\", \"Patient.gender\", issues);\n const sex =\n gender === undefined\n ? undefined\n : invertible(GENDER_TO_V2, gender, \"PID.8\", \"Patient.gender\", issues);\n const pid8 = sex === undefined ? undefined : v2Field([[sex]]);\n if (pid8 !== undefined) fields.set(8, pid8);\n\n const addresses = readComplexes(at(patient, \"address\"), \"PID.11\", \"Patient.address\", issues).map(\n (address) => addressComponents(address, issues),\n );\n const pid11 = v2Field(addresses);\n if (pid11 !== undefined) fields.set(11, pid11);\n\n return fields;\n}\n\n/**\n * Convert a FHIR R4 `Patient` into a **complete** v2 message carrying a `PID` segment, for the\n * demographics-only trigger events (`A28`, `A31`, `A29`, ...) that carry a patient with no visit.\n *\n * The `trigger` argument is **required and never inferred**: no `Patient` element maps to a v2\n * message trigger, so the caller supplies it, and a missing, empty or non-string one returns\n * `{ value: undefined }` plus {@link ISSUE_CODES.TRANSFORM_MISSING_TRIGGER} without calling the\n * message builder at all. It is used verbatim as MSH-9.2 under the `ADT` message code this shape\n * fixes; the caller never supplies the code and it never varies per call.\n *\n * Lossy by design and never round-trip-safe: a value the inverse of the IG map cannot ground is\n * flagged and left absent, never guessed, and a resource of another type is refused outright.\n *\n * A `PID` field v2 requires (PID-3 Patient Identifier List, PID-5 Patient Name) that this resource\n * gives no source for stays absent and is declared with\n * {@link ISSUE_CODES.TRANSFORM_V2_REQUIRED_FIELD_ABSENT}: the emitted message is honest about what\n * it lacks rather than padded to look conformant. A `Patient` that grounds no `PID` field at all\n * yields no message and {@link ISSUE_CODES.TRANSFORM_NO_V2_MESSAGE_EMITTED}.\n *\n * @param resource - The FHIR `Patient` node (build one with `@cosyte/fhir`'s `parseResource`).\n * @param trigger - The bare v2 trigger, e.g. `\"A28\"`. Required; never derived from the resource.\n * @param options - Caller-vetted reverse context: assigning authorities, code systems, MSH envelope.\n * @example\n * ```ts\n * import { parseResource } from \"@cosyte/fhir\";\n * import { toV2Patient } from \"@cosyte/transform\";\n *\n * const { resource } = parseResource('{\"resourceType\":\"Patient\",\"gender\":\"female\"}');\n * const { value, issues } = toV2Patient(resource, \"A28\");\n * // value.toString() starts \"MSH|^~\\\\&|\" and carries \"ADT^A28\" in MSH-9, then a PID segment\n * void value;\n * void issues;\n * ```\n */\nexport function toV2Patient(\n resource: FhirNode,\n trigger: string,\n options: ReverseOptions = {},\n): ReverseResult {\n const issues: TransformIssue[] = [];\n const triggerOk = hasTrigger(trigger, issues);\n const patient = readResource(resource, \"Patient\", \"PID\", issues);\n if (!triggerOk || patient === undefined) return { value: undefined, issues };\n\n flagUnmapped(patient, PATIENT_MAPPED, PATIENT_UNMAPPED, \"Patient\", \"PID\", issues);\n const ctx = reverseContext(options);\n const fields = pidFields(patient, ctx, issues);\n const value = emitMessage(PATIENT_SHAPE, trigger, fields, ctx, issues);\n return { value, issues };\n}\n","/**\n * FHIR `Observation` to a v2 message carrying an `OBX` segment: the inverse of the IG **Segment OBX\n * to Observation** ConceptMap, over the rows whose inverse is defensible.\n *\n * | FHIR element | OBX field | inverse |\n * |---|---|---|\n * | `Observation.code` | OBX-3 (CWE) | coding to CWE.1/2/3 (+ one alternate triplet), `text` to CWE.9 |\n * | `Observation.value[x]` | OBX-2 + OBX-5 | the value type OBX-2 declares is derived from which `value[x]` is present |\n * | `Observation.valueQuantity` units | OBX-6 (CWE) | UCUM code/display, other systems flagged |\n * | `Observation.referenceRange.text` | OBX-7 | carried verbatim, never composed from `low`/`high` |\n * | `Observation.interpretation` | OBX-8 | v3 ObservationInterpretation codes the HL70078 map carries |\n * | `Observation.status` | OBX-11 | Table 0085 where the map inverts |\n * | `Observation.effectiveDateTime` | OBX-14 | lexical timestamp, precision preserved |\n *\n * **OBX-2 is derived, never assumed.** `valueQuantity` writes `NM` (or `SN` when the quantity\n * carries a comparator, which is the only OBX-2 type that can hold one), `valueCodeableConcept`\n * writes `CWE`, `valueString` writes `ST`, `valueDateTime` writes `DTM`. A `value[x]` with no\n * faithful OBX-5 form (`valueRange`, `valueRatio`, `valueBoolean`, ...) writes **nothing** and is\n * flagged: emitting the magnitude of a comparator-bearing or ranged value as a bare number would be\n * a confidently wrong result, which is the one thing this library never does.\n *\n * `Observation.subject` and `.encounter` are flagged rather than emitted: this shape's input is an\n * `Observation` alone, and a PID or PV1 assembled from a bare reference would be fabricated.\n *\n * @packageDocumentation\n */\n\nimport type { FhirComplex, FhirNode } from \"@cosyte/fhir\";\nimport type { RawField } from \"@cosyte/hl7\";\n\nimport { ISSUE_CODES } from \"../diagnostics/codes.js\";\nimport { issue, type TransformIssue } from \"../diagnostics/issue.js\";\nimport {\n HL70078_INTERPRETATION_CODES,\n OBSERVATION_STATUS_MAP,\n V3_OBSERVATION_INTERPRETATION_SYSTEM,\n} from \"../messages/observation.js\";\nimport {\n codeableToCwe,\n codeInSystem,\n reverseContext,\n type ReverseContext,\n type ReverseOptions,\n} from \"./coding.js\";\nimport {\n emitMessage,\n flagUnmapped,\n hasTrigger,\n readResource,\n type RequiredV2Field,\n type ReverseResult,\n type ReverseShape,\n} from \"./message.js\";\nimport { at, readComplexes, readNumberText, readString } from \"./read.js\";\nimport { invertCodeMap, v2Field, v2Number, v2Timestamp, type V2Components } from \"./v2.js\";\n\n/**\n * FHIR `observation-status` to HL7 v2 Table 0085, the invertible rows of the IG's **HL70085 to\n * Observation Status** map. `entered-in-error` is absent on purpose (`D` and `W` both carry it), as\n * are the FHIR statuses the map never targets (`registered`, `unknown`).\n *\n * @example\n * ```ts\n * import { OBSERVATION_STATUS_TO_V2 } from \"@cosyte/transform\";\n * OBSERVATION_STATUS_TO_V2[\"corrected\"]; // => \"C\"\n * OBSERVATION_STATUS_TO_V2[\"entered-in-error\"]; // => undefined (ambiguous inverse, flagged instead)\n * ```\n */\nexport const OBSERVATION_STATUS_TO_V2: Readonly<Record<string, string>> =\n invertCodeMap(OBSERVATION_STATUS_MAP);\n\n/** The FHIR `Quantity.comparator` codes an SN can carry (SN has no \"not equal\" comparator). */\nconst SN_COMPARATORS: ReadonlySet<string> = new Set([\"<\", \"<=\", \">=\", \">\"]);\n\n/** The `Observation` elements this map carries into OBX. */\nconst OBSERVATION_MAPPED: ReadonlySet<string> = new Set([\n \"resourceType\",\n \"code\",\n \"status\",\n \"effectiveDateTime\",\n \"interpretation\",\n \"referenceRange\",\n \"valueQuantity\",\n \"valueCodeableConcept\",\n \"valueString\",\n \"valueDateTime\",\n]);\n\n// The OBX rows whose v2.5.1 usage is `R`, and ONLY those two. OBX-2 (Value Type)\n// and OBX-5 (Observation Value) are `C`, conditional on each other rather than\n// required, and OBX-4 is `C` too, so none of the three is declared here: a\n// conditional field reported as required is a false diagnostic on a clinical\n// field. OBX-1 and OBX-6 through OBX-14 are `O`. Read the grounding banner above\n// `RequiredV2Field` in `message.ts` before adding a row to this list.\n/** The OBX fields v2.5.1 requires, with the `Observation` element this map sources each from. */\nconst OBX_REQUIRED: readonly RequiredV2Field[] = [\n // OBX-3 Observation Identifier. UNREACHABLE TODAY BY CONSTRUCTION, and kept\n // anyway: `obxFields` returns no field at all when it cannot build OBX-3, so an\n // emitted OBX always carries one and this row can only fire if that early return\n // is ever relaxed. It guards the next edit rather than changing this one.\n { position: 3, location: \"OBX.3\", fhirPath: \"Observation.code\" },\n // OBX-11 Observation Result Status.\n { position: 11, location: \"OBX.11\", fhirPath: \"Observation.status\" },\n];\n\n/** What `toV2Observation` emits: an `ORU` message carrying an `OBX`, required fields above. */\nconst OBSERVATION_SHAPE: ReverseShape = {\n messageCode: \"ORU\",\n segment: \"OBX\",\n resourceName: \"Observation\",\n required: OBX_REQUIRED,\n};\n\n/** `Observation` elements with a known OBX/OBR home this narrow map does not implement. */\nconst OBSERVATION_UNMAPPED: Readonly<Record<string, string>> = Object.freeze({\n valueBoolean: \"OBX.5\",\n valueInteger: \"OBX.5\",\n valueRange: \"OBX.5\",\n valueRatio: \"OBX.5\",\n valueTime: \"OBX.5\",\n valuePeriod: \"OBX.5\",\n valueSampledData: \"OBX.5\",\n valueAttachment: \"OBX.5\",\n dataAbsentReason: \"OBX.5\",\n effectivePeriod: \"OBX.14\",\n effectiveInstant: \"OBX.14\",\n issued: \"OBX.19\",\n performer: \"OBX.16\",\n method: \"OBX.17\",\n specimen: \"OBX.18\",\n device: \"OBX.18\",\n bodySite: \"OBX.20\",\n identifier: \"OBX.21\",\n note: \"NTE\",\n subject: \"PID\",\n encounter: \"PV1\",\n basedOn: \"OBR\",\n category: \"OBR\",\n component: \"OBX\",\n hasMember: \"OBX\",\n derivedFrom: \"OBX\",\n});\n\n/** The units CWE for a quantity, or `undefined` when it carries no unit at all. */\nfunction unitComponents(\n quantity: FhirComplex,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): V2Components | undefined {\n const unit = readString(at(quantity, \"unit\"), \"OBX.6\", \"Observation.valueQuantity.unit\", issues);\n const code = readString(at(quantity, \"code\"), \"OBX.6\", \"Observation.valueQuantity.code\", issues);\n const system = readString(\n at(quantity, \"system\"),\n \"OBX.6\",\n \"Observation.valueQuantity.system\",\n issues,\n );\n const mnemonic = system === undefined ? undefined : ctx.mnemonicFor(system);\n if (code !== undefined && mnemonic !== undefined) return [code, unit, mnemonic];\n if (code !== undefined) {\n // A coded unit whose system has no v2 mnemonic (or none at all) cannot be written as a coded\n // unit: the display text survives, the code does not get a borrowed table.\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_SYSTEM_NOT_V2, \"OBX.6\", \"Observation.valueQuantity.system\"),\n );\n }\n return unit === undefined ? undefined : [undefined, unit];\n}\n\n/** OBX-2 / OBX-5 / OBX-6 for a `valueQuantity`. */\nfunction quantityValue(\n quantity: FhirComplex,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): { valueType: string; value: V2Components; units: V2Components | undefined } | undefined {\n const raw = readNumberText(\n at(quantity, \"value\"),\n \"OBX.5\",\n \"Observation.valueQuantity.value\",\n issues,\n );\n const magnitude = raw === undefined ? undefined : v2Number(raw);\n if (magnitude === undefined) {\n if (raw !== undefined) {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE,\n \"OBX.5\",\n \"Observation.valueQuantity.value\",\n ),\n );\n }\n return undefined;\n }\n const units = unitComponents(quantity, ctx, issues);\n const comparator = readString(\n at(quantity, \"comparator\"),\n \"OBX.5\",\n \"Observation.valueQuantity.comparator\",\n issues,\n );\n if (comparator === undefined) return { valueType: \"NM\", value: [magnitude], units };\n if (!SN_COMPARATORS.has(comparator)) {\n // Emitting the magnitude without its comparator would assert a different result: emit neither.\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE,\n \"OBX.5\",\n \"Observation.valueQuantity.comparator\",\n ),\n );\n return undefined;\n }\n // SN.1 comparator, SN.2 number: the structured-numeric shape the IG's OBX-2 = SN row describes.\n return { valueType: \"SN\", value: [comparator, magnitude], units };\n}\n\n/** OBX-2 / OBX-5 / OBX-6 for whichever `value[x]` the observation carries, if any. */\nfunction observationValue(\n observation: FhirComplex,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): { valueType: string; value: V2Components; units: V2Components | undefined } | undefined {\n const quantity = readComplexes(\n at(observation, \"valueQuantity\"),\n \"OBX.5\",\n \"Observation.valueQuantity\",\n issues,\n )[0];\n if (quantity !== undefined) return quantityValue(quantity, ctx, issues);\n\n const concept = readComplexes(\n at(observation, \"valueCodeableConcept\"),\n \"OBX.5\",\n \"Observation.valueCodeableConcept\",\n issues,\n )[0];\n if (concept !== undefined) {\n const cwe = codeableToCwe(concept, ctx, \"OBX.5\", \"Observation.valueCodeableConcept\", issues);\n return cwe === undefined ? undefined : { valueType: \"CWE\", value: cwe, units: undefined };\n }\n\n const text = readString(\n at(observation, \"valueString\"),\n \"OBX.5\",\n \"Observation.valueString\",\n issues,\n );\n if (text !== undefined) return { valueType: \"ST\", value: [text], units: undefined };\n\n const instant = readString(\n at(observation, \"valueDateTime\"),\n \"OBX.5\",\n \"Observation.valueDateTime\",\n issues,\n );\n if (instant !== undefined) {\n const dtm = v2Timestamp(instant);\n if (dtm === undefined) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"OBX.5\", \"Observation.valueDateTime\"),\n );\n return undefined;\n }\n return { valueType: \"DTM\", value: [dtm], units: undefined };\n }\n return undefined;\n}\n\n/** OBX-8: the abnormal flags whose v3 interpretation code the HL70078 map carries. */\nfunction interpretationField(\n observation: FhirComplex,\n issues: TransformIssue[],\n): RawField | undefined {\n const flags: V2Components[] = [];\n for (const concept of readComplexes(\n at(observation, \"interpretation\"),\n \"OBX.8\",\n \"Observation.interpretation\",\n issues,\n )) {\n const code = codeInSystem(\n concept,\n V3_OBSERVATION_INTERPRETATION_SYSTEM,\n \"OBX.8\",\n \"Observation.interpretation\",\n issues,\n );\n if (code === undefined) continue;\n // The HL70078 map is code-preserving, so a v3 code it carries is its own v2 flag; one it does\n // not carry has no v2 abnormal flag and is never coerced to a neighbouring one.\n if (HL70078_INTERPRETATION_CODES.has(code)) flags.push([code]);\n else {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_CODE_NOT_INVERTIBLE, \"OBX.8\", \"Observation.interpretation\"),\n );\n }\n }\n return v2Field(flags);\n}\n\n/** OBX-7: the reference range's text, carried verbatim and never composed from its endpoints. */\nfunction referenceRangeField(\n observation: FhirComplex,\n issues: TransformIssue[],\n): RawField | undefined {\n const ranges = readComplexes(\n at(observation, \"referenceRange\"),\n \"OBX.7\",\n \"Observation.referenceRange\",\n issues,\n );\n if (ranges.length > 1) {\n issues.push(\n issue(ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE, \"OBX.7\", \"Observation.referenceRange\"),\n );\n }\n const first = ranges[0];\n if (first === undefined) return undefined;\n const text = readString(at(first, \"text\"), \"OBX.7\", \"Observation.referenceRange.text\", issues);\n if (text === undefined) {\n // low/high are structured endpoints; OBX-7's own IG row is the text one, and assembling\n // \"3.5-5.0\" from two Quantities would be composing a v2 value this map has no row for.\n issues.push(issue(ISSUE_CODES.TRANSFORM_NO_V2_TARGET, \"OBX.7\", \"Observation.referenceRange\"));\n return undefined;\n }\n return v2Field([[text]]);\n}\n\n/** Every OBX field this map produces, keyed by HL7 field position. */\nfunction obxFields(\n observation: FhirComplex,\n ctx: ReverseContext,\n issues: TransformIssue[],\n): ReadonlyMap<number, RawField> {\n const fields = new Map<number, RawField>();\n\n // OBX-3 is the observation identifier: without one there is no OBX to emit at all.\n const concept = readComplexes(at(observation, \"code\"), \"OBX.3\", \"Observation.code\", issues)[0];\n if (concept === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_RESOURCE_MALFORMED, \"OBX.3\", \"Observation.code\"));\n return fields;\n }\n const cwe = codeableToCwe(concept, ctx, \"OBX.3\", \"Observation.code\", issues);\n const obx3 = cwe === undefined ? undefined : v2Field([cwe]);\n if (obx3 === undefined) return fields;\n fields.set(3, obx3);\n\n const value = observationValue(observation, ctx, issues);\n if (value !== undefined) {\n const obx2 = v2Field([[value.valueType]]);\n const obx5 = v2Field([value.value]);\n if (obx2 !== undefined && obx5 !== undefined) {\n fields.set(2, obx2);\n fields.set(5, obx5);\n }\n const obx6 = value.units === undefined ? undefined : v2Field([value.units]);\n if (obx6 !== undefined) fields.set(6, obx6);\n }\n\n const referenceRange = referenceRangeField(observation, issues);\n if (referenceRange !== undefined) fields.set(7, referenceRange);\n\n const interpretation = interpretationField(observation, issues);\n if (interpretation !== undefined) fields.set(8, interpretation);\n\n const status = readString(at(observation, \"status\"), \"OBX.11\", \"Observation.status\", issues);\n if (status !== undefined) {\n const code = Object.hasOwn(OBSERVATION_STATUS_TO_V2, status)\n ? OBSERVATION_STATUS_TO_V2[status]\n : undefined;\n if (code === undefined) {\n issues.push(issue(ISSUE_CODES.TRANSFORM_CODE_NOT_INVERTIBLE, \"OBX.11\", \"Observation.status\"));\n } else {\n const obx11 = v2Field([[code]]);\n if (obx11 !== undefined) fields.set(11, obx11);\n }\n }\n\n const effective = readString(\n at(observation, \"effectiveDateTime\"),\n \"OBX.14\",\n \"Observation.effectiveDateTime\",\n issues,\n );\n if (effective !== undefined) {\n const dtm = v2Timestamp(effective);\n if (dtm === undefined) {\n issues.push(\n issue(\n ISSUE_CODES.TRANSFORM_VALUE_NOT_REPRESENTABLE,\n \"OBX.14\",\n \"Observation.effectiveDateTime\",\n ),\n );\n } else {\n const obx14 = v2Field([[dtm]]);\n if (obx14 !== undefined) fields.set(14, obx14);\n }\n }\n\n return fields;\n}\n\n/**\n * Convert a FHIR R4 `Observation` into a **complete** v2 message carrying an `OBX` segment, in the\n * result-report (`ORU`) shape.\n *\n * The `trigger` argument is **required and never inferred**: no `Observation` element maps to a v2\n * message trigger, so the caller supplies it, and a missing, empty or non-string one returns\n * `{ value: undefined }` plus {@link ISSUE_CODES.TRANSFORM_MISSING_TRIGGER} without calling the\n * message builder at all. It is used verbatim as MSH-9.2 under the `ORU` message code this shape\n * fixes.\n *\n * The message carries the `OBX` alone: this shape's input is an `Observation`, which names no\n * patient, and a subject segment assembled from a reference would be fabricated. Lossy by design and\n * never round-trip-safe.\n *\n * An `OBX` field v2 requires (OBX-11 Observation Result Status) that this resource gives no source\n * for stays absent and is declared with {@link ISSUE_CODES.TRANSFORM_V2_REQUIRED_FIELD_ABSENT},\n * rather than defaulted to `F`: a result reported as final that the sender never called final is the\n * confidently wrong value this library exists to refuse. An `Observation` that grounds no `OBX`\n * field at all yields no message and {@link ISSUE_CODES.TRANSFORM_NO_V2_MESSAGE_EMITTED}.\n *\n * @param resource - The FHIR `Observation` node.\n * @param trigger - The bare v2 trigger, e.g. `\"R01\"`. Required; never derived from the resource.\n * @param options - Caller-vetted reverse context: code systems and the MSH envelope.\n * @example\n * ```ts\n * import { parseResource } from \"@cosyte/fhir\";\n * import { toV2Observation } from \"@cosyte/transform\";\n *\n * const { resource } = parseResource(\n * '{\"resourceType\":\"Observation\",\"status\":\"final\",\"code\":{\"coding\":[{\"system\":\"http://loinc.org\",\"code\":\"789-8\"}]}}',\n * );\n * const { value, issues } = toV2Observation(resource, \"R01\");\n * // value.toString() carries \"ORU^R01\" in MSH-9, then an OBX whose OBX-3 is \"789-8^^LN\"\n * void value;\n * void issues;\n * ```\n */\nexport function toV2Observation(\n resource: FhirNode,\n trigger: string,\n options: ReverseOptions = {},\n): ReverseResult {\n const issues: TransformIssue[] = [];\n const triggerOk = hasTrigger(trigger, issues);\n const observation = readResource(resource, \"Observation\", \"OBX\", issues);\n if (!triggerOk || observation === undefined) return { value: undefined, issues };\n\n flagUnmapped(observation, OBSERVATION_MAPPED, OBSERVATION_UNMAPPED, \"Observation\", \"OBX\", issues);\n const ctx = reverseContext(options);\n const fields = obxFields(observation, ctx, issues);\n const value = emitMessage(OBSERVATION_SHAPE, trigger, fields, ctx, issues);\n return { value, 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).\n *\n * It also ships a **narrow reverse path**, FHIR → v2: {@link toV2Patient} and\n * {@link toV2Observation} emit a complete v2 message carrying a `PID` or an `OBX` built from the\n * subset of the IG segment maps whose inverse is defensible. Each requires the caller to supply the\n * v2 trigger, because no FHIR resource carries one. It is **lossy by design and not a round-trip**:\n * a value the inverse of the IG map cannot ground is flagged and left absent, never guessed.\n * Terminology **depth beyond these maps**, profiles, and any wider FHIR → v2 conversion are not\n * 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.1.0\";\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 {\n OBSERVATION_STATUS_MAP,\n HL70078_INTERPRETATION_CODES,\n V3_OBSERVATION_INTERPRETATION_SYSTEM,\n OBSERVATION_VALUE_ATTACHMENT_EXTENSION_URL,\n ED_BASE64_ENCODING,\n SAMPLED_DATA_ABSENT_POINT,\n SAMPLED_DATA_UNGROUNDED,\n} from \"./messages/observation.js\";\nexport { DIAGNOSTIC_REPORT_STATUS_MAP } from \"./messages/diagnostic-report.js\";\nexport { SPM_SHIPMENT_IDENTIFIER_TYPE, buildSpecimen } from \"./messages/specimen.js\";\nexport { buildAnnotations } from \"./messages/note.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 completeness: which segments did not reach the returned bundle ─────────────────\nexport {\n SEGMENT_IDENTIFIER_SHAPE,\n SegmentReachLedger,\n enumerateSegmentOccurrences,\n isWellFormedSegmentName,\n segmentOccurrenceLocation,\n} from \"./messages/segment-completeness.js\";\nexport type { SegmentOccurrence } from \"./messages/segment-completeness.js\";\nexport {\n IG_MAPPED_SEGMENT_NAMES,\n IG_SEGMENT_MAPS_PUBLISHED,\n IG_SEGMENT_MAPS_RETRIEVED,\n IG_SEGMENT_MAPS_SOURCE,\n IG_SEGMENT_MAPS_VERSION,\n isIgMappedSegmentName,\n} from \"./messages/ig-segment-maps.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// ── Message-level assembly: AL1 → AllergyIntolerance, wired to the bundle Patient ────────────────\nexport {\n ALLERGY_CLINICAL_STATUS_CODE,\n ALLERGY_CLINICAL_STATUS_SYSTEM,\n ALTERNATE_CODES_EXTENSION_URL,\n AL1_ONSET_WITHDRAWN_AT,\n carriesLegacyOnsetDate,\n collectAllergies,\n} from \"./messages/allergy-intolerance.js\";\nexport type { AllergyBuildOptions } from \"./messages/allergy-intolerance.js\";\n\n// ── Message-level assembly: DG1 → Condition, PR1 → Procedure, IN1 → Coverage ─────────────────────\nexport {\n CONDITION_ENTERED_IN_ERROR,\n CONDITION_VERIFICATION_STATUS_SYSTEM,\n DG1_RETRACTION_ACTION_CODE,\n buildCondition,\n collectDiagnoses,\n deferredDiagnosisIssues,\n} from \"./messages/condition.js\";\nexport {\n PROCEDURE_STATUS_UNKNOWN,\n addMinutes,\n buildProcedure,\n collectProcedures,\n deferredProcedureIssues,\n} from \"./messages/procedure.js\";\nexport {\n COVERAGE_STATUS_UNKNOWN,\n COVERAGE_SUBSCRIBER_ID_EXTENSION_URL,\n IN1_SUBSCRIBER_NUMBER_TYPE,\n buildCoverage,\n collectCoverages,\n deferredCoverageIssues,\n insuranceCompanyName,\n} from \"./messages/coverage.js\";\nexport { emitEncounterDiagnosis, withEncounterDiagnosis } from \"./messages/encounter.js\";\nexport { toFhirEntityIdentifier, withCodeableText } from \"./messages/reference.js\";\nexport type { EntityIdentifier } from \"./messages/reference.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 ALLERGY_CATEGORY_VALUE_MAP,\n ALLERGY_TYPE_VALUE_MAP,\n ALLERGY_CRITICALITY_VALUE_MAP,\n ALLERGY_ORIGINAL_CATEGORY_VALUE_MAP,\n ALLERGY_ORIGINAL_CRITICALITY_VALUE_MAP,\n IG_ALLERGY_VALUE_MAPS_PUBLISHED,\n IG_ALLERGY_VALUE_MAPS_RETRIEVED,\n IG_ALLERGY_VALUE_MAPS_SOURCE,\n IG_ALLERGY_VALUE_MAPS_VERSION,\n V2_0162_SYSTEM,\n V3_ROUTE_OF_ADMINISTRATION_SYSTEM,\n V2_0550_SYSTEM,\n V2_0277_SYSTEM,\n V2_0161_SYSTEM,\n V2_0127_SYSTEM,\n V2_0128_SYSTEM,\n ALLERGY_INTOLERANCE_CATEGORY_SYSTEM,\n ALLERGY_INTOLERANCE_TYPE_SYSTEM,\n ALLERGY_INTOLERANCE_CRITICALITY_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\n// ── The reverse direction: FHIR → a narrow, explicitly-scoped v2 message subset (Phase 7) ────────\nexport { toV2Patient, GENDER_TO_V2, NAME_USE_TO_V2, ADDRESS_USE_TO_V2 } from \"./reverse/patient.js\";\nexport { toV2Observation, OBSERVATION_STATUS_TO_V2 } from \"./reverse/observation.js\";\nexport { invertCodeMap } from \"./reverse/v2.js\";\nexport type { ReverseOptions } from \"./reverse/coding.js\";\nexport type { ReverseResult } from \"./reverse/message.js\";\n"]}