Skip to content

Latest commit

 

History

History
1606 lines (1285 loc) · 70.9 KB

api.md

File metadata and controls

1606 lines (1285 loc) · 70.9 KB

API reference

This guide covers the main runtime API, options, custom functions, DTOs, and common behavior that affects application code.

Entry points

Import Purpose
fhirpath-ts/r4 R4 engine, model, and generated R4 types
fhirpath-ts Engine class, stateless functions, compiler, DTO helpers, and shared types
fhirpath-ts/analyzer Static analyzer APIs
fhirpath-ts/eslint ESLint plugin
fhirpath-ts/sites TypeScript AST expression-site finder
fhirpath-ts/sdc SDC %questionnaire, %qitem, and item contexts
fhirpath-ts/medplum Terminology provider and reference resolver over a Medplum client

Use the bound R4 engine for most application code:

import { r4 } from 'fhirpath-ts/r4'

r4.evaluate('Patient.name.given', patient)
r4.first('Patient.name.family', patient)

Create an engine when the application needs its own defaults:

import { FhirPathEngine } from 'fhirpath-ts'
import { r4Model } from 'fhirpath-ts/r4'

const fp = new FhirPathEngine({
  model: r4Model,
  env: { system: 'http://loinc.org' },
})

Asynchronous services

The free evaluateAsync(expression, input, options) returns a Promise of plain values. compile() also exposes evaluateAsync() and evaluateTypedAsync(); the latter retains FHIR types and element ancestry. Pass the model and context explicitly to these, for example options.model: r4Model. On an engine, r4.evaluateTypedAsync(expression, input, options) uses the engine's model, env, vars, and functions, as evaluateTyped() does, and takes the services per call; the other engine and bound-expression methods are synchronous.

Supply options.terminology, a TerminologyProvider, for memberOf(), subsumes(), subsumedBy(), weight() lookups beyond contained resources (expand for an answer value set, lookup for a CodeSystem), and %terminologies. Its optional async methods are expand, lookup, validateVS, validateCS, subsumes, and translate. They accept plain FHIR JSON and the API's optional URL-encoded parameter string. Return FHIR resources for resource operations and the outcome code for subsumes. Return undefined when the service cannot answer; weight() reports unavailable lookups as errors to prevent partial totals. A supplied empty, plural, or wrongly typed service argument returns empty without calling the provider. Omit the trailing parameter string or pass '' when no additional parameters are needed. Only the asynchronous entry points take terminology and resolver: they belong to AsyncEvaluateOptions, not to EvaluateOptions or engine options. A sync evaluation given either raises an error naming the asynchronous entry points. A function that needs the provider under evaluate(), or without one, raises an error naming evaluateAsync() with options.terminology. A provider without the requested method also raises an error.

For example, a provider that implements validateVS against a FHIR terminology server serves memberOf(). The other methods follow the same pattern with their operations (ValueSet/$expand, CodeSystem/$lookup, and so on):

import { evaluateAsync, type TerminologyProvider } from 'fhirpath-ts'
import { r4Model } from 'fhirpath-ts/r4'

const server = 'https://tx.example.org/fhir'

/**
 * POST a FHIR operation. Servers answer an unknown value set, code system, or
 * concept with 400, 404, or 422: that is `undefined`, an answer the service
 * cannot give. Any other failure, such as rate limiting, stays an error, so it
 * cannot read as "not a member".
 */
