ezmedicationinput 0.3.0 → 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.
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. */
@@ -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. */
@@ -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;
@@ -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;
@@ -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;
@@ -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;
@@ -33,11 +33,14 @@ 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"> & {
@@ -52,6 +55,8 @@ export declare function localAdministrationDurationSpan(frame: AdviceFrame, defi
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
@@ -1,6 +1,6 @@
1
1
  import { type QuantityLexicalContext } from "../quantity-lexicon";
2
2
  import { Token } from "../../parser-state";
3
- import { type AdviceFrame, AdviceRelation, EventTiming, FhirDayOfWeek, FhirPeriodUnit, type CanonicalCalendarEventExpr, type CanonicalAdditionalInstructionExpr, type FhirQuantity, type ParseOptions } from "../../types";
3
+ import { type AdviceFrame, AdviceRelation, EventTiming, FhirDayOfWeek, FhirPeriodUnit, type CanonicalCalendarEventExpr, type CanonicalAdditionalInstructionExpr, type FhirCoding, type FhirQuantity, type ParseOptions } from "../../types";
4
4
  import { HpsgClauseContext, maximumCountLeadAt, maximumDosePerPeriodAt, maximumDosePeriodAt, clinicalDurationAt } from "../rule-context";
5
5
  import { HpsgLexicalRule, HpsgSign } from "../signature";
6
6
  export { followingCourseDurationHeaderAt } from "../timing-lexicon";
@@ -135,7 +135,7 @@ export declare function semanticActivityWindowAt(context: QuantityLexicalContext
135
135
  length: number;
136
136
  display: string;
137
137
  i18n?: Record<string, string>;
138
- coding?: import("../../types").FhirCoding;
138
+ coding?: FhirCoding;
139
139
  } | undefined;
140
140
  } | undefined;
141
141
  export declare function quantityFirstActivityTimingRule(): HpsgLexicalRule<HpsgClauseContext>;
