ezmedicationinput 0.2.0 → 0.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +201 -10
  2. package/dist/adapters/canonical-course.d.ts +128 -0
  3. package/dist/adapters/r5-course.d.ts +24 -0
  4. package/dist/advice.d.ts +36 -5
  5. package/dist/body-site-lookup.d.ts +3 -0
  6. package/dist/body-site-spatial.d.ts +6 -2
  7. package/dist/body-site-target.d.ts +9 -3
  8. package/dist/canonical/compile.d.ts +79 -0
  9. package/dist/canonical/course.d.ts +352 -0
  10. package/dist/canonical/format-course.d.ts +36 -0
  11. package/dist/dosage-course.d.ts +294 -29
  12. package/dist/execution/calendar.d.ts +107 -0
  13. package/dist/execution/engine.d.ts +11 -0
  14. package/dist/fhir-quantity-operator.d.ts +53 -0
  15. package/dist/fhir-translations.d.ts +5 -6
  16. package/dist/fhir.d.ts +99 -14
  17. package/dist/format.d.ts +105 -3
  18. package/dist/hpsg/constructions.d.ts +11 -3
  19. package/dist/hpsg/defaults.d.ts +2 -0
  20. package/dist/hpsg/lexical-classes.d.ts +115 -4
  21. package/dist/hpsg/procedural-context.d.ts +3 -3
  22. package/dist/hpsg/projection.d.ts +28 -1
  23. package/dist/hpsg/rule-context.d.ts +104 -7
  24. package/dist/hpsg/rules/clinical-quantity-rules.d.ts +16 -7
  25. package/dist/hpsg/rules/condition-rules.d.ts +0 -1
  26. package/dist/hpsg/rules/core-rules.d.ts +3 -0
  27. package/dist/hpsg/rules/instruction-rules.d.ts +2 -0
  28. package/dist/hpsg/rules/prn-rules.d.ts +3 -1
  29. package/dist/hpsg/rules/timing-rules.d.ts +17 -1
  30. package/dist/hpsg/signature.d.ts +13 -3
  31. package/dist/hpsg/unification.d.ts +3 -1
  32. package/dist/i18n.d.ts +37 -1
  33. package/dist/index.cjs +63500 -46393
  34. package/dist/index.d.ts +21 -9
  35. package/dist/index.js +63491 -46393
  36. package/dist/instruction-action-locale-adapter.d.ts +31 -3
  37. package/dist/instruction-action-terminology.d.ts +23 -3
  38. package/dist/instruction-concept-terminology.d.ts +7 -0
  39. package/dist/instruction-graph-fhir.d.ts +8 -2
  40. package/dist/instruction-graph.d.ts +80 -38
  41. package/dist/ir.d.ts +1 -1
  42. package/dist/lexer/surface-segmenter.d.ts +1 -1
  43. package/dist/lexer/surface.d.ts +1 -0
  44. package/dist/locale-detection.d.ts +3 -0
  45. package/dist/locales/course/en.d.ts +15 -0
  46. package/dist/locales/course/th.d.ts +12 -0
  47. package/dist/localization.d.ts +73 -0
  48. package/dist/maps.d.ts +10 -2
  49. package/dist/medication-condition.d.ts +1 -1
  50. package/dist/parser-state.d.ts +2 -2
  51. package/dist/regimen/grammar.d.ts +11 -0
  52. package/dist/regimen/parallel-course.d.ts +8 -41
  53. package/dist/regimen/regimen.d.ts +6 -2
  54. package/dist/relation-terminology.d.ts +1 -0
  55. package/dist/schedule.d.ts +14 -10
  56. package/dist/timing-summary.d.ts +82 -1
  57. package/dist/types.d.ts +510 -56
  58. package/dist/unit-lexicon.d.ts +7 -0
  59. package/dist/utils/text.d.ts +3 -0
  60. package/dist/utils/units.d.ts +19 -0
  61. package/package.json +1 -1
package/README.md CHANGED
@@ -43,7 +43,7 @@ console.log(batch.items[0].fhir); // Single FHIR dosage
43
43
 
44
44
  // Complete batch for multi-dose or phased instructions
45
45
  console.log(batch.fhir); // EzDosage[]: flat R5-compatible rows
