Callis architecture
Status: accepted (owner review, 2026-11-03). This is the big picture of Callis, a FHIRPath engine for TypeScript written from scratch and published as
@callis/core. It is deliberately short: the reasons behind decisions live in ADRs, and the detailed design lives with the task that implements it.
How the documentation is organized
| Where | What |
|---|---|
docs/architecture.md | This overview: goals, scope, pipeline, key decisions, layout. |
docs/adr/ | One file per architecture decision (context, decision, consequences). |
docs/roadmap.md | Task index, dependency graph and suggested waves. |
docs/tasks/ | One file per task (T0000-scaffold.md …): goal, scope, design notes, acceptance criteria. A worker only needs its own task file plus the ADRs it links. |
docs/spec-notes.md | Spec interpretations and suite-label exceptions. |
docs/conformance/ | Conformance reports, generated by pnpm conformance and the site build, never committed (from T0022). |
CONTRIBUTING.md, AGENTS.md | How to work in the repository: workflow, PR titles, definition of done; agent rules. |
docs/guides/ | Code style and testing guides. |
Rule: design details belong in the task that implements them. Changing a decision means updating its ADR in the same PR.
Normative references
| Reference | URL |
|---|---|
| FHIRPath N1 (2.0.0, normative release) | https://hl7.org/fhirpath/N1/ |
| FHIRPath N1 grammar (ANTLR) | https://hl7.org/fhirpath/N1/grammar.html |
| FHIRPath 3.0.0 (STU release, July 2026, now "current") | https://hl7.org/fhirpath/STU3/ (change notes) |
| FHIRPath in FHIR R4 | https://hl7.org/fhir/R4/fhirpath.html |
| FHIRPath in FHIR R5 | https://hl7.org/fhir/R5/fhirpath.html |
FHIRPath in FHIR R6 (draft 6.0.0-snapshot1, pinned; not final) | https://hl7.org/fhir/6.0.0-snapshot1/fhirpath.html |
| FHIR JSON format (primitive extensions, choice types) | https://hl7.org/fhir/R4/json.html |
| UCUM | https://ucum.org/ucum |
| Official test suite (R4 and R5; there is no R6 suite) | https://github.com/FHIR/fhir-test-cases/tree/master/r5/fhirpath |
Links of the form N1 §x point into the N1 document, for example N1 §4.5.
Goals and non-goals
Goals
- Correctness first. Behaviour follows the specification and is checked against the official HL7 FHIRPath test suite.
- No runtime dependencies in
@callis/core. - Fast repeated evaluation. Compile once, evaluate many times: search parameters, invariants, mappings.
- Runs anywhere. The same ESM build works in Node.js, browsers, Deno, Bun and edge workers.
- Works without a model, better with one. Plain JSON is enough to get started; a FHIR R4, R5 or R6 model adds choice types, type checks and primitive extensions (FHIR versions).
- Precise values. No binary floating point for
Decimal. Dates keep partial precision. Quantities respect units. - Good diagnostics. Every error has a stable code and a source position.
- Strict TypeScript and a fully typed public API.
Non-goals (for now)
- FHIR XML or RDF as input. JSON only; XML is used only inside the test tooling.
- Being a terminology server or a FHIR client. Callis exposes hooks; hosts implement them.
- CQL, FHIRPath Patch, SQL-on-FHIR. These may become separate packages later.
- Mutating input. FHIRPath has no side effects, except
trace().
Specification baseline and scope
Phase 1 covers the normative part of FHIRPath N1 plus the FHIR-specific additions (owner decision). The STU parts come in phase 2.
FHIRPath 3.0.0 (July 2026) is now the version served at https://hl7.org/fhirpath/. It keeps N1's normative content, marks additions as STU, and clarifies many normative rules. The official test suite follows it. Where 3.0.0 clarifies normative behaviour, Callis follows 3.0.0 and the suite (ADR-0001). Each interpretation that is not obvious from the text is recorded in docs/spec-notes.md.
| Area | Phase 1 | Phase 2 (STU) | Notes |
|---|---|---|---|
Full N1 grammar: literals, operators, invocations, $this, $index, %vars, comments | ✓ | N1 §4, §8 | |
| Functions N1 §5.1–5.6, §5.8, §5.9 | ✓ | existence, filtering/projection, subsetting, combining, conversion, string, tree, utility | |
| Math functions N1 §5.7 | ✓ | STU in N1, included by owner decision | |
| Operations N1 §6, including date/time arithmetic | ✓ | ||
| Environment variables N1 §9 | ✓ | ||
$total, aggregate() N1 §7 | parse only | ✓ | STU |
Reflection type() N1 §10.2 | ✓ | STU | |
Long type, 1L literal, toLong() | ✓ | 3.0.0 STU | |
Other 3.0.0 additions (sort, coalesce, defineVariable, boundaries, date/time components, string additions, …) | ✓ | see T0026–T0031 | |
FHIR variables: %resource, %rootResource, %context, %ucum, %sct, %loinc, %`vs-*`, %`ext-*` | ✓ | R5 §2.1.9.1.4, §2.1.9.1.7 | |
FHIR functions: extension(), hasValue(), getValue(), resolve(), ofType()/is/as on FHIR types | ✓ | R5 §2.1.9.1.5 | |
FHIR functions backed by host hooks: memberOf(), subsumes(), subsumedBy(), conformsTo(), htmlChecks() | ✓ | empty without a hook | |
FHIR equivalence changes (Coding, CodeableConcept, id ignored) | ✓ | R5 §2.1.9.1.6 | |
elementDefinition(), slice(), checkModifiers(); R5 draft APIs %terminologies, %server, %factory | ✓ | T0032; the R6 draft moved the three APIs out of the core specification | |
| CDA logical model, "document functions" (HL7 Java extensions) | out of scope |
Pipeline
flowchart LRsrc["expression (string)"] --> lexer[Lexer]lexer --> tokens["tokens"]tokens --> parser["Parser (Pratt + recursive descent)"]parser --> ast[AST]ast --> analyzer["Analyzer (optional)"]ast --> compiler[Compiler]analyzer -. "diagnostics, inferred types" .-> compilercompiler --> compiled["CompiledExpression (closure tree)"]compiled -- "evaluate(input, options)" --> result["Collection"]result --> output["Output adapter (plain | typed)"]model[ModelProvider] -.-> analyzermodel -.-> compiledregistry[FunctionRegistry] -.-> analyzerregistry -.-> compilerhooks["Host hooks: resolve, terminology, trace, now"] -.-> compiled
| Stage | Responsibility | Details |
|---|---|---|
| Lexer | Characters to tokens with exact spans. No semantics. | T0001 |
| Parser | Tokens to AST. Syntax only; every node has a source span. | T0002 |
| Analyzer (optional) | Semantic checks and type inference, given a model and input type. Never changes the AST. | T0024 |
| Compiler | AST to a tree of closures. Functions, type specifiers and literals are resolved once. | T0008 |
| Runtime | Evaluates the closure tree. Reentrant and safe for concurrent async evaluations. | T0008, T0021 |
| Output adapter | Converts internal values to plain JSON-friendly values or typed values. | T0025, T0038 |
Everything up to and including the compiler is pure and deterministic. The AST is plain, JSON-serializable data, so tools such as formatters and editor integrations can use it directly.
Key decisions
| Topic | Decision | ADR |
|---|---|---|
| Spec baseline | N1 normative + FHIR additions in phase 1, following 3.0.0 clarifications; Math included; STU in phase 2. | 0001 |
| Parsing | Hand-written lexer; Pratt parser for operators, recursive descent for the rest. No parser generator. | 0002 |
| Evaluation | The AST is compiled once to a tree of closures. No eval/new Function, so it works under a strict CSP. | 0003 |
| Sync and async | One closure tree returning MaybePromise<Collection>. evaluate() is sync; evaluateAsync() allows async hooks. Promises are detected structurally. | 0004 |
| Decimal | Own BigInt-based implementation (coefficient + scale) that keeps precision. | 0005 |
| Date/time | Own partial-precision value types; no Temporal and no date library. | 0006 |
| Units | Minimal unit system in core; full UCUM in the opt-in @callis/ucum. | 0007 |
| Model | ModelProvider interface; the core also works on plain JSON. R4, R5 and R6 models are generated and published as separate packages; R6 from a pinned draft (T0039). | 0008 |
| Packaging | ESM only, ES2022, zero runtime dependencies, Node 22/24/26 and browsers. | 0009 |
| Tooling | pnpm, TypeScript 7, tsdown, Biome, Vitest, Changesets. | 0010 |
| Conformance | Vendored HL7 test suite, run in CI with a baseline that may only ratchet upwards. | 0011 |
| Defaults | UTC for date/time values without an offset; Decimal as number in plain output; strict choice types. | 0012 |
Values at a glance
Every expression evaluates to a collection: a read-only JavaScript array of items, never containing null or undefined. Items are represented like this:
| FHIRPath type | JavaScript representation | Details |
|---|---|---|
System.Boolean, System.String | boolean, string | T0003 |
System.Integer | number (32-bit range) | T0003 |
System.Long (phase 2) | bigint | T0028 |
System.Decimal | Decimal (class) | T0004 |
System.Date, System.DateTime, System.Time | DateValue, DateTimeValue, TimeValue (classes) | T0005 |
System.Quantity | Quantity (class) | T0006 |
| Model data: resources, complex types, FHIR primitives | ModelNode | T0018 |
JavaScript primitives cover the most common types without wrappers, and dispatching on typeof and instanceof is cheap. Empty propagation, singleton evaluation and three-valued logic are described in T0003. Equality and equivalence for each type are in T0009.
Public API at a glance
The first public evaluation surface is model-less and synchronous (T0025):
import { compile, evaluate } from '@callis/core';const given = evaluate(patient, 'Patient.name.given');const names = compile('Patient.name.given');names.evaluate(patient);const exact = evaluate({}, '1.234', { decimalOutput: 'string' });
T0025 delivered this surface, and later increments add functions and parseJson(); the guide lists what is supported now. It exposes only implemented capabilities, preserves the existing exported provider/unit contracts and provides plain JSON-friendly results plus stable public errors. Analysis, strict mode and the model options (guide) are public too. Public parsing and AST access, typed output, hooks, async evaluation and compile caching remain in the later API sketch, split into tasks under T0038; their presence in the pipeline describes the target architecture, not current release support. Errors are described in T0000.
The first 0.1 release, published on 2026-11-06 with five packages, followed the minimal API and simple playground, with support, limitations and conformance documented in T0037. Later 0.x releases advance toward full phase 1 without changing its specification baseline. The scope and criteria for 1.0 remain open.
Stability: releases before 1.0 may break the public API, including ModelProvider, but only as a last resort: APIs are designed with later tasks in mind, and each breaking change states its reason in its PR and is called out in its changeset (API changes). Stabilising the API is a goal for 1.0, not for 0.1.0 (roadmap backlog).
Repository layout
callis/├── .changeset/├── .github/workflows/ ci.yml, pr-title.yml, roadmap-sync.yml, release.yml, deploy.yml├── docs/ architecture.md, roadmap.md, adr/, tasks/, spec-notes.md, conformance/├── apps/ private, never published│ └── site/ documentation site and progress page (callis.losol.no)├── packages/│ ├── core/ @callis/core engine, no runtime dependencies│ ├── ucum/ @callis/ucum UCUM unit system, no runtime dependencies│ ├── fhir-r4/ @callis/fhir-r4 generated R4 ModelProvider│ ├── fhir-r5/ @callis/fhir-r5 generated R5 ModelProvider│ ├── fhir-r6/ @callis/fhir-r6 generated R6 ModelProvider (pinned draft)│ └── cli/ @callis/cli later├── scripts/ repository scripts: zero-dependency check, size report├── tools/ private, never published│ ├── model-gen/ StructureDefinition → model data│ └── conformance/ HL7 test-suite runner, vendored fixtures, baseline├── biome.json├── package.json private root with workspace scripts├── pnpm-workspace.yaml├── tsconfig.base.json└── vitest.config.ts projects
packages/core/src/├── index.ts public exports only├── api/ parse, analyze, compile, evaluate, evaluateAsync; options; output adapters; compile cache├── errors/ FhirPathError hierarchy, error codes, SourceSpan, formatting├── lexer/ token.ts, lexer.ts, char-codes.ts, line-table.ts├── parser/ ast.ts, parser.ts (Pratt), precedence.ts├── analysis/ analyzer.ts, type-inference.ts, diagnostics.ts├── compiler/ compile.ts (AST → closures), lambda.ts, literal.ts (literals, constant folding)├── runtime/ context.ts (EvalContext, Frame), maybe-promise.ts, collection.ts, singleton.ts,│ logic.ts, equality.ts, comparison.ts, arithmetic.ts, navigation.ts, node-value.ts,│ type-target.ts, variables.ts├── types/ system-types.ts, type-specifier.ts, model-types.ts, conversions.ts, type-test.ts (is/as/ofType)├── values/│ ├── decimal/ decimal.ts, math.ts│ ├── datetime/ date.ts, datetime.ts, time.ts, parse.ts, compare.ts, arithmetic.ts, now.ts,│ │ calendar.ts, format.ts, precision.ts, temporal-value.ts│ ├── quantity/ quantity.ts, calendar-units.ts, unit-system.ts (interface + minimal implementation)│ └── string.ts equivalence normalization and helpers├── model/ model-provider.ts, model-node.ts, json-navigation.ts, primitive-extensions.ts, lossless-json.ts├── functions/ registry.ts, define.ts, existence.ts, filtering.ts, subsetting.ts, combining.ts,│ conversion.ts, string.ts, math.ts, tree.ts, utility.ts, types.ts, logic.ts└── fhir/ functions.ts, resolve.ts, variables.ts, equivalence.ts, hooks.ts
Tests live next to their sources (*.test.ts). Cross-module integration tests go in packages/core/test/.
Module dependency rules (enforced in review; a lint rule may come later). These rules are what let the first wave of the roadmap run in parallel:
errors→ nothinglexer→errorsparser→lexer,errorsvalues/decimal,values/datetime,values/string→errorsonly; pure and testable on their ownvalues/quantity→values/decimal,errors. This one-way dependency is the only one allowed between value modules. No value module depends ontypes,modelorruntime.types→valuesmodel→types,valuesruntime→values,types,modelfunctions→runtime,values,types. The function modules wrap the pure kernels invalues(Decimal, Quantity, date/time and string helpers), so they import them directly instead of through a facade inruntime. The owner decided this forvalueson 2026-11-09 (#178).fhir→runtime,values,model, and fromfunctionsonlyfunctions/define.ts, the function-definition contract.- In
functions, onlyregistry.tsmay importfhir: it is the composition root that registers every built-in function, the FHIR ones fromfhir/functions.tsincluded.define.tsdoes not importfhir, so the two modules import each other without forming a cycle of file imports. The owner decided this, andfunctions→types, on 2026-11-11 (#193). compiler→parser(AST types),runtime,functionsanalysis→parser,types,model,values,functions, and fromruntimeonly what it shares with the compiler for the same answers at compile time and at run time: the type-target resolution oftype-target.tsand the choice-suffix lookup ofnavigation.ts. It never evaluates anything (T0024).api→ everything;index.ts→apiplus public types
Testing strategy
- Unit tests (Vitest) live next to each module. Every example in the matching spec section becomes a table-driven test with a link to the spec anchor.
- Property-based tests (
fast-check, dev only):Decimalagainstdecimal.jsas an oracle- date comparison laws
- lexer and parser fuzzing: never crash, only throw
FhirPathSyntaxError
- Conformance: the official HL7 suite runs in CI with a ratcheting baseline and a report published on the site (ADR-0011, T0022, T0023).
- Type tests (
expectTypeOf) for the public API. - Package checks: publint, attw, the zero-dependency check and a size budget (T0000).
- Later: differential tests against
fhirpath.jsand benchmarks (T0033).
Line coverage for the core (excluding generated code) is reported in CI with a target of 90% or more. It is not enforced at first.
Security and robustness
- Prototype safety: navigation uses own-property checks (
Object.hasOwn) and never reaches__proto__,constructorand similar. Internal maps useObject.create(null). - No
evalornew Function, so Callis works under a strict CSP. - Regular expressions:
matches()andreplaceMatches()run user-supplied patterns on JavaScript's backtracking engine, so ReDoS is possible. This is documented, and aregexhook lets hosts plug in a safe engine (T0021). - Bounded work:
- parsing has a maximum nesting depth for the whole expression tree, including long chains such as
a.b.c…orx and y and …, and the compiler checks the same limit again for trees built by hand (syntax/nesting-limit, never a stack overflow) - a
Decimalhas at most 10,000 digits and a scale of at most 10,000. Arithmetic beyond that is overflow or underflow and gives empty, as FHIRPath 3.0.0 requires, instead of growing without limit (T0004) repeat()deduplicates per the spec, which only guarantees termination for projections that navigate a finite input tree. A value-generating projection such as'x'.repeat($this & 'x')never runs out of new items.- every evaluation therefore has finite default limits (
limits.maxRepeatItems,limits.maxCollectionSize), and exceeding them raiseseval/limit-exceededin both sync and async mode (T0042, T0038) - async evaluations can be cancelled with a signal (T0021)
- parsing has a maximum nesting depth for the whole expression tree, including long chains such as
- Errors never include input data beyond the expression text, so diagnostics are safe to log.
Owner decisions
The open questions from the first draft were answered by the owner on 2026-11-03:
| Question | Decision | Recorded in |
|---|---|---|
| Spec baseline | Follow FHIRPath 3.0.0's clarifications of normative behaviour. | ADR-0001 |
| Math functions (STU in N1) | Included in phase 1. | ADR-0001 |
| Module format | ESM only; no CommonJS build for now. | ADR-0009 |
| UCUM | Separate opt-in @callis/ucum. After the license check, it ships the unchanged UCUM essence file with its notices and license, and parses it at startup; no generated tables. | ADR-0007, T0007, SOURCE.md |
| Decimal in plain output | number by default; decimalOutput: 'string' and output: 'typed' for exact results. | ADR-0012 |
| Default timezone | UTC for values without an offset; timezoneOffset overrides it, and 'local' uses the host's offset. | ADR-0012 |
Choice-type suffixes (Observation.valueQuantity) | Rejected by default as the spec requires; lenient: { choiceSuffix: true } accepts them. | ADR-0012 |
| Package names and npm scope | @callis/fhir-r4 and @callis/fhir-r5; the @callis scope is secured. | ADR-0008 |
Later owner decisions:
| Question | Decision | Recorded in |
|---|---|---|
| FHIR versions | R4, R5 and R6. R6 is best effort: @callis/fhir-r6 is pinned to the draft 6.0.0-snapshot1, there is no R6 conformance suite, and known gaps are documented instead (R6 in the first release, 2026-11-06; support direction, 2026-11-08). | Roadmap: FHIR versions, T0039 |
New questions go into the relevant task file or a new ADR.