ezmedicationinput 0.3.0 → 0.3.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +138 -0
  2. package/dist/adapters/r5-course.d.ts +6 -0
  3. package/dist/body-site-grammar.d.ts +6 -2
  4. package/dist/body-site-target.d.ts +4 -1
  5. package/dist/canonical/course.d.ts +4 -1
  6. package/dist/canonical/dosage-agreement.d.ts +84 -0
  7. package/dist/canonical/format-course.d.ts +8 -1
  8. package/dist/combine-multilingual-dosages.d.ts +32 -0
  9. package/dist/event-timing-expression.d.ts +3 -1
  10. package/dist/execution/engine.d.ts +2 -1
  11. package/dist/fhir-translations.d.ts +13 -0
  12. package/dist/fhir.d.ts +1 -1
  13. package/dist/format.d.ts +4 -1
  14. package/dist/hpsg/constructions.d.ts +3 -0
  15. package/dist/hpsg/lexical-classes.d.ts +6 -0
  16. package/dist/hpsg/procedural-context.d.ts +11 -6
  17. package/dist/hpsg/projection.d.ts +2 -2
  18. package/dist/hpsg/rule-context.d.ts +9 -4
  19. package/dist/hpsg/rules/core-rules.d.ts +5 -3
  20. package/dist/hpsg/rules/prn-rules.d.ts +2 -1
  21. package/dist/hpsg/rules/timing-rules.d.ts +35 -25
  22. package/dist/hpsg/signature.d.ts +31 -1
  23. package/dist/hpsg/timing-lexicon.d.ts +5 -0
  24. package/dist/i18n.d.ts +3 -0
  25. package/dist/index.cjs +49230 -43847
  26. package/dist/index.d.ts +6 -1
  27. package/dist/index.js +49218 -43846
  28. package/dist/instruction-action-locale-adapter.d.ts +21 -3
  29. package/dist/instruction-action-parser.d.ts +16 -1
  30. package/dist/instruction-action-terminology.d.ts +7 -0
  31. package/dist/instruction-concept-terminology.d.ts +1 -0
  32. package/dist/instruction-graph-ownership.d.ts +9 -2
  33. package/dist/instruction-graph.d.ts +15 -4
  34. package/dist/locale-realization.d.ts +2 -0
  35. package/dist/locales/course/en.d.ts +10 -5
  36. package/dist/localization.d.ts +8 -1
  37. package/dist/medication-condition.d.ts +36 -1
  38. package/dist/prn.d.ts +2 -0
  39. package/dist/schedule.d.ts +5 -2
  40. package/dist/timing-summary.d.ts +3 -2
  41. package/dist/types.d.ts +104 -4
  42. package/package.json +1 -1
package/README.md CHANGED
@@ -108,6 +108,7 @@ contract, not a datatype name or release tag absent from the JSON. Objects in
108
108
  the structural overlap are accepted, including text-only `renderedInstruction`
109
109
  objects and structured dosages using shared fields. Acceptance does not identify
110
110
  which release produced the object or add support for the September schema.
111
+
111
112
  TypeScript callers of the earlier R6 draft should replace `FhirR6DosageDetails`
112
113
  with `FhirR6DosageInstruction`. Its `step` property is optional, matching the
113
114
  current wire contract:
@@ -144,6 +145,114 @@ leaves the relation unresolved.
144
145
  The existing R5 course metadata preserves this boundary and its annotations
145
146
  through saves. Patient-facing wording comes from the course language facet.
146
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
+
147
256
  ### R5 clocks alongside event-based timing
148
257
 
149
258
  For mixed schedules such as `1 tab with meals and @ 10:00`, the R5
@@ -290,6 +399,9 @@ Formatting options:
290
399
  wording, preserves source-faithful clinician text when the semantic graph has
291
400
  same-locale provenance, and realizes typed graph semantics across locales.
292
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 หยด ให้ครบทั้งสองข้าง”.
293
405
  - `groupMealTimingsByRelation`: compacts repeated meal relation phrases when all
294
406
  meal anchors share the same relation.
295
407
  Example EN: `after breakfast, lunch and dinner`
