@dcmjs-org/fhir 1.0.0-beta.4 → 1.0.0-beta.5

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/dist/index.mjs ADDED
@@ -0,0 +1,1023 @@
1
+ import { toStringFirst, MODALITY_DISPLAY, validationLog, toFloatFirst, encodeBase64 } from '@dcmjs-org/core';
2
+ import { extractEncapsulated, PDF_MIME_TYPE, ENCAPSULATED_PDF_SOP_CLASS_UID } from '@dcmjs-org/encapsulated';
3
+
4
+ // packages/fhir/src/helpers.js
5
+ //
6
+ // Shared DICOM → FHIR value mappers. Inputs are values from a NATURALIZED
7
+ // dcmjs dataset (DicomMetaDictionary.naturalizeDataset): keyword keys,
8
+ // single-value arrays collapsed to scalars, PN values as [{ Alphabetic }],
9
+ // IS values as numbers. Helpers are permissive about input shape
10
+ // (string / number / array / PN object) and strict about output — absent
11
+ // or unparseable inputs return null, never partial garbage.
12
+
13
+
14
+ const DICOM_UID_SYSTEM = "urn:dicom:uid";
15
+ const DICOM_MODALITY_SYSTEM =
16
+ "http://dicom.nema.org/resources/ontology/DCM";
17
+
18
+ /**
19
+ * Prefix a DICOM UID with urn:oid: for FHIR identifier/uid slots.
20
+ */
21
+ function uidToUrn(uid) {
22
+ const clean = toStringFirst(uid);
23
+ if (!clean) {
24
+ return null;
25
+ }
26
+ return clean.startsWith("urn:oid:") ? clean : `urn:oid:${clean}`;
27
+ }
28
+
29
+ /**
30
+ * DICOM DA (YYYYMMDD) + optional TM (HHMMSS.ffffff) → a FHIR dateTime.
31
+ *
32
+ * FHIR requires a timezone when a dateTime has a time. The time is written
33
+ * only with a valid `timezoneOffset` (TimezoneOffsetFromUTC (0008,0201),
34
+ * "+HHMM" or "-HHMM"); without it the result is the date only, which is
35
+ * a valid dateTime that asserts no zone.
36
+ *
37
+ * The date must be YYYYMMDD (the ACR-NEMA form YYYY.MM.DD is accepted), else
38
+ * the result is null. The time must start with HHMMSS (the form HH:MM:SS is
39
+ * accepted), else the result is the date only.
40
+ */
41
+ function dicomDateTimeToIso(dicomDate, dicomTime, timezoneOffset) {
42
+ const rawDate = toStringFirst(dicomDate);
43
+ const date = /^\d{4}\.\d{2}\.\d{2}$/.test(rawDate || "")
44
+ ? rawDate.replace(/\./g, "")
45
+ : rawDate;
46
+ if (!date || !/^\d{8}$/.test(date)) {
47
+ return null;
48
+ }
49
+
50
+ let iso = `${date.substring(0, 4)}-${date.substring(4, 6)}-${date.substring(
51
+ 6,
52
+ 8
53
+ )}`;
54
+
55
+ const rawTime = toStringFirst(dicomTime);
56
+ const time = /^\d{2}:\d{2}:\d{2}/.test(rawTime || "")
57
+ ? rawTime.replace(/:/g, "")
58
+ : rawTime;
59
+ const offset = toStringFirst(timezoneOffset);
60
+ if (time && /^\d{6}/.test(time) && offset && /^[+-]\d{4}$/.test(offset)) {
61
+ iso +=
62
+ `T${time.substring(0, 2)}:${time.substring(2, 4)}:` +
63
+ `${time.substring(4, 6)}${offset.substring(0, 3)}:` +
64
+ offset.substring(3);
65
+ }
66
+
67
+ return iso;
68
+ }
69
+
70
+ /**
71
+ * DICOM DA + TM + TimezoneOffsetFromUTC → a FHIR instant, or null when a
72
+ * part is missing (an instant needs the full time and the zone).
73
+ */
74
+ function dicomDateTimeToInstant(dicomDate, dicomTime, timezoneOffset) {
75
+ const iso = dicomDateTimeToIso(dicomDate, dicomTime, timezoneOffset);
76
+ return iso && iso.includes("T") ? iso : null;
77
+ }
78
+
79
+ /**
80
+ * Parse a DICOM person name into FHIR HumanName parts.
81
+ * Accepts the naturalized PN shape ([{ Alphabetic: "Family^Given" }] or
82
+ * { Alphabetic }) as well as a raw "Family^Given^Middle^Prefix^Suffix"
83
+ * string.
84
+ * @returns {Object|null} { family, given, middle, prefix, suffix, text }
85
+ */
86
+ function parsePersonName(pnValue) {
87
+ let raw = pnValue;
88
+ if (Array.isArray(raw)) {
89
+ raw = raw.length > 0 ? raw[0] : null;
90
+ }
91
+ if (raw && typeof raw === "object" && "Alphabetic" in raw) {
92
+ raw = raw.Alphabetic;
93
+ }
94
+ if (typeof raw !== "string" || raw.trim().length === 0) {
95
+ return null;
96
+ }
97
+
98
+ const parts = raw.split("^");
99
+ return {
100
+ family: parts[0] || "",
101
+ given: parts[1] || "",
102
+ middle: parts[2] || "",
103
+ prefix: parts[3] || "",
104
+ suffix: parts[4] || "",
105
+ text: parts.filter(part => part).join(" ")
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Parsed person name → FHIR HumanName element (or null when empty).
111
+ */
112
+ function personNameToHumanName(parsed) {
113
+ if (!parsed) {
114
+ return null;
115
+ }
116
+ const humanName = {};
117
+ if (parsed.family) {
118
+ humanName.family = parsed.family;
119
+ }
120
+ const given = [parsed.given, parsed.middle].filter(Boolean);
121
+ if (given.length > 0) {
122
+ humanName.given = given;
123
+ }
124
+ if (parsed.prefix) {
125
+ humanName.prefix = [parsed.prefix];
126
+ }
127
+ if (parsed.suffix) {
128
+ humanName.suffix = [parsed.suffix];
129
+ }
130
+ if (parsed.text) {
131
+ humanName.text = parsed.text;
132
+ }
133
+ return Object.keys(humanName).length > 0 ? humanName : null;
134
+ }
135
+
136
+ /**
137
+ * DICOM PatientSex (M/F/O) → FHIR administrative gender. PatientSex is an
138
+ * administrative value, so the Patient gets no birth-sex or clinical-sex
139
+ * extension from it (FHIR-USR-3).
140
+ */
141
+ function sexToGender(dicomSex) {
142
+ const mapping = { M: "male", F: "female", O: "other" };
143
+ return mapping[toStringFirst(dicomSex)] || "unknown";
144
+ }
145
+
146
+ /**
147
+ * FHIR administrative gender → DICOM PatientSex (0010,0040).
148
+ *
149
+ * FHIR `Patient.gender` is *administrative
150
+ * gender*; DICOM PatientSex is a three-letter administrative repertoire
151
+ * (M / F / O, Type 2 so empty is legal). These are not the same concept as
152
+ * clinical sex or gender identity, and this mapping deliberately consults
153
+ * ONLY `Patient.gender` — never US Core birthsex / sex-for-clinical-use
154
+ * extensions, which carry different semantics and belong to profiles, not
155
+ * the base resource. The mapping is lossy by design:
156
+ *
157
+ * male → M
158
+ * female → F
159
+ * other → O (as does any unrecognized non-empty value — DICOM has
160
+ * no better bucket, and inventing codes would be worse)
161
+ * unknown → "" (DICOM PatientSex is Type 2: present-but-empty is the
162
+ * standard way to say "not known")
163
+ * absent/blank → ""
164
+ *
165
+ * Mirrors sexToGender above, so M/F/O round-trip exactly and empty ⇄
166
+ * unknown round-trips to empty.
167
+ */
168
+ function genderToSex(gender) {
169
+ const value = toStringFirst(gender);
170
+ if (!value) {
171
+ return "";
172
+ }
173
+ const normalized = value.toLowerCase();
174
+ if (normalized === "male") {
175
+ return "M";
176
+ }
177
+ if (normalized === "female") {
178
+ return "F";
179
+ }
180
+ if (normalized === "unknown") {
181
+ return "";
182
+ }
183
+ return "O";
184
+ }
185
+
186
+ /**
187
+ * FHIR HumanName → DICOM PN string ("Family^Given^Middle^Prefix^Suffix").
188
+ * Inverse of parsePersonName/personNameToHumanName: given[0] is the given
189
+ * name, given[1] the middle; only the first prefix/suffix survive (PN has
190
+ * one slot each). Trailing empty components are trimmed per PN convention.
191
+ *
192
+ * When the name carries no structured parts at all, `HumanName.text`
193
+ * (when present) survives as a single-component PN rather than returning
194
+ * null — a text-only name must not erase an existing PatientName under
195
+ * patientToDataset's deterministic overwrite (review finding 19). The
196
+ * text is used whole; guessing a "Family, Given" split from free text
197
+ * would fabricate structure the resource never asserted.
198
+ * @returns {string|null} null when the name carries no usable parts
199
+ */
200
+ function humanNameToPersonName(humanName) {
201
+ if (!humanName || typeof humanName !== "object") {
202
+ return null;
203
+ }
204
+ const given = Array.isArray(humanName.given) ? humanName.given : [];
205
+ const components = [
206
+ toStringFirst(humanName.family) || "",
207
+ toStringFirst(given[0]) || "",
208
+ toStringFirst(given[1]) || "",
209
+ toStringFirst(
210
+ Array.isArray(humanName.prefix) ? humanName.prefix[0] : null
211
+ ) || "",
212
+ toStringFirst(
213
+ Array.isArray(humanName.suffix) ? humanName.suffix[0] : null
214
+ ) || ""
215
+ ];
216
+ while (components.length && components[components.length - 1] === "") {
217
+ components.pop();
218
+ }
219
+ const pn = components.join("^");
220
+ if (pn.length > 0) {
221
+ return pn;
222
+ }
223
+ // No structured parts: fall back to the free-text form, if any.
224
+ return toStringFirst(humanName.text);
225
+ }
226
+
227
+ /**
228
+ * FHIR date (ISO 8601) → DICOM DA (YYYYMMDD). Inverse of
229
+ * dicomDateTimeToIso for the date part. FHIR allows partial dates (YYYY,
230
+ * YYYY-MM); DICOM DA does not — partial dates return null rather than a
231
+ * fabricated day.
232
+ */
233
+ function isoDateToDicom(isoDate) {
234
+ const value = toStringFirst(isoDate);
235
+ if (!value) {
236
+ return null;
237
+ }
238
+ if (/^\d{8}$/.test(value)) {
239
+ return value;
240
+ }
241
+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})/);
242
+ return match ? `${match[1]}${match[2]}${match[3]}` : null;
243
+ }
244
+
245
+ /**
246
+ * FHIR Coding for a DICOM modality code.
247
+ */
248
+ function modalityCoding(modalityCode) {
249
+ const code = toStringFirst(modalityCode);
250
+ if (!code) {
251
+ return null;
252
+ }
253
+ return {
254
+ system: DICOM_MODALITY_SYSTEM,
255
+ code,
256
+ display: MODALITY_DISPLAY[code] || code
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Guard: only R4B is implemented. Throws on anything else so callers
262
+ * never silently receive the wrong flavor of JSON.
263
+ */
264
+ function assertSupportedFhirVersion(options = {}) {
265
+ const version = options.fhirVersion || "R4B";
266
+ if (version !== "R4B" && version !== "R4") {
267
+ throw new Error(
268
+ `@dcmjs/fhir: unsupported fhirVersion "${version}" (supported: R4, R4B)`
269
+ );
270
+ }
271
+ return version;
272
+ }
273
+
274
+ // packages/fhir/src/patient.js
275
+ //
276
+ // FHIR R4B Patient from the DICOM patient module (group 0010) of a
277
+ // naturalized dataset. Emits standard FHIR only — no ids, no meta.tags,
278
+ // no storage references. Id assignment and any deployment-specific
279
+ // decoration are the consumer's job.
280
+
281
+
282
+ /**
283
+ * Build a FHIR Patient resource from a naturalized DICOM dataset.
284
+ * @param {Object} dataset - DicomMetaDictionary.naturalizeDataset output
285
+ * @returns {Object|null} FHIR Patient, or null when the dataset carries
286
+ * no usable patient module (no PatientName and no PatientID)
287
+ */
288
+ function patientFromDataset(dataset) {
289
+ if (!dataset) {
290
+ return null;
291
+ }
292
+
293
+ const patientId = toStringFirst(dataset.PatientID);
294
+ const humanName = personNameToHumanName(
295
+ parsePersonName(dataset.PatientName)
296
+ );
297
+
298
+ if (!patientId && !humanName) {
299
+ return null;
300
+ }
301
+
302
+ const patient = {
303
+ resourceType: "Patient"
304
+ };
305
+
306
+ if (patientId) {
307
+ patient.identifier = [
308
+ {
309
+ use: "usual",
310
+ type: {
311
+ coding: [
312
+ {
313
+ system: "http://terminology.hl7.org/CodeSystem/v2-0203",
314
+ code: "MR",
315
+ display: "Medical Record Number"
316
+ }
317
+ ],
318
+ text: "Medical Record Number"
319
+ },
320
+ value: patientId
321
+ }
322
+ ];
323
+ }
324
+
325
+ if (humanName) {
326
+ patient.name = [humanName];
327
+ }
328
+
329
+ const birthDate = dicomDateTimeToIso(dataset.PatientBirthDate);
330
+ if (birthDate) {
331
+ patient.birthDate = birthDate;
332
+ }
333
+
334
+ patient.gender = sexToGender(dataset.PatientSex);
335
+
336
+ return patient;
337
+ }
338
+
339
+ // packages/fhir/src/imagingStudy.js
340
+ //
341
+ // FHIR R4B ImagingStudy from naturalized DICOM dataset(s). The DICOM
342
+ // study/series/instance hierarchy maps directly onto
343
+ // ImagingStudy.series[].instance[] — this is deliberately a thin
344
+ // restatement of the Part 10 elements as FHIR-flavored JSON.
345
+ // Based on the IHE Radiology Technical Framework (MADO) mapping.
346
+
347
+
348
+ function instanceFromDataset(dataset) {
349
+ const sopInstanceUid = toStringFirst(dataset.SOPInstanceUID);
350
+ if (!sopInstanceUid) {
351
+ return null;
352
+ }
353
+
354
+ const sopClassUrn = uidToUrn(dataset.SOPClassUID);
355
+ if (!sopClassUrn) {
356
+ validationLog.warn(
357
+ `@dcmjs-org/fhir: skipping instance ${sopInstanceUid} — ` +
358
+ "no SOPClassUID (instance.sopClass is required 1..1)"
359
+ );
360
+ return null;
361
+ }
362
+
363
+ const instance = {
364
+ uid: sopInstanceUid,
365
+ sopClass: {
366
+ system: "urn:ietf:rfc:3986",
367
+ code: sopClassUrn
368
+ }
369
+ };
370
+
371
+ const number = unsignedIntFirst(dataset.InstanceNumber);
372
+ if (number !== null) {
373
+ instance.number = number;
374
+ }
375
+ const numberOfFrames = unsignedIntFirst(dataset.NumberOfFrames);
376
+ if (numberOfFrames !== null) {
377
+ instance.numberOfFrames = numberOfFrames;
378
+ }
379
+ const title =
380
+ toStringFirst(dataset.SeriesDescription) ||
381
+ toStringFirst(dataset.StudyDescription);
382
+ if (title) {
383
+ instance.title = title;
384
+ }
385
+
386
+ return instance;
387
+ }
388
+
389
+ function seriesShellFromDataset(dataset) {
390
+ const series = {
391
+ uid: toStringFirst(dataset.SeriesInstanceUID),
392
+ instance: []
393
+ };
394
+
395
+ const number = unsignedIntFirst(dataset.SeriesNumber);
396
+ if (number !== null) {
397
+ series.number = number;
398
+ }
399
+ // The caller skips a dataset with no Modality (series.modality is 1..1).
400
+ series.modality = modalityCoding(dataset.Modality);
401
+ const description = toStringFirst(dataset.SeriesDescription);
402
+ if (description) {
403
+ series.description = description;
404
+ }
405
+ const started = dicomDateTimeToIso(
406
+ dataset.SeriesDate,
407
+ dataset.SeriesTime,
408
+ dataset.TimezoneOffsetFromUTC
409
+ );
410
+ if (started) {
411
+ series.started = started;
412
+ }
413
+ // A DICOM defined term is not a SNOMED display, so it has no system.
414
+ const bodyPart = toStringFirst(dataset.BodyPartExamined);
415
+ if (bodyPart) {
416
+ series.bodySite = { display: bodyPart };
417
+ }
418
+ const laterality = toStringFirst(dataset.Laterality);
419
+ if (laterality) {
420
+ series.laterality = LATERALITY_CODING[laterality] || {
421
+ display: laterality
422
+ };
423
+ }
424
+
425
+ return series;
426
+ }
427
+
428
+ /** DICOM Laterality (0020,0060) → SNOMED CT (PS3.16 CID 244). */
429
+ const LATERALITY_CODING = {
430
+ L: { system: "http://snomed.info/sct", code: "7771000", display: "Left" },
431
+ R: { system: "http://snomed.info/sct", code: "24028007", display: "Right" },
432
+ B: {
433
+ system: "http://snomed.info/sct",
434
+ code: "51440002",
435
+ display: "Right and left"
436
+ }
437
+ };
438
+
439
+ function warnSkip(dataset, reason) {
440
+ validationLog.warn(
441
+ "@dcmjs-org/fhir: skipping dataset " +
442
+ `${
443
+ toStringFirst(dataset.SOPInstanceUID) || "<no SOPInstanceUID>"
444
+ } — ${reason}`
445
+ );
446
+ }
447
+
448
+ /** The first value as a FHIR unsignedInt, or null. */
449
+ function unsignedIntFirst(value) {
450
+ const number = toFloatFirst(value);
451
+ return Number.isInteger(number) && number >= 0 ? number : null;
452
+ }
453
+
454
+ /**
455
+ * Build one FHIR ImagingStudy from one or more naturalized datasets
456
+ * belonging to the same study. Instances are grouped by
457
+ * SeriesInstanceUID. The first dataset with a StudyInstanceUID anchors the
458
+ * study-level identity.
459
+ *
460
+ * The mapper never fabricates a value that FHIR requires (FHIR-USR-3). It
461
+ * skips, with a validationLog warning: a dataset of another study, a
462
+ * dataset with no SeriesInstanceUID or no Modality (series.uid and
463
+ * series.modality are 1..1), and an instance with no SOPClassUID
464
+ * (instance.sopClass is 1..1).
465
+ *
466
+ * @param {Object[]} datasets - naturalized datasets (same StudyInstanceUID)
467
+ * @param {Object} [options]
468
+ * @param {Object} [options.subject] - FHIR Reference ({ reference, display })
469
+ * to attach as ImagingStudy.subject — generic FHIR, supplied by the caller
470
+ * @returns {Object|null} FHIR ImagingStudy, or null for empty input
471
+ */
472
+ function imagingStudyFromDatasets(datasets, options = {}) {
473
+ const all = (datasets || []).filter(Boolean);
474
+ if (all.length === 0) {
475
+ return null;
476
+ }
477
+
478
+ const first =
479
+ all.find(dataset => toStringFirst(dataset.StudyInstanceUID)) || all[0];
480
+ const anchorStudyUid = toStringFirst(first.StudyInstanceUID);
481
+ const list = all.filter(dataset => {
482
+ const studyUid = toStringFirst(dataset.StudyInstanceUID);
483
+ if (studyUid && studyUid !== anchorStudyUid) {
484
+ warnSkip(
485
+ dataset,
486
+ `StudyInstanceUID ${studyUid} is not the study ` +
487
+ `${anchorStudyUid} of this ImagingStudy`
488
+ );
489
+ return false;
490
+ }
491
+ return true;
492
+ });
493
+
494
+ // No imaging identity at all → not a study
495
+ const hasIdentity = list.some(
496
+ dataset =>
497
+ toStringFirst(dataset.StudyInstanceUID) ||
498
+ toStringFirst(dataset.SeriesInstanceUID) ||
499
+ toStringFirst(dataset.SOPInstanceUID)
500
+ );
501
+ if (!hasIdentity) {
502
+ return null;
503
+ }
504
+
505
+ const seriesMap = new Map();
506
+ list.forEach(dataset => {
507
+ const seriesUid = toStringFirst(dataset.SeriesInstanceUID);
508
+ if (!seriesUid) {
509
+ warnSkip(dataset, "no SeriesInstanceUID (series.uid is 1..1)");
510
+ return;
511
+ }
512
+ if (!toStringFirst(dataset.Modality)) {
513
+ warnSkip(dataset, "no Modality (series.modality is 1..1)");
514
+ return;
515
+ }
516
+ if (!seriesMap.has(seriesUid)) {
517
+ seriesMap.set(seriesUid, seriesShellFromDataset(dataset));
518
+ }
519
+ const instance = instanceFromDataset(dataset);
520
+ if (instance) {
521
+ seriesMap.get(seriesUid).instance.push(instance);
522
+ }
523
+ });
524
+
525
+ const series = Array.from(seriesMap.values()).map(shell => {
526
+ const entry = { ...shell };
527
+ entry.numberOfInstances = entry.instance.length;
528
+ if (entry.instance.length === 0) {
529
+ delete entry.instance;
530
+ }
531
+ return entry;
532
+ });
533
+
534
+ const numberOfInstances = series.reduce(
535
+ (sum, entry) => sum + (entry.numberOfInstances || 0),
536
+ 0
537
+ );
538
+
539
+ const study = {
540
+ resourceType: "ImagingStudy",
541
+ status: "available",
542
+ numberOfSeries: series.length,
543
+ numberOfInstances,
544
+ series
545
+ };
546
+
547
+ const identifiers = [];
548
+ const studyUid = toStringFirst(first.StudyInstanceUID);
549
+ if (studyUid) {
550
+ identifiers.push({
551
+ use: "official",
552
+ system: DICOM_UID_SYSTEM,
553
+ value: uidToUrn(studyUid)
554
+ });
555
+ }
556
+ const accessionNumber = toStringFirst(first.AccessionNumber);
557
+ if (accessionNumber) {
558
+ identifiers.push({
559
+ use: "usual",
560
+ type: {
561
+ coding: [
562
+ {
563
+ system: "http://terminology.hl7.org/CodeSystem/v2-0203",
564
+ code: "ACSN"
565
+ }
566
+ ]
567
+ },
568
+ value: accessionNumber
569
+ });
570
+ }
571
+ if (identifiers.length > 0) {
572
+ study.identifier = identifiers;
573
+ }
574
+
575
+ const started = dicomDateTimeToIso(
576
+ first.StudyDate,
577
+ first.StudyTime,
578
+ first.TimezoneOffsetFromUTC
579
+ );
580
+ if (started) {
581
+ study.started = started;
582
+ }
583
+ const description = toStringFirst(first.StudyDescription);
584
+ if (description) {
585
+ study.description = description;
586
+ }
587
+ const referrer = parsePersonName(first.ReferringPhysicianName);
588
+ if (referrer && referrer.text) {
589
+ study.referrer = { display: referrer.text };
590
+ }
591
+ if (options.subject && options.subject.reference) {
592
+ study.subject = options.subject;
593
+ }
594
+
595
+ // Study-level modality union (distinct series modalities)
596
+ const modalities = [];
597
+ series.forEach(entry => {
598
+ if (
599
+ entry.modality &&
600
+ !modalities.some(m => m.code === entry.modality.code)
601
+ ) {
602
+ modalities.push(entry.modality);
603
+ }
604
+ });
605
+ if (modalities.length > 0) {
606
+ study.modality = modalities;
607
+ }
608
+
609
+ return study;
610
+ }
611
+
612
+ /**
613
+ * Single-dataset convenience wrapper.
614
+ */
615
+ function imagingStudyFromDataset(dataset, options = {}) {
616
+ return imagingStudyFromDatasets(dataset ? [dataset] : [], options);
617
+ }
618
+
619
+ // packages/fhir/src/documentReference.js
620
+ //
621
+ // FHIR R4B DocumentReference from a DICOM Encapsulated Document instance
622
+ // (Encapsulated PDF, SOP Class 1.2.840.10008.5.1.4.1.1.104.1) — the "PDF
623
+ // arrived via DICOM" mapping. Emits standard FHIR only — no ids, no
624
+ // meta.tags; id assignment is the consumer's job (same contract as
625
+ // patient.js / imagingStudy.js).
626
+ //
627
+ // DocumentReference.date is a FHIR instant, so it is written only when the
628
+ // dataset has ContentDate, ContentTime, and TimezoneOffsetFromUTC.
629
+
630
+
631
+ const CODING_SCHEME_SYSTEMS = {
632
+ LN: "http://loinc.org",
633
+ DCM: "http://dicom.nema.org/resources/ontology/DCM",
634
+ SCT: "http://snomed.info/sct",
635
+ SRT: "http://snomed.info/sct"
636
+ };
637
+
638
+ /**
639
+ * Naturalized ConceptNameCodeSequence (item object, array of items, or
640
+ * addAccessors proxy) → FHIR CodeableConcept, or null.
641
+ */
642
+ function conceptNameToCodeableConcept(conceptName) {
643
+ let item = conceptName;
644
+ if (Array.isArray(item)) {
645
+ item = item.length > 0 ? item[0] : null;
646
+ }
647
+ if (!item || typeof item !== "object") {
648
+ return null;
649
+ }
650
+
651
+ const code = toStringFirst(item.CodeValue);
652
+ const meaning = toStringFirst(item.CodeMeaning);
653
+ if (!code && !meaning) {
654
+ return null;
655
+ }
656
+
657
+ const codeableConcept = {};
658
+ if (code) {
659
+ const designator = toStringFirst(item.CodingSchemeDesignator);
660
+ const coding = { code };
661
+ if (designator) {
662
+ coding.system = CODING_SCHEME_SYSTEMS[designator] || designator;
663
+ }
664
+ if (meaning) {
665
+ coding.display = meaning;
666
+ }
667
+ codeableConcept.coding = [coding];
668
+ }
669
+ if (meaning) {
670
+ codeableConcept.text = meaning;
671
+ }
672
+ return codeableConcept;
673
+ }
674
+
675
+ /** The BulkDataURI of a naturalized `{ BulkDataURI }` payload, or null. */
676
+ function bulkDataUriOf(payload) {
677
+ const value = Array.isArray(payload) ? payload[0] : payload;
678
+ return toStringFirst(value?.BulkDataURI);
679
+ }
680
+
681
+ /**
682
+ * Build a FHIR DocumentReference from a naturalized Encapsulated Document
683
+ * dataset.
684
+ * @param {Object} dataset - DicomMetaDictionary.naturalizeDataset output
685
+ * @param {Object} [options]
686
+ * @param {Object} [options.subject] - FHIR Reference for .subject
687
+ * @param {boolean} [options.includeData=true] - inline the document as
688
+ * base64 in content[0].attachment.data (size is always emitted)
689
+ * @returns {Object|null} FHIR DocumentReference, or null when the dataset
690
+ * is not an encapsulated document instance
691
+ */
692
+ function documentReferenceFromDataset(dataset, options = {}) {
693
+ if (!dataset) {
694
+ return null;
695
+ }
696
+
697
+ const mimeType = toStringFirst(dataset.MIMETypeOfEncapsulatedDocument);
698
+ const sopClassUid = toStringFirst(dataset.SOPClassUID);
699
+ const isEncapsulated =
700
+ mimeType !== null || sopClassUid === ENCAPSULATED_PDF_SOP_CLASS_UID;
701
+ if (!isEncapsulated || dataset.EncapsulatedDocument === undefined) {
702
+ return null;
703
+ }
704
+
705
+ const includeData = options.includeData !== false;
706
+ const documentReference = {
707
+ resourceType: "DocumentReference",
708
+ status: "current"
709
+ };
710
+
711
+ const sopInstanceUrn = uidToUrn(dataset.SOPInstanceUID);
712
+ if (sopInstanceUrn) {
713
+ documentReference.masterIdentifier = {
714
+ system: DICOM_UID_SYSTEM,
715
+ value: sopInstanceUrn
716
+ };
717
+ }
718
+
719
+ const type = conceptNameToCodeableConcept(dataset.ConceptNameCodeSequence);
720
+ if (type) {
721
+ documentReference.type = type;
722
+ }
723
+
724
+ if (options.subject) {
725
+ documentReference.subject = options.subject;
726
+ }
727
+
728
+ const date = dicomDateTimeToInstant(
729
+ dataset.ContentDate,
730
+ dataset.ContentTime,
731
+ dataset.TimezoneOffsetFromUTC
732
+ );
733
+ if (date) {
734
+ documentReference.date = date;
735
+ }
736
+
737
+ const title = toStringFirst(dataset.DocumentTitle);
738
+ if (title) {
739
+ documentReference.description = title;
740
+ }
741
+
742
+ const attachment = {
743
+ contentType: mimeType || PDF_MIME_TYPE
744
+ };
745
+ if (title) {
746
+ attachment.title = title;
747
+ }
748
+ const bytes = extractEncapsulated(dataset);
749
+ const bulkDataUri = bulkDataUriOf(dataset.EncapsulatedDocument);
750
+ if (bytes) {
751
+ attachment.size = bytes.byteLength;
752
+ // FHIR does not permit an empty string value.
753
+ if (includeData && bytes.byteLength > 0) {
754
+ attachment.data = encodeBase64(bytes);
755
+ }
756
+ } else if (bulkDataUri) {
757
+ attachment.url = bulkDataUri;
758
+ }
759
+ documentReference.content = [{ attachment }];
760
+
761
+ const studyUrn = uidToUrn(dataset.StudyInstanceUID);
762
+ if (studyUrn) {
763
+ documentReference.context = {
764
+ related: [
765
+ {
766
+ identifier: {
767
+ system: DICOM_UID_SYSTEM,
768
+ value: studyUrn
769
+ }
770
+ }
771
+ ]
772
+ };
773
+ }
774
+
775
+ return documentReference;
776
+ }
777
+
778
+ // packages/fhir/src/patientToDataset.js
779
+ //
780
+ // The FHIR source direction: a FHIR Patient resource → DICOM patient-module
781
+ // attributes (group 0010) in naturalized keyword form. Inverse of
782
+ // patient.js's patientFromDataset, and the primitive behind demographics
783
+ // injection ("apply this Patient to these instances").
784
+ //
785
+ // The result rules are FHIR-USR-6 in packages/fhir/README.md.
786
+
787
+
788
+ const MR_IDENTIFIER_CODE = "MR";
789
+
790
+ /**
791
+ * Pick the name to use: `official` wins, then `usual`, then the first
792
+ * entry with no `use` at all, then the first entry — so a resource
793
+ * carrying both a married (official) and maiden name maps to the married
794
+ * one, never the maiden.
795
+ */
796
+ function selectName(names) {
797
+ if (!Array.isArray(names) || names.length === 0) {
798
+ return null;
799
+ }
800
+ for (const use of ["official", "usual"]) {
801
+ const match = names.find(name => name && name.use === use);
802
+ if (match) {
803
+ return match;
804
+ }
805
+ }
806
+ return names.find(name => name && !name.use) || names[0];
807
+ }
808
+
809
+ /**
810
+ * Pick the identifier for PatientID: an MR-typed identifier wins
811
+ * (type.coding code "MR", the shape patientFromDataset emits), else the
812
+ * first identifier carrying a value.
813
+ */
814
+ function selectIdentifier(identifiers) {
815
+ if (!Array.isArray(identifiers) || identifiers.length === 0) {
816
+ return null;
817
+ }
818
+ const mrTyped = identifiers.find(identifier =>
819
+ identifier?.type?.coding?.some(
820
+ coding => coding && coding.code === MR_IDENTIFIER_CODE
821
+ )
822
+ );
823
+ return mrTyped || identifiers.find(identifier => identifier?.value) || null;
824
+ }
825
+
826
+ /**
827
+ * Map a FHIR Patient resource to DICOM patient-module attributes.
828
+ *
829
+ * @param {Object} patient - FHIR Patient (R4/R4B)
830
+ * @returns {{ PatientName: string, PatientID: string,
831
+ * PatientBirthDate: string, PatientSex: string }} naturalized keyword
832
+ * attributes; absent resource fields are "" (deterministic overwrite)
833
+ * @throws when the input is not a Patient resource
834
+ */
835
+ function patientToDataset(patient) {
836
+ if (!patient || patient.resourceType !== "Patient") {
837
+ throw new Error(
838
+ "patientToDataset expects a FHIR Patient resource " +
839
+ `(got resourceType "${patient?.resourceType}")`
840
+ );
841
+ }
842
+
843
+ const name = selectName(patient.name);
844
+ const identifier = selectIdentifier(patient.identifier);
845
+
846
+ return {
847
+ PatientName: (name && humanNameToPersonName(name)) || "",
848
+ PatientID: identifier?.value || "",
849
+ PatientBirthDate: isoDateToDicom(patient.birthDate) || "",
850
+ PatientSex: genderToSex(patient.gender)
851
+ };
852
+ }
853
+
854
+ // packages/fhir/src/index.js
855
+ //
856
+ // @dcmjs-org/fhir — FHIR both ways.
857
+ //
858
+ // PRELIMINARY API: the exports can change in a minor release while
859
+ // packages/fhir/README.md has the preliminary notice.
860
+ //
861
+ // The sink: naturalized DICOM Part 10 datasets
862
+ // (DicomMetaDictionary.naturalizeDataset output) → FHIR R4B resources.
863
+ // The source: a FHIR Patient → DICOM patient-module attributes
864
+ // (patientToDataset), for demographics injection.
865
+ //
866
+ // Deliberately simple: standard FHIR, nothing deployment-specific.
867
+ // Consumers assign resource ids, storage references, and meta.tags.
868
+ //
869
+ // const { patient, imagingStudy, documentReference } = toFhir(dataset);
870
+ // const bundle = toBundle([dataset1, dataset2]);
871
+ // const attrs = patientToDataset(patientResource); // → { PatientName, ... }
872
+
873
+
874
+ /**
875
+ * Map one naturalized dataset to its FHIR resources.
876
+ *
877
+ * Encapsulated document instances (e.g. Encapsulated PDF from a PACS) map
878
+ * to a DocumentReference and no ImagingStudy; image instances map to an
879
+ * ImagingStudy and no DocumentReference. The 3-key shape is stable either
880
+ * way.
881
+ *
882
+ * Without `options.subject`, the ImagingStudy or DocumentReference
883
+ * references the Patient of the result as `{ reference: "./patient" }`, a
884
+ * path relative to the returned object (FHIR-USR-10). The consumer replaces
885
+ * it when it stores the resources.
886
+ *
887
+ * @param {Object} dataset - DicomMetaDictionary.naturalizeDataset output
888
+ * @param {Object} [options]
889
+ * @param {string} [options.fhirVersion='R4B'] - R4/R4B only; throws otherwise
890
+ * @param {Object} [options.subject] - FHIR Reference for
891
+ * ImagingStudy.subject / DocumentReference.subject
892
+ * @param {boolean} [options.includeData=true] - inline document bytes as
893
+ * base64 in DocumentReference attachments
894
+ * @returns {{ patient: Object|null, imagingStudy: Object|null,
895
+ * documentReference: Object|null }}
896
+ */
897
+ function toFhir(dataset, options = {}) {
898
+ assertSupportedFhirVersion(options);
899
+ const patient = patientFromDataset(dataset);
900
+ const resourceOptions = withSubject(options, patient && "./patient");
901
+ const documentReference = documentReferenceFromDataset(
902
+ dataset,
903
+ resourceOptions
904
+ );
905
+ return {
906
+ patient,
907
+ imagingStudy: documentReference
908
+ ? null
909
+ : imagingStudyFromDataset(dataset, resourceOptions),
910
+ documentReference
911
+ };
912
+ }
913
+
914
+ /** The options with a relative `subject`, unless the caller gave one. */
915
+ function withSubject(options, reference) {
916
+ if (options.subject || !reference) {
917
+ return options;
918
+ }
919
+ return { ...options, subject: { reference } };
920
+ }
921
+
922
+ /**
923
+ * Map one or more datasets (one study's worth of instances) to a FHIR
924
+ * collection Bundle: at most one Patient, a DocumentReference for each
925
+ * encapsulated document, and one aggregated ImagingStudy.
926
+ *
927
+ * The first dataset with a patient module gives the Patient, and the first
928
+ * dataset with a StudyInstanceUID gives the study. A dataset with a
929
+ * different PatientID or StudyInstanceUID is skipped with a validationLog
930
+ * warning (FHIR-USR-3). Each entry has `fullUrl: "./entry/<index>"`, a path
931
+ * relative to the returned Bundle, and without `options.subject` the
932
+ * ImagingStudy and the DocumentReferences reference the Patient by its
933
+ * `fullUrl` (FHIR-USR-10).
934
+ *
935
+ * @param {Object[]} datasets - naturalized datasets
936
+ * @param {Object} [options] - as toFhir
937
+ * @returns {Object} FHIR Bundle (type: collection)
938
+ */
939
+ function toBundle(datasets, options = {}) {
940
+ assertSupportedFhirVersion(options);
941
+
942
+ const all = (datasets || []).filter(Boolean);
943
+ const resources = [];
944
+
945
+ let patient = null;
946
+ let patientId = null;
947
+ for (const dataset of all) {
948
+ patient = patientFromDataset(dataset);
949
+ if (patient) {
950
+ patientId = toStringFirst(dataset.PatientID);
951
+ break;
952
+ }
953
+ }
954
+ const studyUid = all
955
+ .map(dataset => toStringFirst(dataset.StudyInstanceUID))
956
+ .find(Boolean);
957
+ const list = all.filter(dataset =>
958
+ sameContext(dataset, patientId, studyUid)
959
+ );
960
+ if (patient) {
961
+ resources.push(patient);
962
+ }
963
+ const resourceOptions = withSubject(options, patient && "./entry/0");
964
+
965
+ // Encapsulated documents each become a DocumentReference; the
966
+ // remaining (image) datasets aggregate into one ImagingStudy.
967
+ const imageDatasets = [];
968
+ for (const dataset of list) {
969
+ const documentReference = documentReferenceFromDataset(
970
+ dataset,
971
+ resourceOptions
972
+ );
973
+ if (documentReference) {
974
+ resources.push(documentReference);
975
+ } else {
976
+ imageDatasets.push(dataset);
977
+ }
978
+ }
979
+
980
+ const imagingStudy = imagingStudyFromDatasets(
981
+ imageDatasets,
982
+ resourceOptions
983
+ );
984
+ if (imagingStudy) {
985
+ resources.push(imagingStudy);
986
+ }
987
+
988
+ return {
989
+ resourceType: "Bundle",
990
+ type: "collection",
991
+ total: resources.length,
992
+ entry: resources.map((resource, index) => ({
993
+ fullUrl: `./entry/${index}`,
994
+ resource
995
+ }))
996
+ };
997
+ }
998
+
999
+ /** True when the dataset belongs to the patient and study of the Bundle. */
1000
+ function sameContext(dataset, patientId, studyUid) {
1001
+ const datasetPatientId = toStringFirst(dataset.PatientID);
1002
+ const datasetStudyUid = toStringFirst(dataset.StudyInstanceUID);
1003
+ const reason =
1004
+ patientId && datasetPatientId && datasetPatientId !== patientId
1005
+ ? `PatientID ${datasetPatientId} is not ${patientId}`
1006
+ : studyUid && datasetStudyUid && datasetStudyUid !== studyUid
1007
+ ? `StudyInstanceUID ${datasetStudyUid} is not ${studyUid}`
1008
+ : null;
1009
+ if (reason) {
1010
+ validationLog.warn(
1011
+ "@dcmjs-org/fhir: toBundle skips dataset " +
1012
+ `${
1013
+ toStringFirst(dataset.SOPInstanceUID) ||
1014
+ "<no SOPInstanceUID>"
1015
+ } — ${reason}`
1016
+ );
1017
+ return false;
1018
+ }
1019
+ return true;
1020
+ }
1021
+
1022
+ export { DICOM_MODALITY_SYSTEM, DICOM_UID_SYSTEM, assertSupportedFhirVersion, dicomDateTimeToInstant, dicomDateTimeToIso, documentReferenceFromDataset, genderToSex, humanNameToPersonName, imagingStudyFromDataset, imagingStudyFromDatasets, isoDateToDicom, modalityCoding, parsePersonName, patientFromDataset, patientToDataset, personNameToHumanName, sexToGender, toBundle, toFhir, uidToUrn };
1023
+ //# sourceMappingURL=index.mjs.map