ezmedicationinput 0.3.0-beta.1 → 0.3.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 (79) hide show
  1. package/README.md +155 -10
  2. package/dist/adapters/canonical-course.d.ts +7 -4
  3. package/dist/adapters/r5-course.d.ts +11 -2
  4. package/dist/advice-locale-adapter.d.ts +24 -0
  5. package/dist/advice.d.ts +39 -3
  6. package/dist/body-site-grammar.d.ts +21 -2
  7. package/dist/body-site-lookup.d.ts +6 -1
  8. package/dist/body-site-spatial.d.ts +7 -1
  9. package/dist/body-site-target.d.ts +35 -3
  10. package/dist/canonical/compile.d.ts +22 -3
  11. package/dist/canonical/course.d.ts +43 -7
  12. package/dist/canonical/dosage-agreement.d.ts +84 -0
  13. package/dist/canonical/format-course.d.ts +4 -2
  14. package/dist/clause-tail-grammar.d.ts +2 -0
  15. package/dist/combine-multilingual-dosages.d.ts +32 -0
  16. package/dist/date-interpretation.d.ts +36 -2
  17. package/dist/dosage-course.d.ts +26 -17
  18. package/dist/event-timing-expression.d.ts +26 -1
  19. package/dist/execution/engine.d.ts +2 -1
  20. package/dist/fhir-quantity-operator.d.ts +37 -1
  21. package/dist/fhir-translations.d.ts +14 -1
  22. package/dist/fhir.d.ts +25 -5
  23. package/dist/format.d.ts +23 -24
  24. package/dist/hpsg/constructions.d.ts +27 -5
  25. package/dist/hpsg/lexical-classes.d.ts +94 -33
  26. package/dist/hpsg/method-lexicon.d.ts +3 -0
  27. package/dist/hpsg/procedural-context.d.ts +51 -3
  28. package/dist/hpsg/projection.d.ts +7 -3
  29. package/dist/hpsg/quantity-lexicon.d.ts +51 -0
  30. package/dist/hpsg/rule-context.d.ts +101 -33
  31. package/dist/hpsg/rules/clinical-quantity-rules.d.ts +1 -1
  32. package/dist/hpsg/rules/condition-rules.d.ts +13 -2
  33. package/dist/hpsg/rules/core-rules.d.ts +5 -2
  34. package/dist/hpsg/rules/prn-rules.d.ts +10 -1
  35. package/dist/hpsg/rules/site-rules.d.ts +10 -1
  36. package/dist/hpsg/rules/timing-rules.d.ts +108 -24
  37. package/dist/hpsg/segmenter.d.ts +2 -2
  38. package/dist/hpsg/signature.d.ts +50 -5
  39. package/dist/hpsg/timing-lexicon.d.ts +18 -2
  40. package/dist/i18n.d.ts +8 -7
  41. package/dist/index.cjs +84275 -66589
  42. package/dist/index.d.ts +13 -3
  43. package/dist/index.js +84263 -66588
  44. package/dist/instruction-action-locale-adapter.d.ts +69 -5
  45. package/dist/instruction-action-parser.d.ts +48 -0
  46. package/dist/instruction-action-terminology.d.ts +22 -1
  47. package/dist/instruction-concept-terminology.d.ts +14 -1
  48. package/dist/instruction-graph-fhir.d.ts +4 -2
  49. package/dist/instruction-graph-ownership.d.ts +96 -0
  50. package/dist/instruction-graph.d.ts +19 -42
  51. package/dist/lexer/lex.d.ts +5 -1
  52. package/dist/lexer/locale.d.ts +14 -0
  53. package/dist/lexer/locales/en.d.ts +11 -0
  54. package/dist/lexer/surface.d.ts +3 -1
  55. package/dist/lexer/token-types.d.ts +6 -0
  56. package/dist/locale-detection.d.ts +4 -2
  57. package/dist/locales/clause/en.d.ts +14 -0
  58. package/dist/locales/course/en.d.ts +5 -0
  59. package/dist/localization.d.ts +6 -0
  60. package/dist/localized-timing.d.ts +1 -1
  61. package/dist/maps.d.ts +38 -12
  62. package/dist/medication-condition.d.ts +105 -11
  63. package/dist/parser-state.d.ts +10 -0
  64. package/dist/parser.d.ts +5 -3
  65. package/dist/prn.d.ts +15 -2
  66. package/dist/regimen/coordination-scope.d.ts +13 -1
  67. package/dist/regimen/grammar.d.ts +7 -1
  68. package/dist/regimen/parallel-course.d.ts +6 -2
  69. package/dist/regimen/planner.d.ts +2 -3
  70. package/dist/regimen/regimen.d.ts +2 -0
  71. package/dist/schedule.d.ts +5 -2
  72. package/dist/snomed.d.ts +3 -0
  73. package/dist/suggest-locale-adapter.d.ts +15 -0
  74. package/dist/symptom-terminology.d.ts +5 -1
  75. package/dist/timing-summary.d.ts +43 -10
  76. package/dist/types.d.ts +213 -16
  77. package/dist/unit-lexicon.d.ts +2 -6
  78. package/dist/utils/units.d.ts +3 -0
  79. package/package.json +1 -1
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # ezmedicationinput
2
2
 