@@ -961,6 +1073,32 @@ const schedule = nextDueDoses(fhir, {
961
1073
  // → ["2024-01-01T12:30:00+07:00", "2024-01-01T18:30:00+07:00", ...]
962
1074
  ```
963
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
+
964
1102
  Key rules:
965
1103
 
966
1104
  - `when` values map to the clinic `eventClock`. Generic meal codes (`AC`, `PC`, `C`) use `mealOffsets` against breakfast/lunch/dinner anchors.
@@ -13,6 +13,12 @@ import { type DosageSourceTextBaseline } from "../dosage-course";
13
13
  /** A standalone source component uses the same native facts and retained-field
14
14
  * writer as a complete course, without inventing surrounding stages. */
15
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[];
16
22
  /** Native course metadata is serialized once into its FINAL R5 extension
17
23
  * header. Step/member loops write direct rows and their local retained fields.
18
24
  * No R6 object is built, flattened, imported, or used as an adapter input. */
@@ -65,6 +65,9 @@ export interface BodySitePhraseContext {
65
65
  allowTerminalModifierInheritance?: boolean;
66
66
  }
67
67
  export declare function isBodySiteNominalModifier(word: string): boolean;
68
+ /** A locative governor with only determiner/modifier daughters still awaits
69
+ * its anatomical head. An ambiguous route word cannot close that nominal. */
70
+ export declare function bodySiteModifierHasLocativeGovernor(parts: readonly Token[], index: number): boolean;
68
71
  /** Complete registered nominal evidence only. A caller must still license its
69
72
  * grammatical role; this lookup does not attach a site or suppress an action. */
70
73
  export declare function bodySiteModifierNominalAt(parts: readonly Token[], index: number, customSiteMap?: Record<string, BodySiteDefinition>, context?: BodySitePhraseContext, limit?: number): {
@@ -76,8 +79,9 @@ export declare function lookupBodySiteDefinition(map: Record<string, BodySiteDef
76
79
  /** Articles belong to a nominal constituent, including a spatial target.
77
80
  * Callers retain exact whole matches and require recognized remainder meaning. */
78
81
  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;
82
+ /** Compose resolved modifiers in the selected wording's registered locale.
83
+ * A missing capability leaves the caller's complete authored wording intact. */
84
+ export declare function composeBodySiteNominalModifiers(text: string, modifiers: readonly string[]): string | undefined;
81
85
  /** Exact anatomy retains precedence over focus-only modifier inheritance. */
82
86
  export declare function resolveBodySiteAnatomyDefinition(canonical: string, customSiteMap?: Record<string, BodySiteDefinition>): BodySiteDefinition | undefined;
83
87
  /** One lexical interpretation for standalone and clause-level site predicates.
@@ -1,5 +1,5 @@
1
1
  import { type ResolvedBodySitePhrase } from "./body-site-grammar";
2
- import { BodySiteCode, BodySiteDefinition, BodySiteSpatialRelation, CanonicalSiteExpr, CanonicalDoseExpr, FhirR6CodeableConcept, FhirCoding, FhirR6Coding, FhirExtension } from "./types";
2
+ import { BodySiteCode, BodySiteDefinition, BodySiteSpatialRelation, CanonicalSiteExpr, CanonicalDoseExpr, FormatOptions, FhirR6CodeableConcept, FhirCoding, FhirR6Coding, FhirExtension } from "./types";
3
3
  export declare const BODY_SITE_ADMINISTRATION_TARGET_COUNT_EXTENSION_URL = "urn:ezmedicationinput:body-site-administration-target-count";
4
4
  type SiteLike = CanonicalSiteExpr | {
5
5
  text?: string;
@@ -20,6 +20,9 @@ export declare function doseUnitUsesTargetScope(unit: string | undefined, alloca
20
20
  /** Resolve the existing discrete/metric policy only for a typed dose/site
21
21
  * composition. An imported explicit allocation always owns its meaning. */
22
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;
23
26
  /** Count qualifiers for the location actually selected by a renderer. The
24
27
  * caller supplies its resolved visible site and existing per-target wording;
25
28
  * independently supplied coding does not replace that wording's identity. */
@@ -154,7 +154,10 @@ export interface CanonicalBoundary {
154
154
  * Other non-treatment anchors need an external resolver; never reinterpret
155
155
  * them as treatment-relative dates. */
156
156
  anchor: "treatment-start" | "treatment-day-start" | "previous-phase-next-day" | "previous-phase-end" | "coded-event" | "resource-reference" | "definition" | "path" | "unresolved";
157
- contextCode?: CanonicalConcept;
157
+ contextCode?: CanonicalConcept & {
158
+ /** Whole event-label translations selected by the originating provider. */
159
+ i18n?: Record<string, string>;
160
+ };
158
161
  contextReference?: CanonicalReference;
159
162
  contextDefinition?: string;
160
163
  contextPath?: string;
@@ -0,0 +1,84 @@
1
+ import type { FhirDosage, FhirR6DosageInstructionInput, ParseBatchResult, ParseResult } from "../types";
2
+ import type { FhirCoding } from "../types";
3
+ import type { CanonicalAdministration, CanonicalBoundary, CanonicalConcept, CanonicalCourse, CanonicalMeasure, CanonicalStage } from "./course";
4
+ export interface DosageDifference {
5
+ path: string;
6
+ primary: unknown;
7
+ other: unknown;
8
+ reason: "different-meaning" | "unpaired-text" | "ambiguous-alignment" | "uncompared-modifier" | "unknown-unit" | "missing-unit" | "unknown-value" | "unknown-content" | "unresolved-context" | "input";
9
+ }
10
+ /** Clinical compares dosage meaning; structural compares the supplied data shape. */
11
+ export type DosageComparisonMode = "clinical" | "structural" | "permissive" | "custom";
12
+ export type DosageComparisonInput = CanonicalCourse | CanonicalAdministration | readonly CanonicalAdministration[] | FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseResult | ParseBatchResult;
13
+ export interface DosageComparisonPolicy {
14
+ /** Registered compatible dimensions only; never infer strength or substitute a product. */
15
+ units: "registered" | "exact";
16
+ missingUnits: "indeterminate" | "exact";
17
+ unknownUnits: "indeterminate" | "exact";
18
+ /** Retained unmodeled content; "exact" explicitly selects saved-data equality. */
19
+ unknownContent: "indeterminate" | "exact" | "ignore";
20
+ /** Clinical order treats event sets and independently identified parallel members as unordered. Phases remain ordered. */
21
+ ordering: "clinical" | "preserve" | "multiset";
22
+ narrative: "clinical" | "preserve" | "ignore";
23
+ generatedIds: "ignore" | "preserve";
24
+ /** Structural modes only; clinical import already normalizes absent optional collections. */
25
+ emptyValues: "absent" | "preserve";
26
+ }
27
+ export interface DosageComparisonOptions {
28
+ mode?: DosageComparisonMode;
29
+ /** Custom starts with Clinical defaults. Explicit overrides also apply to a named mode. */
30
+ policy?: Partial<DosageComparisonPolicy>;
31
+ primaryLocale?: string;
32
+ otherLocale?: string;
33
+ /** Clinician-established associations, using the same canonical paths as multilingual composition. */
34
+ pairedText?: readonly string[];
35
+ /** A pure caller-context resolver. Equal keys must identify the same anchor, before its retained displacement. */
36
+ resolveAnchor?: (boundary: CanonicalBoundary, side: "primary" | "other") => string | undefined;
37
+ }
38
+ export interface DosageComparisonResult {
39
+ status: "equivalent" | "different" | "indeterminate";
40
+ differences: DosageDifference[];
41
+ }
42
+ interface ComparisonState {
43
+ policy: DosageComparisonPolicy;
44
+ options: DosageComparisonOptions;
45
+ diagnostics?: DosageDifference[];
46
+ uncertainty: boolean;
47
+ usesPaths: boolean;
48
+ }
49
+ declare function sameDuration(left: CanonicalMeasure | undefined, right: CanonicalMeasure | undefined, state?: ComparisonState, path?: string): boolean;
50
+ export interface WordingAgreement {
51
+ primaryLocale: string;
52
+ otherLocale: string;
53
+ pairedText: ReadonlySet<string>;
54
+ comparison?: ComparisonState;
55
+ }
56
+ export declare function comparableAdviceIndices(a: CanonicalAdministration): number[];
57
+ /** A broad finding code does not account for an independently authored qualifier. */
58
+ export declare function prnUsesStockWording(row: CanonicalConcept, registered?: FhirCoding | undefined): boolean;
59
+ export declare function adviceUsesStockWording(row: CanonicalConcept): boolean;
60
+ export declare function administrationDifference(left: CanonicalAdministration, right: CanonicalAdministration, path: string, wording: WordingAgreement): DosageDifference | undefined;
61
+ export declare function stageDifference(left: CanonicalStage, right: CanonicalStage, path: string, state?: ComparisonState): DosageDifference | undefined;
62
+ export declare function courseDifference(left: CanonicalCourse, right: CanonicalCourse, state?: ComparisonState): DosageDifference | undefined;
63
+ export declare function memberSiteIdentity(a: CanonicalAdministration): string | undefined;
64
+ /** Independent members can also be fixed to different authored clocks or calendar anchors. */
65
+ export declare function memberTimingIdentity(a: CanonicalAdministration): string | undefined;
66
+ export { sameDuration };
67
+ export interface DosageMemberPair {
68
+ left: CanonicalAdministration;
69
+ right: CanonicalAdministration;
70
+ path: string;
71
+ }
72
+ /** Read-only clinical agreement shared by comparison and multilingual composition. */
73
+ export declare function agreeCanonicalCourses(left: CanonicalCourse, right: CanonicalCourse, wording: WordingAgreement): {
74
+ pairs: DosageMemberPair[];
75
+ difference?: DosageDifference;
76
+ };
77
+ /**
78
+ * Compare supported dosage data without parsing prose or requiring executable schedules.
79
+ * Clinical is conservative; indeterminate never becomes true through the boolean helper.
80
+ * Structural and Permissive compare the supplied wire/native representation, retaining row order.
81
+ */
82
+ export declare function compareDosages(primary: DosageComparisonInput, other: DosageComparisonInput, options?: DosageComparisonOptions): DosageComparisonResult;
83
+ /** The same status kernel with diagnostics disabled; indeterminate is always false. */
84
+ export declare function areDosagesEquivalent(primary: DosageComparisonInput, other: DosageComparisonInput, options?: DosageComparisonOptions): boolean;
@@ -3,12 +3,13 @@
3
3
  * Display stays separate from executable interpretation: unknown expressions
4
4
  * and boundaries remain visible without inventing values or event dates. */
5
5
  import type { FormatBatchOptions, FormatOptions, MedicationCondition, FhirDayOfWeek, CanonicalSigClause, CanonicalScheduleExpr } from "../types";
6
- import type { CanonicalCourse, CanonicalAdministration, CanonicalRange, CanonicalExpression, CanonicalSafety } from "./course";
6
+ import type { CanonicalCourse, CanonicalAdministration, CanonicalRange, CanonicalExpression, CanonicalDoseLimit, CanonicalSafety } from "./course";
7
7
  import { type SigLocalization, type CourseLanguage } from "../i18n";
8
8
  /** Resolved once per invocation; recursive clinical composition reuses it. */
9
9
  interface CourseFormatEnvironment {
10
10
  localization?: SigLocalization;
11
11
  words: CourseLanguage;
12
+ locale?: string;
12
13
  }
13
14
  export declare function joinGeneratedClauses(clauses: readonly string[], separator?: string): string;
14
15
  export declare function appendMedicationExcludedDatesText(text: string, dates: readonly string[], options?: FormatOptions, environment?: CourseFormatEnvironment): string;
@@ -25,6 +26,12 @@ export declare function rateRangePreview(range: CanonicalRange): string | undefi
25
26
  export declare function prefersSourceInstruction(course: CanonicalCourse): boolean;
26
27
  /** Unconditional membership owns a shared allowance across every selectable path. */
27
28
  export declare function formatCourseChoices<T>(members: readonly T[], render: (member: T, sharedCountAlreadyDisplayed?: boolean) => string, choiceOf: (member: T) => CanonicalAdministration["choice"], words: CourseLanguage, separator?: string, courseLabels?: ReadonlyMap<string, ReadonlyMap<string, string>>, sharedCountOf?: (member: T) => CanonicalScheduleExpr["sharedCount"], memberFormatOverride?: boolean, localization?: SigLocalization): string;
29
+ /** Render the value and scope of each authored limit without evaluating it.
30
+ * Member, stage and course owners share this value rendering; their enclosing
31
+ * wording remains separate so a shared allowance is never repeated per dose.
32
+ * Partial quantities and expressions remain visible rather than disappearing
33
+ * merely because numeric execution cannot use them. */
34
+ export declare function formatDoseLimits(limits: readonly CanonicalDoseLimit[], style: "short" | "long", environment: CourseFormatEnvironment): string;
28
35
  /** Transient renderer result for callers retaining independently authored text. */
29
36
  interface AuthoredDirectionsState {
30
37
  text: string;
@@ -0,0 +1,32 @@
1
+ import type { DosageDifference } from "./canonical/dosage-agreement";
2
+ import type { FhirDosage, FhirR6DosageInstruction, FhirR6DosageInstructionInput, ParseBatchResult } from "./types";
3
+ export type MultilingualDosageInput = FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult;
4
+ export interface CombineMultilingualDosagesOptions {
5
+ /** Locale key whose authored clinical quantities and wording are retained as the originals. Defaults to the first key. */
6
+ primaryLocale?: string;
7
+ /** Zero-based canonical paths of clinician-paired free text, e.g. "stages[0].administrations[0].additionalInstructions[0]". */
8
+ pairedText?: readonly string[];
9
+ }
10
+ export interface MultilingualDosageConflict {
11
+ primaryLocale: string;
12
+ locale: string;
13
+ path: string;
14
+ primary: unknown;
15
+ other: unknown;
16
+ reason: DosageDifference["reason"] | "input" | "different-translation" | "uncompared-modifier";
17
+ }
18
+ export type CombineMultilingualDosagesResult = {
19
+ ok: true;
20
+ primaryLocale: string;
21
+ fhir: FhirDosage[];
22
+ fhirNext: FhirR6DosageInstruction;
23
+ } | {
24
+ ok: false;
25
+ conflicts: MultilingualDosageConflict[];
26
+ };
27
+ /**
28
+ * Compose independently supplied versions of one dosage course. Locale keys
29
+ * associate the authored SIGs. Use pairedText to also associate independently
30
+ * supplied opaque advice or PRN wording at explicitly aligned native positions.
31
+ */
32
+ export declare function combineMultilingualDosages(inputs: Readonly<Record<string, MultilingualDosageInput>>, options?: CombineMultilingualDosagesOptions): CombineMultilingualDosagesResult;
@@ -10,7 +10,9 @@ export declare function resolveEventTimingExpression(parts: readonly string[], s
10
10
  /** A dose head owns its complete registered event modifiers. Return the
11
11
  * selected nominal end so an adjacent calendar daughter can keep its own role.
12
12
  * Withholding valence can also select the whole-medication noun without an event. */
13
- export declare function medicationDoseSlotNominalEnd(words: readonly string[], options?: ParseOptions, requireEvent?: boolean): number | undefined;
13
+ export declare function medicationDoseSlotNominalEnd(words: readonly string[], options?: ParseOptions, requireEvent?: boolean, selectedEvent?: {
14
+ timing?: EventTiming;
15
+ }): number | undefined;
14
16
  /** Complete source coverage prevents an unrelated food or opaque noun from
15
17
  * borrowing a contained event as proof of a medication target. */
16
18
  export declare function isMedicationDoseSlotNominal(words: readonly string[], options?: ParseOptions): boolean;
@@ -1,6 +1,7 @@
1
1
  import type { CanonicalScheduleInput, CanonicalSupplyOptions } from "../canonical/course";
2
- import type { NextDueDoseOptions, TotalUnitsResult } from "../types";
2
+ import type { DueDose, NextDueDoseOptions, TotalUnitsResult } from "../types";
3
3
  export declare function nextDueDoses(dosage: CanonicalScheduleInput, options: NextDueDoseOptions): string[];
4
+ export declare function nextDueDosesDetailed(dosage: CanonicalScheduleInput, options: NextDueDoseOptions): DueDose[];
4
5
  /** Supply math is deterministic only when the administered amount is known.
5
6
  * Clinical conditions/PRN are represented as a maximum permitted supply,
6
7
  * not as a claim that every available dose will actually be administered. */
@@ -1,10 +1,23 @@
1
1
  import { FhirExtension, FhirPrimitiveElement, FhirR6PrimitiveElement, FhirR6Extension } from "./types";
2
2
  export declare const FHIR_TRANSLATION_EXTENSION_URL = "http://hl7.org/fhir/StructureDefinition/translation";
3
+ export declare const FHIR_LANGUAGE_EXTENSION_URL = "http://hl7.org/fhir/StructureDefinition/language";
3
4
  export declare function cloneI18nRecord(i18n: Record<string, string> | undefined): Record<string, string> | undefined;
4
5
  export declare function mergeI18nRecords(...records: Array<Record<string, string> | undefined>): Record<string, string> | undefined;
5
6
  export declare function cloneExtensions(extensions: FhirR6Extension[] | undefined): FhirExtension[] | undefined;
6
7
  export declare function clonePrimitiveElement(element: FhirR6PrimitiveElement | undefined): FhirPrimitiveElement | undefined;
8
+ /** Write or clear one exact locale on the companion of a FHIR string or markdown primitive. */
9
+ export declare function withPrimitiveTranslation(element: FhirPrimitiveElement | undefined, locale: string, content: string | undefined, type?: "string" | "markdown"): FhirPrimitiveElement | undefined;
10
+ export declare function withPrimitiveTranslation(element: FhirR6PrimitiveElement | undefined, locale: string, content: string | undefined, type?: "string" | "markdown"): FhirR6PrimitiveElement | undefined;
11
+ /** The explicit human language of the primitive's original value. */
12
+ export declare function getPrimitiveLanguage(element: FhirR6PrimitiveElement | undefined): string | undefined;
13
+ /** Annotate the original string or markdown value while retaining its translations. */
14
+ export declare function withPrimitiveLanguage(element: FhirPrimitiveElement | undefined, locale: string): FhirPrimitiveElement;
15
+ export declare function withPrimitiveLanguage(element: FhirR6PrimitiveElement | undefined, locale: string): FhirR6PrimitiveElement;
7
16
  export declare function buildTranslationPrimitiveElement(translations: Record<string, string> | undefined, base?: FhirPrimitiveElement): FhirPrimitiveElement | undefined;
8
17
  export declare function mergeTranslationPrimitiveElement(base: FhirPrimitiveElement | undefined, translations: Record<string, string> | undefined): FhirPrimitiveElement | undefined;
18
+ export declare function getTranslationParts(extension: FhirR6Extension): {
19
+ locale?: string;
20
+ content?: string;
21
+ };
9
22
  export declare function getPrimitiveTranslation(element: FhirR6PrimitiveElement | undefined, locale: string | undefined): string | undefined;
10
23
  export declare function getPrimitiveTranslations(element: FhirR6PrimitiveElement | undefined, fallback?: Record<string, string>): Record<string, string> | undefined;
package/dist/fhir.d.ts CHANGED
@@ -262,7 +262,7 @@ export declare function toFhir(state: ParserState): FhirDosage;
262
262
  /** Decode common coded source annotations for either FHIR version.
263
263
  * No dose, rate, Timing, course, or compatibility marker is interpreted here.
264
264
  * Native-course import supplies an R6 CodeableReference's concept explicitly. */
265
- export declare function deserializeCanonicalContext(dosage: Pick<FhirR6Dosage, "text" | "route" | "method" | "asNeeded" | "asNeededFor" | "additionalInstruction" | "patientInstruction" | "extension"> & {
265
+ export declare function deserializeCanonicalContext(dosage: Pick<FhirR6Dosage, "text" | "route" | "method" | "asNeeded" | "asNeededFor" | "additionalInstruction" | "patientInstruction" | "_patientInstruction" | "extension"> & {
266
266
  site?: FhirR6CodeableConcept;
267
267
  }, options?: ParseOptions): CanonicalSigClause;
268
268
  export declare function canonicalFromFhir(dosage: FhirDosage, options?: ParseOptions): CanonicalSigClause;
package/dist/format.d.ts CHANGED
@@ -5,6 +5,9 @@ import { type InstructionGraphPrimaryCondition } from "./instruction-graph";
5
5
  import { type AdviceFrame, type CanonicalAdditionalInstructionExpr, CanonicalScheduleExpr, CanonicalSigClause, EventTiming, FhirPeriodUnit, type MedicationCondition, type FhirDayOfWeek } from "./types";
6
6
  import { type TimingSummaryOptions } from "./timing-summary";
7
7
  export declare function scheduleOf(clause: CanonicalSigClause): CanonicalScheduleExpr;
8
+ /** The explicit exclusion owns a complete weekday-complement label.
9
+ * Keep the full schedule for cadence and execution; only its list is redundant. */
10
+ export declare function calendarExclusionOwnsWeekdayDisplay(clause: CanonicalSigClause): boolean;
8
11
  /** A method can name a registered manner rather than an action head. */
9
12
  export declare function registeredMethodManner(method: CanonicalSigClause["method"], resolvedMethod?: SigLongContext["resolvedMethod"]): import("./types").AdditionalInstructionDefinition | undefined;
10
13
  export declare function alternateDayEvent(schedule: CanonicalScheduleExpr | undefined): EventTiming | undefined;
@@ -92,7 +95,7 @@ export declare function richGraphAdministrationTail(clause: CanonicalSigClause,
92
95
  export declare function instructionGraphMatchesDose(clause: CanonicalSigClause): boolean;
93
96
  export declare function instructionGraphActionHasSequenceSuccessor(clause: CanonicalSigClause, action: AdviceFrame | undefined): boolean;
94
97
  export declare function hasExplicitAdministrationMethod(clause: CanonicalSigClause): boolean;
95
- export declare function instructionGraphCanStandAlone(clause: CanonicalSigClause, timingText: string | undefined, graphRepresentsDose: boolean, richPrimaryAction: AdviceFrame | undefined, graphText: string | undefined, primaryConditions: InstructionGraphPrimaryCondition[] | undefined): boolean;
98
+ export declare function instructionGraphCanStandAlone(clause: CanonicalSigClause, timingText: string | undefined, richPrimaryAction: AdviceFrame | undefined, graphText: string | undefined, primaryConditions: InstructionGraphPrimaryCondition[] | undefined, preparationSuppliesDose?: boolean): boolean;
96
99
  /** Calendar qualifiers use locale-owned labels and stay on their medication
97
100
  * primary before independent instructions are composed. */
98
101
  export declare function appendClinicalCalendarText(text: string, dates: readonly string[] | undefined, weekdays: readonly FhirDayOfWeek[] | undefined, words: CourseLanguage): string;
@@ -116,6 +116,9 @@ export declare function guardHasMeasurement(value: MedicationCondition): boolean
116
116
  * @param scope Existing clinical scope sign (including otherwise-hold ownership).
117
117
  */
118
118
  export declare function scopeMedicationGuardSign(guard: ParsedMedicationGuard, scope: HpsgSign): HpsgSign;
119
+ /** The same predicate constituent is also the daughter of a procedural
120
+ * advice conditional. It need not license a medication administration guard. */
121
+ export declare function closedInstructionPredicate(source: string, tokens: Token[], start: number, end: number, lexicon: MedicationConditionLexicalFeatures, options?: ParseOptions): Pick<import("./signature").HpsgConditionFeature, "predicate" | "predicateTiming">;
119
122
  /** An opaque consequent can select a closed predicate without exporting a
120
123
  * medication guard or inventing a typed action inside that consequent. */
121
124
  export declare function hasFrontedInstructionCondition(source: string, tokens: Token[], head: Token, end: number, lexicon: MedicationConditionLexicalFeatures): boolean;
@@ -140,6 +140,7 @@ export declare const OCCURRENCE_CAP_PERIOD_PHRASES: {
140
140
  parts: string[];
141
141
  period: number;
142
142
  periodUnit: string;
143
+ unitDenominator: boolean | undefined;
143
144
  }[];
144
145
  export declare const FREQUENCY_SIMPLE_WORDS_DATA: Record<string, number>;
145
146
  export declare const FREQUENCY_NUMBER_WORDS_DATA: Record<string, number>;
@@ -460,6 +461,11 @@ export declare function additiveDoseNumberAt(tokens: readonly LexToken[], start:
460
461
  value: number;
461
462
  numericIndex: number;
462
463
  } | undefined;
464
+ /** The connector and fractional part can also continue a compact range. */
465
+ export declare function additiveDoseContinuationAt(tokens: readonly LexToken[], start: number, limit: number, whole: number, allowMillion: boolean): {
466
+ value: number;
467
+ numericIndex: number;
468
+ } | undefined;
463
469
  /** A million is a numeric multiplier, never a medication unit.
464
470
  * Shared by exact/comparative scalar and dimensional quantities. Source
465
471
  * position advances past a separately spelled multiplier only when present. */
@@ -1,6 +1,6 @@
1
1
  import { type InstructionActionProgram } from "../instruction-action-parser";
2
2
  import { frameActionDefinition } from "../instruction-graph";
3
- import { type AdviceFrame } from "../types";
3
+ import { AdviceRelation, type AdviceFrame } from "../types";
4
4
  import { type HpsgClauseContext } from "./rule-context";
5
5
  type OpaqueSpans = NonNullable<InstructionActionProgram["opaqueSpans"]>;
6
6
  type ProceduralProgram = InstructionActionProgram & {
@@ -33,25 +33,30 @@ export declare function actionArgumentSpan(input: string, frame: AdviceFrame, ar
33
33
  } | undefined;
34
34
  /** Existing action-sequence relation shared by condition closure and lexical ownership. */
35
35
  export declare function instructionActionsAreSequenced(context: HpsgClauseContext, startSource: number, endSource: number): boolean;
36
+ /** A later conditional head begins its own instruction. Repeated heads
37
+ * joined inside a Boolean predicate retain their shared predicate owner. */
38
+ export declare function isIndependentAdviceConditionLead(context: HpsgClauseContext, index: number, predicateEnd: number): boolean;
36
39
  /** An independent typed maximum closes the same conditional source scope
37
40
  * as a hard clause boundary. Incomplete and predicate-owned counts do not. */
38
41
  export declare function hasConditionalAdviceBoundary(context: HpsgClauseContext, start: number, end: number, predicateEnd?: number, prnStart?: number): boolean;
39
42
  /** Compose the consecutive action daughters selected by one fronted condition. */
40
- export declare function proceduralInstructionProgram(context: HpsgClauseContext, firstTargetIndex: number, frames: AdviceFrame[], end?: number): AdviceFrame[];
43
+ export declare function proceduralInstructionProgram(context: HpsgClauseContext, firstTargetIndex: number, frames: AdviceFrame[], end?: number, countedProgram?: boolean): AdviceFrame[];
41
44
  /** A written dose outside an already selected action can supply an omitted
42
45
  * administration head. The quantity rule remains its semantic owner. */
43
46
  export declare function unownedDoseLexicalEnd(context: Pick<HpsgClauseContext, "tokens" | "options"> & {
44
47
  limit?: number;
45
48
  }, frames: readonly AdviceFrame[], start: number, limit?: number): number | undefined;
46
- /** A measured procedure's independently selected cadence licenses exact
47
- * elapsed coverage. Without that proof, retain ordinary primary selection.
48
- * Methods with registered administration runtime keep their timing owner. */
49
+ /** Independent selected cadence licenses administration coverage; other heads retain primary selection. */
49
50
  export declare function localAdministrationDurationSpan(frame: AdviceFrame, definition: ReturnType<typeof frameActionDefinition>, program: InstructionActionProgram): import("../types").TextRange | undefined;
51
+ /** A selected relative clock belongs to its measured Time argument. */
52
+ export declare function procedureOwnsRelativeClock(context: HpsgClauseContext, sourceStart: number, value: string, relation: AdviceRelation): boolean;
50
53
  /** Return the conditional's existing action owner, if it is advice rather
51
54
  * than a newly quantified administration. */
52
55
  export declare function conditionalAdviceProgramAt(context: HpsgClauseContext, index: number): AdviceFrame[] | undefined;
53
56
  export declare function hasSelectedProcedurePrn(context: HpsgClauseContext, index: number): boolean;
54
57
  export declare function conditionalAdviceOwnerAt(context: HpsgClauseContext, index: number): AdviceFrame | undefined;
58
+ /** Range of an explicitly selected counted-advice antecedent. */
59
+ export declare function countedAdviceAntecedentAt(context: HpsgClauseContext, index: number): number | undefined;
55
60
  /** Whether this existing action daughter is governed as conditional advice. */
56
61
  export declare function isConditionalAdviceFrame(context: HpsgClauseContext, frame: AdviceFrame): boolean;
57
62
  /** A complete Activity can be local to a prepared use. A leading
@@ -63,5 +68,5 @@ export declare function followingProcedureOwnsTemporalAdjunct(context: HpsgClaus
63
68
  export type HpsgAttachmentClass = "administration" | "procedure";
64
69
  export declare function sourceRangeAttachmentClass(context: HpsgClauseContext, start: number, end: number, selectedNominal?: boolean, selectedPhaseOnset?: boolean, selectedSchedule?: boolean): HpsgAttachmentClass;
65
70
  /** A temporal linker between two complete action events is not an opaque condition. */
66
- export declare function actionEventRelationAt(context: HpsgClauseContext, index: number): import("../types").AdviceRelation | undefined;
71
+ export declare function actionEventRelationAt(context: HpsgClauseContext, index: number): AdviceRelation | undefined;
67
72
  export {};
@@ -1,11 +1,11 @@
1
1
  import { ParserState, Token } from "../parser-state";
2
- import { EventTiming, FhirDayOfWeek, RouteCode, type CanonicalSigClause, type CanonicalSiteExpr, type CanonicalLexicalCategory, type CanonicalScheduleSemanticField } from "../types";
2
+ import { EventTiming, FhirDayOfWeek, RouteCode, type CanonicalSigClause, type CanonicalSiteExpr, type CanonicalSourceSpan, type CanonicalLexicalCategory, type CanonicalScheduleSemanticField } from "../types";
3
3
  import { HpsgScheduleFeature, HpsgSign } from "./signature";
4
4
  export interface HpsgProjectionDeps {
5
5
  addDayOfWeekList: (state: ParserState, days: FhirDayOfWeek[]) => void;
6
6
  addWhen: (target: EventTiming[], whenCode: EventTiming) => void;
7
7
  markToken: (state: ParserState, token: Token) => void;
8
- recordEvidence: (state: ParserState, rule: string, startIndex: number, endIndex: number, scheduleFields?: CanonicalScheduleSemanticField[], lexicalCategory?: CanonicalLexicalCategory) => void;
8
+ recordEvidence: (state: ParserState, rule: string, startIndex: number, endIndex: number, scheduleFields?: CanonicalScheduleSemanticField[], lexicalCategory?: CanonicalLexicalCategory, coordination?: CanonicalSourceSpan["coordination"]) => void;
9
9
  refreshMethodSurface: (state: ParserState) => void;
10
10
  setRoute: (state: ParserState, code: RouteCode, text?: string) => void;
11
11
  }
@@ -5,7 +5,7 @@ import { type FhirCoding, EventTiming, FhirPeriodUnit, ParseOptions, type Canoni
5
5
  import { type LexToken } from "../lexer/token-types";
6
6
  import type { MedicationDateListMatch } from "../date-interpretation";
7
7
  import { type ParsedMedicationGuard } from "./constructions";
8
- import { MEAL_RELATION_BY_TOKEN } from "./lexical-classes";
8
+ import { ADMINISTRATION_WINDOW_INSTRUCTIONS, MEAL_RELATION_BY_TOKEN } from "./lexical-classes";
9
9
  export { normalizeTokenLower, parseClockToken } from "./lexical-classes";
10
10
  import { HpsgLexicalRule, HpsgSign } from "./signature";
11
11
  import { HpsgProjectionDeps } from "./projection";
@@ -33,6 +33,8 @@ export interface HpsgClauseContext {
33
33
  /** Complete administration schedules already admitted by the lexical chart.
34
34
  * Generic source-tail fallback cannot detach their internal words. */
35
35
  scheduleTokenIndices?: Set<number>;
36
+ /** Exact timing daughters owned by a complete, admitted unguarded schedule. */
37
+ ownedScheduleDaughterStarts?: Set<number>;
36
38
  /** Typed nominal signs requested before generic instruction fallback. */
37
39
  siteLookahead?: Map<number, HpsgSign[]>;
38
40
  medicationGuardScanned?: true;
@@ -72,14 +74,16 @@ export declare function infusionDurationAt(context: HpsgClauseContext, start: nu
72
74
  } | undefined;
73
75
  /** The nearest selected action or clause boundary owns a following complement. */
74
76
  export declare function precedingMedicationInstructionAction(context: HpsgClauseContext, start: number): MedicationInstructionActionDefinition | undefined;
75
- /** The selected action licenses both the current duration and any disambiguating runtime. */
76
- export declare function selectedMethodOwnsAdministrationDuration(context: HpsgClauseContext, start: number, relation: string, definition: MedicationInstructionActionDefinition | undefined): boolean;
77
- export declare function precedingMethodOwnsAdministrationDuration(context: HpsgClauseContext, start: number, relation: string): boolean;
77
+ /** The selected method contributes the exact elapsed daughter it licenses. */
78
+ export declare function selectedMethodDurationAt(context: HpsgClauseContext, start: number, relation: string, definition: MedicationInstructionActionDefinition | undefined, recognized?: ClinicalDurationMatch): ClinicalDurationMatch | undefined;
79
+ export declare function precedingMethodDurationAt(context: HpsgClauseContext, start: number, relation: string, recognized?: ClinicalDurationMatch): ClinicalDurationMatch | undefined;
78
80
  export declare function isClockLikeLower(lower: string): boolean;
79
81
  export declare function isAmPmLower(lower: string): boolean;
80
82
  export declare function isAnteMeridiemLower(lower: string): boolean;
81
83
  export declare function isPostMeridiemLower(lower: string): boolean;
82
84
  export declare function tokensAvailable(context: QuantityLexicalContext, start: number, span: number): Token[] | undefined;
85
+ /** Select the longest eligible stock window before its construction takes the tokens. */
86
+ export declare function administrationWindowTemplateAt(context: QuantityLexicalContext, start: number, use: "instruction" | "activity" | "offset"): typeof ADMINISTRATION_WINDOW_INSTRUCTIONS[number] | undefined;
83
87
  /** Read the longest registered activity noun while retaining original tokens.
84
88
  * @param context Shared clause and caller vocabulary.
85
89
  * @param start First noun token, after any separate nominal modifier.
@@ -160,6 +164,7 @@ export declare function occurrenceCapPeriodAt(context: QuantityLexicalContext, s
160
164
  tokens: Token[];
161
165
  period: number;
162
166
  periodUnit: FhirPeriodUnit;
167
+ unitDenominator?: boolean;
163
168
  } | undefined;
164
169
  type MaximumDosePeriod = ({
165
170
  tokens: Token[];