@peerbits/fhir-observation-generator 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity.
18
+
19
+ "You" (or "Your") shall mean an individual or Legal Entity
20
+ exercising permissions granted by this License.
21
+
22
+ "Source" form shall mean the preferred form for making modifications.
23
+
24
+ "Object" form shall mean any form resulting from mechanical
25
+ transformation or translation of a Source form.
26
+
27
+ "Work" shall mean the work of authorship, whether in Source or
28
+ Object form, made available under the License, as indicated by a
29
+ copyright notice that is included in or attached to the work.
30
+
31
+ "Derivative Works" shall mean any work, whether in Source or Object
32
+ form, that is based on (or derived from) the Work.
33
+
34
+ "Contribution" shall mean any work of authorship intentionally
35
+ submitted to Licensor for inclusion in the Work.
36
+
37
+ "Contributor" shall mean Licensor and any individual or Legal Entity
38
+ on behalf of whom a Contribution has been received by Licensor.
39
+
40
+ 2. Grant of Copyright License. Subject to the terms and conditions of
41
+ this License, each Contributor hereby grants to You a perpetual,
42
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
43
+ copyright license to reproduce, prepare Derivative Works of,
44
+ publicly display, publicly perform, sublicense, and distribute the
45
+ Work and such Derivative Works in Source or Object form.
46
+
47
+ 3. Grant of Patent License. Subject to the terms and conditions of
48
+ this License, each Contributor hereby grants to You a perpetual,
49
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
50
+ (except as stated in this section) patent license to make, have
51
+ made, use, offer to sell, sell, import, and otherwise transfer the
52
+ Work. If You institute patent litigation against any entity
53
+ alleging that the Work constitutes direct or contributory patent
54
+ infringement, then any patent licenses granted to You under this
55
+ License for that Work shall terminate as of the date such
56
+ litigation is filed.
57
+
58
+ 4. Redistribution. You may reproduce and distribute copies of the
59
+ Work or Derivative Works thereof provided that You meet the
60
+ following conditions:
61
+
62
+ (a) You must give any other recipients a copy of this License; and
63
+ (b) You must cause modified files to carry prominent notices; and
64
+ (c) You must retain all copyright, patent, trademark, and
65
+ attribution notices from the Source form; and
66
+ (d) If the Work includes a NOTICE file, any Derivative Works must
67
+ include a readable copy of its attribution notices.
68
+
69
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
70
+ any Contribution intentionally submitted for inclusion in the Work
71
+ by You shall be under the terms of this License, without additional
72
+ terms or conditions.
73
+
74
+ 6. Trademarks. This License does not grant permission to use trade
75
+ names, trademarks, service marks, or product names of the Licensor.
76
+
77
+ 7. Disclaimer of Warranty. The Work is provided on an "AS IS" BASIS,
78
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
79
+ implied.
80
+
81
+ 8. Limitation of Liability. In no event shall any Contributor be
82
+ liable for damages arising as a result of this License or out of
83
+ the use or inability to use the Work.
84
+
85
+ 9. Accepting Warranty or Additional Liability. You may choose to offer
86
+ support, warranty, indemnity, or other liability obligations, but
87
+ only on Your own behalf and sole responsibility.
88
+
89
+ END OF TERMS AND CONDITIONS
90
+
91
+ APPENDIX: How to apply the Apache License to your work.
92
+
93
+ Copyright [yyyy] [name of copyright owner]
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License");
96
+ you may not use this file except in compliance with the License.
97
+ You may obtain a copy of the License at
98
+
99
+ http://www.apache.org/licenses/LICENSE-2.0
100
+
101
+ Unless required by applicable law or agreed to in writing, software
102
+ distributed under the License is distributed on an "AS IS" BASIS,
103
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
104
+ See the License for the specific language governing permissions and
105
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,213 @@
1
+ # @peerbits/fhir-observation-generator
2
+
3
+ > Lightweight, dependency-free FHIR R4 Observation generator for normalized RPM device readings.
4
+
5
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](./LICENSE)
6
+ [![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](#3-local-installation)
7
+ [![FHIR](https://img.shields.io/badge/FHIR-R4-orange.svg)](https://hl7.org/fhir/R4/)
8
+ [![CI](https://github.com/PeerbitsSolution/fhir-observation-generator/actions/workflows/ci.yml/badge.svg)](https://github.com/PeerbitsSolution/fhir-observation-generator/actions/workflows/ci.yml)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict-3178C6.svg)](https://www.typescriptlang.org/)
10
+
11
+ **Category:** RPM — Device & Observation Utilities · **License:** Apache-2.0 · **Status:** alpha
12
+
13
+ ---
14
+
15
+ ## Table of contents
16
+
17
+ 1. [What problem does this solve?](#1-what-problem-does-this-solve)
18
+ 2. [Features](#2-features)
19
+ 3. [Local installation](#3-local-installation)
20
+ 4. [Quick Start](#4-quick-start)
21
+ 5. [Architecture](#5-architecture)
22
+ 6. [Example Usage](#6-example-usage)
23
+ 7. [Safety and validation](#7-safety-and-validation)
24
+ 8. [Roadmap](#8-roadmap)
25
+ 9. [Contributing & Testing](#9-contributing--testing)
26
+ 10. [License](#10-license)
27
+ 11. [About PeerbitsSolution](#11-about-peerbitssolution)
28
+
29
+ ---
30
+
31
+ ## 1. What problem does this solve?
32
+ Every Remote Patient Monitoring (RPM) program must transform raw device data into FHIR Observation resources before it enters an EHR or clinical data repository.
33
+ This library provides a focused, auditable conversion layer for the supported vital types, units, and Observation structures.
34
+
35
+ ## 2. Features
36
+
37
+ - **7 Core RPM Vital Types Supported:** Blood pressure, heart rate, body weight, SpO2, body temperature, blood glucose, and respiratory rate.
38
+ - **Component-Based Blood Pressure:** Generates exactly one Observation with systolic (`8480-6`) and diastolic (`8462-4`) components under panel LOINC `85354-9`.
39
+ - **Verified UCUM Unit Conversion:** Converts raw units (e.g. °F to °C, lbs to kg, mg/dL to mmol/L) using standard reference formulas.
40
+ - **Single Source LOINC Mapping:** Fully auditable table of codes (`http://loinc.org`) and FHIR categories (`vital-signs`).
41
+ - **Structural Self-Check:** Built-in validation for essential Observation fields (`status`, `category`, `code`, `subject`, `effectiveDateTime`, `valueQuantity`/`component`).
42
+ - **Zero Runtime Dependencies:** Lightweight, pure TypeScript transformation engine suitable for browser, Node.js, and edge environments.
43
+
44
+ ## 3. Local installation
45
+
46
+ ### Via npm
47
+
48
+ ```bash
49
+ npm install @peerbits/fhir-observation-generator
50
+ ```
51
+
52
+ > **ESM only.** This package ships as native ESM (`"type": "module"`), zero runtime dependencies. Use `import`, not `require`. CommonJS projects can still consume it via a dynamic `await import("@peerbits/fhir-observation-generator")`.
53
+
54
+ ### From source
55
+
56
+ ```bash
57
+ git clone https://github.com/PeerbitsSolution/fhir-observation-generator.git
58
+ cd fhir-observation-generator
59
+ npm ci
60
+ npm run build
61
+ ```
62
+
63
+ ## 4. Quick Start
64
+
65
+ ### Before (Raw RPM Device Reading JSON)
66
+
67
+ ```json
68
+ {
69
+ "deviceType": "blood-pressure",
70
+ "value": {
71
+ "systolic": 120,
72
+ "diastolic": 80
73
+ },
74
+ "unit": "mmHg",
75
+ "timestamp": "2026-08-06T08:30:00Z",
76
+ "patientRef": "Patient/pat-rpm-101",
77
+ "deviceId": "Device/bp-cuff-9021"
78
+ }
79
+ ```
80
+
81
+ ### Conversion Code
82
+
83
+ ```typescript
84
+ import { toObservation, type DeviceReading } from "@peerbits/fhir-observation-generator";
85
+
86
+ const reading: DeviceReading = {
87
+ deviceType: "blood-pressure",
88
+ value: { systolic: 120, diastolic: 80 },
89
+ unit: "mmHg",
90
+ timestamp: "2026-08-06T08:30:00Z",
91
+ patientRef: "Patient/pat-rpm-101",
92
+ deviceId: "Device/bp-cuff-9021",
93
+ };
94
+
95
+ const observation = toObservation(reading, { validate: true });
96
+ ```
97
+
98
+ ### After (Generated FHIR R4 Observation Resource)
99
+
100
+ ```json
101
+ {
102
+ "resourceType": "Observation",
103
+ "status": "final",
104
+ "category": [
105
+ {
106
+ "coding": [
107
+ {
108
+ "system": "http://terminology.hl7.org/CodeSystem/observation-category",
109
+ "code": "vital-signs",
110
+ "display": "Vital Signs"
111
+ }
112
+ ]
113
+ }
114
+ ],
115
+ "code": {
116
+ "coding": [
117
+ {
118
+ "system": "http://loinc.org",
119
+ "code": "85354-9",
120
+ "display": "Blood pressure panel with all children optional"
121
+ }
122
+ ],
123
+ "text": "Blood pressure panel with all children optional"
124
+ },
125
+ "subject": {
126
+ "reference": "Patient/pat-rpm-101"
127
+ },
128
+ "effectiveDateTime": "2026-08-06T08:30:00Z",
129
+ "device": {
130
+ "reference": "Device/bp-cuff-9021"
131
+ },
132
+ "component": [
133
+ {
134
+ "code": {
135
+ "coding": [
136
+ {
137
+ "system": "http://loinc.org",
138
+ "code": "8480-6",
139
+ "display": "Systolic blood pressure"
140
+ }
141
+ ],
142
+ "text": "Systolic blood pressure"
143
+ },
144
+ "valueQuantity": {
145
+ "value": 120,
146
+ "unit": "mmHg",
147
+ "system": "http://unitsofmeasure.org",
148
+ "code": "mm[Hg]"
149
+ }
150
+ },
151
+ {
152
+ "code": {
153
+ "coding": [
154
+ {
155
+ "system": "http://loinc.org",
156
+ "code": "8462-4",
157
+ "display": "Diastolic blood pressure"
158
+ }
159
+ ],
160
+ "text": "Diastolic blood pressure"
161
+ },
162
+ "valueQuantity": {
163
+ "value": 80,
164
+ "unit": "mmHg",
165
+ "system": "http://unitsofmeasure.org",
166
+ "code": "mm[Hg]"
167
+ }
168
+ }
169
+ ]
170
+ }
171
+ ```
172
+
173
+ ## 5. Architecture
174
+
175
+ The library is organized into decoupled, single-responsibility modules:
176
+
177
+ - `src/types.ts`: `DeviceReading`, `GeneratorConfig`, and FHIR Observation / Bundle interfaces.
178
+ - `src/loinc-map.ts`: Centralized LOINC coding catalog (`LOINC_MAP`) mapping each vital type to LOINC codes, display labels, and categories. See [docs/LOINC_REFERENCE.md](./docs/LOINC_REFERENCE.md).
179
+ - `src/units.ts`: Exact UCUM conversion functions (`convertUnit`, `normalizeUcumUnit`).
180
+ - `src/generators/`: Individual per-vital generators (`blood-pressure.ts`, `heart-rate.ts`, `weight.ts`, `spo2.ts`, `temperature.ts`, `glucose.ts`, `respiratory-rate.ts`) and main `toObservation` dispatcher.
181
+ - `src/validate.ts`: Lightweight structural validation (`validateObservation`).
182
+ - `src/bundle.ts`: Transaction bundle compiler (`readingsToBundle`).
183
+
184
+ ## 6. Example Usage
185
+
186
+ Full runnable code examples are available under `docs/examples/`:
187
+
188
+ - [Basic Conversion Example](./docs/examples/basic-conversion): Single reading conversion and temperature unit handling.
189
+ - [Batch with fhir-client](./docs/examples/batch-with-fhir-client): Transaction bundle generation and composition with [`@peerbits/fhir-client`](https://www.npmjs.com/package/@peerbits/fhir-client).
190
+
191
+ ## 7. Safety and validation
192
+
193
+ - The library accepts only its documented source units and supported conversions. Unsupported or incompatible units, `NaN`, and infinite measurements throw an error rather than being relabeled.
194
+ - `validateObservation` is a lightweight structural check; validate generated resources against the FHIR profile required by your receiving system before production submission.
195
+ - This package is a data-transformation utility, not medical advice, a diagnostic tool, or a clinical decision-support system. Integrators remain responsible for device-data quality, clinical review, and regulatory obligations.
196
+
197
+ ## 8. Roadmap
198
+
199
+ - [ ] Additional vital types (e.g. Body Mass Index / BMI, Body Height, Heart Rate Variability / HRV).
200
+ - [ ] Official HL7 FHIR / US Core Validator integration support.
201
+ - [ ] Support for continuous streaming device reading series.
202
+
203
+ ## 9. Contributing & Testing
204
+
205
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for local setup, tests, build, and package checks.
206
+
207
+ ## 10. License
208
+
209
+ Apache License 2.0 — see [LICENSE](./LICENSE).
210
+
211
+ ## 11. About PeerbitsSolution
212
+
213
+ `@peerbits/fhir-observation-generator` is part of the [PeerbitsSolution HealthTech Open Source](https://github.com/PeerbitsSolution) initiative—reusable engineering components extracted from our healthcare technology work. This repository contains generalized, reusable logic only; it is not tied to any specific client engagement or commercial product.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Batch / Bundle Generator for @peerbits/fhir-observation-generator.
3
+ *
4
+ * Converts an array of DeviceReading objects into a FHIR R4 transaction Bundle.
5
+ * Formatted for direct execution with @peerbits/fhir-client's batch/transaction builder.
6
+ */
7
+ import { DeviceReading, FhirBundle, GeneratorConfig } from "./types.js";
8
+ export declare function readingsToBundle(readings: DeviceReading[], config?: GeneratorConfig): FhirBundle;
package/dist/bundle.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Batch / Bundle Generator for @peerbits/fhir-observation-generator.
3
+ *
4
+ * Converts an array of DeviceReading objects into a FHIR R4 transaction Bundle.
5
+ * Formatted for direct execution with @peerbits/fhir-client's batch/transaction builder.
6
+ */
7
+ import { toObservation } from "./generators/index.js";
8
+ export function readingsToBundle(readings, config) {
9
+ if (!Array.isArray(readings)) {
10
+ throw new Error("Invalid input to readingsToBundle: expected array of DeviceReading objects");
11
+ }
12
+ const entries = readings.map((reading) => {
13
+ const observation = toObservation(reading, config);
14
+ return {
15
+ resource: observation,
16
+ request: {
17
+ method: "POST",
18
+ url: "Observation",
19
+ },
20
+ };
21
+ });
22
+ return {
23
+ resourceType: "Bundle",
24
+ type: "transaction",
25
+ entry: entries,
26
+ };
27
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Blood Pressure Observation Generator.
3
+ *
4
+ * Grounded in FHIR R4 and US Core Blood Pressure Profile:
5
+ * Produces EXACTLY ONE Observation resource with systolic and diastolic
6
+ * represented as component elements within the same Observation, NEVER as two separate Observations.
7
+ */
8
+ import { DeviceReading, FhirObservation, GeneratorConfig } from "../types.js";
9
+ export declare function bloodPressureToObservation(reading: DeviceReading, config?: GeneratorConfig): FhirObservation;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Blood Pressure Observation Generator.
3
+ *
4
+ * Grounded in FHIR R4 and US Core Blood Pressure Profile:
5
+ * Produces EXACTLY ONE Observation resource with systolic and diastolic
6
+ * represented as component elements within the same Observation, NEVER as two separate Observations.
7
+ */
8
+ import { LOINC_MAP, LOINC_BP_SYSTOLIC, LOINC_BP_DIASTOLIC, LOINC_SYSTEM, UCUM_SYSTEM, formatCategory, } from "../loinc-map.js";
9
+ import { convertUnit } from "../units.js";
10
+ import { validateObservation } from "../validate.js";
11
+ export function bloodPressureToObservation(reading, config) {
12
+ if (reading.deviceType !== "blood-pressure") {
13
+ throw new Error(`Invalid deviceType for blood pressure generator: expected 'blood-pressure', got '${reading.deviceType}'`);
14
+ }
15
+ let systolic;
16
+ let diastolic;
17
+ if (typeof reading.value === "object" &&
18
+ reading.value !== null &&
19
+ "systolic" in reading.value &&
20
+ "diastolic" in reading.value) {
21
+ const bpVal = reading.value;
22
+ systolic = bpVal.systolic;
23
+ diastolic = bpVal.diastolic;
24
+ }
25
+ else if (typeof reading.value === "string") {
26
+ const parts = reading.value.split("/");
27
+ if (parts.length === 2 && !isNaN(Number(parts[0])) && !isNaN(Number(parts[1]))) {
28
+ systolic = Number(parts[0]);
29
+ diastolic = Number(parts[1]);
30
+ }
31
+ else {
32
+ throw new Error(`Invalid blood pressure reading string format: '${reading.value}'. Expected '120/80'.`);
33
+ }
34
+ }
35
+ else {
36
+ throw new Error(`Invalid blood pressure value structure. Expected { systolic: number, diastolic: number }, got ${JSON.stringify(reading.value)}`);
37
+ }
38
+ const mapping = LOINC_MAP["blood-pressure"];
39
+ const targetUnit = config?.targetUnit || mapping.defaultUcumUnit;
40
+ const systolicConv = convertUnit(systolic, reading.unit, targetUnit);
41
+ const diastolicConv = convertUnit(diastolic, reading.unit, targetUnit);
42
+ const observation = {
43
+ resourceType: "Observation",
44
+ status: config?.status || "final",
45
+ category: formatCategory(mapping.category),
46
+ code: {
47
+ coding: [
48
+ {
49
+ system: LOINC_SYSTEM,
50
+ code: mapping.loincCode,
51
+ display: mapping.display,
52
+ },
53
+ ],
54
+ text: mapping.display,
55
+ },
56
+ subject: {
57
+ reference: reading.patientRef,
58
+ },
59
+ effectiveDateTime: reading.timestamp,
60
+ ...(reading.deviceId ? { device: { reference: reading.deviceId } } : {}),
61
+ component: [
62
+ {
63
+ code: {
64
+ coding: [
65
+ {
66
+ system: LOINC_SYSTEM,
67
+ code: LOINC_BP_SYSTOLIC.loincCode,
68
+ display: LOINC_BP_SYSTOLIC.display,
69
+ },
70
+ ],
71
+ text: LOINC_BP_SYSTOLIC.display,
72
+ },
73
+ valueQuantity: {
74
+ value: systolicConv.value,
75
+ unit: systolicConv.unit,
76
+ system: UCUM_SYSTEM,
77
+ code: systolicConv.ucumCode,
78
+ },
79
+ },
80
+ {
81
+ code: {
82
+ coding: [
83
+ {
84
+ system: LOINC_SYSTEM,
85
+ code: LOINC_BP_DIASTOLIC.loincCode,
86
+ display: LOINC_BP_DIASTOLIC.display,
87
+ },
88
+ ],
89
+ text: LOINC_BP_DIASTOLIC.display,
90
+ },
91
+ valueQuantity: {
92
+ value: diastolicConv.value,
93
+ unit: diastolicConv.unit,
94
+ system: UCUM_SYSTEM,
95
+ code: diastolicConv.ucumCode,
96
+ },
97
+ },
98
+ ],
99
+ };
100
+ if (config?.validate) {
101
+ const result = validateObservation(observation);
102
+ if (!result.valid) {
103
+ throw new Error(`Structural validation failed for blood pressure observation: ${result.errors.join(", ")}`);
104
+ }
105
+ }
106
+ return observation;
107
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Blood Glucose Observation Generator.
3
+ */
4
+ import { DeviceReading, FhirObservation, GeneratorConfig } from "../types.js";
5
+ export declare function glucoseToObservation(reading: DeviceReading, config?: GeneratorConfig): FhirObservation;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Blood Glucose Observation Generator.
3
+ */
4
+ import { LOINC_MAP, LOINC_SYSTEM, UCUM_SYSTEM, formatCategory } from "../loinc-map.js";
5
+ import { convertUnit } from "../units.js";
6
+ import { validateObservation } from "../validate.js";
7
+ export function glucoseToObservation(reading, config) {
8
+ if (reading.deviceType !== "glucose") {
9
+ throw new Error(`Invalid deviceType for glucose generator: expected 'glucose', got '${reading.deviceType}'`);
10
+ }
11
+ if (typeof reading.value !== "number") {
12
+ throw new Error(`Invalid glucose value: expected number, got ${typeof reading.value}`);
13
+ }
14
+ const mapping = LOINC_MAP["glucose"];
15
+ const targetUnit = config?.targetUnit || mapping.defaultUcumUnit;
16
+ const conv = convertUnit(reading.value, reading.unit, targetUnit);
17
+ const observation = {
18
+ resourceType: "Observation",
19
+ status: config?.status || "final",
20
+ category: formatCategory(mapping.category),
21
+ code: {
22
+ coding: [
23
+ {
24
+ system: LOINC_SYSTEM,
25
+ code: mapping.loincCode,
26
+ display: mapping.display,
27
+ },
28
+ ],
29
+ text: mapping.display,
30
+ },
31
+ subject: {
32
+ reference: reading.patientRef,
33
+ },
34
+ effectiveDateTime: reading.timestamp,
35
+ ...(reading.deviceId ? { device: { reference: reading.deviceId } } : {}),
36
+ valueQuantity: {
37
+ value: conv.value,
38
+ unit: conv.unit,
39
+ system: UCUM_SYSTEM,
40
+ code: conv.ucumCode,
41
+ },
42
+ };
43
+ if (config?.validate) {
44
+ const result = validateObservation(observation);
45
+ if (!result.valid) {
46
+ throw new Error(`Structural validation failed for glucose observation: ${result.errors.join(", ")}`);
47
+ }
48
+ }
49
+ return observation;
50
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Heart Rate Observation Generator.
3
+ */
4
+ import { DeviceReading, FhirObservation, GeneratorConfig } from "../types.js";
5
+ export declare function heartRateToObservation(reading: DeviceReading, config?: GeneratorConfig): FhirObservation;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Heart Rate Observation Generator.
3
+ */
4
+ import { LOINC_MAP, LOINC_SYSTEM, UCUM_SYSTEM, formatCategory } from "../loinc-map.js";
5
+ import { convertUnit } from "../units.js";
6
+ import { validateObservation } from "../validate.js";
7
+ export function heartRateToObservation(reading, config) {
8
+ if (reading.deviceType !== "heart-rate") {
9
+ throw new Error(`Invalid deviceType for heart rate generator: expected 'heart-rate', got '${reading.deviceType}'`);
10
+ }
11
+ if (typeof reading.value !== "number") {
12
+ throw new Error(`Invalid heart rate value: expected number, got ${typeof reading.value}`);
13
+ }
14
+ const mapping = LOINC_MAP["heart-rate"];
15
+ const targetUnit = config?.targetUnit || mapping.defaultUcumUnit;
16
+ const conv = convertUnit(reading.value, reading.unit, targetUnit);
17
+ const observation = {
18
+ resourceType: "Observation",
19
+ status: config?.status || "final",
20
+ category: formatCategory(mapping.category),
21
+ code: {
22
+ coding: [
23
+ {
24
+ system: LOINC_SYSTEM,
25
+ code: mapping.loincCode,
26
+ display: mapping.display,
27
+ },
28
+ ],
29
+ text: mapping.display,
30
+ },
31
+ subject: {
32
+ reference: reading.patientRef,
33
+ },
34
+ effectiveDateTime: reading.timestamp,
35
+ ...(reading.deviceId ? { device: { reference: reading.deviceId } } : {}),
36
+ valueQuantity: {
37
+ value: conv.value,
38
+ unit: conv.unit,
39
+ system: UCUM_SYSTEM,
40
+ code: conv.ucumCode,
41
+ },
42
+ };
43
+ if (config?.validate) {
44
+ const result = validateObservation(observation);
45
+ if (!result.valid) {
46
+ throw new Error(`Structural validation failed for heart rate observation: ${result.errors.join(", ")}`);
47
+ }
48
+ }
49
+ return observation;
50
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Per-vital FHIR Observation generators index and generic dispatcher.
3
+ */
4
+ import { DeviceReading, FhirObservation, GeneratorConfig } from "../types.js";
5
+ import { bloodPressureToObservation } from "./blood-pressure.js";
6
+ import { heartRateToObservation } from "./heart-rate.js";
7
+ import { weightToObservation } from "./weight.js";
8
+ import { spo2ToObservation } from "./spo2.js";
9
+ import { temperatureToObservation } from "./temperature.js";
10
+ import { glucoseToObservation } from "./glucose.js";
11
+ import { respiratoryRateToObservation } from "./respiratory-rate.js";
12
+ export { bloodPressureToObservation, heartRateToObservation, weightToObservation, spo2ToObservation, temperatureToObservation, glucoseToObservation, respiratoryRateToObservation, };
13
+ /**
14
+ * Generic dispatcher that maps any supported DeviceReading to a FHIR Observation
15
+ * based on reading.deviceType.
16
+ */
17
+ export declare function toObservation(reading: DeviceReading, config?: GeneratorConfig): FhirObservation;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Per-vital FHIR Observation generators index and generic dispatcher.
3
+ */
4
+ import { bloodPressureToObservation } from "./blood-pressure.js";
5
+ import { heartRateToObservation } from "./heart-rate.js";
6
+ import { weightToObservation } from "./weight.js";
7
+ import { spo2ToObservation } from "./spo2.js";
8
+ import { temperatureToObservation } from "./temperature.js";
9
+ import { glucoseToObservation } from "./glucose.js";
10
+ import { respiratoryRateToObservation } from "./respiratory-rate.js";
11
+ export { bloodPressureToObservation, heartRateToObservation, weightToObservation, spo2ToObservation, temperatureToObservation, glucoseToObservation, respiratoryRateToObservation, };
12
+ /**
13
+ * Generic dispatcher that maps any supported DeviceReading to a FHIR Observation
14
+ * based on reading.deviceType.
15
+ */
16
+ export function toObservation(reading, config) {
17
+ if (!reading || !reading.deviceType) {
18
+ throw new Error("Invalid reading: deviceType property is required");
19
+ }
20
+ switch (reading.deviceType) {
21
+ case "blood-pressure":
22
+ return bloodPressureToObservation(reading, config);
23
+ case "heart-rate":
24
+ return heartRateToObservation(reading, config);
25
+ case "weight":
26
+ return weightToObservation(reading, config);
27
+ case "spo2":
28
+ return spo2ToObservation(reading, config);
29
+ case "temperature":
30
+ return temperatureToObservation(reading, config);
31
+ case "glucose":
32
+ return glucoseToObservation(reading, config);
33
+ case "respiratory-rate":
34
+ return respiratoryRateToObservation(reading, config);
35
+ default:
36
+ throw new Error(`Unsupported deviceType: '${reading.deviceType}'`);
37
+ }
38
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Respiratory Rate Observation Generator.
3
+ */
4
+ import { DeviceReading, FhirObservation, GeneratorConfig } from "../types.js";
5
+ export declare function respiratoryRateToObservation(reading: DeviceReading, config?: GeneratorConfig): FhirObservation;