Package Exports
- babelfhir-ts
- babelfhir-ts/out/src/main.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (babelfhir-ts) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
BabelFHIR-TS
BabelFHIR-TS transforms FHIR® StructureDefinitions into production-ready TypeScript code with full type safety and built-in validation. Unlike generic FHIR type definitions, BabelFHIR-TS generates profile-aware interfaces that understand your Implementation Guide's constraints, extensions, and slicing rules.
What you get
- Strongly typed interfaces that merge profile constraints with base FHIR types (types come from
@types/fhir) - Compiled output by default — packages ship JavaScript (
.js) plus TypeScript declarations (.d.ts) - Runtime validation using FHIRPath expressions from the profile—no external validator required for basic checks
- Type-safe extension handling with proper slicing and nested extension support
- Random data builders for testing and development (when class generation is enabled)
- Zero manual mapping—consume any FHIR package or Implementation Guide directly from registries
- Fast and lightweight—minimal runtime deps; only
fhirpathis required for validators - Install any FHIR profile as a node module—use
babelfhir-ts installto add Implementation Guides directly to your project
Continuous Validation
Every pull request runs two independent CI pipelines that validate generated code against real-world FHIR Implementation Guides. For each IG, the pipeline:
- Downloads the FHIR package from a registry
- Generates TypeScript interfaces, validators, and classes
- Compiles the output with
tsc(zero errors required) - Generates
empty()andrandom()test resources for every profile - Validates those resources against two external FHIR validators
Tested Implementation Guides
| Implementation Guide | Package | Profiles |
|---|---|---|
| US Core | hl7.fhir.us.core@8.0.0 |
Patient, Condition, Observation, Encounter, … |
| ISiK Basis (Germany) | de.gematik.isik-basismodul@4.0.3 |
ISiKPatient, ISiKDiagnose, … |
| IPS (International Patient Summary) | hl7.fhir.uv.ips@2.0.0 |
Composition, MedicationStatement, … |
| SMART App Launch | hl7.fhir.uv.smart-app-launch@2.2.0 |
WellKnown endpoints |
| CH Core (Switzerland) | ch.fhir.ig.ch-core@5.0.0 |
CHCorePatient, CHCoreEncounter, … |
| DaVinci PAS | hl7.fhir.us.davinci-pas@2.0.1 |
PASClaim, PASClaimResponse, … |
Validation with Firely .NET SDK
The first pipeline validates generated resources using the Firely .NET SDK validator (v3.0.1). Results are published as live badges:
11 profiles are excluded from this pipeline due to schema loading issues in the Firely SDK. These profiles validate successfully with the HL7 Java Validator below. Details in docs/FIRELY-VALIDATOR-BUGS.md.
Validation with HL7 Java Validator
The second pipeline validates using the official HL7 FHIR Validator (v6.3.11), the reference implementation for FHIR conformance checking:
Terminology validation requires a tx server. The pipeline uses
--tx-server https://tx.fhir.org/r4during generation to expand ValueSets and produce valid codes.
Installation
Install globally (recommended when using the CLI frequently):
npm install -g babelfhir-tsOr invoke on-demand without a global install:
npx babelfhir-ts --helpRequirements: Node.js 18+ (ESM support) and an internet connection when downloading packages from remote registries.
Quick start
Generate code from a local folder that contains FHIR packages:
babelfhir-ts input/ output/Process a single package archive and write the generated interfaces back into a new .tgz file:
babelfhir-ts hl7.fhir.us.core-8.0.0.tgz us-core-generated.tgzDownload and process a package directly from a registry (defaults to https://packages.simplifier.net):
babelfhir-ts --package hl7.fhir.us.core@8.0.0Download, process and install a processed package into your current project:
babelfhir-ts install hl7.fhir.us.core@8.0.0After generation you can import the emitted classes:
import { USCorePatientClass } from "./output/USCorePatientClass";
const patient = USCorePatientClass.random();
const { errors, warnings } = await patient.validate();Using the generated code in your project
Generated profile packages installed via babelfhir-ts install are published as compiled JavaScript with TypeScript declarations:
- JavaScript for runtime:
index.js,*.js - Type declarations for IDE/TS:
index.d.ts,*.d.ts - Dependencies:
@types/fhiris included as a dependency of the generated package (no extra setup in your app)fhirpathis a peer dependency (required only if you use the generated validators/classes)
Install fhirpath in your app if you plan to call .validate() or use the generated classes.
Module resolution
Generated packages work with all modern TypeScript setups:
- Node.js 18+ with
"type": "module"inpackage.json - Bundlers (Vite, esbuild, Webpack) with ESM output
- TypeScript 5.0+ with any module resolution (
node16,nodenext, orbundler)
FHIR type imports
Generated code imports base FHIR types from "fhir/r4":
import { Appointment, Extension, CodeableConcept } from "fhir/r4";Since @types/fhir doesn't provide a package.json exports field, BabelFHIR-TS includes an ambient module declaration (fhir-r4.d.ts) in every generated package. The generated index.d.ts references this file:
/// <reference path="./fhir-r4.d.ts" />This ensures TypeScript can resolve fhir/r4 imports automatically without any configuration in your project's tsconfig.json.
CLI reference
babelfhir-ts [options] [<input> [output]]| Argument / option | Description |
|---|---|
<input> |
Directory of FHIR packages/StructureDefinitions, single package (.tgz/.zip), or single StructureDefinition .json. Defaults to ./input when omitted. |
<output> |
Destination directory or archive. Defaults to ./output when omitted. |
install |
Downloads, processes, and installs a package as a project dependency. |
--package <pkg@version> |
Fetch a package from a registry and process it without manual download. |
--registry <url> |
Custom registry base URL (default:https://packages.simplifier.net). |
--tx-server <url> |
Terminology server URL for ValueSet expansion (e.g., https://tx.fhir.org/r4). When set, expands ValueSets without explicit codes using the $expand operation. |
--log <level> |
Control logging output:none (default), console, or file. |
--no-cache |
Remove the .cache directory once generation completes. |
--no-classes |
Skip emitting helper classes (interfaces & validators only). |
--cache-dir <path> |
Custom cache directory (default:.cache). Also configurable via FHIR_CACHE_ROOT env var. |
-h, --help |
Print usage help. |
-v, --version |
Print the BabelFHIR-TS version. |
Supported inputs
- Directory – scan all
.tgz,.zip, or.jsonfiles inside the folder - Archive – process a FHIR NPM package in
.tgzor.zipformat - StructureDefinition JSON – generate code for a single profile definition
Scripts for contributors
| Script | Purpose |
|---|---|
npm run generate |
Execute the CLI against the local input/ folder and refresh output/. |
npm run generate:check |
End-to-end check: generate, type-check, and lint the emitted output. |
npm test |
Type-check and run all Vitest suites (coverage enabled). |
npm test pipelineParity |
Run pipeline parity tests against Firely .NET SDK validator. |
Caching notes
The generator caches downloaded StructureDefinitions and packages inside .cache/. When you need a clean run, pass --no-cache or manually remove the folder. Temporary downloads land in .temp-* directories and are cleaned up automatically.
Why BabelFHIR-TS?
The FHIR Challenge: Implementation Guides define strict profiles that constrain base FHIR resources with required or must-support elements, custom extensions, value set bindings, and cardinality rules. Existing TypeScript libraries can't capture these requirements when you need profile-specific types, leading to an overhead when using TypeScript to build apps that interact with FHIR servers.
The BabelFHIR-TS Solution: Automatically generates TypeScript interfaces and validation logic directly from StructureDefinition JSON. Your IDE autocompletes required fields, flags missing extensions at compile-time, and validates FHIRPath invariants at runtime.
Limitations
BabelFHIR-TS is a code generation tool that parses FHIR StructureDefinitions and produces TypeScript interfaces and validators. While it handles many common FHIR profiling patterns, there are important limitations to be aware of:
Profile Mapping Accuracy
- Not guaranteed for all IGs: The generator uses heuristics to interpret StructureDefinition constraints, slicing rules, and extensions. Complex or unusual profiling patterns may not map correctly to TypeScript.
- Test before production: Always validate the generated code against your specific Implementation Guide's examples and test cases. We recommend running the official FHIR validator alongside BabelFHIR-TS in your QA pipeline.
- Edge cases: Rare profiling constructs (deeply nested slicing, conditional constraints, complex discriminators) may generate suboptimal or incomplete types.
Validation Scope
The generated validate() methods DO check:
- FHIRPath constraints from StructureDefinition invariants
- Cardinality rules (min/max occurrences)
- Required fields from profiles
- Pattern constraints (patternCodeableConcept, patternCoding)
- Slice validation for common patterns (coding arrays, BackboneElement slices)
- Data type correctness (string, number, boolean, etc.)
The generated validators DO NOT check:
- Terminology validation (ValueSet expansion, code system membership) - requires terminology server
- Reference resolution (checking that referenced resources exist) - requires FHIR server
- Complex discriminator types (type, profile, exists, position) - only pattern/value discriminators supported
- Cross-resource business rules - application-specific logic
For comprehensive conformance testing, use the official HL7 FHIR Validator!
TypeScript Limitations
- Runtime type checking is limited: TypeScript types are erased at compile time. The generated interfaces provide compile-time safety but cannot enforce constraints at runtime without the validator functions.
- Extension slicing: While the generator creates typed extension interfaces, TypeScript cannot enforce that extension arrays contain exactly the required slices at compile time (this is validated at runtime).
- Choice types: FHIR's
[x]choice types (e.g.,value[x]) are represented as union types in TypeScript, which may require runtime type narrowing.
Generated Helper Methods
random()is not fully conformant: The generated.random()methods create test data that satisfies TypeScript types and basic cardinality, but do not guarantee fully valid FHIR resources. Random data may violate:- Complex FHIRPath invariants
- ValueSet bindings (codes are randomly chosen from required bindings but not guaranteed to be semantically correct)
- Profile-specific business rules
- Reference integrity constraints
Use
random()for development, testing, and prototyping, but always validate production data on the FHIR server side.validate()coverage: The generated validation methods execute FHIRPath expressions and check constraints from StructureDefinitions. They are tested against the HL7 Java Validator and the Firely .NET SDK for the Implementation Guides listed in the Continuous Validation section. Edge cases, complex slicing patterns, or profiles not in the CI pipeline may produce different results. For production conformance testing, use the official HL7 FHIR Validator as the source of truth.
FHIR Version Support
- R4 only: The current version targets FHIR R4. Support for R5, DSTU2, or STU3 is not yet available.
- Dependencies: Generated code depends on
@types/fhir(R4 definitions) andfhirpath(R4 compatible).
Reporting Issues
If you encounter an Implementation Guide that doesn't generate correctly, please open an issue with:
- The package name and version
- The specific StructureDefinition URL
- Expected vs. actual generated output
- Any validation errors or type mismatches
We continuously improve the generator based on real-world IG usage, and your feedback helps make BabelFHIR-TS more robust.
License
ISC © Maximilian Nussbaumer
Contributing
Contributions are welcome! Please read CONTRIBUTING.md for guidelines on how to contribute to this project.
Security
For security issues, please see SECURITY.md for our security policy and how to report vulnerabilities.