# @cognovis/fhir-sdk - **Purpose:** Profile-bound TypeScript SDK for the cognovis FHIR implementation guides. - **Product:** cognovis Health Platform (`chp`), module FHIR Foundation - **Role:** building-block - **Audience:** internal, partners - **Customer:** none - **Depends on:** cognovis FHIR implementation guides (`fhir`) - **Used by:** `cognovis/mira`, `cognovis/chp` - **Target state:** Moves into the chp meta-repo until a third party wants to contribute. Profile-bound TypeScript SDK for the Cognovis FHIR Implementation Guides, backed by Aidbox in ordinary application and adapter use. Install it and read or write conformant resources with typed builders and a profile-scoped client. Ordinary applications and adapters use the authenticated Aidbox factory; Health Samurai remains an internal provider detail. The advanced transport seam and package bootstrap continue to support standard FHIR servers that have the release closure loaded. - Licence: Apache-2.0 - Published `0.23.1` runtime dependencies are pinned exactly: `@cognovis/fhir-release@0.4.13`, `@cognovis/fhir-deidentification-sdk@0.16.1`, and the temporary `@cognovis/aidbox-client-upstream@0.0.0-alpha.7.cognovis.1` bridge. The bridge is built from Cognovis Aidbox client source commit `72a90f2` and is replaced by an exact official Health Samurai release when the upstream contribution ships. ### Migrating to 0.24.0 `@cognovis/fhir-sdk/client` is browser-safe: its import graph reaches no `node:*` module, no `pgsql-ast-parser` and no `@cognovis/fhir-deidentification-sdk`. The Node-only capabilities moved to the new `@cognovis/fhir-sdk/node` entry: - the client members `sqlOnFhir`, `unsafe`, `bootstrap.ensureSearchIndexes`, `bootstrap.ensureViewIndexes`, `withDeidentification` and `withSourceDeidentification`; - the runtime helpers `anonymousExport`, `developmentPseudonymized`, `sourceDeidentificationFieldRules`, `columnDeidentification`, `STANDARD_VIEW_DEFINITION_CANDIDATES`, `codeCategoriesOf`, `codeCategoryOperand`, `jsonbArrayOperand` and `CODE_CATEGORY_UNCLASSIFIED`. `/node` exports everything `/client` exports under the same names, so a Node consumer that uses any of them changes its import path from `@cognovis/fhir-sdk/client` to `@cognovis/fhir-sdk/node` and nothing else. The root entry `@cognovis/fhir-sdk` re-exports `/node` and keeps every export. Type-only exports such as `SqlQueryLibrary`, `ViewDefinition` and `DeidentificationPolicy` stay available from `/client`. A browser application keeps importing `/client` and needs no `node:crypto` shim. ### Migrating to 0.22.0 Dental 0.57.0 changes the ZE finding and therapy accessors on `DentalCarePlanDEProfile`, `AlignerCarePlanDEProfile`, `OsasOralApplianceCarePlanDEProfile` and `PrimarySnoringCarePlanDEProfile`. Their `setZeBefundkuerzel` and `setZeTherapiekuerzel` methods now take a structured extension (`Omit | Extension`). Pass the extension or a generated ZE extension profile's `toResource()` instead of a string or profile object. The matching getters take no mode and return `Extension | undefined`; read its `valueCode` or `valueCoding` explicitly. DPF codings preserve their finding/therapy namespace, case and tooth context. EBZ consumers read the payer decision from `DentalPlanPASClaimResponseDEProfile`'s `payerDecision` extension (`approved`, `rejected`, `changed-approval`). The native processing outcome is separate. `preAuthPeriod` carries approval validity; rejected decisions carry neither approval date nor validity. ## Source and problem reports The package ships its TypeScript source in `src/`, without tests and test fixtures. The source maps in `dist/` resolve to those files, so a debugger opens the original source. The repository the package is built from is not public. Report a problem by email to info@cognovis.de. Name the package version and include the request or resource that shows the problem, with synthetic data only. ## Install The package and its Cognovis dependencies live in the Cognovis npm registry, so the registry and a token must be configured before installing. The package ships no `.npmrc`; put the token in your own: ```ini # ~/.npmrc @cognovis:registry=https://npm.cognovis.de //npm.cognovis.de/:_authToken= ``` ```sh bun add @cognovis/fhir-sdk ``` ### Supported runtime The package root and every public subpath load under plain Node ESM. The browser-facing entries `/client`, `/dental`, `/dental-core`, `/r4`, `/release-profiles`, `/release-compatibility`, `/terminology` and `/canonicals` import no Node built-in and no Node-only dependency, so a browser bundler such as Vite builds them without shims; `src/__tests__/browser-entry-points.test.ts` pins that over the built package. The root entry, `/node` and `/bootstrap` are Node-only. The ordinary Aidbox factory dynamically loads the temporary bridge, whose inherited extensionless imports require Bun, tsx, or a bundler at the point that factory is called. The exact `@cognovis/fhir-release` dependency carries the generated profile modules used by the root and dental entry points. ## Quickstart ```ts import { createAidboxFhirClient, defineProfile } from '@cognovis/fhir-sdk/client' import { buildDentalCondition } from '@cognovis/fhir-sdk/dental' import { DentalConditionDEProfile } from '@cognovis/fhir-sdk/release-profiles' const baseUrl = 'https://aidbox.example.com' // Aidbox root, not its /fhir path const client = await createAidboxFhirClient({ baseUrl, clientId, clientSecret, writeSource: 'urn:example:application', }) const conditions = client.forProfile(defineProfile(DentalConditionDEProfile, 'Condition')) const created = await conditions.createResource( buildDentalCondition({ code: { system: 'http://fhir.de/CodeSystem/bfarm/icd-10-gm', code: 'K02.1' }, subject: { reference: 'Patient/p-1' }, }) ) const readBack = await conditions.read(created.toResource().id!) ``` A complete, runnable flow against Aidbox — write, read back — is [`examples/odontogram-round-trip.ts`](examples/odontogram-round-trip.ts). ## The client `@cognovis/fhir-sdk/client` (browser-safe) and `@cognovis/fhir-sdk/node` (Node). The `/node` client is the `/client` client plus SQL on FHIR (`sqlOnFhir`), raw SQL (`unsafe`), index bootstrap and the deidentification scopes; the rows marked *(node)* exist only there. | Export | Purpose | | --- | --- | | `createAidboxFhirClient(config)` / `FhirClient` | Ordinary authenticated Aidbox-backed client. | | `client.forProfile(descriptor)` | A `ResourceClient` for one release-owned profile; its resource type is bound once in `defineProfile`. | | `client.forResourceType(resourceType)` | A heterogeneous `ResourceFamilyClient` that resolves each returned or prebuilt resource through its declared release-owned leaf profile. | | `loadReleaseCoreResourceProfile(resourceType)` | Loads the exact generated HL7 R4 base descriptor from the pinned release closure for profileless native resources. | | `defineHistoricalReadAlias(binding)` | Binds one exact retired profile identity to a matching R4 base descriptor for explicit compatibility reads. | | `client.withSourceDeidentification(policy, callback)` *(node)* | GET-only source-store reads whose selectors stay literal while returned resource graphs are deidentified. | | `createFhirClient({ transport })` / `FhirTransport` | Advanced seam for tests, replay, and deliberately implemented alternate stores. | | `createFetchTransport(options)` | Ready-made fetch transport. | | `RequestOptions` | Per-request positive deadline (`timeoutMs`) and caller `AbortSignal`. | | `JsonPatchOperation` / `JsonPatchOptions` | Closed RFC 6902 operation union and conditional request controls for profile-bound `patch`. | | `client.metadata(options?)` | Typed FHIR-root `GET /metadata`; no arbitrary root request escape hatch. | | `client.searchResourceProjection(resourceType, params, options)` | Complete, bounded reads of partial `_elements` projections without treating them as complete profiles. | | `client.operations.fhirPackageInstall(input, options?)` | Typed Aidbox FAR package installation and receipt validation. | | `FhirHttpError` / `FhirProfileMismatchError` | Error types. | | `FHIR_SDK_ERROR_CODES` | Stable error-code catalogue. | | `extractNextPageUrl(bundle)` | Relative URL of a search bundle's `next` link. | `ResourceClient` offers `read`, one-page `search`, `next`, `create`, `createResource`, `update` and `delete`. `search` returns `{ items, included, total, next }`; included resources require an explicitly declared descriptor and continuations are opaque capabilities accepted only by their issuing client. Use `forResourceType()` when a search can return several valid leaves of the same FHIR resource type. Each result is `{ canonical, value }`; `canonical` is the resolved release canonical for intentional narrowing. Resolution reads only `meta.profile`, selects a declared most-derived profile from the pinned release registry, and fails closed with `profile-missing`, `profile-unknown`, `profile-unsupported`, or `profile-ambiguous`. It does not guess an R4 base profile or apply application-specific dispatch. `forProfile()` remains the right API when the caller deliberately requires one exact homogeneous profile. `forProfile(...).search` and `forResourceType(...).search` read an entry without `search.mode` as a `match` only in a `Bundle` of type `searchset` whose request declared no includes: no `includeDescriptors` and no `_include`/`_revinclude` parameter on the search or its continuation. Otherwise a modeless entry fails with `profile-validation`. Paging follows the `next` relation of `Bundle.link`; only when `link` is absent does it read Aidbox's non-standard `Bundle.links` with the same shape. A `next` relation without a usable URL fails with `profile-validation` instead of ending the search. `searchResourceProjection()` is the explicit read-only seam for partial `_elements` responses, which cannot satisfy a complete profile validator. It requires positive `pageSize` and `maxPages` bounds plus the confined resource-type continuation policy. By default, every entry must declare `search.mode = match` and every additional page must have a `next` link, read from `Bundle.link` or, only when `link` is absent, from Aidbox's `Bundle.links`. A `next` relation without a usable URL fails with `profile-validation`. Aidbox callers may opt into `missingSearchMode: 'match'` and `missingNextLink: 'page-number'`; the page-number fallback applies only when the Bundle has no `next` relation at all. A full final allowed page fails when more data remains; the client never silently truncates the result. `paginationOriginAliases` on the Aidbox factory applies to both profile-bound and resource-family continuations. It accepts origin-only public addresses emitted in absolute page links. An accepted link must retain the configured FHIR base path and searched resource-type path. The client rewrites it to the configured internal origin before authenticated dispatch, so credentials are never sent to the alias. The shipped registry is generated from the exact `@cognovis/fhir-release` dependency. A reviewed generator-only override may supply different profile definition bytes when the release manifest binds the package, closure version, generator version, archive digest, and review reason. This affects generated validators and registry metadata only; the installed release closure remains the runtime dependency contract. Runtime-only ZTS terminology packages do not contain generated profile validators and remain outside profile-definition archive discovery. A regenerated registry entry may record the exact `StructureDefinition.version` read from its verified package archive. Its bare URL and `URL|version` then resolve to one identity, including when both appear in `meta.profile`. Other versions remain unknown. The SDK preserves declarations for the concrete validator; it never strips a version suffix to make a resource pass. Package versions do not substitute for definition versions. Registry generation follows each selected validator's exact package dependency graph and rejects conflicting profile provenance. A selected validator with a missing or type-mismatched root definition or an unresolved ancestor stops generation with its canonical and the unresolved identity. An unversioned ancestor matching conflicting definitions is rejected; the generator does not guess a preferred version. JSON archive members are classified by `resourceType`, so support does not depend on a filename prefix. When the contract deliberately uses a native R4 resource instead of a retained IG profile, load its generated base descriptor through the public SDK. The resource-specific constructor type comes from the exact pinned release package; the SDK does not recreate removed profiles or inject a replacement `meta.profile`: ```ts import { loadReleaseCoreResourceProfile } from '@cognovis/fhir-sdk/client' import type { Library } from '@cognovis/fhir-sdk/r4' const libraryDescriptor = await loadReleaseCoreResourceProfile('Library') const library: Library = libraryDescriptor.profile.createResource({ status: 'active', type: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/library-type', code: 'asset-collection', }], }, content: [{ contentType: 'application/json', data: encodedManifest }], }) const libraries = client.forProfile(libraryDescriptor) await libraries.createResource(library) ``` The loader inventory is generated for every unambiguous R4 base profile in the installed closure. It binds resource type, canonical, class, and module path; generation fails on incomplete or conflicting identities. Base adapters still provide only their generated validation contract, which may be limited to the resource-type discriminator. Use an explicit retained profile descriptor when its additional constraints are required. For a feed containing generic resources alongside declared profiles, opt in each generic resource type with its published R4 base descriptor: ```ts import { defineProfile } from '@cognovis/fhir-sdk/client' import { CompositionProfile } from '@cognovis/fhir-sdk/r4' const compositions = client.forResourceType('Composition', { genericReadProfiles: [defineProfile(CompositionProfile, 'Composition')], }) const page = await compositions.search({ subject: 'Patient/patient-1', _count: '50' }) for (const item of page.items) { const resource = item.value.toResource() } ``` This option applies only to `read`, one-page `search`, and explicit `next` calls. An absent or empty `meta.profile`, or exactly the configured base canonical, selects that descriptor. Other declarations still use strict concrete profile resolution. Unknown declarations, base-plus-unknown declarations, sibling profiles, malformed metadata, and invalid concrete-profile payloads never retry as generic. Without this option, the existing required-declaration behavior is unchanged. Each configured descriptor must have the matching `http://hl7.org/fhir/StructureDefinition/` canonical. Configure included generic resource types separately in the same `genericReadProfiles` array; configuring a primary type does not authorize generic includes of other types. Continuations retain this configuration and remain bound to their issuing client and FHIR origin. A search never follows its next link automatically. Generic values expose `toResource()` over the raw result of the supplied base adapter, preserving its fields and metadata. Its public type guarantees only the verified literal `resourceType`; other fields are `unknown` until the caller validates them. The literal base `canonical` distinguishes this value from known concrete profile instances in a mixed result. Validation is exactly that adapter's `from()` contract plus SDK resource-type and metadata checks. Some published base adapters check only the resource type; this option does not add full R4 schema validation. Declared profiles retain their concrete validators. Writes, batches, transactions, and bulk submissions do not gain a generic fallback from this option. Existing records can retain a profile canonical whose `StructureDefinition` was deliberately removed from the current release. Admit each such identity explicitly and bind it to the matching generated R4 base descriptor: ```ts import { defineHistoricalReadAlias, loadReleaseCoreResourceProfile, } from '@cognovis/fhir-sdk/client' const documentReferenceBase = await loadReleaseCoreResourceProfile('DocumentReference') const legacyDocument = defineHistoricalReadAlias({ canonical: 'https://records.example.org/fhir/StructureDefinition/legacy-document', resourceType: 'DocumentReference', descriptor: documentReferenceBase, }) const documents = client.forResourceType('DocumentReference', { historicalReadAliases: [legacyDocument], }) const result = await documents.read(documentId) if (result?.canonical === legacyDocument.canonical) { const original = result.value.toResource() // retains all fields and meta.profile } ``` `historicalReadAliases` uses exact equality. It performs no prefix, namespace, glob, version stripping, or unversioned-to-versioned matching. To read both a bare canonical and `canonical|1.2.3`, declare two entries. Every entry must name an absolute HTTP(S) canonical, repeat the descriptor's resource type, and carry the matching `http://hl7.org/fhir/StructureDefinition/` descriptor. Duplicate identities, conflicting base descriptors, current-release identities, malformed canonicals, and resource-type mismatches fail during configuration. The option applies only to point reads, search matches, search includes, and continuations. A historical result is validated by its bound R4 base descriptor, then returned from an independent snapshot with its original fields and declared canonicals unchanged. One historical identity may coexist with its exact R4 base canonical. Unknown neighbours, multiple unrelated historical identities, or any mixture with a current-release profile lineage fail closed. Configure aliases for included resource types in the same finite array. With `validateAllDeclaredProfiles: true`, the reader validates every configured base or historical declaration and every current-release declaration it accepts. This explicit mode can validate one historical identity beside current-release declarations of the same resource type; default resolution rejects that mixture as ambiguous. Unknown identities, wrong resource types, and multiple unrelated historical identities still fail closed. The result's `canonicals` array preserves the accepted declarations in their original first-occurrence order. Current-release profiles continue to use their generated descriptor and lineage rules. Aliases never enter `RELEASE_PROFILE_REGISTRY` and never authorize `createResource`, `update`, JSON Patch, batch, transaction, or bulk validation. Write preflight rejects a configured historical declaration before dispatch, so new writes remain bound to current release profiles even when the same family client is configured for historical reads. The family client resolves its `read`, search matches, search includes, and `next`-page results independently; `createResource` and `update` return the same resolved shape. A resource declaring a leaf and one of its ancestors is resolved to that leaf while its declared compatible ancestor remains in `meta.profile`. Incomparable sibling leaves, an absent declaration, or a foreign declaration outside that lineage fail instead of depending on profile order. This also keeps catalog and rule `ChargeItemDefinition` resources distinct without inspecting business fields. Family `batch` and `transaction` resolve and validate descriptor-less `POST` and `PUT` submissions before dispatch and descriptor-less `GET` results before returning them. Entries with an explicit `descriptor` use the same descriptor validation as the top-level `batch` and `transaction` methods. Family `bulk.submit` does the same for every NDJSON row before the provider is called. Thus prebuilt heterogeneous inputs retain their declared profiles and receive the configured `meta.source`; do not replace this with an application-owned canonical map. `DELETE` remains an id-only operation and has no authoring profile to resolve. The committed `RELEASE_PROFILE_REGISTRY`, `./r4`, `./release-profiles`, and `./release-compatibility` surfaces are generated from the installed `@cognovis/fhir-release` closure. `bun run generate:release-profiles` verifies each source FHIR package archive against the manifest SHA-256 and derives lineage from its `StructureDefinition.baseDefinition`; `bun run check:release-profiles` verifies the committed closure digest, validator inventory, generated export surfaces and package identity without downloading archives. - `read(id)` returns `null` — a "not found" is valid absence. - `search(params)` throws a stable `FhirSdkError` — a 404 on a search endpoint is a transport failure, not an empty result. An empty result is HTTP 200 with an empty bundle. - `delete(id)` returns normally — deletion is idempotent. The ordinary Aidbox factory also accepts successful empty HTTP 204 responses for profile and resource-family deletion; other HTTP failures retain their status. `bulk`, typed `operations`, and intent-specific `bootstrap` are capability groups on the same client. Store-side credentials and AccessPolicy remain authoritative; there is no caller elevation flag. `createAidboxFhirClient` rejects insecure HTTP through its authentication provider by default. `allowInsecureRequests: true` is an explicit local/test-only transport opt-in for an HTTP Aidbox instance such as `127.0.0.1`; it grants no FHIR operation, resource, or administrative authorization. Production clients must use HTTPS and leave this option unset. ### Root metadata and bounded requests Applications can replace a root `fetch` probe, timeout-capable handwritten transport, and application-owned profile dispatch with the public client surface. Use only a named root operation plus `RequestOptions` on the operation being bounded: ```ts import { createAidboxFhirClient, type RequestOptions, } from '@cognovis/fhir-sdk/client' const controller = new AbortController() const request: RequestOptions = { timeoutMs: 2_000, signal: controller.signal } const client = await createAidboxFhirClient({ baseUrl, clientId, clientSecret }) const capability = await client.metadata(request) // exactly GET /metadata const patient = await client.forProfile(patientDescriptor).read(patientId, request) const coverages = client.forResourceType('Coverage') const firstPage = await coverages.search({ _count: '50' }, request) for (const resolved of firstPage.items) { // Narrow on resolved.canonical only where leaf-specific behavior is required. console.log(resolved.canonical, resolved.value) } const nextPage = firstPage.next ? await coverages.next(firstPage.next, request) : undefined ``` Resource-family reads normally require one most-derived release profile. For resources that legitimately declare independent profiles, explicitly opt in: ```ts const patients = client.forResourceType('Patient', { validateAllDeclaredProfiles: true }) const result = await patients.read(patientId, request) if (result) { console.log(result.canonicals) // all validated declared release identities const resource = result.value.toResource() // complete resource, including meta.profile } ``` This read mode validates every supported declared profile independently, including explicitly declared ancestors, and fails on unknown declarations, unsupported exact versions, wrong resource types, or any validation failure. Known lineage-only ancestors remain permitted. `canonicals` preserves declared version aliases and contains supported declarations in first-occurrence order. It provides no single `canonical` discriminator or generated leaf-class narrowing. Each `toResource()` returns an independent copy of the original validated resource. Search matches, included resources and continuations use the same mode. When combined with `genericReadProfiles`, valid undeclared/base-only resources return a singleton base canonical set; unknown profiles never fall back to that base. The default read result and all create, update, PATCH, batch, transaction and bulk validation remain strict; the opt-in does not permit ambiguous writes. This also applies to GET entries in batch and transaction requests: only point `read`, `search` and `next` use the opted-in validated-set result. Both modes require the pinned registry and its generated validator to accept each exact version declaration. In release `0.2.9`, the KBV Patient registry declares `1.8.0`, but the generated validator checks `1.9.0`: a version-only `KBV_PR_Base_Patient|1.8.0` declaration therefore fails with `profile-validation`. The SDK does not inject a bare canonical, rewrite aliases or bypass validation to repair that upstream disagreement. A registry-known version is necessary, but not sufficient, for successful validation. The opt-in eagerly snapshots the raw resource before validating independent copies, including generic base reads. Descriptor transformations do not replace that raw result. Non-cloneable raw input fails during the read with `FhirSdkError` code `profile-validation` and the original cloning error as `cause`; it does not defer a raw cloning exception until `toResource()`. Profile-bound partial writes use RFC 6902 JSON Patch: ```ts const updated = await client.forProfile(taskDescriptor).patch(taskId, [ { op: 'test', path: '/status', value: 'requested' }, { op: 'replace', path: '/status', value: 'in-progress' }, ], { ifMatch: 'W/"4"', timeoutMs: 2_000, signal: controller.signal }) ``` `patch` sends exactly one `PATCH` to the bound resource type and validated ID with `application/json-patch+json`. It preserves operation order, JSON Pointer escapes, null and false values, and the supplied `If-Match`. It supports `add`, `remove`, `replace`, `move`, `copy` and `test`; extra operation members, malformed pointers and non-JSON values fail before dispatch. The SDK does not perform a preceding read or replace the mutation with PUT. It adds a `meta.source` operation only where the client's `patchWriteSource` names the resource type: ```ts const client = createFhirClient({ baseUrl, transport, writeSource: 'my-app', // For example the types a store-to-source adapter writes back. patchWriteSource: async (resourceType) => writtenBackTypes().has(resourceType), }) // A non-empty ChargeItem patch then ends with // { op: 'add', path: '/meta/source', value: 'my-app' }. ``` The decision runs after the operations validate, for `patch`, family `patch` and every `PATCH` entry of a transaction or batch. A failing decision sends no request; an empty patch stays empty. Without the option a patch keeps the stored `meta.source`. Successful resource responses pass through the selected profile validator; 204 and empty successful responses return `undefined`. HTTP failures preserve their status and OperationOutcome on `FhirSdkError`, without mutation retries or credential fallback. For an optimistic concurrency conflict, check `error.status === 412`; the general `error.code` is `'transport'` and does not distinguish this status from other HTTP failures. HTTP-derived `FhirSdkError` instances now retain `status` for all resource-client operations, including existing reads and writes. For a heterogeneous family, pass the existing resource you already read: ```ts const tasks = client.forResourceType('Task') const existing = await tasks.read(taskId) if (!existing) throw new Error('Task is missing') const updated = await tasks.patch(existing.value.toResource(), [ { op: 'replace', path: '/status', value: 'in-progress' }, ], { ifMatch: 'W/"4"', signal: controller.signal }) if (updated) console.log(updated.canonical, updated.value.toResource().id) ``` `forResourceType().patch(existingResource, operations, options)` derives the ID and exact release profile from that context before dispatch. It snapshots the context, operations and request options before asynchronous profile loading. The context must have a matching resource type, valid ID and one unambiguous release-owned leaf declaration; the declared profile validates both context and response. The result is a canonical-discriminated release value or `undefined` for an empty success. This method performs no additional read. An unknown declaration fails before dispatch. `genericReadProfiles` remains a read-only option: unprofiled resources require an explicit `forProfile(base)` write contract. Pass an `If-Match` from the same observed resource version when concurrent changes must be rejected; the context alone does not impose one. JSON Patch is rejected before dispatch inside deidentified target-store scopes because arbitrary paths and values cannot safely use the whole-resource transform. FHIRPath Patch is not part of this operation; a transaction or batch carries JSON Patch as a `PATCH` entry (see Workforce transactions). `timeoutMs` must be positive and finite. A timeout throws `FhirSdkError` with `code: 'timeout'`; a caller-aborted signal throws `code: 'cancelled'`. Both are safe SDK errors and do not expose transport URLs, credentials, provider objects, or response bodies. Request controls cannot alter authorization and do not add an arbitrary root-path API. They are accepted by `metadata`, exact-profile and family `read`, `search`, `next`, `create`/`createResource`, `update`, and `delete`, plus client and family `batch`/`transaction`; omitting them preserves the previous unbounded request behavior. Bulk submission and polling keep their separate existing bulk controls rather than accepting a generic request escape hatch. With `createAidboxFhirClient`, timeout or cancellation rejects the caller's promise but does not abort the underlying in-flight HTTP request. A mutation may still be applied after that rejection. Re-read the resource to establish the outcome before deciding what to do next; do not automatically retry the mutation. The upstream Aidbox transport currently does not forward the abort signal to its HTTP fetch. `createFetchTransport` forwards the signal, but a client disconnect likewise cannot prove that the server did not apply a write. `withDeidentification(policy, callback)` (`@cognovis/fhir-sdk/node`) scopes one resource-level de-identification policy across nested, batch, and multi-resource calls. The callback receives the same profile-bound client. Writes and instance addresses use one transformation context so references and `Bundle.entry.fullUrl` stay consistent. The two ADR-009 policies are `development-pseudonymized` (structured PII is transformed; the result remains pseudonymized personal data) and `anonymous-export` (a technical no-relink transform whose in-memory secret and mapping are destroyed in `finally` on success and failure). The policy name is not a legal or DSGVO anonymization claim, does not authorize Zone-C or third-party disclosure, and does not replace a purpose-specific re-identification risk assessment. Since `@cognovis/fhir-deidentification-sdk` 0.15, `anonymous-export` fails closed on data the PII catalogue does not state: uncatalogued strings are redacted or, when date-shaped, date-shifted, and an unlisted `modifierExtension` or a resource type without catalogue entries is refused. It emits export-local identities only: `urn:uuid:` full URLs and relative internal references, so a deidentified Bundle carries no source base URL. Both policies date-shift MedicationStatement `effective[x]` and `dateAsserted`, DeviceUseStatement `timing[x]` and `recordedOn`, and Observation `issued` with the scope's offset (PII catalog 1.4.1). ```ts import { anonymousExport, developmentPseudonymized, } from '@cognovis/fhir-sdk/node' await client.withDeidentification(developmentPseudonymized(), async (scoped) => { return scoped.forProfile(patientDescriptor).search({ _count: '20' }) }) ``` `withSourceDeidentification(policy, callback)` is the separate read boundary for an identified canonical source store. Source instance ids and search selectors such as `patient` and `subject` are forwarded unchanged. The callback receives only `forProfile`; its profile client exposes `read`, `search`, and `next`, with no writes and no transport access. A search transforms its complete Bundle in one graph operation, so transformed ids, literal references, and full URLs stay consistent. Resources fetched earlier in the same callback remain graph anchors for later responses; that state is cleared and retained readers fail closed when the callback ends. Every match and include must have an explicit public descriptor. Descriptors can be imported directly or loaded with `releaseProfileEntry()` and `loadReleaseProfileDescriptor()` from the release registry. Continuations retain the descriptors declared by the issuing search. ```ts await client.withSourceDeidentification( developmentPseudonymized(), async (source) => { const patient = await source.forProfile(patientDescriptor).search({ _id: authorizedPatientId, }) const conditions = await source.forProfile(conditionDescriptor).search( { patient: `Patient/${authorizedPatientId}` }, { includeDescriptors: [patientDescriptor] }, ) return { patient, conditions } }, ) ``` A source scope also scrubs known names from free text. Every resource whose transform and profile post-validation succeed adds its HumanName `family` and `given` values and their name tokens (each longer than two characters, without name particles such as `von` or `der`) to a set owned by the scope, and every later transform in the scope removes all values collected so far, as whole words, from the free-text fields its policy scrubs, such as `MedicationRequest.dosageInstruction.text` or `Condition.code.text`. A resource whose transform or validation fails adds nothing. A name therefore applies to the resource it came from and to every resource transformed later in the same callback, never to a resource transformed earlier. Read the subject first: read the Patient (and any other person whose name may appear in free text) before the resources whose text may mention them. Under `anonymous-export` every scrubbed free-text field is fully redacted, so known values add nothing there. The collected values stay inside the scope: they are not part of errors or returned resources, and the set is cleared when the callback ends, so a later scope starts empty. ```ts await client.withSourceDeidentification(developmentPseudonymized(), async (source) => { // The Patient's names are scrubbed from the MedicationRequest's free text. await source.forProfile(patientDescriptor).read(authorizedPatientId) return source.forProfile(medicationRequestDescriptor).search({ subject: `Patient/${authorizedPatientId}`, }) }) ``` `sourceDeidentificationFieldRules(policy)` lists, in catalog order, the de-identification field rules a policy applies as `{ resourceType, path, method }` rows: the PII catalog entries of mode `analytics` for `developmentPseudonymized()` and of mode `llm-anonymized` for `anonymousExport()`. Each call returns new objects, so changing a result does not change the catalog or a later call. Use it to assert which fields a scope transforms without depending on the de-identification package directly. The Bundle `entry.fullUrl` rows are listed as catalogued, but the transform does not apply their method to `entry.fullUrl` directly: it rewrites each `fullUrl` together with the references to it, so they stay equal. ```ts import { developmentPseudonymized, sourceDeidentificationFieldRules } from '@cognovis/fhir-sdk/node' const rules = sourceDeidentificationFieldRules(developmentPseudonymized()) // includes { resourceType: 'MedicationRequest', path: 'dosageInstruction.text', method: 'scrubFreeText' } ``` `withDeidentification` remains the target-store boundary: it maps instance ids and `_id`, constrains selectors, and supports transformed writes. Use the source scope only when authorization must address an identified source store and the returned graph must be deidentified before application use. Transform failures throw `CognovisDeidentificationError` (`code: 'deidentification'`). The producer engine result type is not part of this public surface. Column-level de-identification for tabular views, `$run`, `$sqlquery-run`, and table materialization is a different seam from resource-level `withDeidentification`. It is expressed on ViewDefinition columns through `columnDeidentification` helpers and applies only to the SQL-on-FHIR path. A de-identified ViewDefinition can be materialized only as a `table`. Keys never appear in generated-SQL evidence, errors, receipts, or package artifacts. The normal read-model order is FHIR search/read with batch enrichment and lazy detail loading, then live ViewDefinitions and `$sqlquery-run`, then a measured immutable snapshot generation. Applications do not connect to Aidbox PostgreSQL. `sqlOnFhir` and `unsafe` are members of the `@cognovis/fhir-sdk/node` client. `unsafe.rawSql` is isolated, requires the already-authorized administrative grant, and is not the ordinary view or snapshot path. ```ts await client.sqlOnFhir.viewDefinitions.create(view) await client.sqlOnFhir.viewDefinitions.run({ viewReference: view.id, format: 'json', limit: 20 }) const sql = await client.sqlOnFhir.viewDefinitions.sql({ viewReference: view.id }) const table = await client.sqlOnFhir.viewDefinitions.materialize({ viewReference: view.id, type: 'table' }) await client.sqlOnFhir.sqlQueries.run({ libraryId: 'patient-count', format: 'fhir', parameters: { gender: 'female' } }) ``` | SDK method | Aidbox operation | | --- | --- | | `sqlOnFhir.viewDefinitions.create` | `POST /fhir/ViewDefinition` — id optional | | `sqlOnFhir.viewDefinitions.read` | `GET /fhir/ViewDefinition/{id}` — `null` on 404 | | `sqlOnFhir.viewDefinitions.update` | `PUT /fhir/ViewDefinition/{id}` — id required | | `sqlOnFhir.viewDefinitions.delete` | `DELETE /fhir/ViewDefinition/{id}` | | `sqlOnFhir.viewDefinitions.run` | `POST /fhir/ViewDefinition/$run` (`viewReference`, `resource`, `group`, `_since`, `_limit`, `_format`; never `patient`). `Accept` follows `_format`: `application/json`, `application/x-ndjson`, `text/csv`. | | `sqlOnFhir.viewDefinitions.sql` | `POST /fhir/ViewDefinition/$sql` — generated SQL evidence only | | `sqlOnFhir.viewDefinitions.materialize` | `POST /fhir/ViewDefinition/$materialize` (`view`, `materialized-view`, `table`) | | `sqlOnFhir.sqlQueries.create` | `POST /fhir/Library` — id optional | | `sqlOnFhir.sqlQueries.read` | `GET /fhir/Library/{id}` — `null` on 404 | | `sqlOnFhir.sqlQueries.update` | `PUT /fhir/Library/{id}` — id required | | `sqlOnFhir.sqlQueries.delete` | `DELETE /fhir/Library/{id}` | | `sqlOnFhir.sqlQueries.run` | `POST /fhir/Library/$sqlquery-run` or `POST /fhir/Library/{id}/$sqlquery-run`. `_format=fhir` requires Library `parameter` entries with `use: "out"`. A SQLQuery Library is a single read-only `SELECT` over unqualified declared `relatedArtifact` labels, not `unsafe.rawSql`. | | `sqlOnFhir.snapshots.create` | Unique `POST /fhir/ViewDefinition` generation, `POST /fhir/ViewDefinition/$materialize` as `table`, then `POST /fhir/Library` bound to that generation | | `sqlOnFhir.snapshots.read` | `POST /fhir/Library/{id}/$sqlquery-run` against the receipt's query Library | | `bootstrap.ensureSearchIndexes` | idempotent GIN `jsonb_path_ops` on validated resource tables via administrative `POST /$sql` | | `bootstrap.ensureViewIndexes` | structured `ViewIndexSpec` compiled from the ViewDefinition model via administrative `POST /$sql`; with `{ concurrently: true }` each index is built `CONCURRENTLY` through `POST /fhir/AidboxMigration` (`execution-type: not-in-transaction`, Aidbox 2607 or later), after a `pg_index` read that keeps a valid index whose table, method, operator class and `pg_get_indexdef` column expressions match and drops an invalid or different one `CONCURRENTLY`; a second read must find it valid, and the receipt names each `outcome` (`present`, `built`, `rebuilt`) | | `unsafe.rawSql` | administrative `POST /$sql` | `$materialize` replaces a same-named object and creates no indexes. It is not atomic unless Aidbox proves otherwise. Live views stay current; snapshot generations are uniquely named, immutable, and selected by an explicit freshness or billing cut-off. Index bootstrap never slices `$sql` output. Index bootstrap compiles a closed scalar FHIRPath subset to the native store expressions (`getResourceKey()` is the physical `id`, reference keys retain the type filter). Repeated `forEach`/`forEachOrNull`/`repeat` contexts, inherited iteration, unmodelled selection contexts and collection columns are rejected before DDL. Scalar contexts support only `column`/`select` and FHIR element metadata (`id`/`extension`). Optional structured `ViewIndexSpec.expression` forms match reference-ID normalization (`reference-id`, native ID first), canonical reference normalization (`reference-string`, nonempty string first, with named type/ID columns), and recorded calendar days (`calendar-day`, first ten text characters). They accept no SQL. Provision these indexes with the separately authorized installation identity; applications keep their scoped live queries. `reference-id` accepts JSON Reference projections ending in `subject`, `beneficiary`, `actor`, `individual`, `patient`, `serviceProvider`, `performingOrganization`, `requester`, `sender`, `owner`, `context`, or `encounter`; scalar IDs, keys and `.reference` strings are rejected. Index columns may be untyped or explicitly `string`/`dateTime`. Other explicit types are rejected before DDL rather than indexed with a mismatched native cast. Two GIN strategies cover an untyped member-path column of a repeated element, which Aidbox renders as the element's JSON array text (a choice type may name its element: `medication.ofType(CodeableConcept).coding`). `jsonb-containment` indexes the array itself; a stored query compares `jsonbArrayOperand(column) @> '[{"system":"…","code":"…"}]'`. Its `with` names further such columns of the view; they become further columns of the same GIN index, so one index scan answers a condition on each (`accounts` with `performers`: the ChargeItems of one Account that name one performer). A JSON path predicate (`jsonbArrayOperand(column) @@ CAST('exists($[*] ? (… || …))' AS jsonpath)`) answers several alternative forms in that one scan as well. `code-category` (with `system`) indexes the categories of that system's codes: a code that starts with a letter and two digits (an ICD-10 category, an ATC level 2 group) becomes those three characters, every other code `*`. A stored query compares `codeCategoryOperand(column, system) @> ANY (...)` with the categories `codeCategoriesOf(prefixes)` lists (`C` reaches C00 to C99, `E11.9` reaches E11, always plus `*`) and keeps its own `LIKE` filter, which decides every row; the index only narrows the rows that filter reads. The `CREATE INDEX` runs through the administrative `$sql`, which Aidbox executes inside a transaction, so it blocks writes to the table while it builds. Snapshot reuse is identity-checked, not name-checked. A receipt matches only when `recipeViewCanonical`, ViewDefinition content digest, query Library digest, `sourceWatermark`, admission kind (and query/plan when measured), and the declared cut-off or freshness all agree. `selection.rebuildBeforeRun` skips reuse and builds a new generation. `builtAt` is captured after materialization and Library create. The bound query Library is part of the receipt; changing its SQL is a different snapshot. Bulk polling is bounded twice: 30 status requests and a 120-second deadline by default. It waits 1 second before the second request, doubles the delay through 10 seconds, and accepts `bulkPolling` defaults on `createAidboxFhirClient` or per-call overrides on `bulk.poll`. These controls change scheduling only; they do not retry the non-idempotent submission. Every submitted bulk input carries an `open()` function that streams the exact immutable bytes associated with its URL. Aidbox 2607.1 expects gzip-compressed NDJSON by default. The SDK detects gzip from those exact bytes, decompresses it as a stream, then parses and profile-validates the NDJSON before it sends the URL with `contentEncoding: "gzip"`; empty, malformed, wrong-type, or profile-invalid sources fail without submission. The upstream Aidbox contract also permits plain NDJSON, which is detected and submitted explicitly with `contentEncoding: "plain"`; one run cannot mix encodings. Preflight bounds each decoded NDJSON line to 1 MiB. Inputs containing a larger line fail before provider submission. This is an explicit trusted seam: the caller must ensure `open()` and the URL expose the same immutable compressed object for the whole operation, normally by using content-addressed storage or an upload receipt. The SDK never replaces that stream with a second resource list. A mutable URL can change after preflight, which the URL-only Aidbox `$import` primitive cannot cryptographically prevent. `bulk.batchValidateDiagnostic` must be granted separately by an Aidbox `AccessPolicy` restricted to the intended actor, resource types, and controlled environment. The SDK cannot create that authority and a boolean in application configuration never substitutes for the store-side policy. The Aidbox-backed `client.bootstrap.install` capability writes `AccessPolicy` at the tenant root and `Subscription` below the configured FHIR base. Unless the explicit real-store gates described under Development are supplied, these exact routes are mock-backed contract evidence; they are not claims that a particular Aidbox deployment accepted the fixtures. ### Errors Every profile-bound client failure carries a stable ADR-009 discriminant such as `transport`, `authorization`, `server`, `profile-validation`, or `deidentification`. `CognovisDeidentificationError` is the only public de-identification failure type. Branch on the code, not on message text: ```ts try { await conditions.create(input) } catch (error) { if ((error as { code?: string }).code === 'authorization') { // ... } } ``` `FhirHttpError` is the advanced transport SPI's HTTP signal. `ResourceClient` translates it at every operation boundary and retains its body only when that body is a FHIR `OperationOutcome`; provider response objects, headers, timing, request metadata, and bridge result envelopes never cross the public client boundary. An `OperationOutcome` may contain patient data, so do not log `FhirSdkError.outcome` raw. ## Dental builders `@cognovis/fhir-sdk/dental` Builders for the `de.cognovis.fhir.dental` guide: odontogram, periodontal and peri-implant observations, gingival thickness and recession, dental findings, conditions, periodontitis conditions, procedures, service requests and communications, plus the shared FDI tooth and surface helpers and the dental extension URLs. ```ts import { buildOdontogramObservation } from '@cognovis/fhir-sdk/dental' const observation = buildOdontogramObservation({ subject: { reference: 'Patient/p-1' }, status: 'final', toothNumber: '16', effectiveDateTime: '2026-08-25T09:00:00Z', toothPresence: { value: { system: 'http://snomed.info/sct', code: '278661005' } }, }) ``` Each builder returns a plain FHIR resource with `meta.profile` set, typed by the generated profile classes. `buildDentalRootFinding` writes the Dental Core `DentalRootFinding` for a whole tooth or, with `root`, for one root as a contained BodyStructure. ## Dental Core profile classes `@cognovis/fhir-sdk/dental-core` Applications import Dental Core profile and extension classes only from this subpath. It re-exports every generated class of the pinned `de.cognovis.fhir.dental.core` package, plus the package identity and canonical URLs already published under `@cognovis/fhir-sdk/canonicals`. Consumers do not depend on `@cognovis/fhir-release` or on its projection layout. ```ts import { ComponentBodyStructureExtProfile, DentalRestorationProfile, DentalToothStateProfile, DentalTreatmentPlanProfile, } from '@cognovis/fhir-sdk/dental-core' const resource = DentalToothStateProfile.createResource({ subject: { reference: 'Patient/example' }, bodySite: { text: '16' }, status: 'final', }) const observation = DentalToothStateProfile.apply(resource).toResource() ``` The surface is generated from the installed release closure by `scripts/generate-release-profile-registry.ts`. A projection bump regenerates it; `bun run check:release-profiles` fails when a class is missing or extra. A logical model such as `ToothReadingModel` has no class: the subpath exports its interfaces as types only (`import type { ToothReadingModel } from '@cognovis/fhir-sdk/dental-core'`). ## HL7 R4 base resource profiles `@cognovis/fhir-sdk/r4` Applications import ordinary HL7 R4 base resource profile classes, generated resource and datatype interfaces, nested backbone-element interfaces, and `is` type guards only from this subpath. It re-exports every generated base resource class of the pinned `hl7.fhir.r4.core` package together with the own-declared types and guards from each core module. Consumers do not depend on `@cognovis/fhir-release` or on its projection layout. ```ts import { isQuestionnaire, PatientProfile, CompositionProfile, } from '@cognovis/fhir-sdk/r4' import type { Questionnaire, QuestionnaireItem } from '@cognovis/fhir-sdk/r4' import { defineProfile } from '@cognovis/fhir-sdk/client' const patientDescriptor = defineProfile(PatientProfile, 'Patient') const compositionDescriptor = defineProfile(CompositionProfile, 'Composition') const draft: Questionnaire = { resourceType: 'Questionnaire', status: 'draft' } if (isQuestionnaire(draft)) { const unusedItem: QuestionnaireItem | undefined = draft.item?.[0] void unusedItem } ``` `AccountProfile` and `ChargeItemProfile` also accept complete typed constructor inputs through the public SDK facade. The input omits `resourceType`; required FHIR fields remain required by TypeScript, and every supplied field is preserved: ```ts import { AccountProfile, ChargeItemProfile } from '@cognovis/fhir-sdk/r4' const account = AccountProfile.createResource({ status: 'active', name: 'Treatment account', }) const chargeItem = ChargeItemProfile.createResource({ status: 'billable', code: { text: 'Consultation' }, subject: { reference: 'Patient/p-1' }, account: [{ reference: 'Account/a-1' }], }) ``` The legacy no-argument constructors and `from()` methods remain available. These constructors supply the resource type and preserve typed fields; they do not perform full R4 or constrained-profile validation. Use these base descriptors with `defineProfile` and `genericReadProfiles`. They discriminate resource type and preserve the published base canonical; they do not perform full R4 schema validation. ## Registry-backed estate and IG profile classes `@cognovis/fhir-sdk/release-profiles` Applications import concrete estate, KBV, eAU, praxis and other registry-backed profile classes from this subpath. It re-exports every validator class bound in the shipped `RELEASE_PROFILE_REGISTRY`. Consumers do not declare a direct `@cognovis/fhir-release` dependency. ```ts import { KBV_PR_Base_PatientProfile, KBV_PR_EAU_CompositionProfile, } from '@cognovis/fhir-sdk/release-profiles' import { defineProfile } from '@cognovis/fhir-sdk/client' const eauDescriptor = defineProfile(KBV_PR_EAU_CompositionProfile, 'Composition') const kbvPatientDescriptor = defineProfile(KBV_PR_Base_PatientProfile, 'Patient') ``` For registry metadata and lazy descriptor loading, continue to use `RELEASE_PROFILE_REGISTRY`, `releaseProfileEntry`, and `loadReleaseProfileDescriptor` from `@cognovis/fhir-sdk/client`. The generated class exports are the supported way to obtain validators for `defineProfile` without importing `@cognovis/fhir-release` directly. When the release generator emits the same class name for multiple canonicals, `RELEASE_PROFILE_COLLISION_EXPORTS` documents the unique public export for each profile. Import the documented `exportedName` (for example `Example_Lipid_Profile_cholesterol` and `Example_Lipid_Profile_lipidprofile`); the bare generated class name is not exported when it would be ambiguous. ## Release compatibility and upgrades `@cognovis/fhir-sdk/release-compatibility` Each SDK release ships a generated compatibility receipt that binds the SDK version, the exact `@cognovis/fhir-release` dependency, the closure digest and the registry content digest. `npm pack` and `npm publish` run `prepack`, which builds the package and then runs `bun run check:release-profiles`; a dependency or registry identity mismatch fails closed before a tarball is produced. The dependency names one exact release, never a range: the registry names the validator modules of that release, and a range would let a fresh install resolve a later release without them. `npm pack|publish --ignore-scripts` bypasses `prepack` and must not be used for releases; CI and human publish flows must run `bun run check:release-profiles` explicitly when packaging with `--ignore-scripts` (for example in fast packed consumer tests). ```ts import { RELEASE_COMPATIBILITY } from '@cognovis/fhir-sdk/release-compatibility' console.log(RELEASE_COMPATIBILITY.sdkVersion) // 0.36.0 console.log(RELEASE_COMPATIBILITY.releaseVersion) // 0.5.0 ``` The package is released from cognovis/chp: a merge to chp main that bumps the version in `package.json` publishes it (`package-publish.yml`, entry `@cognovis/fhir-sdk` in `release/packages.json`). Each version is published under the npm dist-tag named by `publishConfig.tag`, and under `latest` when that field is absent. `publishConfig.tag` is a per-release setting: it names a new, unfollowed dist-tag for that one version, and a version published under it leaves `latest` unchanged. Before publishing, the workflow refuses to move a dist-tag other than `latest` that already names another version; a re-run for the same version passes. `0.15.12` is published under `fmgt-181`, `0.15.13` under `fsdk-50`, `0.15.14`, the first release from chp, under `chp-394` and `0.15.15` under `chp-506`, so `latest` stays at `0.15.12`; install them with the exact version. The next release must change or remove `publishConfig.tag`: remove it to publish under `latest`, or name another new dist-tag. `0.16.0` uses the `chp-540` tag, and `0.16.1` uses the new `chp-497-sdk-0-16-1` tag. Both leave the existing dist-tags unchanged. `0.17.0` uses the new `chp-595` tag and also leaves `latest` unchanged. The unreleased candidate workflow installs a digest-verified local release archive, supplies each private candidate archive to the release-profile generator, and records the observed candidate in this receipt. Pass the release archive with both `--release-candidate ` and `--release-candidate-sha256 `. The expected digest must come from the source-bound Management handoff or receipt, independently of the archive and its package metadata. Candidate mode fails closed when that digest is missing, malformed, or does not match the archive. `sha256:` and a bare lowercase 64-character digest are accepted. Candidate SDK tarballs pin the observed release version; the published dependency remains unchanged until the coordinated release is cut. The current unpublished candidate is generated from the Management closure that carries both the `dental-billing` and `praxis-billing` adapter sets. The generated SDK receipt binds that exact release archive, its identity, and its source receipt; another archive with the same package version is not accepted. **When a release change requires an SDK update.** Adopt a new FHIR release closure when your application needs registry entries, generated validators or compatibility receipts from that release. Bump `@cognovis/fhir-sdk` to a version that declares the matching `@cognovis/fhir-release` pin. Verify `RELEASE_COMPATIBILITY` after install. An SDK can ship against an unchanged release; a release can ship without a simultaneous SDK publication when no SDK surface changes are required. **How downstream apps adopt the tested combination.** Declare only `@cognovis/fhir-sdk` in application `package.json`. Import models from `@cognovis/fhir-sdk/r4`, concrete profiles from `@cognovis/fhir-sdk/release-profiles` or `@cognovis/fhir-sdk/dental-core`, and client/registry APIs from `@cognovis/fhir-sdk/client`. npm install pulls the pinned release transitively through the SDK; do not add a direct release dependency or rely on hoisting. **Migrating direct `@cognovis/fhir-release` imports.** | Previous import | SDK import | | --- | --- | | `@cognovis/fhir-release/.../profiles/Patient.js` (`PatientProfile`) | `@cognovis/fhir-sdk/r4` | | `@cognovis/fhir-release/.../profiles/Composition.js` (`CompositionProfile`) | `@cognovis/fhir-sdk/r4` | | `@cognovis/fhir-release/.../Questionnaire.js` (`Questionnaire`, `isQuestionnaire`) | `@cognovis/fhir-sdk/r4` | | `@cognovis/fhir-release/.../Condition_DentalConditionDE.js` | `@cognovis/fhir-sdk/release-profiles` | | `@cognovis/fhir-release/de-cognovis-fhir-dental-core/...` | `@cognovis/fhir-sdk/dental-core` | | Other generated profile modules in the shipped registry | `@cognovis/fhir-sdk/release-profiles` | ## Terminology and canonical URLs `@cognovis/fhir-sdk/terminology` and `@cognovis/fhir-sdk/canonicals` Both surfaces are generated from the installed release closure by `scripts/generate-terminology.ts` and are stamped with the release version and the closure digest they came from: ```sh bun run generate:terminology # regenerate bun run check:terminology # fail if the committed output is stale ``` - `terminology` exports the system URL constants of the estate guides, the codes those guides fix (`DENTAL_CODES`, `PRAXIS_CODES`, ...), the displays they define (`DENTAL_DISPLAYS`, ...), every external system URI bound by a shipped closure or declared profile (`referenced-systems`: fhir.de sids, KBV systems, BfArM, LOINC, SNOMED CT, `identifier-type-de-basis`, ...), and the provenance constants `RELEASE_VERSION` and `RELEASE_CLOSURE_DIGEST`. - The rule is: **URIs are generated, displays are store-resolved.** External systems contribute a URL constant at most — never codes or displays. Systems no shipped profile binds (for example consumer-owned code systems) stay consumer literals and are never hand-added to the generated surface. - `canonicals` exports one module per estate Implementation Guide with its profile and extension canonical URLs, so applications stop hand-maintaining URL literals. ### Resolving KBV displays This package deliberately ships no KBV display constants and no KBV concept lists, and the same holds for SNOMED CT, LOINC, the BfArM terminologies and the billing catalogues. Only URLs, and codes the Cognovis guides author themselves, are generated. Displays are resolved store-side. The bootstrap installs `kbv.all.st-combined` and the other closure packages into your FHIR server, so the server holds those CodeSystems under their original licences and answers: ```ts // $lookup against the server that holds the CodeSystem const outcome = await transport.request('GET', '/CodeSystem/$lookup', { query: { system: 'https://fhir.kbv.de/CodeSystem/KBV_CS_SFHIR_KBV_DMP', code: '01' }, }) ``` A plain `CodeSystem` read works the same way. This keeps licensed terminology in exactly one place — the store — instead of copying it into every consumer. ## Bootstrap `@cognovis/fhir-sdk/bootstrap` This subpath installs the release package closure into an arbitrary standard FHIR server with plain FHIR interactions only: conformance resources are written with `PUT //`, or `POST /` when they carry no id. It does not install Aidbox-native runtime resources. For the two Aidbox runtime resources owned by ADR-009, an ordinary authenticated client instead exposes the intent-specific `client.bootstrap.install(resource)` call. It accepts only identified `AccessPolicy` and `Subscription` resources and translates authorization, server, and transport failures to `FhirSdkError`. `AccessPolicy` is written at the Aidbox tenant root, while `Subscription` is a FHIR resource written below the configured FHIR base. The credential still needs the corresponding store-side administrative grant. Store-side `AccessPolicy` is the authority boundary for this controlled-environment operation; no SDK option can elevate the caller. ```ts import { bootstrapStore, loadInstalledManifest } from '@cognovis/fhir-sdk/bootstrap' const result = await bootstrapStore({ transport, closure: loadInstalledManifest().closure, cognovisRegistryHeaders: { Authorization: `Bearer ${registryToken}` }, }) // result.packages: installed | skipped (+ reason) | failed (+ error) ``` With no argument, `loadInstalledManifest()` returns the exact release manifest pinned by the installed SDK. The manifest is bundled with standalone consumers, so a compiled Bun executable does not need the original SDK or `node_modules` tree at runtime. Pass a directory explicitly only when resolving a compatible `@cognovis/fhir-release` installation from that directory. Routing follows the `origin` of each closure entry: | Origin | Behaviour | | --- | --- | | `private` | Fetched from `https://npm.cognovis.de` (token required). | | `public` | Fetched from `packages.fhir.org`, falling back to `packages2.fhir.org` and `packages.simplifier.net`. Never proxied through Cognovis infrastructure. | | `zts` | Skipped with a recorded reason. Licensed terminology bytes are never mirrored, bundled or redistributed by this SDK; the operator loads them from the terminology service. | | lock snapshot | Skipped: no registry serves those bytes. | Verification is not optional. Every tarball is checked against the SHA-256 digest the release manifest pins: a mismatch aborts that package with `BootstrapDigestMismatchError`, and an entry that carries no digest at all is refused with `BootstrapUnverifiableError` before anything is downloaded. `cognovisRegistryHeaders` travels to the Cognovis registry and to nothing else. Public FHIR registries are third-party hosts, so a custom `fetchTarball` also receives an empty header set for those URLs; `headersForUrl` is exported so the rule can be asserted independently. A credentialed request is additionally sent with `redirect: 'manual'` and its response origin is checked, so a redirect cannot decide at runtime which host receives the token — the header name is yours to choose, and no runtime-level stripping rule can be assumed for it. The registry token is the same value as the `_authToken` in your `.npmrc`, sent as `Authorization: Bearer `, which is what the Cognovis registry expects. Two limits bound what a hostile or broken registry can do, both stated in code as `MAX_TARBALL_BYTES` and `MAX_UNCOMPRESSED_BYTES`: | Limit | Value | Largest package in the closure | | --- | --- | --- | | Download | 64 MiB, enforced on `Content-Length` and while streaming | `hl7.fhir.r4.core@4.0.1`, 12.8 MB | | Decompression | 256 MiB `maxOutputLength` | the same package, 49 MB expanded | The download ceiling is enforced *before* the digest is computed, because the digest gate only protects bytes that have already been read. Archive content is treated as untrusted after the digest gate as well: a digest attests identity, not benignity. Tar headers are checksum-verified and their size fields bounded, and a resource whose `id` or `resourceType` is not a valid FHIR identifier is refused with `BootstrapUnsafeResourceError` rather than interpolated into a request path. Resources under an `example/` directory of a package are not installed. `ImplementationGuide` resources are not installed — they are packaging metadata whose references point at guide examples, which servers enforcing referential integrity reject. ## Migrating from a predecessor package The rename table, the behavioural changes and the module moves for consumers coming from the package this SDK was extracted from are not part of the published package. Request them from info@cognovis.de. ## Development ```sh bun install bun run typecheck bun run build # dist/ with declarations bun run test # unit tests + the package-surface policy test bun run check:terminology bun run test:integ # needs a live Aidbox, see below ``` The real-Aidbox factory probe is gated by `FHIR_SDK_AIDBOX_INTEG=1` plus `FHIR_SDK_AIDBOX_BASE_URL`, `FHIR_SDK_AIDBOX_CLIENT_ID`, and `FHIR_SDK_AIDBOX_CLIENT_SECRET`; its fixture must contain at least two Patients so a one-item search produces a continuation. An AccessPolicy write is excluded from that ordinary probe. It runs only when `FHIR_SDK_AIDBOX_ADMIN_INTEG=1`, `FHIR_SDK_AIDBOX_BASE_URL`, dedicated `FHIR_SDK_AIDBOX_ADMIN_CLIENT_ID`/`FHIR_SDK_AIDBOX_ADMIN_CLIENT_SECRET` credentials, and an operator-reviewed identified AccessPolicy in `FHIR_SDK_AIDBOX_ACCESS_POLICY_JSON` are all supplied. The test never invents a permissive policy or logs the payload or credentials. Without these explicit inputs, real-store AccessPolicy installation remains unexecuted and the route contract is covered by prefix-aware mocks. SQL-on-FHIR live cases live in `src/__tests__/sql-on-fhir.integ.test.ts` and use the same `FHIR_SDK_AIDBOX_INTEG=1` ordinary credentials. Administrative index creation and `EXPLAIN` require `FHIR_SDK_AIDBOX_ADMIN_INTEG=1` plus the dedicated admin credentials. The optional real-Aidbox bulk probe additionally requires `FHIR_SDK_AIDBOX_BULK_INTEG=1`, `FHIR_SDK_AIDBOX_BULK_INPUT_URL`, and `FHIR_SDK_AIDBOX_BULK_SOURCE_FILE`. The URL must expose an immutable gzip Patient NDJSON object, and the source file must be that exact `.ndjson.gz` object, not its decompressed form. The SDK streams those gzip bytes through its preflight validation and Aidbox fetches the identical object. The local integration harness enables insecure HTTP only when `FHIR_SDK_AIDBOX_BASE_URL` resolves to loopback; all other targets retain the bridge's HTTPS requirement. The package-surface policy test scans what `npm pack` would publish and fails when it finds traces of the platform this SDK was extracted from, anonymization or PII symbols, third-party concept content, or dependency drift. Run `bun run build` before the suite; the test fails loudly when `dist/` is missing rather than passing vacuously. `prepack` rebuilds and runs `check:release-profiles` automatically, so a publish cannot ship a `dist/` or compatibility receipt that no longer matches the pinned release closure. Release packaging with `npm pack|publish --ignore-scripts` skips that gate; use only in local test harnesses and run `bun run check:release-profiles` in CI before publish. The entry-point test asserts that the root export and the subpath exports resolve to one build of each module. They must: `ResourceClient` decides whether a 404 is absence or an error with `instanceof`, and a second copy of `FhirHttpError` would silently break the documented 404 contract. ### Workforce transactions Use one ordinary client per verified workforce request. The SDK does not verify application roles or exchange the credential. It sends that credential only to the configured Aidbox base, refuses redirects, and never falls back to a machine account. The factory accepts exactly one of `bearerToken`, `basicAuth: { username, password }`, or `clientId` plus `clientSecret`. HTTP needs explicit `allowInsecureRequests: true` for local testing. ```ts const client = await createAidboxFhirClient({ baseUrl, bearerToken: verifiedToken }) const result = await client.forResourceType('Condition').transaction([ { method: 'GET', resourceType: 'Condition', id: conditionId }, { method: 'PUT', resource: correctedCondition, ifMatch: previousEtag }, { method: 'PUT', descriptor: provenanceDescriptor, resource: provenance, ifNoneMatch: '*', fullUrl: provenanceUrn }, ], { signal, timeoutMs: 5000 }) const { resource, response } = result.entry[0]! // response.status, response.location, response.etag, response.lastModified, // and response.outcome retain the server's ordered FHIR response evidence. ``` `POST` and `PUT` accept a resource. `GET` and `DELETE` accept an id and a resource type on the family API, or an id and descriptor on `client.transaction`. `PATCH` accepts the same id and resource type or descriptor plus RFC 6902 `operations`, validated like `patch()` before dispatch and sent as a FHIR `Binary` of content type `application/json-patch+json`; pass `ifMatch` to bind it to an observed version. The patched resource the server returns must carry the entry's resource type and id; a descriptor validates it, and a family PATCH entry resolves it to its declared release profile, as `patch()` does. PATCH entries are rejected inside deidentified target-store scopes. Migrate old DELETE entries from `{ resource, method: 'DELETE' }` to `{ descriptor, id, method: 'DELETE' }` or `{ resourceType, id, method: 'DELETE' }`. Both composite APIs preserve `ifMatch`, `ifNoneMatch`, and `fullUrl`. Family transactions can contain different resource types and mix inferred entries with explicit descriptor entries. A `provenanceDescriptor` created with `defineProfile` can bind a generic audit resource while the clinical entries retain their declared leaf profiles. A descriptor-less GET result must resolve to a release profile; an explicit GET result must satisfy its supplied descriptor. Conditional GET may return 304 without a resource. The SDK returns raw validated resources in composite results. In a family batch, failure to resolve a descriptor-less input profile rejects the whole call before dispatch. An explicit descriptor validation failure is returned as a per-entry batch failure; valid sibling entries still run. Successful batch writes can omit `resource`; an OperationOutcome returned by a write is retained in `response.outcome`, never exposed as the selected profile's resource. Batch GET still requires a profile resource unless the status is 304. Writes stamp the configured `writeSource` by default. Set `preserveResourceSource: true` only when the caller owns provenance semantics: an existing non-empty `meta.source` is then retained, while an absent or empty source is still stamped. Descriptor profile admission and post-stamp validation remain mandatory for ordinary, batch, and transaction writes. A transaction uses one atomic server request. `FhirTransactionFailedError` retains HTTP `status`, `outcome`, and complete server entries when supplied, or submitted entries when the server provides only an OperationOutcome. Evidence can contain patient data and must not be logged raw. When the transaction fails before any FHIR response, for example on a socket reset, an abort, a failed token acquisition or an undecodable response, the error keeps the original exception as the standard, non-enumerable `cause` and exposes sanitised `causeName` (error class) and `causeCode` (such as `ECONNRESET`, `AbortError`, an HTTP status or `TOKEN_ACQUISITION_401`) fields, each taken only from a finite allowlist; an unlisted class reads `Error` and an unlisted code is omitted. Its message names that class and code and never repeats the provider's message text. Log `causeName`, `causeCode` and the message; the raw `cause` may contain URLs, tokens or response payload and must not be logged. The SDK never retries a failed transaction as individual writes. A successful commit followed by invalid response evidence raises a validation error; callers must reconcile state before retrying. Inside `withDeidentification`, the complete bundle is transformed together so fullUrl references and Provenance targets remain consistent. An id-less create with a fullUrl receives a temporary identity for that graph transform; its generated id is removed before dispatch while the transformed fullUrl and sibling references remain. Every transformed resource is revalidated. Request conditions remain unchanged. Deidentification guard errors reject both batch and transaction calls before dispatch. SQLQuery validation parses PostgreSQL structure with the pinned `pgsql-ast-parser` dependency. Nonrecursive CTEs, derived SELECTs, joins, UNION/UNION ALL, scalar subqueries, EXISTS, DISTINCT ON, aggregate FILTER and supported window expressions may read only declared ViewDefinition labels. CTE names are visible within their lexical scope; a derived alias never grants access to another relation. Nested writes, schema-qualified base tables, locking clauses and prohibited functions fail before dispatch. Recursive CTEs, MATERIALIZED CTE modifiers, table functions and other unsupported parser syntax also fail closed. Named placeholders are checked outside quoted text and comments, including PostgreSQL casts. Parsing uses a temporary normalized copy; the original SQL and parameter binding reach Aidbox unchanged. FHIR output checks the outer SELECT projection, so CTE-local aliases need not match the declared result columns. ### Named terminology and Encounter change operations The same authenticated client owns these fixed operations. Canonical `url` and `system` values are operation parameters, never HTTP destinations. ```ts const concept = await client.terminology.lookup({ system: codeSystemUrl, code, version: installedVersion, property: ['parent', 'child', 'inactive'], }, { signal, timeoutMs: 5000 }) const expanded = await client.terminology.expand({ url: valueSetUrl, valueSetVersion: installedValueSetVersion, filter, count: 100, }) const validation = await client.terminology.validateCode({ url: valueSetUrl, system, code }) const codeSystemValidation = await client.terminology.validateCodeSystem({ url: codeSystemUrl, code }) const translation = await client.terminology.translate({ url: conceptMapUrl, system, code }) const changes = await client.encounterChanges({ version: persistedVersion, count: 5000 }) ``` Terminology results retain Parameters names, repeated properties, Coding values, translation equivalence and nested ValueSet expansion concepts. Public result fields derive from the pinned release's core Parameters and ValueSet types; operation-specific validators check their shapes without resolving a resource profile. Unsupported Parameters value choices fail closed. Lookup and translate send POST Parameters; expand and both validate-code methods use GET query parameters. The optional `ValueSetExpandRequest.valueSetVersion` is the standard FHIR R4 `$expand` parameter selecting the exact ValueSet version. It is an opaque, nonblank string of at most 256 UTF-16 code units without ASCII control characters or unpaired surrogates; it need not be a SemVer. Accepted values are sent unchanged as `valueSetVersion`, separately from `url`; the SDK does not normalize them or append them to the canonical URL. Invalid supplied values fail with `profile-validation` before transport. Omitting the parameter preserves the existing expansion behavior. HTTP errors retain `FhirSdkError.status` and `.outcome`, including 404 for missing codes and OperationOutcome details. HTTP 401/403 use the `authorization` discriminant; other rejected responses use `server`. No operation changes credentials on failure. Translation match concept and equivalence are optional R4 fields, validated when present; unmatched evidence may omit the concept. `encounterChanges` calls the fixed root `/Encounter/$changes` endpoint. It uses a numeric version when supplied, always sets `omit-resources=true`, and bounds `_count` to 1–5000, default 5000. The result includes `version`, `upsertIds`, `deleteIds`, and ordered created/updated/deleted change identities. Each change resource contains only `resourceType` and `id`, even if the server returns additional resource fields. An initial request without a version accepts a cursor-only response and returns that version with empty change lists and `notModified: false`. Responses to versioned requests must contain a `changes` array. HTTP 304 returns `notModified: true`, empty changes and the caller's original version. Invalid or decreasing versions, and changes without an advancing version, fail before any caller cursor is changed. This feed is unavailable inside a deidentification scope because its cursor names an identifying source stream. Every named operation accepts `RequestOptions`. `timeoutMs` bounds the caller's wait and `signal` supports cancellation; failures use the distinct `timeout` and `cancelled` SDK discriminants. Late responses do not become successful results after either control has fired. Terminology methods obtained inside `withDeidentification` remain bound to that scope's lifetime. After the callback ends, retained clients and detached methods fail with `deidentification` before authenticated dispatch. The live atomicity proof extends `src/__tests__/round-trip.integ.test.ts` and is inert by default. Run it only against an isolated Reetfurt loopback endpoint, with `FHIR_SDK_REETFURT_ATOMIC_INTEG=1` and an explicit `FHIR_SDK_ATOMIC_BASE_URL`. It never falls back to the shared integration URL. Supply exactly one existing credential alternative through `FHIR_SDK_AIDBOX_BEARER_TOKEN`, `FHIR_SDK_AIDBOX_BASIC_USERNAME` plus `FHIR_SDK_AIDBOX_BASIC_PASSWORD`, or `FHIR_SDK_AIDBOX_CLIENT_ID` plus `FHIR_SDK_AIDBOX_CLIENT_SECRET`. ```sh bun test src/__tests__/round-trip.integ.test.ts --test-name-pattern 'isolated Reetfurt conditional transactions' ``` The proof records transactional GET/ETag evidence and checks that stale-version and create-only failures leave Patient and Provenance unchanged, with no new audit resource. It retains two generated synthetic resources for inspection, marked with a unique `urn:cognovis:fhir-sdk:isolated-atomic-proof:` source. It performs no cleanup or deletion. Searches can opt into resource-type continuation confinement and cycle rejection: ```ts const page = await organizations.search({ active: 'true' }, { continuationPolicy: { path: 'resource-type', rejectCycles: true }, }) if (page.next) await organizations.next(page.next) ``` Both exact-profile and resource-family clients support this search-only option. The SDK snapshots it before dispatch and carries it in opaque continuation tokens. Next targets must resolve to the exact searched resource-type path within the configured origin and FHIR base; instance, operation, root and trailing-slash paths are rejected before HTTP dispatch. Default searches still follow a same-base next link that pages through a root query (`?...`). Cycle identity uses the resolved pathname and serialized query, ignoring fragments without sorting or decoding query parameters. Only successfully consumed next requests enter the descendant token's history; the initial search is excluded. Retrying the same token, even after success, is permitted. Independent searches and branches do not share history, and failed requests or page validation do not consume a target. Callers retain responsibility for page-count limits.