Package Exports
- fhir-runtime
- fhir-runtime/package.json
Readme
fhir-runtime
A production-ready FHIR R4 runtime engine for TypeScript/Node.js
fhir-runtime is a structural FHIR R4 engine that provides comprehensive capabilities for parsing, validating, and manipulating FHIR resources โ without requiring a running FHIR server, database, or external terminology service.
Designed as a lightweight runtime layer with a single dependency (fhir-definition), it's suitable for embedding in servers, CLIs, web applications, or custom platforms.
๐ฎ Live Demo: fhir-runtime-tools.vercel.app/ โ Try fhir-runtime in your browser
Features
Core Capabilities
- FHIR R4 JSON Parsing โ Full support for primitives, choice types, extensions
- Profile-Based Validation โ 9 structural validation rules + FHIRPath invariants
- Validation Pipeline (STAGE-2) โ Composable multi-step pipeline with hooks, batch validation, and enhanced error messages
- Terminology Binding (STAGE-3) โ InMemoryTerminologyProvider, binding strength validation, CS/VS registries
- IG Package Loading (STAGE-4) โ NpmPackageLoader, PackageManager, cross-package canonical resolution
- Server/Persistence Integration (STAGE-5) โ SearchParameter parsing, search value extraction, reference extraction, CapabilityStatement generation
- fhir-definition Integration (STAGE-6) โ
DefinitionProviderinterface,DefinitionBridgeadapter,createRuntime()factory,DefinitionProviderLoader - Provider Abstraction Layer (STAGE-1) โ Terminology and reference contracts with default NoOp implementations
- Snapshot Generation โ HAPI-equivalent differential expansion
- FHIRPath Engine โ 60+ functions, Pratt parser with AST caching
- Bundle Loading โ Load FHIR specification bundles and IGs
- Context Management โ Registry, loaders, inheritance resolution
- InnerType Extraction โ BackboneElement schema for UI/validation
- OperationOutcomeBuilder โ Convert validation, parse, and snapshot results to FHIR R4
OperationOutcome
Quality & Testing
- 4,153 tests across 106 test files โ 100% passing
- US Core IG verified โ 70 StructureDefinitions loaded from real US Core v9.0.0 package
- IG package tested โ 138 package tests including real US Core integration
- Integration tested โ 110 tests for SearchParameter, value extraction, references, capability builder
- Definition integration tested โ 59 tests for DefinitionProvider, DefinitionBridge, createRuntime, E2E
- HAPI-equivalent โ 35/35 snapshot fixtures match HAPI output
- Stress tested โ Malformed input, deep nesting, large payloads, concurrency
- Single dependency โ
fhir-definition(FHIR Knowledge Engine) - Type-safe โ Full TypeScript definitions for all FHIR R4 types
๐ฆ Installation
npm install fhir-runtimeRequirements:
- Node.js โฅ18.0.0
- TypeScript โฅ5.0 (for TypeScript projects)
๐ฎ Try it Online
Live Demo: fhir-runtime-tools.vercel.app/
FHIR Runtime Tools โ Developer toolset built on fhir-runtime, providing utilities for FHIR resource inspection, debugging, and development workflows.
๐ Quick Start
Parse a FHIR Resource
import { parseFhirJson } from "fhir-runtime";
const result = parseFhirJson(`{
"resourceType": "Patient",
"id": "example",
"name": [{ "family": "Doe", "given": ["John"] }]
}`);
if (result.success) {
console.log(result.data.resourceType); // "Patient"
console.log(result.data.name[0].family); // "Doe"
}Validate Against a Profile
import {
StructureValidator,
buildCanonicalProfile,
parseStructureDefinition,
} from "fhir-runtime";
// Load a profile
const sdResult = parseStructureDefinition(profileJson);
const profile = buildCanonicalProfile(sdResult.data);
// Validate a resource
const validator = new StructureValidator();
const result = validator.validate(patientResource, profile);
if (!result.valid) {
result.issues.forEach((issue) => {
console.error(`${issue.severity}: ${issue.message} at ${issue.path}`);
});
}Validate with Pipeline + Terminology (v0.5.0)
import {
ValidationPipeline,
StructuralValidationStep,
TerminologyValidationStep,
InvariantValidationStep,
InMemoryTerminologyProvider,
generateReport,
} from "fhir-runtime";
// Set up terminology provider
const terminology = new InMemoryTerminologyProvider();
terminology.loadFromBundle(terminologyBundle);
const pipeline = new ValidationPipeline({
terminologyProvider: terminology,
failFast: true,
minSeverity: "warning",
});
pipeline.addStep(new StructuralValidationStep());
pipeline.addStep(new TerminologyValidationStep());
pipeline.addStep(new InvariantValidationStep());
const result = await pipeline.validate(resource, profile);
const report = generateReport(result);createRuntime() โ One-step Setup (v0.8.0)
import { createRuntime } from "fhir-runtime";
// Pattern 1: With fhir-definition (recommended)
import { InMemoryDefinitionRegistry, loadFromDirectory } from "fhir-definition";
const registry = new InMemoryDefinitionRegistry();
await loadFromDirectory("./definitions", registry);
const runtime = await createRuntime({ definitions: registry });
// Pattern 2: Bare minimum (auto-loads R4 core definitions)
const runtime2 = await createRuntime();
// Validate
const result = await runtime.validate(
patient,
"http://hl7.org/fhir/StructureDefinition/Patient",
);
// Get search parameters
const sps = runtime.getSearchParameters("Patient");Generate a Snapshot
import { FhirContextImpl, SnapshotGenerator } from "fhir-runtime";
const ctx = new FhirContextImpl({ loaders: [] });
await ctx.preloadCoreDefinitions();
const generator = new SnapshotGenerator(ctx, { generateCanonical: true });
const result = await generator.generate(myProfile);
if (result.success) {
console.log(
`Generated ${result.structureDefinition.snapshot.element.length} elements`,
);
}Evaluate FHIRPath
import { evalFhirPath, evalFhirPathBoolean } from "fhir-runtime";
const patient = { resourceType: "Patient", name: [{ given: ["John"] }] };
const names = evalFhirPath("Patient.name.given", patient);
// โ ['John']
const hasOfficial = evalFhirPathBoolean(
"name.where(use='official').exists()",
patient,
);
// โ false๐ Documentation
- Technical Overview โ Architecture, design principles, capabilities
- API Reference โ Public API reference for the v0.7.0 release surface
- Capability Contract โ Behavioral guarantees and release contract for v0.7.0
- Release Notes v0.7.0 โ Detailed v0.7.0 release notes
๐งช Testing & Quality
Test Coverage
โ
3,376 tests across 88 test files
โ
100% pass rate on HAPI snapshot fixtures (35/35)
โ
All 11 modules fully tested (model, parser, context, profile, validator, fhirpath, provider, terminology, package, pipeline, integration)
โ
IG package tested โ 138 package tests including real US Core v9.0.0 integration
โ
Integration tested โ 110 tests for SearchParameter, value extraction, references, capabilityv0.7.0 Integration Coverage
โ
110 new tests across 6 integration test files
โ
SearchParameter parser โ 24 tests
โ
Search value extractor โ 21 tests (string, token, reference, date, number, quantity, uri)
โ
Reference extractor โ 22 tests (literal, contained, absolute, logical, bundle)
โ
CapabilityStatement builder โ 12 tests
โ
Resource type registry โ 16 tests
โ
End-to-end integration โ 15 testsv0.6.0 Package Coverage
โ
138 new tests across 7 package-focused test files
โ
Package manifest parser โ 13 tests
โ
Package index parser โ 14 tests
โ
NpmPackageLoader โ 32 tests (index, scan, load, filter, bulk)
โ
Dependency resolver โ 15 tests (graph, topo sort, cycle detection)
โ
Canonical resolver โ 22 tests (version-aware, multi-loader)
โ
PackageManager โ 17 tests (register, discover, resolve)
โ
Integration โ 25 tests (11 mock + 14 real US Core v9.0.0)US Core IG Verification
โ
70 US Core StructureDefinitions parsed
โ
55 resource profiles converted to CanonicalProfiles
โ
15 extension definitions processed
โ
Official examples validated against declared profiles
โ
FHIRPath evaluation on US Core resources
โ
Profile-to-example matching verifiedStress Testing
โ
Malformed input resilience โ graceful error handling
โ
Deep nesting stress โ recursive structure validation
โ
Large payload stress โ bundle processing performance
โ
FHIRPath complexity โ complex expression evaluation
โ
Memory pressure โ batch processing stability
โ
Concurrent safety โ parallel operation validation๐๏ธ Architecture
Module Structure
src/
โโโ model/ โ FHIR R4 type definitions (branded primitives, enums, complex types)
โโโ parser/ โ JSON parsing & serialization
โโโ context/ โ SD registry, loaders, inheritance resolution, bundle loading
โโโ profile/ โ Snapshot generation, canonical builder, constraint merging
โโโ validator/ โ Structural validation (9 rules + FHIRPath invariants)
โโโ fhirpath/ โ FHIRPath expression engine (Pratt parser, 60+ functions)
โโโ provider/ โ Terminology/reference abstractions, NoOp providers, OperationOutcomeBuilder
โโโ terminology/ โ Binding validation, InMemoryTerminologyProvider, CS/VS registries
โโโ package/ โ IG package loading, NpmPackageLoader, PackageManager, canonical resolution
โโโ integration/ โ SearchParameter, search value extraction, references, CapabilityStatement
โโโ pipeline/ โ Composable validation pipeline, hooks, batch, reports, enhanced messagesHAPI FHIR Equivalence
| fhir-runtime | HAPI FHIR |
|---|---|
FhirContextImpl |
FhirContext + DefaultProfileValidationSupport |
SnapshotGenerator |
ProfileUtilities.generateSnapshot() |
StructureValidator |
FhirInstanceValidator |
evalFhirPath() |
FHIRPathEngine.evaluate() |
CompositeLoader |
ValidationSupportChain |
๐ฏ Use Cases
- FHIR Servers โ Validation layer for REST operations
- FHIR Server Foundations โ Start
fhir-serverdevelopment with NoOp providers before terminology is implemented - CLI Tools โ Parse, validate, generate snapshots, evaluate FHIRPath
- Web Applications โ Client-side FHIR processing without server dependency
- IG Publishers โ Profile validation and snapshot generation
- Testing Frameworks โ FHIR resource validation in test suites
- Data Pipelines โ ETL with FHIR validation and transformation
๐ License
MIT License - see LICENSE file for details.
๐ Package Details
| Property | Value |
|---|---|
| Package name | fhir-runtime |
| Version | 0.7.0 |
| License | MIT |
| FHIR Version | R4 (4.0.1) |
| Module formats | ESM + CJS |
| Runtime dependencies | None (zero dependencies) |
| Bundled core definitions | 73 FHIR R4 StructureDefinitions |
| Public exports | ~280+ symbols across 11 modules |
| Test coverage | 3,376 tests across 88 files |
๐ Release Highlights
v0.7.0
- SearchParameter Parsing โ
parseSearchParameter()andparseSearchParametersFromBundle()for typed SearchParameter resource parsing - Search Value Extraction โ
extractSearchValues()andextractAllSearchValues()using FHIRPath to extract indexable values from resources - Reference Extraction โ
extractReferences()walks resource tree to find all Reference elements (literal, logical, contained, absolute) - CapabilityStatement Builder โ
buildCapabilityFragment()generates REST fragments from profiles and search parameters - Resource Type Registry โ
ResourceTypeRegistrywithFHIR_R4_RESOURCE_TYPES(148 R4 resource types) - Reference Validation โ
validateReferenceTargets()checks reference target types against profile constraints - 110 new tests โ 3,376 total across 88 test files
v0.6.0
- IG Package Loading โ
NpmPackageLoaderfor loading FHIR IG packages from extracted NPM directories - PackageManager โ Register, discover, and manage multiple IG packages with dependency resolution
- Canonical Resolution โ Version-aware cross-package canonical URL resolution (
url|version) - Dependency Graph โ Topological sorting with circular dependency detection
- US Core verified โ Real US Core v9.0.0 package loaded and validated (70 SDs, 20 ValueSets)
- 138 new tests โ 3,266 total across 82 test files
v0.5.0
- Terminology Binding Validation โ
InMemoryTerminologyProviderwith fullTerminologyProviderinterface - Binding strength โ
required/extensible/preferred/examplevalidation - Registries โ
CodeSystemRegistry(hierarchical) +ValueSetRegistryfor in-memory terminology storage - ValueSet membership โ expansion, compose include/exclude, hierarchical filters
v0.4.0
- Validation Pipeline โ Composable
ValidationPipelinewith pluggable steps, priority ordering, and failFast mode - Built-in steps โ
StructuralValidationStep,TerminologyValidationStep,InvariantValidationStep - Hook system โ Lifecycle events for monitoring and customizing validation flow
- Batch validation โ Validate multiple resources in a single pipeline run
- Enhanced errors โ Fix suggestions, documentation links, expected/actual values
- Validation reports โ Structured reports with multi-axis issue grouping
v0.3.0
- Provider Abstraction Layer landed โ
TerminologyProviderandReferenceResolverare now part of the public API - Default NoOp implementations โ Safe placeholders for higher-level services and integration work
- OperationOutcomeBuilder support โ Convert structured engine results into FHIR-native error payloads
- Backward compatible โ Existing validation flows continue to work with optional provider hooks
๐ Related Projects
- FHIR Runtime Tools โ Developer toolset built on fhir-runtime (GitHub)
- HAPI FHIR โ Reference Java implementation
- HL7 FHIR Specification โ Official FHIR R4 spec
- US Core IG โ US Core Implementation Guide
โก Performance
- Zero dependencies โ Minimal bundle size, fast installation
- AST caching โ FHIRPath expressions cached (LRU, 128 entries)
- Deterministic โ Same input always produces same output
- Memory efficient โ Streaming bundle loading, lazy evaluation
Made with โค๏ธ for the FHIR community