async function operation(path: string, parameter: object[]): Promise<unknown> {
  const response = await fetch(`${server}/${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/fhir+json' },
    body: JSON.stringify({ resourceType: 'Parameters', parameter }),
  })
  if ([400, 404, 422].includes(response.status)) return undefined
  if (!response.ok) throw new Error(`Terminology server answered ${response.status}`)
  return response.json()
}

const terminology: TerminologyProvider = {
  validateVS: (valueSet, coded) =>
    operation('ValueSet/$validate-code', [
      typeof valueSet === 'string' ? { name: 'url', valueUri: valueSet } : { name: 'valueSet', resource: valueSet },
      typeof coded === 'string'
        ? { name: 'code', valueCode: coded }
        : 'coding' in (coded as object)
          ? { name: 'codeableConcept', valueCodeableConcept: coded }
          : { name: 'coding', valueCoding: coded },
    ]),
}

const observation = {
  resourceType: 'Observation',
  status: 'final',
  code: { coding: [{ system: 'http://loinc.org', code: '29463-7' }] },
}

await evaluateAsync('Observation.code.coding.where(memberOf(%vitals)).code', observation, {
  model: r4Model,
  terminology,
  env: { vitals: 'http://hl7.org/fhir/ValueSet/observation-vitalsignresult' },
}) // ['29463-7']

The evaluator caches service answers per evaluation and replays the expression when answers arrive. Each distinct request calls its provider once. Requests from independent items (each item of weight(), where(), select(), all(), exists(), and repeat()) and from the two operands of an operator start together, as in fhirpath.js. Only a request that needs an earlier answer waits for another round. The clock stays fixed and only the successful pass emits trace() output. Host functions may run again on replay: keep them deterministic and free of side effects, and keep input and environment values unchanged until evaluation ends. Work before a service call can repeat once per round, so cost grows with the depth of dependent requests and the expression's work. Provider rejections propagate to the caller.

The memberOf() and Boolean subsumption functions return empty for non-singleton inputs. Unknown service outcomes remain empty. For different code systems, subsumes() returns empty and subsumedBy() raises an error when no matching Coding pair establishes the relationship. A configured provider reserves %terminologies; applications must not replace it through env or vars. Static analysis accepts an explicit variable declaration for this host service, while strict runtime evaluation supplies that declaration automatically.

Medplum

fhirpath-ts/medplum has providers over an authenticated MedplumClient, or any object with its fhirUrl(), get(), and post() methods: medplumTerminology(client) posts the six operations as Parameters resources, and medplumResolver(client) reads referenced resources from the client's FHIR base. Only a literal Type/id or Type/id/_history/vid read on that base is sent; a reference to another server, or a search or operation URL, resolves to nothing, because the client sends its credentials with every request. lookup and validateCS send a Coding's version as the version parameter, where Medplum reads it. subsumes sends system, codeA, and codeB, the form Medplum's $subsumes accepts, with the Codings' version as version; Codings naming two different versions fail the call. fhirClient(baseUrl, headers) is the same client shape over plain fetch, for a terminology server without a Medplum session. A failure whose body is an OperationOutcome with only not-found or invalid issues is an answer the server cannot give; any other failure is an error. Medplum also answers a request it cannot parse with invalid, so a malformed request looks like an unknown value set: memberOf(), subsumes(), and translate() return empty, while weight() reports an error.

import { evaluateAsync } from 'fhirpath-ts'
import { medplumResolver, medplumTerminology } from 'fhirpath-ts/medplum'
import { r4Model } from 'fhirpath-ts/r4'

await evaluateAsync('Observation.code.coding.where(memberOf(%vitals)).code', observation, {
  model: r4Model,
  terminology: medplumTerminology(medplum),
  resolver: medplumResolver(medplum),
  env: { vitals: 'http://hl7.org/fhir/ValueSet/observation-vitalsignresult' },
})

weight() asks lookup(coding, 'property=itemWeight'). Medplum's $lookup reports the concept properties that CodeSystem/$import loaded, not the ordinalValue extensions an R4 CodeSystem resource carries on its concepts, so when the answer has no itemWeight property the provider reads every version of the CodeSystem resource, across all search pages, and reports the concept's weight as that property. It selects the version as weight() does for contained CodeSystems, using the Coding's version or else the one $lookup answered with, and a malformed weight or a conflict between versions is an error. A concept found without a weight is empty; a code system or concept the server does not have is an error. The provider reads each system's CodeSystem resources once and keeps them for its lifetime, so a provider sees later edits only when the host creates a new one, for example per request or session; a failed read is not kept and is retried on the next lookup. The engine reads contained CodeSystems before it asks the provider. pnpm record:tx:medplum records the provider against a live Medplum server.

A synchronous evaluation that needs a terminology service throws FhirPathAsyncRequiredError, a FhirPathRuntimeError. An asynchronous evaluation without options.terminology throws a plain FhirPathRuntimeError, since a retry cannot help. A synchronous resolve() of an external reference returns empty rather than throwing.

A host that offers both modes, as fhirpath.js's async: true option does, passes syncWhenPossible: true to evaluateAsync() or evaluateTypedAsync(). The result is then the values themselves when no service answered any part of the evaluation, and a Promise when one did, an external resolve() included. An error of an evaluation that needed no service is thrown, not returned as a rejected Promise. Without a service call, the cost is that of evaluate():

const result = evaluateAsync('Observation.code.coding.where(memberOf(%vitals)).code', observation, {
  model: r4Model,
  terminology,
  syncWhenPossible: true,
  env: { vitals: 'http://hl7.org/fhir/ValueSet/observation-vitalsignresult' },
})
const codes = result instanceof Promise ? await result : result

The return type is a Promise only when the options cannot set syncWhenPossible: an options value typed AsyncEvaluateOptions gives the values or a Promise of them. PromisedAsyncOptions names the options that keep a Promise.

External references

options.resolver is a ReferenceResolver: (reference: string, base: string | undefined) => Promise<unknown>. resolve() first searches the originating resource and available Bundle. Only unresolved external references reach the callback; #fragment misses stay empty. Independent references, such as the items of one resolve() call, are requested together.

The engine passes the reference unchanged. For a relative reference, base is the server base of the resource that holds it, when known: from its Bundle entry fullUrl, or else from the absolute reference that fetched it or the Bundle holding it (or the base that one was resolved against). FHIR resolves a relative reference against that base. A reference in the input with no fullUrl, or a string literal, has no base. The host chooses how to resolve it, including the default server base, credentials, and request policy.

For example, a resolver for one FHIR server. References come from the data, so it sends credentials only to that server and leaves other references unresolved:

import { evaluateAsync, type ReferenceResolver } from 'fhirpath-ts'
import { r4Model } from 'fhirpath-ts/r4'

const server = 'https://fhir.example.org/fhir'

const resolver: ReferenceResolver = async (reference, base) => {
  // A relative reference resolves against the base of the resource holding it.
  const url = new URL(reference, `${base ?? server}/`)
  // References come from the data: send credentials only to the trusted server.
  if (!url.href.startsWith(`${server}/`)) return undefined
  const response = await fetch(url, {
    headers: { Accept: 'application/fhir+json', Authorization: `Bearer ${process.env.FHIR_ACCESS_TOKEN}` },
  })
  if (response.status === 404 || response.status === 410) return undefined
  if (!response.ok) throw new Error(`FHIR server answered ${response.status}`)
  return response.json()
}

const observation = {
  resourceType: 'Observation',
  status: 'final',
  code: { text: 'Body weight' },
  subject: { reference: 'Patient/123' },
}

await evaluateAsync('Observation.subject.resolve().name.given', observation, { model: r4Model, resolver }) // ['Ana']

Return a FHIR resource as plain JSON, or undefined if it cannot be resolved. Answers without a string resourceType are ignored. Provider rejections propagate. Each reference and base pair is requested once per asynchronous evaluation. A returned resource becomes the owner for subsequent navigation, so its contained references resolve locally and its other references go to the resolver, never to the input Bundle. The same options and cache remain available for further external hops.

Without a resolver, external misses remain empty, including under the synchronous evaluate(), which refuses one; local resolution works there as usual.

Strict evaluation

Evaluation is lenient by default: invalid model members navigate to an empty collection. Set strict: true on an engine to run the analyzer before every evaluation and throw FhirPathTypeError when it reports an error:

const strict = new FhirPathEngine({ model: r4Model, strict: true })

strict.evaluate('Patient.name.givenn', patient)
// FhirPathTypeError: Strict evaluation failed:
// - [unknown-element] Element 'givenn' is not defined on FHIR.HumanName ...

strict is also an EvaluateOptions field, so one call can enable or disable it:

r4.evaluate('Patient.name.givenn', patient, { strict: true })
strict.evaluate('Patient.name.givenn', patient, { strict: false }) // []

Strict evaluation rejects every error-severity analyzer diagnostic. Warnings, including regex-backtracking, do not stop evaluation. It checks vars and expression-defined custom functions with the same model, functions, and environment declarations as the evaluator. The analysis starts at the input's resource type, or at the type a compiled expression declares, which also types input without a resourceType. FHIR member checks require a model; values whose resource type is unknown to that model remain opaque.

Runtime contracts still apply in lenient mode. Unknown functions and variables, wrong function arguments, invalid type names, and invalid cardinality are evaluation errors required by FHIRPath; strict does not control them. See What throws errors and what doesn't? for the full boundary.

Engine methods

evaluate()

Evaluates an expression and returns every result as plain JavaScript values. Literal expressions infer their result and input types.

r4.evaluate('Patient.name.given', patient) // string[]

A FHIR primitive with only an id or extensions, such as a masked _birthDate without birthDate, has no plain value and gives no item. The element still exists in the expression: birthDate.count() is 1, birthDate.hasValue() is false, and birthDate.extension reads its extensions. evaluateTyped() returns the element itself, with an undefined value.

first()

Returns the first result, or undefined for an empty collection.

r4.first('Patient.name.family', patient) // string | undefined

Use this when application code expects one optional value. Use single() in the FHIRPath expression when more than one value should be an error.

test()

Applies the boolean rules used by FHIR criteria. One boolean returns itself. An empty result is false. More than one value is an error. The input is typed as for evaluate().

r4.test(patient, 'active = true') // boolean

filter()

Keeps resources for which test() returns true, testing each item of an array or each entry of a Bundle on its own. Each array item is typed as one evaluate() input, and the result keeps the item type. A Bundle returns unknown[]; TypeScript checks its entries only against a compiled expression's declared type.

r4.filter(patients, 'birthDate < @1990-01-01') // Patient[]

checkConstraints()

Checks expressions shaped like ElementDefinition.constraint values:

const result = r4.checkConstraints(patient, [
  {
    key: 'pat-1',
    severity: 'error',
    human: 'Contact needs a name or telecom',
    expression: 'contact.all(name.exists() or telecom.exists())',
  },
])

result.valid
result.issues
result.toOperationOutcome()

valid is false only when an error-severity constraint fails. Issues retain the constraint data. toOperationOutcome() creates a FHIR report with issue.code = 'invariant'.

This method checks constraint expressions. It does not validate profile cardinality, terminology bindings, slicing, or the rest of a StructureDefinition.

Arrays and Bundles are checked one resource at a time. Issues include the input index. Bundle issues point to Bundle.entry[i].resource. Wrap a Bundle in an array to check the Bundle itself.

project()

Projects each input resource into either a plain object or a DTO instance. Plain column records support these shapes:

const rows = r4.project(patients, {
  id: 'Patient.id',
  family: 'Patient.name.family.first()',
  given: { path: 'Patient.name.given', collection: true },
  born: { path: 'Patient.birthDate', as: 'Date' },
  gender: { path: 'Patient.gender', default: 'unknown' },
  active: { test: 'Patient.active = true' },
})

A scalar column must return zero or one value. More than one value is an error. Set collection: true for an array. Other options are:

Option Meaning
path FHIRPath expression for a value column
test FHIRPath expression with test() semantics
type Compile-time result declaration when inference cannot read the expression
as Convert each value to a named JavaScript type or with a function
default Value used for an empty result; also removes undefined from the type
enum Allowed literal values; a different value becomes empty
choices Code-to-value table or record
pick Field to return from a choices table row
collection Return all results instead of one scalar
required DTO columns only: the input must carry this path; see Required columns

type is a TypeScript declaration. The runtime does not validate it. Use the analyzer or a DTO check when an expression falls outside TypeScript's inference subset.

Each row evaluates with %rowIndex and %rowTotal. Indexes are zero-based. A single resource gets index 0 and total 1.

Row errors

By default, the first row that fails throws its error unchanged and no rows are returned. For an array or a Bundle, onRowError decides per row instead. It receives a ProjectionRowError and returns 'skip' to drop the row and go on, or 'stop' to throw that error:

const failures: ProjectionRowError[] = []
const rows = r4.project(patients, columns, {
  onRowError: error => {
    failures.push(error)
    return 'skip'
  },
})
Field Meaning
index The row's %rowIndex; for a Bundle, its position among entries that have a resource
total The batch's %rowTotal, skipped rows included
column The column being read, or undefined when the row failed first, as with a wrong resourceType or a vars error
cause The error the default path would throw, unchanged
subject The input resource

The error's message names only the row and column. subject is not enumerable, so logging or serializing the error leaves the resource out; the engine never logs or keeps it. Errors that do not depend on a row, such as a column that does not compile, still throw before any row is read. DTO from() takes the same option.

project() creates application data. Structure-to-structure transformation is the job of StructureMap and the FHIR Mapping Language.

defineDto(), defineView(), and register()

engine.defineView(fhirType) and engine.defineDto(fhirType) return base classes for projected rows, and engine.register(...dtos) returns a new engine with DTO columns as FHIRPath functions. See DTOs.

compile()

Parses once and returns a reusable expression:

const given = r4.compile('Patient.name.given')
given.evaluate(patient)

An optional second argument declares the input type for a relative expression:

const visible = r4.compile("(status in ('entered-in-error' | 'draft')).not()", 'MedicationRequest')

The result is inferred against the declared type, even when the input's static type names no resource, such as parsed JSON. The input must be that type or an array of it; for a root other than a resource, typed values of it (see Type name or declared root). Static checkers and strict evaluation analyze the expression against the declared type.

Engine methods type any compiled expression that declares its type, whether it comes from compile(expression, type), fhirpath(expression, type), new CompiledExpression(expression, type), or the expression of r4.compile(expression, type). evaluate(), first(), test(), and evaluateTyped() take that type or an array of it, and filter() an array of it or a Bundle whose entries are that type. r4.evaluate() and r4.first() infer the result against the declared type:

const status = compile('clinicalStatus.coding.first().code', 'Condition')
r4.evaluate(status, condition) // string[]
r4.evaluate(status, patient) // compile error: a Patient is not a Condition

Type name or declared root

A type name at the start of the path is part of the expression, and evaluation tests it against the data: it matches a resource of that type or a subtype, and any other value gives an empty result. A declared root types the input for TypeScript, the static checkers, and strict evaluation; evaluation doesn't test it. The two differ when the data is not what its static type says, such as parsed JSON:

const named = r4.compile('Patient.name.family')
const declared = r4.compile('name.family', 'Patient')
const practitioner = JSON.parse(text) // a Practitioner

named.evaluate(practitioner) // []
declared.evaluate(practitioner) // the Practitioner's family names
named.evaluate(practitioner, { strict: true }) // throws: Element 'Patient' is not defined on FHIR.Practitioner

Declare the root when the path can't start with a type name: a datatype root, since a type name at the root matches only a resource; data without a resourceType; or an expression written relative to its resource or datatype, such as a FHIR constraint.

A root other than a resource takes typed input only, in TypeScript and, on an engine with a model, at runtime: JSON has no owning resource, while the static types read %resource from the root's path. Type the value with toTyped(), inside its resource when it has one, so choice elements such as an extension's value resolve:

r4.compile('given', 'HumanName').evaluate(r4.toTyped(name, 'HumanName')) // ['Peter', 'James']
// nickname is { url: 'http://example.org/nickname', valueString: 'Pete' }, also in patient.extension
r4.compile("extension('http://example.org/nickname').value", 'Patient').evaluate(patient) // ['Pete']
r4.compile('value', 'Extension').evaluate(r4.toTyped(nickname, 'Extension', { in: patient })) // ['Pete']

A declared root checks typed input, which states its type: a value of another type throws. So does a contained resource under a resource root, because its %rootResource is its container while the static types read %rootResource as the root. JSON under a resource root is not checked.

evaluateTyped()

Returns internal TypedValue[] values instead of unwrapped JavaScript values. Each item includes its FHIRPath type. Decimal, Quantity, date, time, and dateTime values keep their internal exact representations. The input is typed as for evaluate(). Each item also keeps its ancestry: where it was read, up to the resource. The results can be the input of a later call; see Element contexts.

Element contexts

evaluate(), first(), test(), evaluateTyped(), their async forms, and compiled expressions take typed values as input. The expression then runs at those elements:

const [group] = r4.evaluateTyped("QuestionnaireResponse.item.where(linkId = 'meds')", response)
r4.evaluate('item.answer.value', [group]) // choice elements and `_field` metadata resolve
r4.evaluate('%resource.status', [group]) // the QuestionnaireResponse

JSON input loses this: evaluate() results are plain values with no type or ancestry, and a raw QuestionnaireResponse.item object reads as an untyped object, so answer.value is empty. Keep evaluateTyped() results when the next expression runs at them.

With typed input:

  • $this and %context are the input items.
  • %resource is their owning resource: the nearest resource in their ancestry. Inside a Bundle that is the entry's resource, not the Bundle.
  • %rootResource is the container of a contained owning resource, and otherwise %resource.
  • resolve(), weight(), and pathname() read the same ancestry.
  • Items with different owning resources, or typed values mixed with JSON, throw. Evaluate them one at a time.
  • An env value for resource, rootResource, or context still overrides the derived one, and may be typed (see %context apart from the input).

JSON input is its own %resource and %rootResource, as before.

toTyped() types a JSON value the host found itself. With { in: resource } it finds the value inside that resource by object identity, so the value keeps its ancestry. It throws when the value is not of the given type, is not in the resource, appears there more than once, or is a primitive:

const item = response.item[0] // JSON
r4.evaluate('answer.value', r4.toTyped(item, 'QuestionnaireResponse.item', { in: response }))

Without in, the value is unattached: it is typed, so choice elements resolve, but it has no owning resource. Reading %resource or %rootResource then throws, unless env sets them, and pathname() paths start at the value.

At the type level, typed input has no known root, so a relative expression infers unknown[]. Declare the root to type it; a declared root also checks the input's types at runtime (see Type name or declared root):

const answers = r4.compile('answer.value', 'QuestionnaireResponse.item')
answers.evaluate(items)

For a backbone root such as QuestionnaireResponse.item, %resource is typed as the resource its path starts with, and %rootResource is untyped, since a contained resource's container can be any resource. A datatype root types neither.

filter(), project(), checkConstraints(), and DTO from() take JSON only.

%context apart from the input

env binds typed values as they are, so they keep their types and ancestry. An env value for context makes %context that element, while $this and relative paths start at the input. SDC template extraction needs this: an expression runs on each result of a templateExtractContext, while %context stays the QuestionnaireResponse item being extracted. fhirpath.js takes context from its environment variables the same way.

%resource and %rootResource still come from the input. Set them in env too when the input is not inside the resource, such as the Bundle a search returned or a copy of an item:

const root = r4.toTyped(response, 'QuestionnaireResponse')
const [meds] = r4.evaluateTyped("item.where(linkId = 'meds')", root)
const names = r4.evaluateTyped('item', meds)
r4.evaluate('answer.value | %context.linkId', names, { env: { context: meds } }) // ['Aspirin', 'meds']
r4.evaluate('entry.resource.id | %resource.status', searchset, {
  env: { context: meds, resource: root, rootResource: root },
}) // ['m1', 'completed']

A typed env value is recognized as typed values given as the input are, never by its shape, and an array that mixes typed values and JSON throws. The analyzer takes the same env and types %context from it (see Public analyzer).

Structured Data Capture

fhirpath-ts/sdc gives the variables SDC defines for expressions in a Questionnaire. sdcScope(engine, questionnaire) reads the Questionnaire's items once. Its contexts(response) walks a QuestionnaireResponse in SDC evaluation order: the response, then each item instance depth-first, including items under answers. Each context comes with %questionnaire and, inside an item, %qitem, the Questionnaire item with the same linkId:

import { sdcScope } from 'fhirpath-ts/sdc'

const scope = sdcScope(r4, questionnaire)
for (const { context, vars } of scope.contexts(response)) {
  r4.evaluate(calculatedExpression, context, { vars: { ...vars, ...namedVariables } })
}

scope.vars(context) gives the same variables for one context, such as each result of a templateExtractContext expression:

for (const medication of r4.evaluateTyped("item.where(linkId = 'meds')", root)) {
  const context = [medication]
  r4.first("item.where(linkId = 'name').answer.value", context, { vars: scope.vars(context) })
}

Both throw when a response item's linkId is not in the Questionnaire. Named variable extensions and launch contexts are the host's: evaluate them and pass the results through vars.

toFhirJson() and jsonElement()

toFhirJson(value, type) turns a typed value into the FHIR JSON of an element of type type, the reverse of toTyped(). SDC template extraction and $populate write expression results into resources this way:

const [authored] = r4.evaluateTyped('authored', response)
r4.toFhirJson(authored, 'dateTime') // '2025-09-16T12:34:56.000-07:00'
const [dose] = r4.evaluateTyped("5.5 'mg'")
r4.toFhirJson(dose, 'Quantity') // { value: 5.5, unit: 'mg', system: 'http://unitsofmeasure.org', code: 'mg' }

The value must fit the element:

  • A string fills a string-like or temporal element when it has that type's format, from ModelProvider.valuePattern(). A date also has to exist in the calendar, so '2023-02-29' is refused, and a date-time with a time needs a timezone.
  • A date, date-time, or time fills date, dateTime, instant, time, string, or markdown under the same format rules.
  • A boolean fills only boolean.
  • A number fills decimal, or integer, unsignedInt, or positiveInt when it is a whole number in that type's range. A Decimal becomes a JS number, so it loses the zeros of its scale.
  • A FHIRPath Quantity fills Quantity and its profiles (Age, Duration, and so on) as a UCUM Quantity; a calendar duration takes its UCUM code, a for year.
  • A FHIR value fills its own type or a supertype. It is copied, so the result shares nothing with the data.

A value that does not fit throws a FhirPathTypeError naming the types, never the value. A primitive's id and extensions are not carried; write its _name sibling from the data if it needs them.

evaluate() unwraps results without a target type: a Decimal becomes a number and a date-time its text with no check, and a Quantity becomes { value, unit } with no UCUM code. Use evaluate() to read results and toFhirJson() to write them into a resource.

jsonElement(type, key) finds the element a JSON property is, so a host walking FHIR JSON knows the type to convert to. A choice element's key carries its type: r4.jsonElement('Observation', 'effectiveDateTime') is { key: 'effectiveDateTime', type: 'dateTime', isCollection: false, isPrimitive: true }. It is undefined for a key the type does not have, including a choice element's stem alone. An element the R4 model types as a System type, such as Resource.id, has its FHIR primitive type, string.

x-fhir-query

An x-fhir-query is a FHIR search string with FHIRPath expressions between {{ and }}. Each embedded expression is evaluated and its results are put into the string before the search runs. SDC uses it for extraction contexts, $populate, answer and candidate expressions, and launch contexts. evaluateXFhirQuery() evaluates each embedded expression on the input with the engine's options:

r4.evaluateXFhirQuery('Observation?subject.identifier={{identifier}}&date=ge{{%since}}', patient, {
  env: { since: '2024-01-01' },
}) // 'Observation?subject.identifier=http://example.org/mrn|mrn-1&date=ge2024-01-01'

compileXFhirQuery(query) parses the query once. Its evaluate(input, options) and evaluateAsync(input, options) do the same as evaluateXFhirQuery(), the async form with terminology and reference services; the options need a model, as for a compiled expression. When several embedded expressions fail, the error is the first one's in query order. A host that evaluates each embedded expression itself, with its own focus, analysis, and error reporting, reads expressions and gives substitute() the typed results of each, in order:

import { compileXFhirQuery } from 'fhirpath-ts'

const query = compileXFhirQuery('Observation?subject={{%resource.subject.reference}}&code={{code}}')
const results = query.expressions.map(expression => expression.evaluateTyped(focus, { model: r4Model }))
query.substitute(results)

Each result becomes its search form:

Result Search form
String, number, Boolean, date, date-time, or time Its text
Coding system|code, or the code alone without a system
Identifier system|value, or the value alone without a system
CodeableConcept One Coding form per coding
Reference Its reference
canonical Its text, with |version kept as the version separator
Quantity and its profiles (Age, Duration, ...) value|system|code, with the unit when there is no code
FHIRPath Quantity value|http://unitsofmeasure.org|code, a calendar duration with its UCUM code (a for year)

Several results become a comma-separated list, as the x-fhir-query rules say, and no result an empty value; a primitive with only extensions gives nothing. Inside each value, a \ goes before \, $, ,, and |, the FHIR search escaping, so a server reads them as data rather than as separators: an Identifier value a,b stays one value, not a or b. Then each value is percent-encoded except |, :, and /, so & and # cannot change the query either. Any other type has no search form: substitute() throws a FhirPathTypeError that names the type, such as A FHIR.HumanName value cannot be put in an x-fhir-query, and never writes the value. A query that is not valid FHIRPath throws a FhirPathSyntaxError that counts the embedded expressions from 1: Embedded expression 2 of the x-fhir-query is not valid FHIRPath: .... Its cause is the expression's own syntax error, with the position in that expression. Expressions hold no braces, so {{ {a} }} is not one.

Stateless API

The package root also exports stateless forms:

import { compile, evaluate, fhirpath } from 'fhirpath-ts'
import { r4Model } from 'fhirpath-ts/r4'

evaluate('Patient.name.given', patient, { model: r4Model }) // unknown[]
compile('Patient.name.given').evaluate(patient, { model: r4Model }) // string[]
fhirpath('Patient.name.given').evaluate(patient, { model: r4Model }) // string[]
fhirpath`Patient.name.given`.evaluate(patient, { model: r4Model }) // unknown[]

Tagged templates remain untyped because TypeScript does not preserve their literal types. The call form and compile() do preserve them. Without a model, the stateless evaluator navigates plain JSON.

Options

Engine construction and evaluation calls share most options. Per-call values replace engine defaults, except env, vars, and functions, which merge by name.

Option Meaning
model A ModelProvider; use r4Model for FHIR R4
env Plain host values available as %name
envTypes Explicit types or refinements for env values
vars FHIRPath bindings evaluated against the input
varTypes Static declarations or explicit overrides for vars
now Clock for now(), today(), and timeOfDay()
trace Sink for trace() calls
functions Host or expression-defined functions
regex Regular expression implementation
narrativeSanitizer HTML sanitizer htmlChecks() also requires to accept a narrative; see Narrative checking
cacheSize Engine parse-cache capacity; construction only
type Compile-time result declaration for evaluate() or first(); per-call only

Use type when an expression is outside TypeScript's inference subset. It does not perform a runtime check and cannot be set as an engine default.

Fresh literal option objects reject unknown keys, so a misspelling such as envTypez fails at the call site. Reusable application options may extend EvaluateOptions or EngineOptions, and index-signature records remain assignable. These widened shapes opt out of exact-key checking and no longer retain literal declarations for result inference.

A literal that spreads a value already typed as EvaluateOptions is also widened, so the call cannot distinguish its explicit keys from a reusable extension. Validate a composed object where it is built to catch an adjacent typo:

const options = {
  ...baseOptions,
  envTypez: { report: { type: 'DiagnosticReport' } },
} satisfies EvaluateOptions // error: envTypez is not an option

Use satisfies EngineOptions instead for constructor-only fields. The exported Declaring<Options, Accepted> type is the parameter shape used by generic engine calls when a wrapper needs the same literal checks and widening rules.

Type context declarations

Literal expressions infer primitive, resource, collection, and structural types from env. Literal vars expressions can carry those types through property navigation. Use envTypes or varTypes when a value is widened, ambiguous, or needs an explicit override. Declarations do not create or validate values.

import type { EvaluateOptions } from 'fhirpath-ts'

const options = {
  env: { report },
} as const satisfies EvaluateOptions

const statuses = r4.evaluate('%report.status', undefined, options) // string[]

Each FhirpathTypeDeclaration has these fields:

Field Meaning
type One R4/FHIRPath type name, or an array of possible type names
collection Omit for at most one item; set true when many items are possible
targets Resource targets for a declared Reference, used by resolve()

Use as const satisfies EvaluateOptions when options are stored in a variable. It checks the shape without widening the type-name literals. A literal env value beside its declaration is also checked for compatible type and singleton cardinality. Use declarations for pre-resolved vars, Reference targets, or data whose TypeScript type is too broad. Explicit declarations take precedence.

FhirpathTypeContext is the declaration-only form used by FhirpathResult and FhirpathResultIn. Its fields are named env, vars, and functions. Engine and per-call options infer from values and accept envTypes and varTypes as overrides. Names may include or omit their leading %.

Engine defaults and per-call declarations merge by normalized name, with the per-call declaration winning. A BoundExpression returned by engine.compile() keeps the engine declarations. A plain CompiledExpression uses declarations supplied when it is evaluated. An explicit column or call type remains the escape hatch for an opaque expression.

Inference type exports

These package-root types support wrappers and compile-time assertions. Most applications only need FhirpathResult, FhirpathResultIn, and the declaration types.

Type Purpose
FhirpathResult<Expr, Context> Infer a literal expression without an input root
FhirpathResultIn<Expr, Input, Context> Infer a literal expression against a named input type
FhirpathTypeDeclaration / FhirpathTypeDeclarations Declare host value types, collection shape, and Reference targets
FhirpathTypeContext / FhirpathFunctionDeclaration Describe standalone env, var, and function declarations
EmptyFhirpathTypeContext / EmptyContextMap Importable empty defaults used by context-aware generic wrappers and diagnostics
CompiledExpressionResult / InferredExpressionResult Select and compute a compiled expression's inferred result
EngineExpression / EngineInputRoot Describe accepted engine expressions and normalized input roots
EngineResult Compute the inferred result of an engine or bound-expression call
EngineProjectionContext / EngineProjection Compute projection declarations and row results
Declaring<Options, Accepted> Preserve literal option inference with fresh-literal key checks

env and vars

Both accept keys with or without %. Both merge by name between engine defaults and call options. They hold different kinds of values:

  • env contains plain JavaScript data such as URLs, lookup tables, and request parameters.
  • vars contains FHIRPath expressions evaluated against the call input. Their results keep FHIRPath type information.
fp.evaluate('%threshold + 1', patient, { env: { threshold: 5 } })

fp.project(observations, columns, {
  vars: { weight: 'value.ofType(Quantity)' },
})

Variables are evaluated in declaration order, so a later variable may use an earlier one. A variable cannot replace an environment value. Neither vars nor defineVariable() can take a name in RESERVED_VARIABLE_NAMES: context, resource, rootResource, ucum, sct, loinc, and terminologies, the last even without a terminology provider.

env also takes typed values, such as evaluateTyped() results, which keep their types and ancestry; see %context apart from the input.

TypeScript does not retain object-property declaration order. Type inference can use env, the input, and explicit declarations while reading a literal variable body, but it does not assume that another expression variable ran first. Use varTypes for that dependency. Runtime evaluation and the analyzer still honor declaration order.

During projection, variables are evaluated once per row. %context, %rowIndex, and %rowTotal are in scope. Every column reads the same bindings.

Fixed clocks

Pass now when tests or application logic need repeatable answers:

r4.test(patient, 'birthDate <= today()', {
  now: new Date('2026-08-04T12:00:00Z'),
})

Tracing

trace() calls the provided sink. It does not log by default:

fp.evaluate("name.trace('names').given", patient, {
  trace: (name, values) => debugSink(name, values),
})

Traced values may contain PHI. Keep them out of production logs. To log where values are without the values, trace their paths: trace('missing', pathname()).

Element paths

pathname() returns the path of each input item inside %rootResource, written with element names and indexers, such as Observation.component[0].code[0].coding[0]. Every element gets an indexer. pathname(true) leaves the indexer out when an element is not an array in the data or in the model: Observation.component[0].code.coding[0].

  • Only items read by navigation from this evaluation's input have a path. Computed values (upper(), &, arithmetic), values from env, and evaluateTyped() items of another evaluation passed through vars are left out of the result.
  • A resource reached with resolve() has a path when it is a contained resource or a Bundle entry of the input, such as Patient.contained[1], Bundle.entry[3].resource[0], or Bundle.entry[3].resource[0].contained[1].
  • When the input has no resourceType, paths start at its elements, such as given[0], and the input itself has no path.
  • For typed input, paths start at the derived %rootResource, so a typed item of a Bundle entry gives QuestionnaireResponse.item[0]. An env override of %rootResource doesn't change where paths start. Paths of unattached input start at the input.
  • With a model, a choice element uses its FHIRPath name (value). Without one, it uses the JSON key (valueQuantity).

Custom functions

A custom function record defines runtime behavior and, optionally, its analyzer signature:

import type { CustomFunction } from 'fhirpath-ts'

const functions = {
  initials: {
    minArity: 0,
    maxArity: 0,
    signature: {
      input: { kind: 'String' },
      result: { types: ['System.String'], single: false, ordered: true },
    },
    fn: (input: unknown[]) => input.map(value => String(value).charAt(0)),
  },
} satisfies Record<string, CustomFunction>

Arguments are evaluated before fn is called. Plain JavaScript values cross the function boundary, as in evaluate(), so a primitive with only extensions is not in input. Built-in names cannot be replaced.

The native signature's result supplies both analyzer and TypeScript inference. Set the result's ordered when a collection result has a defined or undefined order; omit it when ordering is unknown. Set input: { ordered: true } when the function needs a defined input order, like the built-in first() and skip(); the analyzer then rejects calls on a collection known to be unordered. Without a result signature, the result is unknown and checking resumes after a later as() or ofType() narrows it.

Expression-defined functions

Use expression instead of fn for a zero-argument function written in FHIRPath. It accepts a string or a compiled expression. Compiling with an input type lets static checking validate the relative path:

import { compile, type CustomFunction } from 'fhirpath-ts'

const functions = {
  displayText: {
    expression: compile('(text | coding.display.first() | coding.first().code).first()', 'CodeableConcept'),
    signature: {
      input: { types: ['CodeableConcept'] },
    },
  },
} satisfies Record<string, CustomFunction>

The body receives the call focus. %context and environment values remain the caller's. Results keep FHIRPath type information. Direct or indirect recursion is an error. A literal body supplies its result type to callers. Add a signature result for a widened body, or use the manual call type escape hatch when the function is intentionally opaque. Function-local env values infer the same way as engine values; add envTypes only when they need refinement.

Set criteria: true when the function should always return one boolean using the same rules as test():

import { compile, type CustomFunction } from 'fhirpath-ts'

const functions = {
  isFinal: {
    expression: compile("status = 'final'", 'Observation'),
    criteria: true,
  },
} satisfies Record<string, CustomFunction>

signature.input.types limits the focus types that may call a function. The runtime and analyzer report a mismatch only when the model can prove that no input type fits. Empty or unknown focus types remain allowed.

An overloaded function carries the declarations of each overload. A statically known focus selects the first compatible declaration, matching runtime dispatch. If the focus cannot distinguish the overloads safely, TypeScript keeps the result opaque.

DTOs

DTOs and views are classes defined on an engine. Each field initialized with this.column() or this.criteria() is a projection column, and its type is inferred from the expression:

import { r4 } from 'fhirpath-ts/r4'

class WeightRow extends r4.defineView('Observation') {
  lbs = this.column("value.ofType(Quantity).toQuantity('[lb_av]').value", { default: 0 }) // number
  at = this.column('(effective.ofType(dateTime) | issued).first()', { as: 'Date' }) // Date | undefined
  notes = this.column('note.text', { collection: true }) // string[]
  final = this.criteria("status = 'final'") // boolean

  get rounded(): number {
    return Math.round(this.lbs)
  }
}

const rows = WeightRow.from(observations) // WeightRow[]

Dto.from(input, options?) projects on the engine the class was defined on; engine.project(input, Dto, options?) does the same on that engine or one derived from it. Both accept one resource, an array, or a Bundle, and return one row per resource. See Inputs for what the input type demands.

There are two kinds:

  • engine.defineDto(fhirType, options?) defines a DTO whose columns become FHIRPath functions once it is registered. It holds only columns and methods.
  • engine.defineView(fhirType, options?) defines a projected row. A view may also hold getters and plain fields, and its columns may convert values with as or choices.

this.column() accepts the same options as a plain project column. Rows are class instances, so derived values can be getters or methods. Plain fields of a view keep their ordinary JavaScript behavior and are not projected.

A field may also declare its type. TypeScript then checks that the declared type can hold the column value:

class ReportRow extends r4.defineView('DiagnosticReport') {
  issued: string | undefined = this.column('issued')
}

When TypeScript cannot infer an expression, the field type is unknown. combine(), caller values without a declared type, and calls to a column of the same class are the common cases. TypeScript cannot type a call to a column of the class being defined, because a field's type cannot depend on its own class. Set the column type option to give the field a type. analyzeDto() checks that option when it can infer the expression result; otherwise the option is an unchecked assertion.

Write each column as the whole initializer of a public instance field. Projection reads columns by constructing the class once, and it reports a column in a private field, a static field, or a nested value.

Registering DTOs

engine.register(...dtos) returns a new engine on which every column of those DTOs is a FHIRPath function. The engine it is called on does not change.

class CodeableConceptDto extends r4.defineDto('CodeableConcept') {
  displayText = this.column('(text | coding.display.first() | coding.first().code).first()')
}

const fp = r4.register(CodeableConceptDto)

fp.first('Condition.code.displayText()', condition) // string | undefined

Registration publishes every column under its field name. Each function accepts the DTO's fhirType. A model is required so the engine can reject calls on an incompatible focus.

The new engine's type includes the registered functions, so calls to them are typed in engine calls and in the columns of DTOs and views defined on it. A TypeScript string column may hold any FHIR type represented as a string, so its call result is the union of those types; ofType(code) keeps the value. A column whose value no FHIR type represents, such as a lookup-table row, keeps an unknown[] call result.

A registered column is also a function that returns its expression's own result, without default or other projection options. register() therefore accepts only DTOs from defineDto() on that engine or an engine it derives from. It rejects views, getters, and plain fields, because the engine's types read every non-method field of a registered DTO as a column.

Names are scoped by input type. A CodeableConcept DTO and a Coding DTO may both declare displayText. The call focus selects the matching declaration.

Registration fails when two declarations with the same name cannot be distinguished. This includes two DTOs on the same FHIR type, overlapping input types such as Quantity and SimpleQuantity, and a DTO name already accepted by a host function. Built-in names are always reserved.

Several DTOs may target the same FHIR type when their field names are different. When one registered DTO calls another's column, define it on the engine that already registers the callee:

const withConcepts = r4.register(CodeableConceptDto)

class MedicationRequestDto extends withConcepts.defineDto('MedicationRequest') {
  medicationName = this.column('medication.ofType(CodeableConcept).displayText()') // string | undefined
}

export const fp = withConcepts.register(MedicationRequestDto)

Engines and file layout

Build every registered DTO in one *.dto.ts module: define the DTOs, register them, and export the final engine. Views may live anywhere in the codebase. Each view module imports that engine and extends engine.defineView(...):

// patient-portal.dto.ts
export class CodeableConceptDto extends r4.defineDto('CodeableConcept') {
  displayText = this.column('(text | coding.display.first() | coding.first().code).first()')
}
export const fp = r4.register(CodeableConceptDto)
// problems/problem-row.ts
import { fp } from '../patient-portal.dto'

export class ProblemRow extends fp.defineView('Condition') {
  name = this.column('code.displayText()', { default: 'Condition' }) // string
}

A custom engine works the same way as r4: build it with new FhirPathEngine(options), define DTOs on it, and register them. Columns see the engine's env and typed functions. Engine vars stay untyped in columns, because a registered column called inside another expression evaluates them against that expression's resource.

A DTO or view projects on the engine it was defined on and on engines derived from it with register(). project() on any other engine throws. A column body always reads the engine's env and calls the engine's functions, projected or called, so a per-call value or function of the same name does not reach it: the columns' types came from the engine's own.

DTO environment and variables

Use env for lookup values owned by a DTO:

class LabRow extends r4.defineView('DiagnosticReport', {
  env: { system: 'http://loinc.org' },
}) {
  loincCode = this.column('code.coding.where(system = %system).first().code', {
    default: '',
  })
}

These values are available only while evaluating that DTO's columns. Registering the DTO does not publish them to other engine expressions. Column types are inferred from the values, so a lookup table types the columns that read it.

Declare data supplied by each projection with callerEnv. A declaration map types the supplied values, and DTO vars carry that type into later columns:

class LabResultRow extends r4.defineView('ServiceRequest', {
  callerEnv: { reports: { type: 'DiagnosticReport', collection: true } },
  vars: { report: "%reports.where(basedOn.reference = 'ServiceRequest/' + %context.id).first()" },
}) {
  status = this.column('%report.status', { default: 'waiting' }) // string
}

callerEnv tells TypeScript and the analyzer which names the call provides. Use an array of names when their structure is intentionally opaque, or a declaration map when FHIRPath navigates through them. It does not create values. Pass them to project() through env. A name cannot be both in env and in callerEnv, and it cannot be a name the engine's env binds.

DTO env and vars take priority over engine and per-call values with the same name, and the engine's env and functions take priority over per-call ones, so a column means the same thing however it is reached. %rowIndex and %rowTotal are also available to every column.

DTO vars apply only when the DTO is projected. They are row expressions and do not travel with a registered function call, which has a focus but no projection row.

Inheritance and shared columns

Subclasses inherit columns, environment values, and variables. A subclass can add columns, or replace an inherited column with a field of the same name:

class ObservationRow extends r4.defineView('Observation') {
  at = this.column('(effective.ofType(dateTime) | issued).first()', { as: 'Date' })
}

class HeightRow extends ObservationRow {
  meters = this.column("value.ofType(Quantity).toQuantity('m').value", { default: 0 })
}

Columns shared by DTOs and views on different FHIR types come from a base defined on a model base type: Resource for every resource, DomainResource for the resources that carry text and extension, or the same type for plain composition. Pass it as base:

class ResourceDto extends fp.defineDto('Resource') {
  id = this.column('id', { required: true })
  lastUpdated = this.column('meta.lastUpdated')
}

class ProblemRow extends fp.defineView('Condition', { base: ResourceDto }) {
  status = this.column('clinicalStatus.coding.first().code')
}

ProblemRow.from(condition) // ProblemRow { id, lastUpdated, status }; the input must carry `id`

The subclass extends the base class: it inherits the base's columns, methods, and getters, and a redeclared column overrides. It also inherits the base's env, vars, and callerEnv, and its own columns are inferred in the merged context. A name the base binds cannot be rebound, because the inherited columns were typed against the base's binding. A required column of the base is required by every subclass. analyzeDto() checks an inherited column against the root it was written for, so a column that dispatches on the resource type stays valid on every subclass.

The rules: a DTO takes a DTO as base, a view takes a DTO or a view; the base root is the root itself or one of its model base types (without a model, only the same root); the base was defined on the same engine or one the engine derives from. A base on an ancestor root projects any resource of that root, so ResourceDto.from(resource) accepts every resource type. Register the subclasses, not the base: an inherited column registered for both roots is an overlap register() rejects.

When shared columns depend on options each subclass passes, a function that forwards them to defineView() still works. Its return type is needed only when an exported class extends the result and the project emits declaration files; ViewBaseClass names the base class that engine's defineView() returns, plus the columns the function adds:

function badgedRow<const Root extends FhirTypeName, const Options extends DtoOptions = DtoOptions>(
  fhirType: Root,
  options?: Options
): ViewBaseClass<typeof fp, Root, Options, { badge: string }> {
  return class BadgedRow extends fp.defineView(fhirType, options) {
    badge = this.column('%badge', { type: 'string', default: '' })
  }
}

class LabRow extends badgedRow('DiagnosticReport', { vars: { badge: 'reportBadge()' } }) {
  name = this.column('code.text')
}

Inputs

A DTO or view on a resource type accepts a value whose resourceType is that type: { resourceType: 'Patient' }, a generated or @medplum/fhirtypes Patient, an array of them, or a Bundle. Any other type is a compile error, including unknown and { resourceType: string }. A datatype root such as CodeableConcept accepts any object. DtoInput<typeof Dto> names the accepted input.

A Bundle is accepted as a whole by a DTO without required columns, so its entries are checked only at runtime: each entry resource must carry the DTO's fhirType or a type deriving from it in the model, or project() throws. A DTO with a required column refuses a Bundle at compile time, because an entry cannot prove the path; read the entries with ofType() and narrow them. A value that is not an object, or has no resourceType, is rejected the same way. To project one resource type out of a mixed search Bundle, read the entries with ofType(), which infers the resource type:

const patients = r4.evaluate('Bundle.entry.resource.ofType(Patient)', searchset) // Patient[]
const rows = PatientRow.from(patients)

To keep only search matches, add where(search.mode = 'match') on the entries.

Required columns

required: true marks a column whose path the input must carry. The requirement is on the input type, not a check at read time: the accepted input gains the path as a required property, and the field's type drops undefined because the input proves presence.

class ScheduledAppointmentRow extends r4.defineView('Appointment') {
  id = this.column('id', { required: true }) // string
  start = this.column('start', { required: true }) // string
  lastUpdated = this.column('meta.lastUpdated', { required: true }) // string
  end = this.column('end') // string | undefined
}

type ScheduledAppointment = DtoInput<typeof ScheduledAppointmentRow>
// { resourceType: 'Appointment'; id: string; start: string; meta: { lastUpdated: string } }

ScheduledAppointmentRow.from(appointment) // compiles only when `appointment` has those properties

required is allowed only on a path of singular element names from the root, such as id or meta.lastUpdated. An expression, a collection element, a choice element, or a root-prefixed path is a compile error; use default to drop undefined from such a column. required excludes default, collection, as, choices, and enum, because each of those can replace or drop the value, and type, because a singular model path already has an exact type. A required column of a base class is required by every subclass.

The field type carries the path it requires, as string & RequiredColumn<'id'>. The marker is an optional symbol property, so the field reads and assigns as a plain string.

There is no runtime check for required: a cast or a registered function call that reaches a missing value reads undefined or empty, as any column does. The only input that could reach a required column unchecked is a Bundle, so a class with a required column refuses one; read the entries and narrow them.

Narrowing is the caller's job, and TypeScript narrows a property access, not the object that holds it: after if (appointment.start !== undefined), appointment is still an Appointment. A named type guard is what a mapper module writes, and it narrows an array through filter():

type ScheduledAppointment = DtoInput<typeof ScheduledAppointmentRow> & Appointment

function isScheduled(appointment: Appointment): appointment is ScheduledAppointment {
  return appointment.id !== undefined && appointment.start !== undefined && appointment.meta?.lastUpdated !== undefined
}

const appointments = r4.evaluate('Bundle.entry.resource.ofType(Appointment)', bundle) // Appointment[]
ScheduledAppointmentRow.from(appointments.filter(isScheduled)) // ScheduledAppointmentRow[]

For one resource, either call the guard or rebuild the object from the narrowed properties; a spread carries the narrowed types into a new object:

const { id, start } = appointment
const lastUpdated = appointment.meta?.lastUpdated
if (id !== undefined && start !== undefined && lastUpdated !== undefined) {
  ScheduledAppointmentRow.from({ ...appointment, id, start, meta: { ...appointment.meta, lastUpdated } })
}

Checking DTOs

Use the analyzer in unit tests:

import { analyzeDto, analyzeEngineDtos } from 'fhirpath-ts/analyzer'

expect(analyzeDto(LabResultRow)).toEqual([])
expect(analyzeEngineDtos(fp)).toEqual([])

analyzeDto() checks the complete expression language against the model, functions, and environment of the engine the DTO was defined on. It also compares a declared column type or enum with the analyzer's inferred result.

analyzeEngineDtos() checks only registered DTOs. Use the fhirpath-check DTO scan to find exported DTOs that are used only for projection.

Bundles

A Bundle is one resource, as in FHIRPath, so evaluate(), first(), test(), and evaluateTyped() run on the Bundle itself. A path reads its entries and keeps their types:

r4.evaluate('Bundle.entry.resource.ofType(Patient).name.family', searchset) // string[]
r4.first('entry.count()', searchset) // number | undefined

The per-resource methods, filter(), project(), checkConstraints(), and a DTO's from(), read a Bundle as its entry resources and skip entries without one:

r4.filter(searchset, 'birthDate < @1990-01-01')
r4.project(searchset, { id: 'id' })

A search Bundle may include resources of several types through _include and _revinclude. Read one type out of it with Bundle.entry.resource.ofType(Patient) before projecting a DTO; see Inputs. To keep only search matches, read entries where search.mode = 'match'.

Typed values read from a Bundle entry have the entry's resource as their %resource; see Element contexts.

What throws errors and what doesn't?

By default, evaluate() does not run static analysis. FHIRPath uses an empty collection for absence, so ordinary path navigation is lenient at runtime:

Example Result Reason
r4.evaluate('Encounter.id', patient) [] The root type does not match the input.
r4.evaluate('Patient.telecom.value', patient) [] The element is absent from this resource.
r4.evaluate('Patient.name.givenn', patient) [] An unknown path segment, including a misspelling, navigates to empty.
r4.evaluate('Observation.valueQuantity', observation) [] A choice JSON key is not a FHIRPath element; use the Observation.value stem.
r4.evaluate('Patient.name[99]', patient) [] The index is outside the collection.

The fhirpath-check CLI, ESLint rule, analyzer API, and strict: true evaluation report unknown or misspelled elements against the FHIR model.

The application helpers convert an empty result: first() returns undefined, test() returns false, and filter() drops that input.

Engine-generated failures use these exported FhirPathError subclasses:

Error Example Why it throws
FhirPathSyntaxError r4.evaluate('Patient..name', patient) Parsing fails because the expression does not match the grammar.
FhirPathTypeError r4.evaluate('frobnicate()', patient) The function is unknown. Wrong argument types or counts and undefined %variables also throw this error.
FhirPathTypeError r4.evaluate('Patient.name.givenn', patient, { strict: true }) Strict evaluation runs the analyzer and rejects its error diagnostics before reading data.
FhirPathTypeError r4.evaluate('Observation.valueQuantity', observation, { strict: true }) A choice JSON key is an unknown path in FHIRPath; strict evaluation requires the Observation.value stem.
FhirPathTypeError r4.evaluate('Patient.children().skip(1)', patient, { strict: true }) children() has undefined order, so strict analysis rejects the order-dependent skip().
FhirPathRuntimeError r4.evaluate('(1 | 2).single()') The operation requires at most one item, but the data contains two.
FhirPathRuntimeError r4.test(patient, 'Patient.name.given') A criteria result must contain at most one item.
ProjectionRowError r4.project(patients, columns, { onRowError }) Passed to onRowError when a row fails; thrown when it returns 'stop'. See Row errors.

and, or, implies, and xor skip the right operand when the left one decides the result: false and x, true or x, false implies x, and {} xor x. FHIRPath allows this short-circuiting but does not require it. So r4.evaluate('false and (1 | 2).single()') returns [false] here, while an engine that evaluates both operands throws. In an expression that other engines also run, guard a failing operand with iif(), which every engine evaluates lazily. The analyzer's type guards rely on this skip (Static checking).

This follows FHIRPath's empty propagation and singleton evaluation rules and its type-safety and strict evaluation model. Caller-supplied callbacks, including custom functions, conversions, regular expression engines, and trace sinks, may throw their own errors; the engine does not swallow them. Use static checking to catch wrong paths and other expression errors before runtime.

Engine error messages name types, functions, variables, elements, counts, text from the expression, and form identifiers such as a CodeSystem, ValueSet, or profile URL and a linkId. They never repeat another value read from the data, such as a code, a version, a string, or a free-text unit, so an application can log or show them. Errors from callbacks and terminology services, such as an OperationOutcome a server returns, pass through unchanged and carry whatever their source put in them.

safeErrorMessage(error) gives the message of an error caught around an evaluation that is safe to log or show: a FhirPathError's own message, or Unexpected <name>, such as Unexpected TypeError, for any other error, and Unexpected error for a value that is not an Error:

import { safeErrorMessage } from 'fhirpath-ts'

try {
  r4.evaluate(expression, resource, { functions })
} catch (error) {
  logger.warn(`Expression ${expressionId} failed: ${safeErrorMessage(error)}`)
}

Parse caching

Each engine has a private LRU parse cache. The default capacity is DEFAULT_PARSE_CACHE_SIZE (500). Set cacheSize: 0 to disable it.

const fp = new FhirPathEngine({ model: r4Model, cacheSize: 2000 })

The value is read only at construction. Compiled expressions do not use the cache. Keep a long-lived engine instead of creating one per request, and pass request-specific values through call options.

Medplum types

fhirpath-ts/r4 and @medplum/fhirtypes are generated from the same R4 StructureDefinitions. Medplum resources can be passed directly to this engine.

The generated interfaces require the elements FHIR marks as required (minimum cardinality 1) and enumerate every required and extensible code binding the definitions can list, with Reference.type as the resource names: a superset of Medplum's enumerations, so a datatype result such as an Extension, an Address, or a Quantity is assignable to the Medplum type without a cast. Inferred results carry the union of a required binding: r4.evaluate('Observation.status', observation) infers the status codes, while Reference.type infers string, since an extensible binding admits other codes. A whole resource is not assignable to Medplum's: contained and Bundle.entry.resource hold any { resourceType } here, while Medplum's Resource is a closed union that also names Medplum's own resources.

Inputs stay lenient. A root-prefixed expression, a declared root, and a declared host value accept { resourceType: 'Observation' } with every other element optional, because data read from a server, a fixture, or a form may be incomplete. A misspelled property or status is still rejected; only a code set that names resources, such as Reference.type, accepts any string, which is what lets a Medplum resource in. The types are not a profile validator.

Pass explicit generics to use Medplum types for both input and result:

import type { HumanName, Patient } from '@medplum/fhirtypes'
import { compile } from 'fhirpath-ts'
import { r4Model } from 'fhirpath-ts/r4'

const names = compile<'Patient.name', Patient, HumanName[]>('Patient.name')
names.evaluate(patient, { model: r4Model })