46
- console.log(batch.fhirNext); // R6-like course and phases
46
+ console.log(batch.fhirNext); // Current FHIR R6 DosageInstruction
47
47
  ```
48
48
 
49
49
  Example output:
@@ -80,7 +80,7 @@ Example output:
80
80
  - `count`: number of parsed dosage clauses.
81
81
  - `items[n].fhir`: the dosage for an individual clause.
82
82
  - `fhir`: `EzDosage[]` containing all flat R5-compatible dosage rows.
83
- - `fhirNext`: R6-like course details, including phases and independent dosing schedules.
83
+ - `fhirNext`: native FHIR R6 `DosageInstruction`, with sequential steps and concurrent dosing components.
84
84
  - `meta.segments`: source ranges for each clause.
85
85
  - `shortText`, `longText`, `warnings`, and `meta`: batch-level display and diagnostics.
86
86
 
@@ -89,6 +89,108 @@ Use `items[0].fhir` when displaying or editing a single dosage, and
89
89
  `formatSig` and `fromFhirDosage` accept one dosage; `formatSigBatch`
90
90
  accepts an array of dosages.
91
91
 
92
+ The R5 array under `fhir` remains the compatibility/editing surface.
93
+ The `fhirNext` object follows the **pinned HL7 R6 CI build dated November 13, 2026**,
94
+ whose profiles use the version label `6.0.0-snapshot1`. The
95
+ [checked-in contract](fhir/r6/official-snapshot1-20261113-contract.json) records
96
+ the supported schema: `DosageInstruction.step[].component[]` contains R6
97
+ `Dosage` values. Use `fromFhir(fhirNext)` to import that structure.
98
+ The [published September 2026 snapshot](https://www.hl7.org/fhir/6.0.0-snapshot1/dosage.html)
99
+ uses the same version label but defines `DosageDetails`; that schema is not a
100
+ supported interchange target. The importer checks the current structural
101
+ contract, not a datatype name or release tag absent from the JSON. Objects in
102
+ the structural overlap are accepted, including text-only `renderedInstruction`
103
+ objects and structured dosages using shared fields. Acceptance does not identify
104
+ which release produced the object or add support for the September schema.
105
+ TypeScript callers of the earlier R6 draft should replace `FhirR6DosageDetails`
106
+ with `FhirR6DosageInstruction`. Its `step` property is optional, matching the
107
+ current wire contract:
108
+
109
+ ```ts
110
+ import type { FhirR6DosageInstruction } from "ezmedicationinput";
111
+
112
+ function firstStepComponents(instruction: FhirR6DosageInstruction) {
113
+ return instruction.step?.[0]?.component ?? [];
114
+ }
115
+ ```
116
+
117
+ Empty R6 step lists are omitted on output. For a header containing only shared
118
+ Element metadata (such as an ID and unknown extensions), use the explicit
119
+ `fromFhir` boundary; mixed R5/R6 dispatch cannot infer a version from those fields.
120
+ The R5 editing/export APIs are unchanged; the current reader accepts previously
121
+ saved R5 rows without a downstream storage migration. New exports encode an
122
+ approximation on `SimpleQuantity` using the EMA quantity-operator coding. The
123
+ current reader accepts both that encoding and the older package comparator
124
+ child. Older package readers may not recover `~` from a new export; this is not
125
+ a guarantee that an older reader can interpret every newer extension encoding.
126
+
127
+ A phase beginning on the day after the preceding phase uses an application-owned
128
+ `step.start.contextCode`: system
129
+ `urn:ezmedicationinput:CodeSystem:course-phase-event`, code
130
+ `previous-phase-next-day`. It names local midnight following the predecessor's
131
+ last occupied treatment day. The scheduler derives that date from the completed
132
+ phase, including admitted doses and administration durations, so delayed starts,
133
+ count limits, and daylight-saving changes retain their meaning. Any supplied
134
+ `offsetDuration` or exact `offsetRange` is applied from that midnight. The
135
+ relation binds to the current preceding step in the ordered course. Reordering or
136
+ removing a step changes that predecessor; a first step has no predecessor and
137
+ leaves the relation unresolved.
138
+ The existing R5 course metadata preserves this boundary and its annotations
139
+ through saves. Patient-facing wording comes from the course language facet.
140
+
141
+ ### R5 clocks alongside event-based timing
142
+
143
+ For mixed schedules such as `1 tab with meals and @ 10:00`, the R5
144
+ `Timing.repeat.when` retains the meal event. Additional clocks are stored in
145
+ `Timing.repeat.extension` under
146
+ `urn:ezmedicationinput:StructureDefinition:medication-timing-additional-clock`.
147
+ Read each matching extension's `valueTime`; `_valueTime` holds its optional
148
+ primitive metadata. Do not rely only on `repeat.timeOfDay` to recover clocks
149
+ from a mixed R5 schedule.
150
+
151
+ ```json
152
+ {
153
+ "repeat": {
154
+ "when": ["C"],
155
+ "extension": [{
156
+ "url": "urn:ezmedicationinput:StructureDefinition:medication-timing-additional-clock",
157
+ "valueTime": "10:00:00"
158
+ }]
159
+ }
160
+ }
161
+ ```
162
+
163
+ ### Internal native clinical model (unstable)
164
+
165
+ **INTERNAL USE ONLY — NOT A BACKWARD-COMPATIBLE API OR PERSISTENCE FORMAT.**
166
+ `CanonicalCourse`, `CanonicalStage`, `CanonicalAdministration`, their
167
+ nested clinical types, `meta.canonical`, and the native
168
+ import/project/format helpers are implementation surfaces for EZMED
169
+ development. **Their structures, identities, field names, invariants, and
170
+ function signatures may be changed or removed at any time without
171
+ deprecation, migration, compatibility adapters, or support for earlier
172
+ internal shapes.** This remains true even where TypeScript types or helper
173
+ functions are currently exported from the package. Do not persist these
174
+ objects, build downstream integrations against them, or assume one version
175
+ can load another version's internal model.
176
+
177
+ **Only the documented external interchange contracts are compatibility
178
+ boundaries:** `.fhir` and the established R5 editing/persistence APIs
179
+ remain R5; `.fhirNext` and `fromFhir` use the *current supported* R6
180
+ structure, not obsolete R6 drafts. The internal model is deliberately free
181
+ to evolve for maximum clinical expressiveness, performance, and
182
+ maintainability; no old internal representation must be retained.
183
+
184
+ Native courses are parser implementation data. EZMED does not expose a native
185
+ editing workflow. Parser and projection outputs, including borrowed provider
186
+ listings, are immutable by caller contract; ordinary imports do not deep-clone
187
+ or freeze them defensively. Instruction action and concept vocabulary lookups
188
+ and listings also return borrowed immutable definitions.
189
+ Applications that modify external R5 or current R6 data pass those values back
190
+ through the corresponding import boundary. Native scheduling, formatting, and
191
+ supply consume clinical facts directly; the R5 reconciliation bridge is confined
192
+ to R5 persistence and interchange.
193
+
92
194
  ### PRN reasons & additional instructions
93
195
 
94
196
  `parseSig` identifies PRN (as-needed) clauses and trailing instructions, then
@@ -238,6 +340,79 @@ Highlights:
238
340
  without imposing timing-sensitive test thresholds.
239
341
 
240
342
 
343
+ ## Extending course realization to another language
344
+
345
+ **Internal extension example:** the native course-realization facet and its
346
+ clinical-model inputs are not a versioned third-party plugin contract.
347
+ They may be restructured along with the internal model, without preserving
348
+ previous facet shapes. Future language packs should depend on language
349
+ boundaries and shared clinical semantics rather than pinning a historic
350
+ `CanonicalCourse` layout.
351
+
352
+ Whole-course wording is a typed optional `course` facet on the existing
353
+ `SigLocalization` registration. It complements the same `formatShort` and
354
+ `formatLong` clause hooks—there is no separate registry or second parser.
355
+
356
+ The `formatLong` callback receives the complete clause, `defaultText`, and
357
+ `formatDefault(style)`. Its returned string is the final clause wording: custom
358
+ formatters may wrap or replace the whole clause and are responsible for that
359
+ wording. Defaults use the resolved locale and include the clause's native timing
360
+ qualifiers, authored directions, and independent advice. Built-in defaults compose
361
+ medication conditions and independent advice from typed facts.
362
+
363
+ ```ts
364
+ import {
365
+ importCanonicalCourse,
366
+ FhirPeriodUnit,
367
+ registerSigLocalization,
368
+ resolveSigLocalization,
369
+ formatCanonicalCourse,
370
+ } from "ezmedicationinput";
371
+
372
+ const english = resolveSigLocalization("en")!;
373
+ registerSigLocalization({
374
+ locale: "example",
375
+ formatShort: ({ defaultText }) => defaultText,
376
+ formatLong: ({ defaultText }) => defaultText,
377
+ course: {
378
+ ...english.course!,
379
+ dayRange: (first, last) => `Jours ${first}–${last}`,
380
+ noDoseDays: (first, last) => `Pause ${first}–${last}.`,
381
+ rateLabel: "Débit: ",
382
+ unspecified: "non spécifié",
383
+ },
384
+ });
385
+
386
+ // An explicit treatment-day window uses both clause and course wording.
387
+ const treatmentDayStart = { coding: [{
388
+ system: "urn:ezmedicationinput:CodeSystem:course-phase-event", code: "treatment-day-start",
389
+ }] };
390
+ const nativeCourse = importCanonicalCourse({ step: [{
391
+ start: { contextCode: treatmentDayStart, offsetDuration: { value: 0, unit: "d" } },
392
+ end: { contextCode: treatmentDayStart, offsetDuration: { value: 3, unit: "d" } },
393
+ component: [{
394
+ doseAndRate: [{ doseQuantity: { value: 1, unit: "tab" } }],
395
+ timing: { repeat: { frequency: 1, period: 1, periodUnit: FhirPeriodUnit.Day } },
396
+ }],
397
+ }] });
398
+ const text = formatCanonicalCourse(nativeCourse, "long", {
399
+ locale: "example", realizationMode: "normalized",
400
+ });
401
+ // text includes "Jours 1–3" from the registered course.dayRange callback.
402
+ ```
403
+
404
+ A full language implementation supplies its own clause hooks and course facet;
405
+ the example deliberately inherits the other English strings. Course templates
406
+ receive resolved counts, intervals, unit codes, predicates and stage windows.
407
+ They do not change clinical scope, calculate dates, choose a treatment branch,
408
+ or reinterpret dose numbers. `i18n.inherit`/`i18n.course` can inherit or override
409
+ the facet using the existing per-call configuration.
410
+
411
+ Adding course wording alone does **not** add parsing or autocomplete in that
412
+ language. Lexer, relation/action terminology and suggestion registrations keep
413
+ their existing roles. This boundary lets a future language-pack installer group
414
+ those registrations without changing the shared clinical engine.
415
+
241
416
  ## Formal HPSG substrate
242
417
 
243
418
  The HPSG core now uses an actual typed-feature-structure runtime on the live parse path. Signs participate in a subtype hierarchy, feature appropriateness is validated, general feature unification preserves reentrancy/structure sharing, and phrase mothers unify daughter `SYNSEM` structures rather than relying only on flat TypeScript object merging. Structural AVMs are immutable and memoized because the medication grammar reuses a small number of SYNSEM shapes heavily.
@@ -786,22 +961,35 @@ Key rules:
786
961
  - Pure frequency schedules (`BID`, `TID`, etc.) fall back to clinic-defined institution times.
787
962
  - All timestamps are emitted as ISO strings that include the clinic time-zone offset.
788
963
 
964
+ Timezone-aware scheduling and supply require `Intl.DateTimeFormat.prototype.formatToParts` and support for the requested IANA time zone.
965
+
789
966
  `from` is required and marks the evaluation window. `orderedAt` is optional—when supplied it acts as the baseline for interval calculations; otherwise the `from` timestamp is reused. The options bag also accepts `timeZone`, `eventClock`, `mealOffsets`, and `frequencyDefaults` at the top level (mirroring the legacy `config` object). `limit` defaults to 10 when omitted.
790
967
 
791
968
  ### Medication amount calculation
792
969
 
793
- `calculateTotalUnits` computes the total amount of medication (and optionally the number of containers) required for a specific duration. It accounts for complex schedules, dose ranges (using the high value), and unit conversions between doses and containers.
970
+ `calculateTotalUnits` computes the total amount of medication (and optionally the number of containers) required for a specific duration. It accounts for complex schedules, dose ranges, and unit conversions between doses and containers. A range uses its upper quantity where feasible; interacting quantity and administration-count limits are considered together. For example, 1.5–2 tablets, at most once per day, with a three-tablet limit over 48 hours permits three tablets across two days as 1.5 + 1.5.
971
+
972
+ Ranged supply with interacting limits uses a bounded exact calculation.
973
+ Successful calls return a `TotalUnitsResult`. When the calculation cannot provide
974
+ an exact attainable maximum, it throws `MedicationQuantityCalculationError`;
975
+ catch the exception and inspect its `code`. For `ranged-capacity-complexity`,
976
+ use a shorter supply window or supply a resolved per-administration quantity.
977
+ For `ranged-capacity-open-maximum`, a strict range has a finite supremum but
978
+ no attainable maximum; the prescriber can resolve the dose or provide a closed
979
+ range before requesting a numeric maximum. These exceptions affect supply
980
+ calculation only. The structured instruction and source remain available for
981
+ parsing, display, persistence, and correction.
794
982
 
795
983
  ```ts