@@ -234,6 +234,10 @@ export interface CycleSchedule {
234
234
  anchor?: string;
235
235
  events: CanonicalCalendarEventExpr[];
236
236
  error?: string;
237
+ cycleConcept?: FhirCoding;
238
+ startDay?: number;
239
+ maxTreatmentDays?: number;
240
+ dayOneEvent?: FhirCoding;
237
241
  kind?: 'calendar-days' | 'recurring-on-off';
238
242
  onDuration?: FhirQuantity;
239
243
  offDuration?: FhirQuantity;
@@ -245,6 +249,8 @@ export interface CycleSchedule {
245
249
  }
246
250
  /** Recognize finite anchored cycle/day-offset expressions; never guess an absent anchor or cycle length. */
247
251
  export declare function recognizeCycles(input: string, options?: ParseOptions, sourceTokens?: readonly Token[]): CycleSchedule[];
252
+ type CycleClauseContext = Pick<HpsgClauseContext, "state" | "options">;
253
+ export declare function cycleSchedulesForContext(context: CycleClauseContext): readonly CycleSchedule[];
248
254
  /** Finite cycles emit exact events; recurring active/rest cycles emit their
249
255
  * typed active duration and whole-course repeat interval on the same sign. */
250
256
  export declare function cycleScheduleRule(): HpsgLexicalRule<HpsgClauseContext>;
@@ -1,7 +1,7 @@
1
1
  import type { HpsgSigSegment } from "./segmenter";
2
2
  import type { CanonicalEvidence, CanonicalSigClause, CanonicalScheduleExpr, ParseOptions } from "../types";
3
3
  import type { MedicationDateListMatch } from "../date-interpretation";
4
- import { AdviceFrame, AdviceRelation, CanonicalDoseRange, CanonicalClinicalAdjuncts, CanonicalAdditionalInstructionExpr, CanonicalActivityTimingExpr, CanonicalCalendarEventExpr, CanonicalCycleDayConstraint, CanonicalDosePeriodMaximumExpr, CanonicalOccurrenceCapExpr, AdministrationTargetCoordinationKind, CanonicalScheduleSemanticField, CanonicalLexicalCategory, BodySiteRestriction, BodySiteRestrictionPredicate, BodySiteSpatialRelation, EventTiming, FhirCoding, FhirDayOfWeek, FhirPeriodUnit, FhirPrimitiveElement, FhirQuantity, MedicationCondition, RouteCode, PrnReasonLookupRequest, SiteCodeLookupRequest, TextRange } from "../types";
4
+ import { AdviceArgument, CanonicalInstructionCondition, AdviceFrame, AdviceRelation, CanonicalDoseRange, CanonicalClinicalAdjuncts, CanonicalAdditionalInstructionExpr, CanonicalActivityTimingExpr, CanonicalCalendarEventExpr, CanonicalCycleDayConstraint, CanonicalDosePeriodMaximumExpr, CanonicalOccurrenceCapExpr, AdministrationTargetCoordinationKind, CanonicalScheduleSemanticField, CanonicalLexicalCategory, BodySiteRestriction, BodySiteRestrictionPredicate, BodySiteSpatialRelation, EventTiming, FhirCoding, FhirDayOfWeek, FhirPeriodUnit, FhirPrimitiveElement, FhirQuantity, MedicationCondition, RouteCode, PrnReasonLookupRequest, SiteCodeLookupRequest, TextRange } from "../types";
5
5
  import { Token, type ParserState } from "../parser-state";
6
6
  import type { HpsgFeatureNode } from "./type-system";
7
7
  export type HpsgType = "sign" | "word-sign" | "phrase-sign" | "headed-phrase" | "head-complement-phrase" | "head-adjunct-phrase" | "head-marker-phrase" | "procedure-sequence-phrase" | "conditional-instruction-phrase" | "coordination-phrase" | "site-coordination-phrase" | "clause-sign" | "administration-clause" | "method-sign" | "route-sign" | "site-sign" | "site-relative-marker-sign" | "site-predicate-sign" | "site-relative-clause" | "restricted-site-phrase" | "recurring-course-phrase" | "dose-sign" | "schedule-sign" | "prn-sign" | "instruction-sign" | "conditional-sign" | "clinical-adjunct-sign" | "guard-predicate-sign" | "guard-operator-sign" | "guard-marker-sign" | "guard-predicate-phrase" | "guard-coordination-tail" | "guard-negation-phrase" | "medication-guard-phrase" | "adjustment-sign" | "connector-sign";
@@ -26,6 +26,8 @@ export interface HpsgConstruction {
26
26
  }
27
27
  export interface HpsgMethodFeature {
28
28
  verb: string;
29
+ /** An unqualified registered support head admits a more specific method. */
30
+ supportVerb?: true;
29
31
  headClass?: "administration" | "procedure";
30
32
  text?: string;
31
33
  textElement?: FhirPrimitiveElement;
@@ -33,6 +35,7 @@ export interface HpsgMethodFeature {
33
35
  }
34
36
  export interface HpsgRouteFeature {
35
37
  code: RouteCode;
38
+ productFormKey?: string;
36
39
  attachmentClass?: "administration" | "procedure";
37
40
  text?: string;
38
41
  }
@@ -88,6 +91,8 @@ export interface HpsgConditionFeature {
88
91
  relation: AdviceRelation;
89
92
  text: string;
90
93
  fullText: string;
94
+ predicate?: CanonicalInstructionCondition;
95
+ predicateTiming?: AdviceArgument;
91
96
  sourceStart: number;
92
97
  sourceEnd: number;
93
98
  targetStart: number;
@@ -127,6 +132,7 @@ export interface HpsgGuardFeature {
127
132
  expression?: HpsgGuardExpression;
128
133
  operator?: "all" | "any" | "not";
129
134
  marker?: "if" | "only-if" | "unless";
135
+ intervalEligibility?: true;
130
136
  licensesBareIf?: true;
131
137
  }
132
138
  export interface HpsgClinicalAdjunctFeature {
@@ -445,6 +451,8 @@ export interface ProbeSummary extends Range {
445
451
  hasClocks: boolean;
446
452
  hasOffset: boolean;
447
453
  method: boolean;
454
+ methodVerb?: string;
455
+ productFormKey?: string;
448
456
  prn: boolean;
449
457
  clocks: readonly string[];
450
458
  conditionStarts: readonly number[];
package/dist/i18n.d.ts CHANGED
@@ -15,6 +15,7 @@ export interface SigFormatContext {
15
15
  readonly includeTimesPerDaySummary: boolean;
16
16
  readonly realizationMode: "normalized" | "roundtrip";
17
17
  readonly sitePlacement: "natural" | "trailing";
18
+ readonly pairedSiteWording: NonNullable<TimingSummaryOptions["pairedSiteWording"]>;
18
19
  readonly instructionActionMap?: TimingSummaryOptions["instructionActionMap"];
19
20
  readonly resolvedMethod?: MedicationInstructionActionDefinition;
20
21
  formatDefault(style: "short" | "long"): string;