3
- `ezmedicationinput` parses concise clinician shorthand medication instructions and produces [FHIR R5 Dosage](https://hl7.org/fhir/dosage.html) JSON. It is designed for use in lightweight medication-entry experiences and ships with batteries-included normalization for common Thai/English sig abbreviations.
3
+ `ezmedicationinput` parses concise clinician shorthand medication instructions into editable dosage rows, with [FHIR R5 Dosage](https://hl7.org/fhir/dosage.html) and current R6 export. It is designed for use in lightweight medication-entry experiences and ships with batteries-included normalization for common Thai/English sig abbreviations.
4
4
 
5
5
  ## Features
6
6
 
7
- - Converts shorthand strings (e.g. `1x3 po pc`, `500 mg po q6h prn pain`) into FHIR-compliant dosage JSON.
7
+ - Converts shorthand strings (e.g. `1x3 po pc`, `500 mg po q6h prn pain`) into extended editable dosage rows, with separate R5 and R6 projections.
8
8
  - Parses multi-clause sigs into multiple dosage items (e.g. `OD ... , OS ...`), with all dosage rows available in the complete `batch.fhir` array.
9
9
  - Emits timing abbreviations (`timing.code`) and repeat structures simultaneously where possible.
10
10
  - Maps meal/time blocks to the correct `Timing.repeat.when` **EventTiming** codes and can auto-expand AC/PC/C into specific meals.
@@ -33,17 +33,20 @@ npm install ezmedicationinput
33
33
  ## Usage
34
34
 
35
35
  ```ts
36
- import { parseSig } from "ezmedicationinput";
36
+ import { parseSig, toFhirR5Dosages } from "ezmedicationinput";
37
37
 
38
38
  const batch = parseSig("1x3 po pc", { context: { dosageForm: "tab" } });
39
39
 
40
- // Individual clause and one FHIR Dosage
40
+ // Individual clause and its editable dosage row
41
41
  console.log(batch.count); // 1
42
- console.log(batch.items[0].fhir); // Single FHIR dosage
42
+ console.log(batch.items[0].fhir); // Single EzDosage
43
43
 
44
44
  // Complete batch for multi-dose or phased instructions
45
- console.log(batch.fhir); // EzDosage[]: flat R5-compatible rows
45
+ console.log(batch.fhir); // EzDosage[]: extended R5-shaped editable rows
46
46
  console.log(batch.fhirNext); // Current FHIR R6 DosageInstruction
47
+
48
+ // Strict R5 wire export, including the batch course metadata
49
+ const r5Dosages = toFhirR5Dosages(batch.fhir, batch.course);
47
50
  ```
48
51
 
49
52
  Example output:
@@ -78,8 +81,8 @@ Example output:
78
81
  `parseSig` and `parseSigAsync` return one batch result containing:
79
82
 
80
83
  - `count`: number of parsed dosage clauses.
81
- - `items[n].fhir`: the dosage for an individual clause.
82
- - `fhir`: `EzDosage[]` containing all flat R5-compatible dosage rows.
84
+ - `items[n].fhir`: the editable `EzDosage` for an individual clause.
85
+ - `fhir`: `EzDosage[]` containing all extended R5-shaped editable rows; these are not strict FHIR R5 JSON.
83
86
  - `fhirNext`: native FHIR R6 `DosageInstruction`, with sequential steps and concurrent dosing components.
84
87
  - `meta.segments`: source ranges for each clause.
85
88
  - `shortText`, `longText`, `warnings`, and `meta`: batch-level display and diagnostics.
@@ -89,7 +92,10 @@ Use `items[0].fhir` when displaying or editing a single dosage, and
89
92
  `formatSig` and `fromFhirDosage` accept one dosage; `formatSigBatch`
90
93
  accepts an array of dosages.
91
94
 
92
- The R5 array under `fhir` remains the compatibility/editing surface.
95
+ The extended rows under `fhir` remain the compatibility/editing surface.
96
+ Use `toFhirR5Dosages(batch.fhir, batch.course)` for strict R5 wire export.
97
+ This projects the extended clinical fields into supported R5 fields and extensions,
98
+ while retaining the supplied course metadata.
93
99
  The `fhirNext` object follows the **pinned HL7 R6 CI build dated November 13, 2026**,
94
100
  whose profiles use the version label `6.0.0-snapshot1`. The
95
101
  [checked-in contract](fhir/r6/official-snapshot1-20261113-contract.json) records
@@ -102,6 +108,7 @@ contract, not a datatype name or release tag absent from the JSON. Objects in
102
108
  the structural overlap are accepted, including text-only `renderedInstruction`
103
109
  objects and structured dosages using shared fields. Acceptance does not identify
104
110
  which release produced the object or add support for the September schema.
111
+
105
112
  TypeScript callers of the earlier R6 draft should replace `FhirR6DosageDetails`
106
113
  with `FhirR6DosageInstruction`. Its `step` property is optional, matching the
107
114
  current wire contract:
@@ -138,6 +145,114 @@ leaves the relation unresolved.
138
145
  The existing R5 course metadata preserves this boundary and its annotations
139
146
  through saves. Patient-facing wording comes from the course language facet.
140
147
 
148
+ ### Compose independently authored language versions
149
+
150
+ `combineMultilingualDosages` accepts parsed batches, single R5 `Dosage` values,
151
+ ordered R5 arrays, and current R6 `DosageInstruction` values in the same call.
152
+
153
+ ```ts
154
+ import { combineMultilingualDosages, getPrimitiveTranslation, parseSig } from "ezmedicationinput";
155
+
156
+ const result = combineMultilingualDosages({
157
+ "th-TH": parseSig("รับประทานครั้งละ 1 เม็ด วันละ 2 ครั้ง", { locale: "th" }),
158
+ "en-US": parseSig("Take 1 tablet by mouth twice daily", { locale: "en" }),
159
+ });
160
+
161
+ if (result.ok) {
162
+ const { fhir, fhirNext } = result; // Strict R5 rows and one current R6 course
163
+ const english = getPrimitiveTranslation(fhirNext._renderedInstruction, "en-US");
164
+ } else {
165
+ console.log(result.conflicts); // Locale, clinical path and submitted values
166
+ }
167
+ ```
168
+
169
+ The first locale key owns the original wording and authored quantities. Use
170
+ `{ primaryLocale: "en-US" }` to select a different original. Stage order comes
171
+ from the clinical course. Concurrent members need a unique correspondence, such
172
+ as distinct coded sites or authored clock times. A missing clinical fact, a
173
+ different fact, or an ambiguous match returns a conflict.
174
+
175
+ The locale keys identify clinician-supplied language versions of the full SIG.
176
+ Structured facts are compared independently of that wording. To associate opaque
177
+ supplemental instructions or PRN wording, pass their conflict paths in `pairedText`, for example
178
+ `["stages[0].administrations[0].additionalInstructions[0]"]`. Only use paths for
179
+ wording you have confirmed conveys the same instruction. Both slots must have
180
+ wording and their structured context must agree.
181
+
182
+ Original wording and embedded translations travel on the relevant primitive
183
+ companions, such as `_renderedInstruction`, `additionalInstruction[]._text`, or
184
+ `asNeededFor[]._text`.
185
+ Use `getPrimitiveTranslation` or `getPrimitiveTranslations` to read them.
186
+ `withPrimitiveTranslation` and `withPrimitiveLanguage` return new companion
187
+ values while preserving the other annotations. Pass `"markdown"` as the fourth
188
+ argument of `withPrimitiveTranslation` when writing R6 `renderedInstruction`,
189
+ or pass `undefined` as the content to clear one exact locale.
190
+
191
+ ### Compare dosages without composing or executing them
192
+
193
+ `compareDosages` uses the same complete clinical agreement traversal as
194
+ `combineMultilingualDosages`. It accepts native courses or administrations,
195
+ parsed results, R5/EzDosage rows or ordered arrays, and R6 instructions. Existing
196
+ native courses are reused and wire inputs are imported once. The boolean helper uses that same kernel with diagnostic collection disabled;
197
+ Structural/Permissive same-reference calls exit immediately and direct saved-data
198
+ comparison does not construct diagnostic paths. The comparison
199
+ does not parse source prose, project the input to another FHIR version, schedule
200
+ doses, or mutate caller data.
201
+
202
+ ```ts
203
+ import { areDosagesEquivalent, compareDosages, parseSig } from "ezmedicationinput";
204
+
205
+ const english = parseSig("1 tab po bid", { locale: "en" });
206
+ const thai = parseSig("รับประทานครั้งละ 1 เม็ด วันละ 2 ครั้ง", { locale: "th" });
207
+ const result = compareDosages(english, thai);
208
+ // { status: "equivalent", differences: [] }
209
+
210
+ const same = areDosagesEquivalent(english, thai); // true only for "equivalent"
211
+ const changed = compareDosages(english, parseSig("2 tabs po bid"));
212
+ // status: "different"; differences contain the canonical path and both values
213
+
214
+ const savedDataChanged = !areDosagesEquivalent(english.fhir, thai.fhir, {
215
+ mode: "permissive",
216
+ });
217
+ ```
218
+
219
+ | Mode | Compared data and defaults |
220
+ | --- | --- |
221
+ | `clinical` (default) | Native clinical meaning, proven registered unit conversions, unordered event sets, and uniquely aligned parallel members. Unknown units or unmodeled clinical content produce `indeterminate`. |
222
+ | `structural` | The supplied representation, with exact values, array order, authored text, IDs, and metadata. For a parsed batch it selects `fhirNext`; for a parsed single result it selects `fhir`, excluding parser diagnostics. |
223
+ | `permissive` | Structural legacy change detection: normalizes absent/undefined and empty optional arrays, ignores dosage-row and dose-entry IDs, and compares event/weekday/clock arrays as multisets. Duplicate counts, row/phase order, null, and nested metadata IDs remain significant. |
224
+ | `custom` | Clinical comparison with explicit `policy` overrides. |
225
+
226
+ A clinical difference is established independently of incidental wording or
227
+ generated names. Phases, predecessor dependencies, choices, shared allowances,
228
+ independent tracks, relative boundaries, route/site/allocation, quantities,
229
+ PRN conditions, maxima, and material advice remain significant. Registered
230
+ mass or volume conversions do not infer product strength, and calendar months
231
+ are not assumed to have a fixed number of days. An ambiguous correspondence or
232
+ unpaired supplemental text is `indeterminate`, rather than a claim of equality.
233
+
234
+ The `policy` options are `units` (`registered` or `exact`),
235
+ `missingUnits`/`unknownUnits` (`indeterminate` or `exact`),
236
+ `unknownContent` (`indeterminate`, `exact`, or `ignore`),
237
+ `ordering` (`clinical`, `preserve`, or `multiset`),
238
+ `narrative` (`clinical`, `preserve`, or `ignore`),
239
+ `generatedIds` (`ignore` or `preserve`), and
240
+ `emptyValues` (`absent` or `preserve`). Use exact or ignored unknown content
241
+ only when the caller has established that policy for its use case. Ordering
242
+ options never erase phase order, instruction order, or relationship bindings.
243
+ Structural modes compare the supplied data shape; unit and unknown-content
244
+ interpretation belong to Clinical/Custom. The `emptyValues` switch applies to
245
+ Structural/Permissive; clinical import already normalizes absent optional
246
+ collections.
247
+
248
+ For example, `{ mode: "custom", policy: { units: "exact",
249
+ narrative: "preserve" } }` preserves authored quantity units and full SIG text.
250
+ `primaryLocale`, `otherLocale`, and `pairedText` can establish confirmed
251
+ supplemental wording associations using the same paths as multilingual
252
+ composition. A `resolveAnchor(boundary, side)` callback can return a shared
253
+ identity for an otherwise unresolved external anchor; retained displacement
254
+ still has to agree. It supplies context, not a guessed date or a schedule.
255
+
141
256
  ### R5 clocks alongside event-based timing
142
257
 
143
258
  For mixed schedules such as `1 tab with meals and @ 10:00`, the R5
@@ -176,7 +291,8 @@ can load another version's internal model.
176
291
 
177
292
  **Only the documented external interchange contracts are compatibility
178
293
  boundaries:** `.fhir` and the established R5 editing/persistence APIs
179
- remain R5; `.fhirNext` and `fromFhir` use the *current supported* R6
294
+ remain R5-shaped; `toFhirR5Dosages` produces strict R5 wire output.
295
+ `.fhirNext` and `fromFhir` use the *current supported* R6
180
296
  structure, not obsolete R6 drafts. The internal model is deliberately free
181
297
  to evolve for maximum clinical expressiveness, performance, and
182
298
  maintainability; no old internal representation must be retained.
@@ -283,6 +399,9 @@ Formatting options:
283
399
  wording, preserves source-faithful clinician text when the semantic graph has
284
400
  same-locale provenance, and realizes typed graph semantics across locales.
285
401
  - `i18n`: overrides or augments the registered localization callbacks.
402
+ - `pairedSiteWording`: defaults to `"each"`. In normalized long text, use
403
+ `"both"` to name both sites and retain the per-site dose, for example
404
+ “Instill 1 drop in both eyes (dose per eye)” or “หยอดตาข้างละ 1 หยด ให้ครบทั้งสองข้าง”.
286
405
  - `groupMealTimingsByRelation`: compacts repeated meal relation phrases when all
287
406
  meal anchors share the same relation.
288
407
  Example EN: `after breakfast, lunch and dinner`
@@ -954,6 +1073,32 @@ const schedule = nextDueDoses(fhir, {
954
1073
  // → ["2024-01-01T12:30:00+07:00", "2024-01-01T18:30:00+07:00", ...]
955
1074
  ```
956
1075
 
1076
+ Use `nextDueDosesDetailed(input, options)` when a caller also needs the dose
1077
+ that goes with each timestamp. It accepts the same inputs and options, and
1078
+ preserves the same order and simultaneous administrations.
1079
+
1080
+ ```ts
1081
+ import { nextDueDosesDetailed, parseSig } from "ezmedicationinput";
1082
+
1083
+ const prescription = parseSig("1 tablet at 08:00 and 2 tablets at 20:00");
1084
+ const doses = nextDueDosesDetailed(prescription, {
1085
+ from: "2026-01-05T00:00:00Z",
1086
+ orderedAt: "2026-01-05T00:00:00Z",
1087
+ timeZone: "UTC",
1088
+ limit: 2
1089
+ });
1090
+ const amounts = doses.map(dose => dose.administration.amounts?.[0]?.quantity?.value);
1091
+ // [1, 2]
1092
+ ```
1093
+
1094
+ Each result includes the readonly canonical administration and, when known,
1095
+ its normalized course position and selected clock, event or date origins.
1096
+ An anchor for a generic meal can include the particular selected meal.
1097
+ `asNeeded` and `condition` distinguish PRN and conditional opportunities
1098
+ from routine scheduling. A condition is `assumed` without an evaluator and
1099
+ `evaluated` when the supplied evaluator admits it. Ranges, rates, and unknown
1100
+ amounts retain their authored forms. Use `nextDueDoses` for timestamps alone.
1101
+
957
1102
  Key rules:
958
1103
 
959
1104
  - `when` values map to the clinic `eventClock`. Generic meal codes (`AC`, `PC`, `C`) use `mealOffsets` against breakfast/lunch/dinner anchors.
@@ -7,7 +7,7 @@
7
7
  * versions are projections of the same canonical clinical course. Unknown
8
8
  * source metadata is retained separately and never consulted by execution.
9
9
  */
10
- import type { FhirDosage, EzDosage, FhirR6Dosage, FhirR6DosageInstruction, FhirR6DosageInstructionInput, FhirR6DoseLimit, FhirR6DosageSafety, FhirR6DosageStep, CanonicalSigClause, FhirR6RelativeTime, FhirQuantity, FhirR6Quantity, FhirRange, FhirR6Range, FhirRatio, ParseBatchResult, FhirR6Extension, FormatOptions } from "../types";
10
+ import type { FhirDosage, EzDosage, FhirR6Dosage, FhirR6DosageInstruction, FhirR6DosageInstructionInput, FhirR6DoseLimit, FhirR6DosageSafety, FhirR6DosageStep, CanonicalSigClause, FhirR6RelativeTime, FhirQuantity, FhirR6Quantity, FhirRange, FhirR6Range, FhirRatio, ParseBatchResult, NextDueDoseOptions, FhirR6Extension, FormatOptions } from "../types";
11
11
  import type { CanonicalMeasure, CanonicalAmount, CanonicalRange, CanonicalAdministration, CanonicalSafety, CanonicalDoseLimit, CanonicalCourse, CanonicalStage, CanonicalBoundary, CanonicalScheduleInput } from "../canonical/course";
12
12
  import type { FhirProjectionOptions } from "../fhir";
13
13
  /** A maximum without both endpoint objects is retained source, not an invented R6 limit. */
@@ -33,7 +33,7 @@ export declare function courseFromR6(raw: FhirR6DosageInstructionInput, sourceCo
33
33
  /** Reconciliation is solely an R5 import concern, never part of native
34
34
  * course execution. A simple scalar needs no course reconstruction. */
35
35
  export declare function isR6DosageInstruction(input: object): input is FhirR6DosageInstructionInput;
36
- export declare function inputToCanonical(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalScheduleInput): CanonicalScheduleInput;
36
+ export declare function inputToCanonical(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalScheduleInput, alternativeChoices?: NextDueDoseOptions["alternativeChoices"]): CanonicalScheduleInput;
37
37
  export declare function boundaryToWire(b: CanonicalBoundary | undefined): FhirR6RelativeTime | undefined;
38
38
  /** Use the supplied dose unit, including one carried by either range endpoint. */
39
39
  export declare function r5MaximumDoseBasis(amounts: FhirDosage["doseAndRate"]): FhirQuantity | undefined;
@@ -56,12 +56,15 @@ export interface R5MaximumSelection extends SelectedR5Maximum {
56
56
  export declare function selectR5Maximum(current: R5MaximumSelection | undefined, quantity: CanonicalMeasure, index?: number, dose?: CanonicalMeasure): R5MaximumSelection;
57
57
  /** Shared wire serializer for current maxima and retained R5 edit baselines. */
58
58
  export declare function periodMaximumToR5(amount: CanonicalMeasure, period: CanonicalMeasure, source?: object): FhirRatio;
59
+ /** Both direct wire projection and supplied parser rows carry this native
60
+ * dose fact. The anatomical count marker is deliberately not allocation proof. */
61
+ export declare function writeAdministrationDoseAllocation(output: FhirDosage | FhirR6Dosage, administration: CanonicalAdministration): void;
59
62
  /** Direct native-to-R6 component writer. */
60
63
  /** Emit native R6 directly from modeled clinical facts. Shared serializers
61
64
  * encode vocabulary and grammar-source annotations only, never an R5 course. */
62
- export declare function administrationToR6(a: CanonicalAdministration, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirR6Dosage;
65
+ export declare function administrationToR6(a: CanonicalAdministration, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause, phaseSequence?: number, trackCycleMember?: boolean): FhirR6Dosage;
63
66
  /** 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;
67
+ export declare function administrationToR5(a: CanonicalAdministration, sequence: number | undefined, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause, trackCycleMember?: boolean): FhirDosage;
65
68
  /** Header/step metadata is shared fragment serialization, NOT a course in
66
69
  * another external format. The R5 writer encodes it directly in R5 extensions. */
67
70
  export declare function courseMetadataToWire(course: CanonicalCourse): Omit<FhirR6DosageInstruction, "step" | "renderedInstruction">;
@@ -6,10 +6,19 @@
6
6
  * stays compatible with saved client data; it is NOT an intermediate R6
7
7
  * dosage/course used to obtain the R5 result.
8
8
  */
9
- import type { FhirDosage, EzDosage, EzCourseMetadata } from "../types";
10
- import type { CanonicalCourse } from "../canonical/course";
9
+ import type { FhirDosage, EzDosage, EzCourseMetadata, CanonicalSigClause } from "../types";
10
+ import type { CanonicalCourse, CanonicalAdministration } from "../canonical/course";
11
11
  import type { FhirProjectionOptions } from "../fhir";
12
12
  import { type DosageSourceTextBaseline } from "../dosage-course";
13
+ /** A standalone source component uses the same native facts and retained-field
14
+ * writer as a complete course, without inventing surrounding stages. */
15
+ export declare function projectNativeR5Administration(administration: CanonicalAdministration, sequence: number | undefined, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirDosage;
16
+ /** Normalize emitted course and activity-timing markers without touching
17
+ * unfamiliar user-provided extensions. Ordinary R5 dosages cost only
18
+ * cheap presence checks for these known semantic markers.
19
+ * @param rows New FHIR dosage rows owned by the bridge.
20
+ */
21
+ export declare function normalizeEmittedSemanticMarkers(rows: FhirDosage[], keepExtendedSource?: boolean): FhirDosage[];
13
22
  /** Native course metadata is serialized once into its FINAL R5 extension
14
23
  * header. Step/member loops write direct rows and their local retained fields.
15
24
  * No R6 object is built, flattened, imported, or used as an adapter input. */
@@ -1,3 +1,4 @@
1
+ import type { MedicationConditionLexicalFeatures } from "./medication-condition";
1
2
  import { AdviceFrame, AdviceModality } from "./types";
2
3
  export interface AdviceLocaleRealizationInput {
3
4
  frame: AdviceFrame;
@@ -6,14 +7,37 @@ export interface AdviceLocaleRealizationInput {
6
7
  argText?: string;
7
8
  modalityText?: string;
8
9
  relationText?: string;
10
+ /** Complete wording from the selected typed action. Stock realization keeps
11
+ * its argument roles and relations; registered providers may replace it. */
12
+ typedText?: string;
9
13
  }
10
14
  export interface AdviceLocaleAdapter {
11
15
  locale: string;
16
+ medicationConditions?: MedicationConditionLexicalFeatures;
17
+ referentIdentity?(text: string): string;
18
+ siteCoordination?(text: string): {
19
+ left: string;
20
+ right: string;
21
+ connector: string;
22
+ } | undefined;
12
23
  realizeModality(modality: AdviceModality | undefined): string | undefined;
13
24
  siteArgument(text: string): string;
14
25
  joinArguments(texts: string[]): string | undefined;
15
26
  realize(input: AdviceLocaleRealizationInput): string;
16
27
  finalize(text: string): string;
17
28
  }
29
+ /** Revision of the registered lexical capabilities used by derived caches. */
30
+ export declare function adviceLocaleAdapterRevision(): number;
18
31
  export declare function registerAdviceLocaleAdapter(adapter: AdviceLocaleAdapter): void;
19
32
  export declare function getAdviceLocaleAdapter(locale: string): AdviceLocaleAdapter;
33
+ /** A registered wording provider keeps its complete advice realization even
34
+ * when typed graph facts can supply the stock default. Recognition-only
35
+ * registration does not replace that default; no callback runs for this test. */
36
+ export declare function hasRegisteredAdviceWording(locale: string, hook?: "realize" | "realizeModality" | "siteArgument" | "joinArguments" | "finalize"): boolean;
37
+ /** Stock wording is used only to recognize an unchanged materialized label. */
38
+ export declare function getDefaultAdviceLocaleAdapter(locale: string): AdviceLocaleAdapter;
39
+ /** Recognize a connector independently of the languages of its two nouns. */
40
+ export declare function matchAdviceSiteCoordination(text: string, locale: string): ReturnType<NonNullable<AdviceLocaleAdapter["siteCoordination"]>>;
41
+ /** Clause admission consumes registered lexical cues independently of the
42
+ * language selected for rendering; registration owns matcher cursor semantics. */
43
+ export declare function isAdviceConditionCue(text: string): boolean;
package/dist/advice.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { AdditionalInstructionDefinition, AdviceArgument, AdviceForce, AdviceFrame, FhirCoding, TextRange } from "./types";
1
+ import type { LexToken } from "./lexer/token-types";
2
+ import { AdditionalInstructionDefinition, AdviceArgument, AdviceForce, AdviceFrame, FhirCoding, MedicationInstructionActionDefinition, TextRange } from "./types";
2
3
  /** Directed clinical Coding identity; presentation and Element annotations stay on their owner. */
3
4
  export declare function preservesAdviceCoding(selected: FhirCoding | undefined, actual: FhirCoding | undefined): boolean;
4
5
  export declare function preservesAdviceCodings(selected: readonly FhirCoding[] | undefined, actual: readonly FhirCoding[] | undefined): boolean;
@@ -14,6 +15,8 @@ export declare function preservesAdviceComponents(selected: readonly {
14
15
  /** Text, source spans and retained Element annotations are not typed argument facts. */
15
16
  export declare function hasAdviceArgumentFacts(argument: AdviceArgument): boolean;
16
17
  export declare function preservesAdviceArgumentFacts(selected: AdviceArgument, actual: AdviceArgument): boolean;
18
+ /** Argument roles are independent slots; the order within a role is retained. */
19
+ export declare function correspondingAdviceArguments(selected: readonly AdviceArgument[], actual: readonly AdviceArgument[], matches: (left: AdviceArgument, right: AdviceArgument) => boolean, complete?: boolean): boolean;
17
20
  /**
18
21
  * Preserve selected typed facts while a caller licenses the same occurrence/head.
19
22
  * Source/value correspondence and provisional opaque valence remain caller-owned.
@@ -39,12 +42,19 @@ export interface AdviceParseContext {
39
42
  export declare function matchComposedAdviceCodings(frames: readonly AdviceFrame[]): AdditionalInstructionDefinition[];
40
43
  /** Determine whether a rule's coding must be rechecked against scoped HPSG frames. */
41
44
  export declare function adviceCodingNeedsComposedScope(system: string, code: string): boolean;
45
+ /** Return the same composed-only declaration for preview lexical ownership. */
46
+ export declare function composedAdviceCodingDefinition(system: string, code: string): AdditionalInstructionDefinition | undefined;
47
+ /** Retain the selected occurrences whose complete qualifiers are represented by
48
+ * the coding template. One unrepresented member does not invalidate its siblings;
49
+ * source locations and registered lexical enrichment are not additional meaning.
50
+ * Association without a selected locale must retain every supplied predicate label. */
51
+ export declare function adviceTemplateRepresentedActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code" | "_system">, locale?: string): AdviceFrame[];
42
52
  /**
43
53
  * Retain the existing coding matcher's exact supporting action objects for
44
54
  * occurrence-aware realization. Clinical coding and wording remain with their
45
55
  * existing owners; no action identity is reconstructed from rendered text.
46
56
  */
47
- export declare function composedCodedAdviceActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code"> | undefined): AdviceFrame[];
57
+ export declare function composedCodedAdviceActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code" | "_system"> | undefined): AdviceFrame[];
48
58
  /** Existing advice terminology supplies manner modifiers to the main action
49
59
  * grammar. It is lexical evidence, not a second clause parser. */
50
60
  export declare function resolveAdviceMannerModifier(surface: string): {
@@ -53,9 +63,35 @@ export declare function resolveAdviceMannerModifier(surface: string): {
53
63
  } | undefined;
54
64
  /** Exact advice nominals share their existing lexical identity with action arguments. */
55
65
  export declare function resolveAdviceNominalArgument(surface: string, sourceText?: string): AdviceArgument | undefined;
56
- export declare function realizeAdviceFramesText(frames: AdviceFrame[], locale?: string): string | undefined;
66
+ /** A complete compound nominal retains its lexical owner when its final word
67
+ * also names a generic event. Only declared compounds ending at that word are checked. */
68
+ export declare function resolveCompoundAdviceNominalEndingAt(tokens: readonly Pick<LexToken, "canonical" | "lower">[], endExclusive: number): {
69
+ start: number;
70
+ argument: AdviceArgument;
71
+ } | undefined;
72
+ /** The same declared compound owner resolves a complete following conjunct. */
73
+ export declare function resolveCompoundAdviceNominalAt(tokens: readonly Pick<LexToken, "canonical" | "lower">[], start: number): {
74
+ end: number;
75
+ argument: AdviceArgument;
76
+ } | undefined;
77
+ export declare function classifyArgument(text: string, completeNominal?: boolean): AdviceArgument;
78
+ export declare function realizeAdviceFramesText(frames: AdviceFrame[], locale?: string, typed?: {
79
+ text: string;
80
+ argumentText: (argument: AdviceArgument) => string;
81
+ }): string | undefined;
57
82
  export declare function parseAdditionalInstructions(sourceText: string, span: TextRange, context?: AdviceParseContext): ParsedAdditionalInstruction[];
83
+ /** Complete registered wording permits only the existing presentation variants.
84
+ * This proves stock lexical ownership, never equality of rendered instructions. */
85
+ export declare function isStockAdditionalInstructionWording(text: string | undefined, definition: AdditionalInstructionDefinition): boolean;
86
+ /** Exact registered advice remains one lexical constituent before a generic
87
+ * action frame can split its nominal or relation-shaped words. */
88
+ export declare function resolveRegisteredAdditionalInstruction(sourceText: string, span: TextRange, selectedAction: MedicationInstructionActionDefinition | undefined): ParsedAdditionalInstruction | undefined;
58
89
  export declare function findAdditionalInstructionDefinitionByCoding(system: string, code: string): AdditionalInstructionDefinition | undefined;
90
+ /** Select known advice meaning without reducing the original wire coding list. */
91
+ export declare function selectAdditionalInstructionCoding<T extends {
92
+ system?: string;
93
+ code?: string;
94
+ }>(codings: readonly T[] | undefined): T | undefined;
59
95
  export declare const __test__: {
60
96
  createDefinitionFromSource(source: {
61
97
  system?: string;
@@ -1,3 +1,4 @@
1
+ import type { Token } from "./parser-state";
1
2
  import { BodySiteDefinition, BodySiteSpatialRelation, FhirCoding, type BodySiteRestriction, type BodySiteRestrictionPredicate, type TextRange } from "./types";
2
3
  import type { BodySiteLocativeRelation } from "./relation-terminology";
3
4
  export type BodySiteGrammarKind = "nominal" | "partitive" | "locative";
@@ -26,6 +27,7 @@ export interface BodySiteNominalFeatures {
26
27
  }
27
28
  export interface BodySitePartitiveFeatures {
28
29
  kind: "partitive";
30
+ canonical: string;
29
31
  part: string;
30
32
  relationKey?: string;
31
33
  whole: BodySiteNominalFeatures;
@@ -53,6 +55,8 @@ export interface ResolvedBodySitePhrase {
53
55
  * It deliberately grants no code to a qualified site merely because its
54
56
  * unqualified anatomy is coded. */
55
57
  siteI18n?: Record<string, string>;
58
+ /** Registered modifiers retained outside the selected anatomical head. */
59
+ nominalModifiers?: readonly string[];
56
60
  restrictions?: BodySiteRestriction[];
57
61
  preferredPreposition?: "to" | "at" | "in" | "into";
58
62
  }
@@ -60,7 +64,22 @@ export interface BodySitePhraseContext {
60
64
  bodySiteContext?: string;
61
65
  allowTerminalModifierInheritance?: boolean;
62
66
  }
67
+ export declare function isBodySiteNominalModifier(word: string): boolean;
68
+ /** Complete registered nominal evidence only. A caller must still license its
69
+ * grammatical role; this lookup does not attach a site or suppress an action. */
70
+ export declare function bodySiteModifierNominalAt(parts: readonly Token[], index: number, customSiteMap?: Record<string, BodySiteDefinition>, context?: BodySitePhraseContext, limit?: number): {
71
+ start: number;
72
+ end: number;
73
+ site: ResolvedBodySitePhrase;
74
+ } | undefined;
63
75
  export declare function lookupBodySiteDefinition(map: Record<string, BodySiteDefinition> | undefined, canonical: string): BodySiteDefinition | undefined;
76
+ /** Articles belong to a nominal constituent, including a spatial target.
77
+ * Callers retain exact whole matches and require recognized remainder meaning. */
78
+ export declare function withoutBodySiteNominalArticles(text: string): string;
79
+ /** Position already resolved nominal modifiers through their registered class. */
80
+ export declare function composeBodySiteNominalModifiers(text: string, modifiers: readonly string[]): string;
81
+ /** Exact anatomy retains precedence over focus-only modifier inheritance. */
82
+ export declare function resolveBodySiteAnatomyDefinition(canonical: string, customSiteMap?: Record<string, BodySiteDefinition>): BodySiteDefinition | undefined;
64
83
  /** One lexical interpretation for standalone and clause-level site predicates.
65
84
  * Introducers and terminology are resolved here once, never in FHIR lowering.
66
85
  * @param text Predicate surface text, excluding the relation marker.
@@ -79,9 +98,9 @@ export declare function resolveBodySiteRestrictionPredicate(text: string, range?
79
98
  export declare function formBodySiteRestriction(predicate: BodySiteRestrictionPredicate, markerRange?: TextRange, sourceText?: string): BodySiteRestriction;
80
99
  /** Realize a typed restriction by lexical identity, never by re-parsing prose.
81
100
  * @param restriction Typed site-local relative clause.
82
- * @param locale English or Thai output locale.
101
+ * @param locale Registered output locale.
83
102
  */
84
- export declare function realizeBodySiteRestriction(restriction: BodySiteRestriction, locale: "en" | "th"): string | undefined;
103
+ export declare function realizeBodySiteRestriction(restriction: BodySiteRestriction, locale: string): string | undefined;
85
104
  export declare function resolveBodySitePhrase(text: string, customSiteMap?: Record<string, BodySiteDefinition>, context?: BodySitePhraseContext): ResolvedBodySitePhrase | undefined;
86
105
  /** Anatomical vocabulary lookup only. Full-SIG lexical rules use this entrypoint
87
106
  * so a lexical site cannot independently absorb a relative clause.
@@ -1,3 +1,4 @@
1
+ import { ResolvedBodySitePhrase } from "./body-site-grammar";
1
2
  import { BodySiteCode, BodySiteDefinition, BodySiteSpatialRelation, FhirCoding } from "./types";
2
3
  export interface BodySiteLookupOptions {
3
4
  siteCodeMap?: Record<string, BodySiteDefinition>;
@@ -77,7 +78,11 @@ export declare function getBodySiteCode(input: string, options?: BodySiteLookupO
77
78
  export declare function getBodySiteCodeAsync(input: string, options?: BodySiteLookupOptions): Promise<BodySiteCode | undefined>;
78
79
  /** Realize an already selected laterality with the existing anatomical text owner.
79
80
  * Internal consumers must establish anatomical compatibility before calling. */
80
- export declare function bodySiteTextWithLaterality(text: string, lateralityCode: string): string | undefined;
81
+ export declare function bodySiteTextWithLaterality(text: string, lateralityCode: string, features?: ResolvedBodySitePhrase["features"]): string | undefined;
82
+ /** Recover the registered base wording of an authored paired site. Code-only
83
+ * lookup keeps its exact preferred label; splitting an authored alias retains
84
+ * that alias through the existing language provider's laterality realization. */
85
+ export declare function bilateralBodySiteSourceBaseText(sourceText: string | undefined, parent: BodySiteCode): string | undefined;
81
86
  export declare function getBodySiteText(input: BodySiteCodeInput, options?: BodySiteTextOptions): string | undefined;
82
87
  export declare function getBodySiteTextAsync(input: BodySiteCodeInput, options?: BodySiteTextOptions): Promise<string | undefined>;
83
88
  export declare function suggestBodySites(input: string, options?: BodySiteLookupOptions): BodySiteLookupResult[];
@@ -1,10 +1,16 @@
1
- import { BodySiteSpatialRelation, FhirR6CodeableConcept, FhirR6Coding, FhirExtension } from "./types";
1
+ import { BodySiteSpatialRelation, FhirR6CodeableConcept, FhirR6Coding, FhirR6Extension, FhirExtension } from "./types";
2
2
  export declare const BODY_SITE_SPATIAL_RELATION_EXTENSION_URL = "urn:ezmedicationinput:body-site-spatial-relation";
3
3
  /** Top-level and nested sites share the existing anatomical Coding preference. */
4
4
  export declare function selectPreferredSiteCoding<TCoding extends FhirR6Coding>(site: {
5
5
  coding?: TCoding[];
6
6
  } | undefined): TCoding | undefined;
7
+ /** Exact typed relation equality shared by unification and realization.
8
+ * Coding display/translation annotations do not change the relation; authored
9
+ * relation, target and source text still have to agree completely. Rendering
10
+ * may supply its neutral target resolver to prove equivalent retained labels. */
11
+ export declare function sameBodySiteSpatialRelation(left: BodySiteSpatialRelation | undefined, right: BodySiteSpatialRelation | undefined, resolveTarget?: (relation: BodySiteSpatialRelation) => string | undefined): boolean;
7
12
  export declare function cloneBodySiteSpatialRelation(relation: BodySiteSpatialRelation | undefined): BodySiteSpatialRelation | undefined;
13
+ export declare function bodySiteSpatialRelationForWire(relation: BodySiteSpatialRelation | undefined, target: "r5" | "r6"): FhirR6Extension | undefined;
8
14
  export declare function buildBodySiteSpatialRelationExtension(relation: BodySiteSpatialRelation | undefined): FhirExtension | undefined;
9
15
  export declare function buildBodySiteSpatialRelationExtensions(relation: BodySiteSpatialRelation | undefined): FhirExtension[] | undefined;
10
16
  export declare function parseBodySiteSpatialRelationExtension(concept: FhirR6CodeableConcept | undefined): BodySiteSpatialRelation | undefined;
@@ -1,4 +1,5 @@
1
- import { BodySiteCode, BodySiteDefinition, BodySiteSpatialRelation, CanonicalSiteExpr, FhirR6CodeableConcept, FhirCoding, FhirExtension } from "./types";
1
+ import { type ResolvedBodySitePhrase } from "./body-site-grammar";
2
+ import { BodySiteCode, BodySiteDefinition, BodySiteSpatialRelation, CanonicalSiteExpr, CanonicalDoseExpr, FormatOptions, FhirR6CodeableConcept, FhirCoding, FhirR6Coding, FhirExtension } from "./types";
2
3
  export declare const BODY_SITE_ADMINISTRATION_TARGET_COUNT_EXTENSION_URL = "urn:ezmedicationinput:body-site-administration-target-count";
3
4
  type SiteLike = CanonicalSiteExpr | {
4
5
  text?: string;
@@ -11,11 +12,42 @@ interface BodySiteTargetCountOptions {
11
12
  bodySiteContext?: string;
12
13
  }
13
14
  export declare function normalizeAdministrationTargetCount(value: number | undefined): number | undefined;
14
- export declare function bodySiteTextConflictsWithCoding(text: string, coding: Pick<FhirCoding, "system" | "code"> | undefined): boolean;
15
+ /** Intrinsic multiplicity of a registered anatomical identity, independent of
16
+ * an additionally supplied count or its provider-owned surface. */
17
+ export declare function bodySiteCodingTargetCount(coding: Pick<FhirCoding, "system" | "code"> | undefined): number | undefined;
18
+ /** Discrete doses distribute across paired targets; metric amounts are totals. */
19
+ export declare function doseUnitUsesTargetScope(unit: string | undefined, allocation?: CanonicalDoseExpr["allocation"]): boolean;
20
+ /** Resolve the existing discrete/metric policy only for a typed dose/site
21
+ * composition. An imported explicit allocation always owns its meaning. */
22
+ export declare function doseAllocationForTargets(unit: string | undefined, targetCount: number | undefined, allocation?: CanonicalDoseExpr["allocation"]): CanonicalDoseExpr["allocation"];
23
+ export declare function usesExplicitPairedSiteWording(options?: Pick<FormatOptions, "pairedSiteWording" | "realizationMode">): boolean;
24
+ /** Optional wording for a recognized paired site whose dose already uses per-target text. */
25
+ export declare function pairedSiteDoseScope(count: number | undefined, site: ResolvedBodySitePhrase | undefined, locale: string): string | undefined;
26
+ /** Count qualifiers for the location actually selected by a renderer. The
27
+ * caller supplies its resolved visible site and existing per-target wording;
28
+ * independently supplied coding does not replace that wording's identity. */
29
+ export declare function bodySiteTargetScope(count: number | undefined, resolvedSite: Pick<ResolvedBodySitePhrase, "coding" | "definition"> | undefined, unit: string | undefined, perTargetWording: boolean, allocation?: CanonicalDoseExpr["allocation"]): {
30
+ count?: number;
31
+ perTarget: boolean;
32
+ } | undefined;
33
+ /** Anatomical selection is containment; it does not weaken exact site identity. */
34
+ export declare function bodySiteSelectionIncludes(target: CanonicalSiteExpr, member: CanonicalSiteExpr): boolean;
35
+ /** Select paired anatomy from registered identity; provider wording is not a lookup key. */
36
+ export declare function registeredBilateralBodySiteDefinition(coding: BodySiteCode | undefined): BodySiteDefinition | undefined;
37
+ /** Split a typed bilateral administration only when a selective adjunct requires it. */
38
+ export declare function bilateralBodySiteTargets(site: CanonicalSiteExpr): CanonicalSiteExpr[] | undefined;
39
+ /** A broader selected anatomy may omit a side already owned by its source head.
40
+ * Explicit selected laterality and unrelated anatomy retain their own authority. */
41
+ export declare function bodySiteTextWithInheritedLaterality(selected: BodySiteDefinition, sourceHead: string | undefined): string | undefined;
42
+ /** A complete label or independently realized registered anatomy can retain
43
+ * its coded target once. wordingCoding describes recognized rendered words,
44
+ * never the separately supplied site coding. Broader wording retains laterality. */
45
+ export declare function bodySiteWordingIncludesTarget(text: string, coding: FhirCoding, wordingCoding?: FhirCoding): boolean;
46
+ export declare function bodySiteTextConflictsWithCoding(text: string, coding: Pick<FhirCoding | FhirR6Coding, "system" | "_system" | "code"> | undefined): boolean;
15
47
  export declare function resolveBodySiteTargetText(site: string | SiteLike | FhirR6CodeableConcept | undefined, options?: BodySiteTargetCountOptions): string | undefined;
16
48
  /** Realization may use a retained equivalent Coding's label without changing
17
49
  * the selected anatomical identity or materializing text into its wire carrier. */
18
- export declare function resolveBodySiteSpatialTargetText(relation: BodySiteSpatialRelation): string | undefined;
50
+ export declare function resolveBodySiteSpatialTargetText(relation: BodySiteSpatialRelation, locale?: string): string | undefined;
19
51
  export declare function buildBodySiteAdministrationTargetCountExtension(targetCount: number | undefined): FhirExtension | undefined;
20
52
  export declare function parseBodySiteAdministrationTargetCountExtension(concept: FhirR6CodeableConcept | {
21
53
  extension?: FhirExtension[];