@dcmjs-org/fhir 0.0.0-bootstrap.0 → 1.0.0-beta.3

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.
@@ -0,0 +1,317 @@
1
+ // packages/fhir/test/documentReference.test.js
2
+ //
3
+ // FHIR DocumentReference from Encapsulated PDF instances — the "PDF out of
4
+ // PACS" mapping. buildPdfDataset constructs the naturalized shape of
5
+ // @dcmjs-org/encapsulated's encapsulatePdf directly, with fixed UIDs and
6
+ // payload shapes for each case. The round-trip case still serializes and
7
+ // re-reads through @dcmjs-org/legacy (test-only; the package itself never
8
+ // imports legacy), and the image fixture naturalizes through
9
+ // @dcmjs-org/parser as in toFhir.test.js.
10
+
11
+ import fs from "fs";
12
+ import path from "path";
13
+ import { validationLog } from "@dcmjs-org/core";
14
+ import { fromPart10, NaturalizedListener } from "@dcmjs-org/parser";
15
+ import { datasetToBuffer, DicomMessage } from "@dcmjs-org/legacy";
16
+ import { DicomMetaDictionary } from "@dcmjs-org/core";
17
+ import {
18
+ toFhir,
19
+ toBundle,
20
+ documentReferenceFromDataset
21
+ } from "../src/index.js";
22
+
23
+ validationLog.setLevel(5);
24
+
25
+ const ENCAPSULATED_PDF_SOP_CLASS_UID = "1.2.840.10008.5.1.4.1.1.104.1";
26
+
27
+ const PDF_STRING =
28
+ "%PDF-1.4\n" +
29
+ "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n" +
30
+ "trailer<</Size 2/Root 1 0 R>>\n" +
31
+ "%%EOF";
32
+ const PDF_BYTES = new TextEncoder().encode(PDF_STRING);
33
+
34
+ const FIXTURE = path.join(
35
+ __dirname,
36
+ "..",
37
+ "..",
38
+ "fixtures",
39
+ "dicom",
40
+ "sample-dicom.dcm"
41
+ );
42
+
43
+ async function loadNaturalizedFixture() {
44
+ const buffer = fs.readFileSync(FIXTURE);
45
+ const arrayBuffer = buffer.buffer.slice(
46
+ buffer.byteOffset,
47
+ buffer.byteOffset + buffer.byteLength
48
+ );
49
+ const listener = new NaturalizedListener();
50
+ await fromPart10(arrayBuffer, listener);
51
+ return listener.result;
52
+ }
53
+
54
+ /** Standalone ArrayBuffer copy of a byte payload. */
55
+ function toArrayBuffer(bytes) {
56
+ return bytes.buffer.slice(
57
+ bytes.byteOffset,
58
+ bytes.byteOffset + bytes.byteLength
59
+ );
60
+ }
61
+
62
+ // The naturalized shape dcmjs.encapsulated.encapsulatePdf emits in v2:
63
+ // Encapsulated PDF SOP class, DOC modality, the document as an
64
+ // ArrayBuffer, plus the identifying attributes.
65
+ function buildPdfDataset(options = {}) {
66
+ return {
67
+ SOPClassUID: ENCAPSULATED_PDF_SOP_CLASS_UID,
68
+ SOPInstanceUID: "1.2.3.4.5.6.7",
69
+ StudyInstanceUID: "1.2.3.4.5",
70
+ SeriesInstanceUID: "1.2.3.4.5.1",
71
+ Modality: "DOC",
72
+ MIMETypeOfEncapsulatedDocument: "application/pdf",
73
+ EncapsulatedDocument: toArrayBuffer(PDF_BYTES),
74
+ PatientName: [{ Alphabetic: "Doe^Jane" }],
75
+ PatientID: "MRN-42",
76
+ DocumentTitle: "Discharge Summary",
77
+ ContentDate: "20260803",
78
+ ContentTime: "101500",
79
+ TimezoneOffsetFromUTC: "-0600",
80
+ ...options
81
+ };
82
+ }
83
+
84
+ describe("documentReferenceFromDataset", () => {
85
+ test("maps an Encapsulated PDF dataset to a DocumentReference", () => {
86
+ const dataset = buildPdfDataset();
87
+ const documentReference = documentReferenceFromDataset(dataset);
88
+
89
+ expect(documentReference.resourceType).toBe("DocumentReference");
90
+ expect(documentReference.status).toBe("current");
91
+ expect(documentReference.masterIdentifier).toEqual({
92
+ system: "urn:dicom:uid",
93
+ value: `urn:oid:${dataset.SOPInstanceUID}`
94
+ });
95
+ expect(documentReference.description).toBe("Discharge Summary");
96
+ expect(documentReference.date).toBe("2026-08-03T10:15:00-06:00");
97
+
98
+ const attachment = documentReference.content[0].attachment;
99
+ expect(attachment.contentType).toBe("application/pdf");
100
+ expect(attachment.title).toBe("Discharge Summary");
101
+ expect(attachment.size).toBe(PDF_BYTES.byteLength);
102
+ // base64 round-trip is byte-identical to the original PDF
103
+ expect(Buffer.from(attachment.data, "base64").toString("latin1")).toBe(
104
+ PDF_STRING
105
+ );
106
+
107
+ // Attached to the originating study
108
+ expect(documentReference.context.related[0].identifier).toEqual({
109
+ system: "urn:dicom:uid",
110
+ value: "urn:oid:1.2.3.4.5"
111
+ });
112
+ });
113
+
114
+ test("omits date when the dataset has no timezone (an instant needs one)", () => {
115
+ const documentReference = documentReferenceFromDataset(
116
+ buildPdfDataset({ TimezoneOffsetFromUTC: undefined })
117
+ );
118
+ expect(documentReference.date).toBeUndefined();
119
+ });
120
+
121
+ test("honors subject and includeData options", () => {
122
+ const dataset = buildPdfDataset();
123
+ const documentReference = documentReferenceFromDataset(dataset, {
124
+ subject: { reference: "Patient/12345" },
125
+ includeData: false
126
+ });
127
+
128
+ expect(documentReference.subject).toEqual({
129
+ reference: "Patient/12345"
130
+ });
131
+ const attachment = documentReference.content[0].attachment;
132
+ expect(attachment.data).toBeUndefined();
133
+ expect(attachment.size).toBe(PDF_BYTES.byteLength);
134
+ });
135
+
136
+ test("uses ConceptNameCodeSequence for type when present", () => {
137
+ const dataset = buildPdfDataset({
138
+ ConceptNameCodeSequence: {
139
+ CodeValue: "18842-5",
140
+ CodingSchemeDesignator: "LN",
141
+ CodeMeaning: "Discharge summary"
142
+ }
143
+ });
144
+ const documentReference = documentReferenceFromDataset(dataset);
145
+ expect(documentReference.type.coding[0].code).toBe("18842-5");
146
+ expect(documentReference.type.coding[0].display).toBe(
147
+ "Discharge summary"
148
+ );
149
+ });
150
+
151
+ test("returns null for a non-encapsulated dataset", async () => {
152
+ const dataset = await loadNaturalizedFixture();
153
+ expect(documentReferenceFromDataset(dataset)).toBeNull();
154
+ });
155
+
156
+ test("survives a Part 10 round trip (odd-length OB padding)", () => {
157
+ const source = buildPdfDataset({
158
+ _meta: {
159
+ TransferSyntaxUID: { Value: ["1.2.840.10008.1.2.1"] }
160
+ }
161
+ });
162
+ const buffer = datasetToBuffer(source);
163
+ const arrayBuffer = buffer.buffer.slice(
164
+ buffer.byteOffset,
165
+ buffer.byteOffset + buffer.byteLength
166
+ );
167
+ const readBack = DicomMetaDictionary.naturalizeDataset(
168
+ DicomMessage.readFile(arrayBuffer).dict
169
+ );
170
+
171
+ const documentReference = documentReferenceFromDataset(readBack);
172
+ const attachment = documentReference.content[0].attachment;
173
+ // Trailing NUL pad trimmed: size and payload match the original PDF
174
+ expect(attachment.size).toBe(PDF_BYTES.byteLength);
175
+ expect(Buffer.from(attachment.data, "base64").toString("latin1")).toBe(
176
+ PDF_STRING
177
+ );
178
+ });
179
+
180
+ // Regression for review finding 8: the event-stream naturalizer wraps
181
+ // binary elements with no decoded Value as { InlineBinary } (base64
182
+ // string, ArrayBuffer, or view). payloadBytes never unwrapped that
183
+ // shape — new Uint8Array(<plain object>) is empty — so every
184
+ // naturalized encapsulated document silently mapped to
185
+ // { size: 0, data: "" }.
186
+ test("unwraps { InlineBinary } base64 byte-exactly (finding 8)", () => {
187
+ const base64 = Buffer.from(PDF_BYTES).toString("base64");
188
+ const dataset = buildPdfDataset({
189
+ EncapsulatedDocument: { InlineBinary: base64 }
190
+ });
191
+ const documentReference = documentReferenceFromDataset(dataset);
192
+ const attachment = documentReference.content[0].attachment;
193
+ expect(attachment.size).toBe(PDF_BYTES.byteLength);
194
+ expect(new Uint8Array(Buffer.from(attachment.data, "base64"))).toEqual(
195
+ PDF_BYTES
196
+ );
197
+ });
198
+
199
+ test("unwraps { InlineBinary } ArrayBuffer and view shapes (finding 8)", () => {
200
+ for (const inline of [
201
+ toArrayBuffer(PDF_BYTES),
202
+ new Uint8Array(toArrayBuffer(PDF_BYTES))
203
+ ]) {
204
+ const dataset = buildPdfDataset({
205
+ EncapsulatedDocument: { InlineBinary: inline }
206
+ });
207
+ const attachment =
208
+ documentReferenceFromDataset(dataset).content[0].attachment;
209
+ expect(attachment.size).toBe(PDF_BYTES.byteLength);
210
+ expect(
211
+ new Uint8Array(Buffer.from(attachment.data, "base64"))
212
+ ).toEqual(PDF_BYTES);
213
+ }
214
+ });
215
+
216
+ // Regression for review finding 16: the Part 10 writer pads only
217
+ // odd-length OB values, so an even stored length has no pad byte —
218
+ // but the heuristic trimmed a trailing 0x00 anyway, corrupting any
219
+ // even-length payload that genuinely ends in a zero byte (ordinary
220
+ // for STL/OBJ/CDA/octet-stream). EncapsulatedDocumentLength
221
+ // (0042,0015) carries the exact length and must win when present.
222
+ test("EncapsulatedDocumentLength preserves a real trailing zero (finding 16)", () => {
223
+ const payload = new Uint8Array([
224
+ 0x53, 0x54, 0x4c, 0x20, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x00
225
+ ]); // 10 bytes, even, ends in a real 0x00
226
+ const dataset = buildPdfDataset({
227
+ MIMETypeOfEncapsulatedDocument: "model/stl",
228
+ EncapsulatedDocument: toArrayBuffer(payload),
229
+ EncapsulatedDocumentLength: 10
230
+ });
231
+ const attachment =
232
+ documentReferenceFromDataset(dataset).content[0].attachment;
233
+ expect(attachment.size).toBe(10);
234
+ expect(new Uint8Array(Buffer.from(attachment.data, "base64"))).toEqual(
235
+ payload
236
+ );
237
+ });
238
+
239
+ test("EncapsulatedDocumentLength trims the pad the writer added (finding 16)", () => {
240
+ // 9 content bytes padded to 10 on write; (0042,0015) says 9.
241
+ const padded = new Uint8Array([
242
+ 0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34, 0x00, 0x00
243
+ ]);
244
+ const dataset = buildPdfDataset({
245
+ EncapsulatedDocument: toArrayBuffer(padded),
246
+ EncapsulatedDocumentLength: 9
247
+ });
248
+ const attachment =
249
+ documentReferenceFromDataset(dataset).content[0].attachment;
250
+ expect(attachment.size).toBe(9);
251
+ expect(new Uint8Array(Buffer.from(attachment.data, "base64"))).toEqual(
252
+ padded.subarray(0, 9)
253
+ );
254
+ });
255
+ });
256
+
257
+ describe("toFhir / toBundle integration", () => {
258
+ test("toFhir yields { patient, documentReference } for encapsulated PDFs", () => {
259
+ const { patient, imagingStudy, documentReference } = toFhir(
260
+ buildPdfDataset()
261
+ );
262
+ expect(patient.resourceType).toBe("Patient");
263
+ expect(patient.identifier[0].value).toBe("MRN-42");
264
+ expect(imagingStudy).toBeNull();
265
+ expect(documentReference.resourceType).toBe("DocumentReference");
266
+ });
267
+
268
+ test("toFhir still yields imagingStudy (and null documentReference) for images", async () => {
269
+ const dataset = await loadNaturalizedFixture();
270
+ const { imagingStudy, documentReference } = toFhir(dataset);
271
+ expect(imagingStudy.resourceType).toBe("ImagingStudy");
272
+ expect(documentReference).toBeNull();
273
+ });
274
+
275
+ test("toBundle includes DocumentReference entries", () => {
276
+ const bundle = toBundle([buildPdfDataset()]);
277
+ const resourceTypes = bundle.entry.map(
278
+ entry => entry.resource.resourceType
279
+ );
280
+ expect(resourceTypes).toContain("Patient");
281
+ expect(resourceTypes).toContain("DocumentReference");
282
+ expect(bundle.total).toBe(bundle.entry.length);
283
+ });
284
+
285
+ test("toBundle skips a document of another patient (FHIR-USR-3)", () => {
286
+ const bundle = toBundle([
287
+ buildPdfDataset(),
288
+ buildPdfDataset({
289
+ PatientID: "OTHER",
290
+ SOPInstanceUID: "1.2.3.4.5.6.8"
291
+ })
292
+ ]);
293
+ const documents = bundle.entry.filter(
294
+ entry => entry.resource.resourceType === "DocumentReference"
295
+ );
296
+ expect(documents).toHaveLength(1);
297
+ expect(documents[0].resource.subject).toEqual({
298
+ reference: "./entry/0"
299
+ });
300
+ });
301
+ });
302
+
303
+ describe("a document that is not in the dataset", () => {
304
+ test("a { BulkDataURI } payload gives attachment.url, and no size or data", () => {
305
+ const documentReference = documentReferenceFromDataset(
306
+ buildPdfDataset({
307
+ EncapsulatedDocument: { BulkDataURI: "http://x/bulk/1" },
308
+ EncapsulatedDocumentLength: undefined
309
+ })
310
+ );
311
+ expect(documentReference.content[0].attachment).toEqual({
312
+ contentType: "application/pdf",
313
+ title: "Discharge Summary",
314
+ url: "http://x/bulk/1"
315
+ });
316
+ });
317
+ });
@@ -0,0 +1,234 @@
1
+ // packages/fhir/test/patientToDataset.test.js
2
+ //
3
+ // The FHIR source direction: Patient resource → DICOM patient-module
4
+ // attributes. Test identity: JANE DOE (maiden) → JANE FOX (official).
5
+ // The genderToSex table is pinned exhaustively — administrative gender
6
+ // only, lossy by design, empty for unknown/absent.
7
+
8
+ // Imports point at the concrete modules rather than the package index:
9
+ // the index (and the toFhir surface it exports) lands in a later slice.
10
+ import { patientToDataset } from "../src/patientToDataset.js";
11
+ import { patientFromDataset } from "../src/patient.js";
12
+ import {
13
+ genderToSex,
14
+ humanNameToPersonName,
15
+ isoDateToDicom
16
+ } from "../src/helpers.js";
17
+
18
+ const JANE_FOX = {
19
+ resourceType: "Patient",
20
+ identifier: [
21
+ {
22
+ use: "usual",
23
+ type: {
24
+ coding: [
25
+ {
26
+ system: "http://terminology.hl7.org/CodeSystem/v2-0203",
27
+ code: "MR",
28
+ display: "Medical Record Number"
29
+ }
30
+ ]
31
+ },
32
+ value: "22446688"
33
+ }
34
+ ],
35
+ name: [
36
+ { use: "official", family: "FOX", given: ["JANE"] },
37
+ { use: "maiden", family: "DOE", given: ["JANE"] }
38
+ ],
39
+ gender: "female",
40
+ birthDate: "1980-04-15"
41
+ };
42
+
43
+ describe("patientToDataset", () => {
44
+ test("maps the full JANE FOX resource", () => {
45
+ expect(patientToDataset(JANE_FOX)).toEqual({
46
+ PatientName: "FOX^JANE",
47
+ PatientID: "22446688",
48
+ PatientBirthDate: "19800415",
49
+ PatientSex: "F"
50
+ });
51
+ });
52
+
53
+ test("official name wins over maiden regardless of order", () => {
54
+ const maidenFirst = {
55
+ ...JANE_FOX,
56
+ name: [
57
+ { use: "maiden", family: "DOE", given: ["JANE"] },
58
+ { use: "official", family: "FOX", given: ["JANE"] }
59
+ ]
60
+ };
61
+ expect(patientToDataset(maidenFirst).PatientName).toBe("FOX^JANE");
62
+ });
63
+
64
+ test("usual name is second preference; unadorned beats maiden", () => {
65
+ const usual = {
66
+ ...JANE_FOX,
67
+ name: [
68
+ { use: "maiden", family: "DOE", given: ["JANE"] },
69
+ { use: "usual", family: "FOX", given: ["JANE"] }
70
+ ]
71
+ };
72
+ expect(patientToDataset(usual).PatientName).toBe("FOX^JANE");
73
+
74
+ const unadorned = {
75
+ ...JANE_FOX,
76
+ name: [
77
+ { use: "maiden", family: "DOE", given: ["JANE"] },
78
+ { family: "FOX", given: ["JANE"] }
79
+ ]
80
+ };
81
+ expect(patientToDataset(unadorned).PatientName).toBe("FOX^JANE");
82
+ });
83
+
84
+ test("MR-typed identifier wins over other identifiers", () => {
85
+ const multiId = {
86
+ ...JANE_FOX,
87
+ identifier: [
88
+ {
89
+ system: "urn:oid:2.16.840.1.113883.4.1",
90
+ value: "999-99-9999"
91
+ },
92
+ JANE_FOX.identifier[0]
93
+ ]
94
+ };
95
+ expect(patientToDataset(multiId).PatientID).toBe("22446688");
96
+ });
97
+
98
+ test("deterministic overwrite: absent fields are empty strings", () => {
99
+ expect(patientToDataset({ resourceType: "Patient" })).toEqual({
100
+ PatientName: "",
101
+ PatientID: "",
102
+ PatientBirthDate: "",
103
+ PatientSex: ""
104
+ });
105
+ });
106
+
107
+ test("partial FHIR birthDate maps to empty, never a fabricated day", () => {
108
+ expect(
109
+ patientToDataset({ ...JANE_FOX, birthDate: "1980" })
110
+ .PatientBirthDate
111
+ ).toBe("");
112
+ expect(
113
+ patientToDataset({ ...JANE_FOX, birthDate: "1980-04" })
114
+ .PatientBirthDate
115
+ ).toBe("");
116
+ });
117
+
118
+ test("non-Patient input throws with the resourceType named", () => {
119
+ expect(() => patientToDataset({ resourceType: "Observation" })).toThrow(
120
+ /expects a FHIR Patient.*Observation/
121
+ );
122
+ expect(() => patientToDataset(null)).toThrow(/expects a FHIR Patient/);
123
+ });
124
+ });
125
+
126
+ describe("genderToSex — the full table", () => {
127
+ test.each([
128
+ ["male", "M"],
129
+ ["female", "F"],
130
+ ["other", "O"],
131
+ ["unknown", ""],
132
+ ["", ""],
133
+ [null, ""],
134
+ [undefined, ""],
135
+ ["Male", "M"], // case-insensitive
136
+ ["FEMALE", "F"],
137
+ ["Unknown", ""],
138
+ ["nonbinary", "O"], // unrecognized non-empty → O, never a guess
139
+ ["x", "O"]
140
+ ])("%p → %p", (gender, expected) => {
141
+ expect(genderToSex(gender)).toBe(expected);
142
+ });
143
+ });
144
+
145
+ describe("round trips with the sink direction", () => {
146
+ test("dataset → Patient → dataset is stable for JANE FOX", () => {
147
+ const dataset = {
148
+ PatientName: [{ Alphabetic: "FOX^JANE" }],
149
+ PatientID: "22446688",
150
+ PatientBirthDate: "19800415",
151
+ PatientSex: "F"
152
+ };
153
+ const resource = patientFromDataset(dataset);
154
+ expect(patientToDataset(resource)).toEqual({
155
+ PatientName: "FOX^JANE",
156
+ PatientID: "22446688",
157
+ PatientBirthDate: "19800415",
158
+ PatientSex: "F"
159
+ });
160
+ });
161
+
162
+ test("PatientSex M/F/O survive the round trip; empty stays empty", () => {
163
+ for (const sex of ["M", "F", "O"]) {
164
+ const resource = patientFromDataset({
165
+ PatientID: "22446688",
166
+ PatientSex: sex
167
+ });
168
+ expect(patientToDataset(resource).PatientSex).toBe(sex);
169
+ }
170
+ // empty PatientSex → gender "unknown" → empty PatientSex
171
+ const resource = patientFromDataset({
172
+ PatientID: "22446688",
173
+ PatientSex: ""
174
+ });
175
+ expect(resource.gender).toBe("unknown");
176
+ expect(patientToDataset(resource).PatientSex).toBe("");
177
+ });
178
+
179
+ test("full PN components survive", () => {
180
+ const resource = patientFromDataset({
181
+ PatientID: "1",
182
+ PatientName: [{ Alphabetic: "FOX^JANE^MARIE^DR^III" }]
183
+ });
184
+ expect(patientToDataset(resource).PatientName).toBe(
185
+ "FOX^JANE^MARIE^DR^III"
186
+ );
187
+ });
188
+ });
189
+
190
+ describe("inverse helpers", () => {
191
+ test("humanNameToPersonName trims trailing empties", () => {
192
+ expect(humanNameToPersonName({ family: "FOX", given: ["JANE"] })).toBe(
193
+ "FOX^JANE"
194
+ );
195
+ expect(humanNameToPersonName({ given: ["JANE"] })).toBe("^JANE");
196
+ expect(humanNameToPersonName({})).toBe(null);
197
+ expect(humanNameToPersonName(null)).toBe(null);
198
+ });
199
+
200
+ // Regression for review finding 19: a HumanName carrying only `text`
201
+ // used to map to null, and patientToDataset's deterministic overwrite
202
+ // then erased the existing PatientName. Text-only names are common in
203
+ // real FHIR feeds, so `text` must survive as a single-component PN.
204
+ test("text-only HumanName falls back to text (finding 19)", () => {
205
+ expect(humanNameToPersonName({ text: "Jane Doe" })).toBe("Jane Doe");
206
+
207
+ const result = patientToDataset({
208
+ resourceType: "Patient",
209
+ name: [{ text: "Jane Doe" }],
210
+ gender: "female"
211
+ });
212
+ expect(result.PatientName).toBe("Jane Doe");
213
+ expect(result.PatientName).not.toBe("");
214
+ });
215
+
216
+ test("structured parts still win over text (finding 19)", () => {
217
+ expect(
218
+ humanNameToPersonName({
219
+ family: "FOX",
220
+ given: ["JANE"],
221
+ text: "Jane Fox"
222
+ })
223
+ ).toBe("FOX^JANE");
224
+ });
225
+
226
+ test("isoDateToDicom accepts full dates and passthrough DA", () => {
227
+ expect(isoDateToDicom("1980-04-15")).toBe("19800415");
228
+ expect(isoDateToDicom("19800415")).toBe("19800415");
229
+ expect(isoDateToDicom("1980-04-15T10:30:00Z")).toBe("19800415");
230
+ expect(isoDateToDicom("1980")).toBe(null);
231
+ expect(isoDateToDicom("1980-04")).toBe(null);
232
+ expect(isoDateToDicom("")).toBe(null);
233
+ });
234
+ });