JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 148
  • Score
    100M100P100Q71314F
  • License MIT

Production-ready FHIR R4 runtime engine for TypeScript/Node.js. Includes parser, validator, snapshot generator, FHIRPath engine, and fhir-definition integration.

Package Exports

  • fhir-runtime
  • fhir-runtime/package.json

Readme

fhir-runtime

A production-ready FHIR R4 runtime engine for TypeScript/Node.js

License: MIT TypeScript Node.js Tests

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) โ€” DefinitionProvider interface, DefinitionBridge adapter, createRuntime() factory, DefinitionProviderLoader
  • fhir-server Prerequisites (STAGE-B) โ€” RemoteTerminologyProvider interface, validateMany() batch API, SnapshotCache lazy loading, warmupSnapshots()
  • Profile Slicing & UI Utilities (STAGE-7) โ€” SlicedElement/SliceDefinition types, matchSlice(), generateSliceSkeleton(), Choice Type helpers (isChoiceType(), resolveActiveChoiceType()), BackboneElement helpers (isBackboneElement(), getBackboneChildren()), inferComplexType fix
  • IG Extraction API (v0.11.0) โ€” extractSDDependencies() for SD dependency graphs, extractElementIndexRows() for element index table population, flattenConceptHierarchy() for CodeSystem concept tree flattening
  • 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,277 tests across 117 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
  • Batch validation tested โ€” 28 new tests for validateMany, RemoteTerminologyProvider, SnapshotCache
  • Profile slicing tested โ€” 69 new tests for slicing extraction, matching, choice types, backbone elements
  • IG extraction tested โ€” 27 new tests for SD dependencies, element index rows, concept hierarchy flattening
  • HAPI-equivalent โ€” 35/35 snapshot fixtures match HAPI output
  • Stress tested โ€” Malformed input, deep nesting, large payloads, concurrency
  • Single dependency โ€” fhir-definition@0.6.0 (FHIR Knowledge Engine)
  • Type-safe โ€” Full TypeScript definitions for all FHIR R4 types

๐Ÿ“ฆ Installation

npm install fhir-runtime

Requirements:

  • 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.


fhir-runtime-cli

Command-line interface for fhir-runtime โ€” A powerful CLI tool for FHIR resource validation, IG package management, and development workflows.

Key Features:

  • Validate โ€” Validate FHIR resources against profiles with support for local IG packages
  • IG Package Loading โ€” Load and inspect FHIR Implementation Guide packages
  • Search Parameters โ€” List and explore SearchParameters for resource types
  • Batch Operations โ€” Validate multiple resources in batch mode
  • Configuration Support โ€” .fhir-runtime.json config file for project-specific settings

Installation:

npm install -g fhir-runtime-cli

Quick Example:

# Validate a Patient resource against US Core profile
fhir-runtime-cli validate \
  --file patient.json \
  --profile http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient \
  --ig-path ./fhir-packages/hl7.fhir.us.core

# List SearchParameters for Patient resource type
fhir-runtime-cli search-params Patient

# Load and inspect an IG package
fhir-runtime-cli load-package ./fhir-packages/hl7.fhir.us.core

Repository: github.com/medxaidev/fhir-runtime-cli


๏ฟฝ๐Ÿš€ 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


๐Ÿงช 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, capability

v0.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 tests

v0.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 verified

Stress 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 messages

HAPI 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-server development 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() and parseSearchParametersFromBundle() for typed SearchParameter resource parsing
  • Search Value Extraction โ€” extractSearchValues() and extractAllSearchValues() 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 โ€” ResourceTypeRegistry with FHIR_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 โ€” NpmPackageLoader for 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 โ€” InMemoryTerminologyProvider with full TerminologyProvider interface
  • Binding strength โ€” required / extensible / preferred / example validation
  • Registries โ€” CodeSystemRegistry (hierarchical) + ValueSetRegistry for in-memory terminology storage
  • ValueSet membership โ€” expansion, compose include/exclude, hierarchical filters

v0.4.0

  • Validation Pipeline โ€” Composable ValidationPipeline with 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 โ€” TerminologyProvider and ReferenceResolver are 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


โšก 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