796
- import { calculateTotalUnits, parseSig } from "ezmedicationinput";
984
+ import { calculateTotalUnits, parseSig, FhirPeriodUnit } from "ezmedicationinput";
797
985
 
798
- const { fhir } = parseSig("1x3 po pc");
986
+ const { fhir } = parseSig("1 tab PO TID after meals");
799
987
 
800
988
  const result = calculateTotalUnits({
801
989
  dosage: fhir,
802
990
  from: "2024-01-01T08:00:00Z",
803
991
  durationValue: 7,
804
- durationUnit: "d",
992
+ durationUnit: FhirPeriodUnit.Day,
805
993
  timeZone: "Asia/Bangkok",
806
994
  context: {
807
995
  containerValue: 30, // 30 tabs per bottle
@@ -823,7 +1011,7 @@ calculateTotalUnits({
823
1011
  dosage: parsed.fhir,
824
1012
  from: "2024-01-01T08:00:00Z",
825
1013
  durationValue: 7,
826
- durationUnit: "d",
1014
+ durationUnit: FhirPeriodUnit.Day,
827
1015
  timeZone: "Asia/Bangkok"
828
1016
  });
829
1017
 
@@ -858,16 +1046,19 @@ parseStrength("1%", { dosageForm: "cream" });
858
1046
  parseStrength("250mg/5mL");
859
1047
  // → { strengthRatio: { numerator: { value: 250, unit: "mg" }, denominator: { value: 5, unit: "mL" } } }
860
1048
 
861
- // Composite (sums components into a single ratio)
1049
+ // Composite (preserves each ingredient separately)
862
1050
  parseStrength("875mg + 125mg");
863
- // → { strengthQuantity: { value: 1000, unit: "mg" } }
1051
+ // → { strengthComponents: [
1052
+ // { strengthQuantity: { value: 875, unit: "mg" } },
1053
+ // { strengthQuantity: { value: 125, unit: "mg" } }
1054
+ // ] }
864
1055
 
865
1056
  // Simple Quantity
866
1057
  parseStrength("500mg");
867
1058
  // → { strengthQuantity: { value: 500, unit: "mg" } }
868
1059
  ```
869
1060
 
870
- `parseStrengthIntoRatio` is also available if you specifically need a FHIR Ratio object regardless of the denominator.
1061
+ `parseStrengthIntoRatio` is also available when you need a FHIR Ratio for one ingredient; it returns `null` for composite strengths.
871
1062
 
872
1063
  ### Ocular & intravitreal shortcuts
873
1064
 
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Interchange boundary for EZMED's canonical course.
3
+ *
4
+ * R6 input is read directly: never flatten to R5, attach persistence markers,
5
+ * decode those markers, and reconstruct clinical meaning merely to execute.
6
+ * R5 edit reconciliation remains the R5 adapter's responsibility. Both output
7
+ * versions are projections of the same canonical clinical course. Unknown
8
+ * source metadata is retained separately and never consulted by execution.
9
+ */
10
+ import type { FhirDosage, EzDosage, FhirR6Dosage, FhirR6DosageInstruction, FhirR6DosageInstructionInput, FhirR6DoseLimit, FhirR6DosageSafety, FhirR6DosageStep, CanonicalSigClause, FhirR6RelativeTime, FhirQuantity, FhirR6Quantity, FhirRange, FhirR6Range, FhirRatio, ParseBatchResult, FhirR6Extension, FormatOptions } from "../types";
11
+ import type { CanonicalMeasure, CanonicalAmount, CanonicalRange, CanonicalAdministration, CanonicalSafety, CanonicalDoseLimit, CanonicalCourse, CanonicalStage, CanonicalBoundary, CanonicalScheduleInput } from "../canonical/course";
12
+ import type { FhirProjectionOptions } from "../fhir";
13
+ /** A maximum without both endpoint objects is retained source, not an invented R6 limit. */
14
+ export declare const R5_SOURCE_ONLY_MAXIMUM_URL = "urn:ezmedicationinput:StructureDefinition:r5-source-only-maximum";
15
+ export declare function measureFromWire(q: FhirQuantity | FhirR6Quantity | undefined): CanonicalMeasure | undefined;
16
+ export declare function rangeFromFhir(r: FhirRange | FhirR6Range | undefined): CanonicalRange | undefined;
17
+ export declare function boundaryFromR6(b: FhirR6RelativeTime | undefined): CanonicalBoundary | undefined;
18
+ /** Every understood safety rule is typed. Unknown element metadata stays
19
+ * only on the retained external source object, never in an executable bag. */
20
+ export declare function doseLimitFromWire(limit: FhirR6DoseLimit): CanonicalDoseLimit;
21
+ export declare function safetyFromWire(safety: FhirR6DosageSafety | undefined, includeLimits?: boolean): CanonicalSafety | undefined;
22
+ /** Wire safety output owns coding/retained external metadata; clinical facts
23
+ * own the live ifExceeded and limits. No generic internal safety fields leak. */
24
+ export declare function safetyToWire(policy: CanonicalSafety | undefined, source: FhirR6DosageSafety | undefined, limits?: CanonicalDoseLimit[], inferCoding?: boolean): FhirR6DosageSafety | undefined;
25
+ export declare function amountFromWire(a: NonNullable<FhirR6Dosage["doseAndRate"]>[number], r5?: boolean): CanonicalAmount;
26
+ /** Import one native R6 administration WITHOUT any R5 projection. */
27
+ export declare function administrationFromR6(raw: FhirR6Dosage, sourceContext?: boolean): CanonicalAdministration;
28
+ /** Remove only generated source mirrors already owned by a lifted partial
29
+ * limit. Authored markers and unmatched Ratios keep their exact multiplicity. */
30
+ export declare function removeLiftedPartialMaximumMirrors(fresh: CanonicalAdministration, row: FhirDosage, safety: FhirR6DosageSafety | undefined): void;
31
+ export declare function administrationFromR5(raw: FhirDosage | EzDosage, sourceContext?: boolean): CanonicalAdministration;
32
+ export declare function courseFromR6(raw: FhirR6DosageInstructionInput, sourceContext?: boolean): CanonicalCourse;
33
+ /** Reconciliation is solely an R5 import concern, never part of native
34
+ * course execution. A simple scalar needs no course reconstruction. */
35
+ export declare function isR6DosageInstruction(input: object): input is FhirR6DosageInstructionInput;
36
+ export declare function inputToCanonical(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalScheduleInput): CanonicalScheduleInput;
37
+ export declare function boundaryToWire(b: CanonicalBoundary | undefined): FhirR6RelativeTime | undefined;
38
+ /** Use the supplied dose unit, including one carried by either range endpoint. */
39
+ export declare function r5MaximumDoseBasis(amounts: FhirDosage["doseAndRate"]): FhirQuantity | undefined;
40
+ interface SelectedR5Maximum {
41
+ quantity: CanonicalMeasure;
42
+ /** A same-code label can establish a comparison scale without rewriting the winning quantity. */
43
+ comparisonBasis?: CanonicalMeasure;
44
+ definite: boolean;
45
+ strict: boolean;
46
+ index?: number;
47
+ }
48
+ export interface R5MaximumSelection extends SelectedR5Maximum {
49
+ groups?: Map<string, SelectedR5Maximum>;
50
+ }
51
+ /** Select a comparable numeric upper bound for R5's singular maximum field.
52
+ * Equal bounds retain the last annotated source; a strict bound wins an equal
53
+ * inclusive one. Approximate siblings stay retained without replacing an
54
+ * available definite upper bound. Prefer the dose-compatible group when known.
55
+ * Only interleaved units allocate group state. */
56
+ export declare function selectR5Maximum(current: R5MaximumSelection | undefined, quantity: CanonicalMeasure, index?: number, dose?: CanonicalMeasure): R5MaximumSelection;
57
+ /** Shared wire serializer for current maxima and retained R5 edit baselines. */
58
+ export declare function periodMaximumToR5(amount: CanonicalMeasure, period: CanonicalMeasure, source?: object): FhirRatio;
59
+ /** Direct native-to-R6 component writer. */
60
+ /** Emit native R6 directly from modeled clinical facts. Shared serializers
61
+ * encode vocabulary and grammar-source annotations only, never an R5 course. */
62
+ export declare function administrationToR6(a: CanonicalAdministration, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirR6Dosage;
63
+ /** Direct native-to-R5 component writer. No R6 component is constructed. */
64
+ export declare function administrationToR5(a: CanonicalAdministration, sequence: number | undefined, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirDosage;
65
+ /** Header/step metadata is shared fragment serialization, NOT a course in
66
+ * another external format. The R5 writer encodes it directly in R5 extensions. */
67
+ export declare function courseMetadataToWire(course: CanonicalCourse): Omit<FhirR6DosageInstruction, "step" | "renderedInstruction">;
68
+ /** Native typed facts come from metadata fragments, not from a whole other
69
+ * external course. Foreign annotations are kept on the source envelope. */
70
+ export declare function stageFromFields(fields: Omit<FhirR6DosageStep, "component">, members: CanonicalAdministration[]): CanonicalStage;
71
+ export declare function stageMetadataToWire(stage: CanonicalStage): Omit<FhirR6DosageStep, "component">;
72
+ /** Ordinary native export must derive source-annotation views from current
73
+ * native fields because callers may have edited them. */
74
+ export declare function courseToR6(course: CanonicalCourse, options?: FhirProjectionOptions): FhirR6DosageInstruction;
75
+ /** Parser construction-only export: the caller has JUST compiled these exact
76
+ * clauses and has not exposed them for edits. Reusing their annotation views
77
+ * avoids rebuilding every canonical clause merely to write its first output.
78
+ * This is not a persistent cache and is never used for public edited exports. */
79
+ export declare function projectFreshlyCompiledCourseToR6(course: CanonicalCourse, options?: FhirProjectionOptions): FhirR6DosageInstruction;
80
+ export declare function courseToR5(course: CanonicalCourse): FhirDosage[];
81
+ /** Source-only R6 instructions have no structured administration to preview.
82
+ * A nonempty header on a structured import is original text, not evidence
83
+ * that its dose/timing still agrees with the independently editable fields. */
84
+ export declare function unchangedR6SourceDisplay(raw: FhirR6DosageInstructionInput, options?: FormatOptions): string | undefined;
85
+ /** Explicit editable import for applications that already hold R5 rows.
86
+ * Import normalization and persistence reconciliation happen once here, not
87
+ * inside any native edit, formatter, or execution operation. Metadata-only
88
+ * R6 headers share R5's Element shape; use fromFhir for that known-R6 input. */
89
+ export declare function importCanonicalCourse(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalCourse): CanonicalCourse;
90
+ /**
91
+ * R6-only serialization of editable information that has no active core slot.
92
+ * These annotations contain current FHIR fragments, never a persisted native
93
+ * model. Draft steps remain source data; a one-step safety projection records
94
+ * its original scope so an unchanged export can be reopened for editing.
95
+ */
96
+ export declare const R6_DRAFT_STEPS_SOURCE_URL = "urn:ezmedicationinput:r6-draft-steps-source";
97
+ export declare const R6_SINGLE_STEP_SAFETY_SOURCE_URL = "urn:ezmedicationinput:r6-single-step-safety-source";
98
+ export declare const R6_SCOPED_SAFETY_MODIFIER_URL = "urn:ezmedicationinput:r6-scoped-safety-policy";
99
+ export declare function retainDraftSteps(output: FhirR6DosageInstruction, drafts: Array<{
100
+ index: number;
101
+ step: Omit<FhirR6DosageStep, "component">;
102
+ }> | undefined, synthesizedStarts?: number[]): void;
103
+ /** Restore inactive editable stages while their active phase owners and
104
+ * boundaries still agree. Current doses and other live fields stay current. */
105
+ export declare function editableCourseSteps(input: FhirR6DosageInstructionInput): FhirR6DosageStep[];
106
+ /** Indices from the current external draft source, for R5 membership edits. */
107
+ export declare function retainedDraftStepIndices(input: {
108
+ extension?: FhirR6Extension[];
109
+ }): readonly number[] | undefined;
110
+ interface LiftedSafety {
111
+ course?: FhirR6DosageSafety;
112
+ step: FhirR6DosageSafety;
113
+ projected: FhirR6DosageSafety;
114
+ ownerId?: string;
115
+ ownerComponentIds?: string[];
116
+ ownerFingerprint?: string;
117
+ /** Resolved current wire owner; never part of the serialized source record. */
118
+ owner?: FhirR6DosageStep;
119
+ }
120
+ /** Only a matching live policy can reuse its saved scope. A later wire edit
121
+ * replaces that authority rather than reviving an old safety instruction. */
122
+ export declare function retainedSingleStepSafety(input: FhirR6DosageInstructionInput): LiftedSafety | undefined;
123
+ export declare function liftSingleStepSafety(output: FhirR6DosageInstruction): void;
124
+ /** Conflicting externally edited choices have no single active clinical meaning.
125
+ * Keep every submitted value in typed source data, leaving the independent
126
+ * dose/rate dimension available without inventing a winner for the conflict. */
127
+ export declare function retainConflictingAmountChoices(amount: Record<string, unknown>, doseConflict: boolean, rateConflict: boolean): void;
128
+ export {};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Direct CanonicalCourse -> R5 writer.
3
+ *
4
+ * Native clinical fields write the R5 dosage once. Only facts R5 cannot hold
5
+ * go into the existing typed R5 retention extension. The extension spelling
6
+ * stays compatible with saved client data; it is NOT an intermediate R6
7
+ * dosage/course used to obtain the R5 result.
8
+ */
9
+ import type { FhirDosage, EzDosage, EzCourseMetadata } from "../types";
10
+ import type { CanonicalCourse } from "../canonical/course";
11
+ import type { FhirProjectionOptions } from "../fhir";
12
+ import { type DosageSourceTextBaseline } from "../dosage-course";
13
+ /** Native course metadata is serialized once into its FINAL R5 extension
14
+ * header. Step/member loops write direct rows and their local retained fields.
15
+ * No R6 object is built, flattened, imported, or used as an adapter input. */
16
+ export declare function projectNativeR5Course(course: CanonicalCourse, options?: FhirProjectionOptions, editable?: boolean, freshlyCompiled?: boolean, attachInstruction?: boolean, strictPreview?: boolean, suppliedRows?: readonly (FhirDosage | EzDosage)[], deferSourceProvenance?: boolean): {
17
+ dosages: EzDosage[];
18
+ course: EzCourseMetadata;
19
+ strictDosages?: FhirDosage[];
20
+ sourceBaselines?: readonly (DosageSourceTextBaseline | undefined)[];
21
+ };
22
+ export declare function courseFromR5(dosages: readonly (FhirDosage | EzDosage)[], renderedInstruction?: string, course?: EzCourseMetadata, options?: {
23
+ resolvedPhaseSequences?: readonly number[];
24
+ }, sourceContext?: boolean, classifiedCarriers?: Set<number>): CanonicalCourse;
package/dist/advice.d.ts CHANGED
@@ -1,4 +1,24 @@
1
- import { AdditionalInstructionDefinition, AdviceForce, AdviceFrame, FhirCoding, TextRange } from "./types";
1
+ import { AdditionalInstructionDefinition, AdviceArgument, AdviceForce, AdviceFrame, FhirCoding, TextRange } from "./types";
2
+ /** Directed clinical Coding identity; presentation and Element annotations stay on their owner. */
3
+ export declare function preservesAdviceCoding(selected: FhirCoding | undefined, actual: FhirCoding | undefined): boolean;
4
+ export declare function preservesAdviceCodings(selected: readonly FhirCoding[] | undefined, actual: readonly FhirCoding[] | undefined): boolean;
5
+ export declare function preservesAdviceComponents(selected: readonly {
6
+ role: string;
7
+ text?: string;
8
+ coding?: FhirCoding;
9
+ }[] | undefined, actual: readonly {
10
+ role: string;
11
+ text?: string;
12
+ coding?: FhirCoding;
13
+ }[] | undefined): boolean;
14
+ /** Text, source spans and retained Element annotations are not typed argument facts. */
15
+ export declare function hasAdviceArgumentFacts(argument: AdviceArgument): boolean;
16
+ export declare function preservesAdviceArgumentFacts(selected: AdviceArgument, actual: AdviceArgument): boolean;
17
+ /**
18
+ * Preserve selected typed facts while a caller licenses the same occurrence/head.
19
+ * Source/value correspondence and provisional opaque valence remain caller-owned.
20
+ */
21
+ export declare function preservesAdviceFrameFacts(selected: AdviceFrame, actual: AdviceFrame): boolean;
2
22
  export interface ParsedAdditionalInstruction {
3
23
  text?: string;
4
24
  coding?: FhirCoding & {
@@ -20,17 +40,19 @@ export declare function matchComposedAdviceCodings(frames: readonly AdviceFrame[
20
40
  /** Determine whether a rule's coding must be rechecked against scoped HPSG frames. */
21
41
  export declare function adviceCodingNeedsComposedScope(system: string, code: string): boolean;
22
42
  /**
23
- * Standardized coded warnings retain their clinical wording when precisely
24
- * one composed action entails that warning. Return its original action source
25
- * for exclusion from a DUPLICATE realization; neither action nor code is lost.
43
+ * Retain the existing coding matcher's exact supporting action objects for
44
+ * occurrence-aware realization. Clinical coding and wording remain with their
45
+ * existing owners; no action identity is reconstructed from rendered text.
26
46
  */
27
- export declare function composedCodedWarningActionSources(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code"> | undefined): string[];
47
+ export declare function composedCodedAdviceActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code"> | undefined): AdviceFrame[];
28
48
  /** Existing advice terminology supplies manner modifiers to the main action
29
49
  * grammar. It is lexical evidence, not a second clause parser. */
30
50
  export declare function resolveAdviceMannerModifier(surface: string): {
31
51
  lemma: string;
32
52
  i18n?: Record<string, string>;
33
53
  } | undefined;
54
+ /** Exact advice nominals share their existing lexical identity with action arguments. */
55
+ export declare function resolveAdviceNominalArgument(surface: string, sourceText?: string): AdviceArgument | undefined;
34
56
  export declare function realizeAdviceFramesText(frames: AdviceFrame[], locale?: string): string | undefined;
35
57
  export declare function parseAdditionalInstructions(sourceText: string, span: TextRange, context?: AdviceParseContext): ParsedAdditionalInstruction[];
36
58
  export declare function findAdditionalInstructionDefinitionByCoding(system: string, code: string): AdditionalInstructionDefinition | undefined;
@@ -43,4 +65,13 @@ export declare const __test__: {
43
65
  thai: string;
44
66
  }): AdditionalInstructionDefinition;
45
67
  };
68
+ /** Keep authored wording when the selected advice identity has no display. */
69
+ export declare function additionalInstructionFallbackText(concept: {
70
+ text?: string;
71
+ coding?: readonly {
72
+ display?: string;
73
+ }[];
74
+ }, selectedCoding: {
75
+ display?: string;
76
+ } | undefined): string | undefined;
46
77
  export declare function buildAdditionalInstructionFramesFromCoding(system: string, code: string, sourceText?: string, span?: TextRange): AdviceFrame[] | undefined;
@@ -75,6 +75,9 @@ export declare function lookupBodySite(input: string, options?: BodySiteLookupOp
75
75
  export declare function lookupBodySiteAsync(input: string, options?: BodySiteLookupOptions): Promise<BodySiteLookupResult | undefined>;
76
76
  export declare function getBodySiteCode(input: string, options?: BodySiteLookupOptions): BodySiteCode | undefined;
77
77
  export declare function getBodySiteCodeAsync(input: string, options?: BodySiteLookupOptions): Promise<BodySiteCode | undefined>;
78
+ /** Realize an already selected laterality with the existing anatomical text owner.
79
+ * Internal consumers must establish anatomical compatibility before calling. */
80
+ export declare function bodySiteTextWithLaterality(text: string, lateralityCode: string): string | undefined;
78
81
  export declare function getBodySiteText(input: BodySiteCodeInput, options?: BodySiteTextOptions): string | undefined;
79
82
  export declare function getBodySiteTextAsync(input: BodySiteCodeInput, options?: BodySiteTextOptions): Promise<string | undefined>;
80
83
  export declare function suggestBodySites(input: string, options?: BodySiteLookupOptions): BodySiteLookupResult[];
@@ -1,6 +1,10 @@
1
- import { BodySiteSpatialRelation, FhirCodeableConcept, FhirExtension } from "./types";
1
+ import { BodySiteSpatialRelation, FhirR6CodeableConcept, FhirR6Coding, FhirExtension } from "./types";
2
2
  export declare const BODY_SITE_SPATIAL_RELATION_EXTENSION_URL = "urn:ezmedicationinput:body-site-spatial-relation";
3
+ /** Top-level and nested sites share the existing anatomical Coding preference. */
4
+ export declare function selectPreferredSiteCoding<TCoding extends FhirR6Coding>(site: {
5
+ coding?: TCoding[];
6
+ } | undefined): TCoding | undefined;
3
7
  export declare function cloneBodySiteSpatialRelation(relation: BodySiteSpatialRelation | undefined): BodySiteSpatialRelation | undefined;
4
8
  export declare function buildBodySiteSpatialRelationExtension(relation: BodySiteSpatialRelation | undefined): FhirExtension | undefined;
5
9
  export declare function buildBodySiteSpatialRelationExtensions(relation: BodySiteSpatialRelation | undefined): FhirExtension[] | undefined;
6
- export declare function parseBodySiteSpatialRelationExtension(concept: FhirCodeableConcept | undefined): BodySiteSpatialRelation | undefined;
10
+ export declare function parseBodySiteSpatialRelationExtension(concept: FhirR6CodeableConcept | undefined): BodySiteSpatialRelation | undefined;
@@ -1,4 +1,4 @@
1
- import { BodySiteCode, BodySiteDefinition, CanonicalSiteExpr, FhirCodeableConcept, FhirExtension } from "./types";
1
+ import { BodySiteCode, BodySiteDefinition, BodySiteSpatialRelation, CanonicalSiteExpr, FhirR6CodeableConcept, FhirCoding, FhirExtension } from "./types";
2
2
  export declare const BODY_SITE_ADMINISTRATION_TARGET_COUNT_EXTENSION_URL = "urn:ezmedicationinput:body-site-administration-target-count";
3
3
  type SiteLike = CanonicalSiteExpr | {
4
4
  text?: string;
@@ -10,9 +10,15 @@ interface BodySiteTargetCountOptions {
10
10
  siteCodeMap?: Record<string, BodySiteDefinition>;
11
11
  bodySiteContext?: string;
12
12
  }
13
+ export declare function normalizeAdministrationTargetCount(value: number | undefined): number | undefined;
14
+ export declare function bodySiteTextConflictsWithCoding(text: string, coding: Pick<FhirCoding, "system" | "code"> | undefined): boolean;
15
+ export declare function resolveBodySiteTargetText(site: string | SiteLike | FhirR6CodeableConcept | undefined, options?: BodySiteTargetCountOptions): string | undefined;
16
+ /** Realization may use a retained equivalent Coding's label without changing
17
+ * the selected anatomical identity or materializing text into its wire carrier. */
18
+ export declare function resolveBodySiteSpatialTargetText(relation: BodySiteSpatialRelation): string | undefined;
13
19
  export declare function buildBodySiteAdministrationTargetCountExtension(targetCount: number | undefined): FhirExtension | undefined;
14
- export declare function parseBodySiteAdministrationTargetCountExtension(concept: FhirCodeableConcept | {
20
+ export declare function parseBodySiteAdministrationTargetCountExtension(concept: FhirR6CodeableConcept | {
15
21
  extension?: FhirExtension[];
16
22
  } | undefined): number | undefined;
17
- export declare function getBodySiteAdministrationTargetCount(site: string | SiteLike | FhirCodeableConcept | undefined, options?: BodySiteTargetCountOptions): number | undefined;
23
+ export declare function getBodySiteAdministrationTargetCount(site: string | SiteLike | FhirR6CodeableConcept | undefined, options?: BodySiteTargetCountOptions): number | undefined;
18
24
  export {};
@@ -0,0 +1,79 @@
1
+ /** Compile the EXISTING scoped HPSG clause/regimen into the native clinical
2
+ * course. No FHIR serialization or reconstruction occurs in this module.
3
+ * Source grammar is interpreted once; numerical execution consumes only
4
+ * these normalized facts and preserves syntax as read-only evidence. */
5
+ import type { CanonicalSigClause, ParseOptions } from "../types";
6
+ import type { CanonicalAdministration, CanonicalMeasure, CanonicalRange, CanonicalCourse, CanonicalBoundary } from "./course";
7
+ import type { CanonicalParallelRegimen, RegimenPosition } from "../regimen/parallel-course";
8
+ /** A single authored time denominator is shared by native and FHIR rate projection. */
9
+ export declare function clinicalQuantityTimeDenominator(quantity: NonNullable<CanonicalSigClause["clinicalQuantity"]>): import("../hpsg/signature").HpsgDimensionalQuantityTerm | undefined;
10
+ /** Choose the native rate shape once, preserving an authored numeric time
11
+ * denominator. Protocol adapters only encode this clinical amount. */
12
+ export declare function rateFromClinicalQuantity(quantity: NonNullable<CanonicalSigClause["clinicalQuantity"]>): {
13
+ rateRange: {
14
+ low: {
15
+ value: number;
16
+ unit: string;
17
+ } | undefined;
18
+ high: {
19
+ value: number;
20
+ unit: string;
21
+ } | undefined;
22
+ };
23
+ rateRatio?: undefined;
24
+ rate?: undefined;
25
+ } | {
26
+ rateRatio: {
27
+ numerator: {
28
+ comparator?: "<" | "<=" | ">=" | ">" | "ad" | "~" | undefined;
29
+ value: number;
30
+ unit: string;
31
+ };
32
+ denominator: {
33
+ value: number;
34
+ unit: string;
35
+ };
36
+ };
37
+ rateRange?: undefined;
38
+ rate?: undefined;
39
+ } | {
40
+ rate: {
41
+ comparator?: "<" | "<=" | ">=" | ">" | "ad" | "~" | undefined;
42
+ value: number;
43
+ unit: string;
44
+ };
45
+ rateRange?: undefined;
46
+ rateRatio?: undefined;
47
+ };
48
+ export declare function administrationFromClause(clause: CanonicalSigClause, text?: string, stageOrdinal?: number): CanonicalAdministration;
49
+ /** Calendar tracks use explicit dates; not offsets from treatment start. */
50
+ export declare function precedingCalendarDay(value: string): string | undefined;
51
+ /** Dates without times are inclusive local calendar days, never UTC timestamps. */
52
+ export declare function orderedCalendarBounds(earlier: string, later: string): boolean;
53
+ export declare function clinicalBoundary(position: RegimenPosition | {
54
+ value: number;
55
+ unit: string;
56
+ }): CanonicalBoundary;
57
+ export declare function courseFromParallel(regimen: Extract<CanonicalParallelRegimen, {
58
+ kind: "resolved";
59
+ }>, clauseTexts: readonly (string | undefined)[], instruction: string): CanonicalCourse;
60
+ /** Preserve independent member origins when global stage cuts are unresolved.
61
+ * Each member retains its own course length; an uncertain transition never
62
+ * supplies the origin or end of another track. */
63
+ export declare function courseFromPartialParallel(regimen: Extract<CanonicalParallelRegimen, {
64
+ kind: "unresolved";
65
+ }>, clauseTexts: readonly (string | undefined)[], instruction: string): CanonicalCourse;
66
+ /** The grammar's compact dose range has one shared unit and no endpoint
67
+ * operators. Rich native ranges must retain each independently authored
68
+ * endpoint instead of compressing them into a misleading scalar-unit view. */
69
+ export declare function doseRangeNeedsEndpointPreview(range: CanonicalRange): boolean;
70
+ /** Project native live facts back into the existing grammar realization view.
71
+ * This is NOT a parser and reads no wire object: grammar evidence and source
72
+ * spans remain unchanged; edited dose/schedule/guard values are authoritative.
73
+ */
74
+ export declare function clauseForAdministration(a: CanonicalAdministration, options?: ParseOptions): CanonicalSigClause;
75
+ /** Compose the already-scoped administrations into a single clinical course.
76
+ * Stable stage order belongs here, not to R5 sequences or R6 conversion.
77
+ * Relative phase starts, shared delays and shared ends are lowered from
78
+ * existing typed facts once; independent component timing is not overwritten. */
79
+ export declare function courseFromAdministrations(members: readonly CanonicalAdministration[], instruction: string, cycleInterval?: CanonicalMeasure, repeatCount?: number): CanonicalCourse;