@dcmjs-org/parser 0.0.0-stage → 1.0.0-beta.2

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.cjs ADDED
@@ -0,0 +1,3224 @@
1
+ 'use strict';
2
+
3
+ var core = require('@dcmjs-org/core');
4
+ var pako = require('pako');
5
+
6
+ /**
7
+ * EventStreamListener — the push-core of the dcmjs event-stream contract.
8
+ *
9
+ * This is the canonical, low-allocation listener interface that every reader,
10
+ * writer, filter, validator, and anonymizer speaks (see CLAUDE_REFACTOR_PLAN.md,
11
+ * slice A). It formalizes the implicit `next`-middleware model that previously
12
+ * lived in DicomMetadataListener, with the richer, explicit vocabulary the
13
+ * Naturalized DICOM Metadata Behavior Specification calls for (§15.1).
14
+ *
15
+ * The vocabulary:
16
+ *
17
+ * Lifecycle: startDataSet / endDataSet
18
+ * startFileMetaInformation / endFileMetaInformation
19
+ * Structural: startElement / endElement
20
+ * startSequence / endSequence
21
+ * startItem / endItem
22
+ * value(v, { index, rawValue? })
23
+ * Binary: bulkDataReference
24
+ * startBinary / binaryFragment / endBinary
25
+ *
26
+ * The `value` event's options bag is optional and extensible; `rawValue` carries
27
+ * the source string (when available) for precision-preserving retention
28
+ * (§16/§27). Consumers that don't need it ignore it.
29
+ *
30
+ * Structural and value callbacks are synchronous (allocation-free hot path,
31
+ * §15.4 / §24.1). Backpressure is applied out of band via setDrain/awaitDrain,
32
+ * which generators await only at defined checkpoints (top-level element
33
+ * boundaries and binary-fragment emission).
34
+ *
35
+ * Filters are first-class: each filter is an object that may implement any
36
+ * vocabulary method as `method(next, ...args)`; calling `next(...)` invokes the
37
+ * rest of the chain, ending in the listener's `_base<Method>` implementation.
38
+ */
39
+
40
+ const EVENT_STREAM_VOCABULARY = [
41
+ "startDataSet",
42
+ "endDataSet",
43
+ "startFileMetaInformation",
44
+ "endFileMetaInformation",
45
+ "startElement",
46
+ "endElement",
47
+ "startSequence",
48
+ "endSequence",
49
+ "startItem",
50
+ "endItem",
51
+ "value",
52
+ "bulkDataReference",
53
+ "startBinary",
54
+ "binaryFragment",
55
+ "endBinary"
56
+ ];
57
+
58
+ /** Contract version — generators and listeners can declare conformance. */
59
+ const CONTRACT_VERSION = "1.0.0-A";
60
+
61
+ /**
62
+ * Merge raw encapsulated-pixel-data fragments into one buffer per Basic
63
+ * Offset Table window (issue #204 — eager-reader shape parity for
64
+ * BOT-aware listeners). The event stream itself stays raw (one
65
+ * binaryFragment per on-wire fragment); listeners that rebuild a dataset
66
+ * call this at endBinary time when startBinary carried a non-empty
67
+ * `basicOffsetTable`.
68
+ *
69
+ * Fragment offsets are reconstructed from the fragment lengths: fragment
70
+ * i's item header starts at Σ_{j<i} (8 + length_j), matching the BOT's
71
+ * item-header-relative offset convention. Grouping and merge semantics
72
+ * mirror BinaryRepresentation.readBytes: a single-fragment window stays
73
+ * that fragment's buffer; a multi-fragment window merges into one
74
+ * ArrayBuffer.
75
+ *
76
+ * @param {Array<ArrayBuffer|TypedArray>} fragments raw fragment buffers
77
+ * @param {number[]} basicOffsetTable BOT offsets (item-header relative)
78
+ * @returns {Array<ArrayBuffer|TypedArray>} one entry per BOT window
79
+ */
80
+ function mergeFragmentsPerBotWindow(fragments, basicOffsetTable) {
81
+ if (!basicOffsetTable || basicOffsetTable.length === 0) {
82
+ return fragments;
83
+ }
84
+ const toBytes = f =>
85
+ f instanceof ArrayBuffer
86
+ ? new Uint8Array(f)
87
+ : new Uint8Array(f.buffer, f.byteOffset, f.byteLength);
88
+ let offset = 0;
89
+ const placed = fragments.map(fragment => {
90
+ const length = fragment.byteLength;
91
+ const entry = { fragment, offset, length };
92
+ offset += 8 + length;
93
+ return entry;
94
+ });
95
+ const frames = [];
96
+ for (let i = 0; i < basicOffsetTable.length; i++) {
97
+ const start = basicOffsetTable[i];
98
+ const stop =
99
+ i + 1 < basicOffsetTable.length
100
+ ? basicOffsetTable[i + 1]
101
+ : Number.POSITIVE_INFINITY;
102
+ const windowFragments = placed.filter(
103
+ f => f.offset >= start && f.offset < stop
104
+ );
105
+ if (windowFragments.length === 1) {
106
+ frames.push(windowFragments[0].fragment);
107
+ continue;
108
+ }
109
+ const frameSize = windowFragments.reduce((n, f) => n + f.length, 0);
110
+ const merged = new Uint8Array(frameSize);
111
+ let position = 0;
112
+ for (const f of windowFragments) {
113
+ merged.set(toBytes(f.fragment), position);
114
+ position += f.length;
115
+ }
116
+ frames.push(merged.buffer);
117
+ }
118
+ return frames;
119
+ }
120
+
121
+ class EventStreamListener {
122
+ /**
123
+ * @param {...Object} filters - Filter objects. Each may implement any
124
+ * vocabulary method as `method(next, ...args)`.
125
+ */
126
+ constructor(...filters) {
127
+ this.filters = filters.filter(Boolean);
128
+ this._drain = null;
129
+ this._createMethodChains();
130
+ }
131
+
132
+ /**
133
+ * Builds, for every vocabulary method, a chain that threads each filter's
134
+ * implementation in front of the base implementation via `next`.
135
+ * @private
136
+ */
137
+ _createMethodChains() {
138
+ for (const methodName of EVENT_STREAM_VOCABULARY) {
139
+ const baseName = `_base${methodName[0].toUpperCase()}${methodName.slice(
140
+ 1
141
+ )}`;
142
+ let chain = this[baseName].bind(this);
143
+
144
+ for (let i = this.filters.length - 1; i >= 0; i--) {
145
+ const filter = this.filters[i];
146
+ const filterFn = filter && filter[methodName];
147
+ if (typeof filterFn === "function") {
148
+ const next = chain;
149
+ chain = (...args) => filterFn.call(this, next, ...args);
150
+ }
151
+ }
152
+
153
+ this[methodName] = chain;
154
+ }
155
+ }
156
+
157
+ // --- Backpressure -------------------------------------------------------
158
+
159
+ /**
160
+ * Install a backpressure gate. The function should return a Promise that
161
+ * resolves when it is safe to emit more data. Pass null to clear.
162
+ * @param {(() => Promise<void>) | null} fn
163
+ */
164
+ setDrain(fn) {
165
+ this._drain = typeof fn === "function" ? fn : null;
166
+ }
167
+
168
+ /**
169
+ * Await the backpressure gate (resolves immediately when none is set).
170
+ * Generators call this only at defined checkpoints.
171
+ * @returns {Promise<void>}
172
+ */
173
+ awaitDrain() {
174
+ return this._drain ? this._drain() : Promise.resolve();
175
+ }
176
+
177
+ // --- Base (no-op) vocabulary implementations ----------------------------
178
+ // Consumers override these (or subclass) to do real work. They are no-ops
179
+ // here so the base listener is a valid, inert sink.
180
+
181
+ _baseStartDataSet() {}
182
+ _baseEndDataSet() {}
183
+ _baseStartFileMetaInformation() {}
184
+ _baseEndFileMetaInformation() {}
185
+ _baseStartElement() {}
186
+ _baseEndElement() {}
187
+ _baseStartSequence() {}
188
+ _baseEndSequence() {}
189
+ _baseStartItem() {}
190
+ _baseEndItem() {}
191
+ _baseValue() {}
192
+ _baseBulkDataReference() {}
193
+ _baseStartBinary() {}
194
+ _baseBinaryFragment() {}
195
+ _baseEndBinary() {}
196
+ }
197
+
198
+ /**
199
+ * CollectorListener — a reference event-stream consumer that rebuilds a
200
+ * tag-keyed `{ meta, dict }` tree from the contract events.
201
+ *
202
+ * Its purpose is to validate the contract: a generator's event stream, fed
203
+ * through this listener, should reconstruct a tree equivalent to the existing
204
+ * dcmjs parse. It is intentionally NOT the naturalized listener (slice D) — it
205
+ * preserves the raw tag-keyed `{ vr, Value }` shape so it can be deep-compared
206
+ * against `DicomMessage.readFile` output.
207
+ *
208
+ * Value shapes match the existing parse:
209
+ * - scalar/multi-value element → { vr, Value: [...] }
210
+ * - sequence → { vr, Value: [ {itemDict}, ... ] }
211
+ * - binary → { vr, Value: [ArrayBuffer, ...] } (one entry
212
+ * per fragment; boundaries preserved, §33 —
213
+ * except encapsulated pixel data whose
214
+ * startBinary carries a non-empty
215
+ * basicOffsetTable: those fragments are
216
+ * merged per BOT window at endBinary, so the
217
+ * final Value shape matches the eager
218
+ * reader's one-entry-per-frame contract,
219
+ * issue #204)
220
+ * - bulk data reference → { vr, Value: [ { BulkDataURI } ] }
221
+ */
222
+ class CollectorListener extends EventStreamListener {
223
+ constructor(...filters) {
224
+ super(...filters);
225
+ this.result = { meta: {}, dict: {} };
226
+ this._stack = [];
227
+ this._current = null;
228
+ }
229
+
230
+ /** Top container: an object (dataset/item) or array (sequence Value). */
231
+ _top() {
232
+ return this._stack[this._stack.length - 1];
233
+ }
234
+
235
+ _baseStartDataSet() {
236
+ this.result = { meta: {}, dict: {} };
237
+ this._stack = [this.result.dict];
238
+ this._current = null;
239
+ }
240
+
241
+ _baseEndDataSet() {
242
+ this._current = null;
243
+ }
244
+
245
+ _baseStartFileMetaInformation() {
246
+ this._stack.push(this.result.meta);
247
+ }
248
+
249
+ _baseEndFileMetaInformation() {
250
+ this._stack.pop();
251
+ }
252
+
253
+ _baseStartElement(tag, info = {}) {
254
+ const el = { vr: info.vr, Value: [] };
255
+ this._top()[tag] = el;
256
+ this._current = el;
257
+ }
258
+
259
+ _baseEndElement() {
260
+ this._current = null;
261
+ }
262
+
263
+ _baseValue(v) {
264
+ this._current.Value.push(v);
265
+ }
266
+
267
+ _baseStartSequence(tag, info = {}) {
268
+ const seq = { vr: info.vr, Value: [] };
269
+ this._top()[tag] = seq;
270
+ this._stack.push(seq.Value);
271
+ this._current = null;
272
+ }
273
+
274
+ _baseEndSequence() {
275
+ this._stack.pop();
276
+ }
277
+
278
+ _baseStartItem() {
279
+ const item = {};
280
+ this._top().push(item);
281
+ this._stack.push(item);
282
+ this._current = null;
283
+ }
284
+
285
+ _baseEndItem() {
286
+ this._stack.pop();
287
+ }
288
+
289
+ _baseBulkDataReference(ref = {}) {
290
+ this._current.Value.push({ BulkDataURI: ref.uri });
291
+ }
292
+
293
+ _baseStartBinary(info = {}) {
294
+ // The current element accumulates fragments as Value entries. A
295
+ // non-empty basicOffsetTable is kept so endBinary can merge the
296
+ // fragments per BOT window (eager-reader shape parity, issue #204).
297
+ this._binaryInfo = info;
298
+ }
299
+
300
+ _baseBinaryFragment(chunk) {
301
+ this._current.Value.push(chunk);
302
+ }
303
+
304
+ _baseEndBinary() {
305
+ const bot = this._binaryInfo && this._binaryInfo.basicOffsetTable;
306
+ this._binaryInfo = null;
307
+ if (bot && bot.length && this._current) {
308
+ this._current.Value = mergeFragmentsPerBotWindow(
309
+ this._current.Value,
310
+ bot
311
+ );
312
+ }
313
+ }
314
+ }
315
+
316
+ /**
317
+ * NaturalizedListener — slice D1: the core naturalized value model.
318
+ *
319
+ * An event-stream consumer that builds the application-facing naturalized
320
+ * object per the Naturalized DICOM Metadata Behavior Specification: canonical
321
+ * keyword keys (§5) and VM-driven cardinality (§7-§14). Because it consumes the
322
+ * source-agnostic contract, the SAME naturalized object is produced from Part 10
323
+ * bytes, a dcmjs dict, or DICOMweb JSON.
324
+ *
325
+ * Scope (D1): keyword naming, VM cardinality, single-item sequences with hidden
326
+ * length (§12, via core addAccessors, no Proxy), empty→null/[], binary
327
+ * assembly (InlineBinary/BulkDataURI), and the cardinality-violation policy
328
+ * (§15.2, default warnAndPreserve). Deferred to D2: the PN proxy/toString sugar
329
+ * (§17), private-tag grouping (§18), and precision/raw retention (§16/§27, which
330
+ * needs the contract to carry raw values).
331
+ *
332
+ * Sequence note: a DICOM sequence's declared VM ("1") constrains how many times
333
+ * the attribute appears, NOT its item count — multi-item sequences (e.g.
334
+ * PerFrameFunctionalGroupsSequence) are normal, not violations. Violations apply
335
+ * to non-sequence scalar VRs whose value count exceeds the declared VM.
336
+ */
337
+ class NaturalizedListener extends EventStreamListener {
338
+ /**
339
+ * @param {Object} [options]
340
+ * @param {string} [options.cardinalityViolationPolicy="warnAndPreserve"]
341
+ * One of preserve | discardExtra | warnAndPreserve | warnAndDiscardExtra |
342
+ * recordAndPreserve | recordAndDiscardExtra | throw.
343
+ */
344
+ constructor(options = {}, ...filters) {
345
+ super(...filters);
346
+ this.policy = options.cardinalityViolationPolicy || "warnAndPreserve";
347
+ this.result = {};
348
+ this.meta = {};
349
+ this.violations = [];
350
+ // Frame stack. Each frame is one of:
351
+ // { kind: "object", obj } dataset or sequence item
352
+ // { kind: "element", tag, vr, values, binary }
353
+ // { kind: "sequence", tag, vr, items }
354
+ this._stack = [];
355
+ }
356
+
357
+ _objectFrame() {
358
+ for (let i = this._stack.length - 1; i >= 0; i--) {
359
+ if (this._stack[i].kind === "object") {
360
+ return this._stack[i];
361
+ }
362
+ }
363
+ return null;
364
+ }
365
+
366
+ _baseStartDataSet() {
367
+ this.result = {};
368
+ this.meta = {};
369
+ this.violations = [];
370
+ this._stack = [{ kind: "object", obj: this.result }];
371
+ }
372
+
373
+ _baseEndDataSet() {}
374
+
375
+ _baseStartFileMetaInformation() {
376
+ this._stack.push({ kind: "object", obj: this.meta });
377
+ }
378
+
379
+ _baseEndFileMetaInformation() {
380
+ this._stack.pop();
381
+ }
382
+
383
+ _baseStartElement(tag, info = {}) {
384
+ this._stack.push({
385
+ kind: "element",
386
+ tag,
387
+ vr: info.vr,
388
+ values: [],
389
+ rawValues: [],
390
+ binary: undefined
391
+ });
392
+ }
393
+
394
+ _baseValue(v, opts = {}) {
395
+ const frame = this._stack[this._stack.length - 1];
396
+ frame.values.push(v);
397
+ frame.rawValues.push(opts.rawValue);
398
+ }
399
+
400
+ _baseBulkDataReference(ref = {}) {
401
+ this._stack[this._stack.length - 1].binary = { BulkDataURI: ref.uri };
402
+ }
403
+
404
+ _baseStartBinary(info = {}) {
405
+ const frame = this._stack[this._stack.length - 1];
406
+ frame._fragments = [];
407
+ // A non-empty basicOffsetTable is kept so endBinary can merge the
408
+ // raw fragments per BOT window (eager-reader frame shape parity,
409
+ // issue #204).
410
+ frame._binaryInfo = info;
411
+ }
412
+
413
+ _baseBinaryFragment(chunk) {
414
+ this._stack[this._stack.length - 1]._fragments.push(chunk);
415
+ }
416
+
417
+ _baseEndBinary() {
418
+ const frame = this._stack[this._stack.length - 1];
419
+ let fragments = frame._fragments || [];
420
+ const bot = frame._binaryInfo && frame._binaryInfo.basicOffsetTable;
421
+ if (bot && bot.length) {
422
+ fragments = mergeFragmentsPerBotWindow(fragments, bot);
423
+ }
424
+ frame.binary = {
425
+ InlineBinary: fragments.length === 1 ? fragments[0] : fragments
426
+ };
427
+ frame._fragments = undefined;
428
+ frame._binaryInfo = undefined;
429
+ }
430
+
431
+ _baseEndElement() {
432
+ const frame = this._stack.pop();
433
+ const targetFrame = this._objectFrame();
434
+
435
+ // §16 precision: where a canonical JS number would lose precision and a
436
+ // raw source string is available, retain the raw string.
437
+ if (frame.binary === undefined && frame.rawValues) {
438
+ for (let i = 0; i < frame.values.length; i++) {
439
+ frame.values[i] = retainPrecision(
440
+ frame.vr,
441
+ frame.values[i],
442
+ frame.rawValues[i]
443
+ );
444
+ }
445
+ }
446
+
447
+ if (isPrivateTag(frame.tag)) {
448
+ this._placePrivate(targetFrame, frame);
449
+ return;
450
+ }
451
+
452
+ const entry = core.lookupTagHex(frame.tag);
453
+ const key = (entry && entry.name) || frame.tag;
454
+ if (frame.binary !== undefined) {
455
+ targetFrame.obj[key] = frame.binary;
456
+ return;
457
+ }
458
+ let shaped = this._shapeValues(frame, entry, key);
459
+ if (frame.vr === "PN" && shaped !== null) {
460
+ shaped = addPersonNameAccessors(shaped);
461
+ }
462
+ targetFrame.obj[key] = shaped;
463
+ }
464
+
465
+ _baseStartSequence(tag, info = {}) {
466
+ this._stack.push({ kind: "sequence", tag, vr: info.vr, items: [] });
467
+ }
468
+
469
+ _baseStartItem() {
470
+ this._stack.push({ kind: "object", obj: {} });
471
+ }
472
+
473
+ _baseEndItem() {
474
+ const itemFrame = this._stack.pop();
475
+ // The enclosing frame is the sequence.
476
+ this._stack[this._stack.length - 1].items.push(itemFrame.obj);
477
+ }
478
+
479
+ _baseEndSequence() {
480
+ const frame = this._stack.pop();
481
+ const targetFrame = this._objectFrame();
482
+ const shaped = this._shapeSequence(frame, core.lookupTagHex(frame.tag));
483
+
484
+ if (isPrivateTag(frame.tag)) {
485
+ this._placePrivateValue(targetFrame, frame.tag, frame.vr, shaped);
486
+ return;
487
+ }
488
+ const entry = core.lookupTagHex(frame.tag);
489
+ const key = (entry && entry.name) || frame.tag;
490
+ targetFrame.obj[key] = shaped;
491
+ }
492
+
493
+ // --- private-tag grouping (§18) -----------------------------------------
494
+
495
+ _placePrivate(targetFrame, frame) {
496
+ const elem = parseInt(frame.tag.slice(4, 8), 16);
497
+ // Private creator (gggg,00xx): record it for the block; do NOT emit it
498
+ // as an ordinary attribute (§18.5).
499
+ if (elem <= 0x00ff) {
500
+ const v =
501
+ frame.values && frame.values.length ? frame.values[0] : null;
502
+ if (v != null) {
503
+ targetFrame.creators = targetFrame.creators || {};
504
+ targetFrame.creators[elem] = String(v);
505
+ }
506
+ return;
507
+ }
508
+ const value =
509
+ frame.binary !== undefined
510
+ ? frame.binary
511
+ : privateShape(frame.values);
512
+ this._placePrivateValue(targetFrame, frame.tag, frame.vr, value);
513
+ }
514
+
515
+ _placePrivateValue(targetFrame, tag, vr, value) {
516
+ const elem = parseInt(tag.slice(4, 8), 16);
517
+ const slot = elem >> 8; // creator slot (high byte of the element)
518
+ const offset = elem & 0xff; // block-relative element (low byte)
519
+ const creator = targetFrame.creators && targetFrame.creators[slot];
520
+
521
+ if (creator) {
522
+ const groupKey = `${hex2(slot)}:${creator}`;
523
+ let group = targetFrame.obj[groupKey];
524
+ if (!group) {
525
+ group = { originalTagOffset: slot };
526
+ targetFrame.obj[groupKey] = group;
527
+ }
528
+ group[privateKeyFor(tag, creator, offset, group)] = value;
529
+ return;
530
+ }
531
+ // §18.4: no identifiable creator -> full tag key, unknown attribute shape.
532
+ targetFrame.obj[tag] = {
533
+ vr,
534
+ Value: Array.isArray(value) ? value : value == null ? [] : [value]
535
+ };
536
+ }
537
+
538
+ // --- cardinality shaping ------------------------------------------------
539
+
540
+ _shapeValues(frame, entry, key) {
541
+ const values = frame.values;
542
+ const multi = core.isMultiVM(entry && entry.vm);
543
+
544
+ if (multi) {
545
+ // §10/§11: always list-like; present-empty -> [].
546
+ return values;
547
+ }
548
+ // Scalar VM (1 or 0-1).
549
+ if (values.length === 0) {
550
+ return null; // §7/§9 present-empty
551
+ }
552
+ if (values.length === 1) {
553
+ return values[0];
554
+ }
555
+ // §8: scalar VM with 2+ actual values -> cardinality violation.
556
+ return this._applyViolation(key, values, 1);
557
+ }
558
+
559
+ _shapeSequence(frame, entry) {
560
+ const items = frame.items;
561
+ const declaredMulti = core.isMultiVM(entry && entry.vm);
562
+
563
+ if (items.length === 0) {
564
+ return []; // §12 present-empty
565
+ }
566
+ if (items.length === 1 && !declaredMulti) {
567
+ // §12: the item object itself, with a hidden [0] and length 1
568
+ return core.addAccessors(items);
569
+ }
570
+ // §13: multiple items -> list-like. Not a violation (declared SQ VM
571
+ // constrains attribute occurrence, not item count).
572
+ return items;
573
+ }
574
+
575
+ _applyViolation(keyword, values, declaredMax) {
576
+ const violation = {
577
+ keyword,
578
+ declaredMax,
579
+ actual: values.length
580
+ };
581
+ const discard = /DiscardExtra$/.test(this.policy);
582
+ const kept = discard ? values.slice(0, declaredMax) : values.slice();
583
+
584
+ if (this.policy === "throw") {
585
+ throw new Error(
586
+ `Cardinality violation: ${keyword} has ${values.length} values, declared VM ${declaredMax}`
587
+ );
588
+ }
589
+ if (/^warn/.test(this.policy)) {
590
+ core.log.warn(
591
+ `Cardinality violation: ${keyword} has ${values.length} values (declared VM ${declaredMax})`
592
+ );
593
+ }
594
+ this.violations.push(violation);
595
+
596
+ // discardExtra of a now-scalar VM collapses to the single kept value.
597
+ if (discard && declaredMax === 1) {
598
+ return kept[0];
599
+ }
600
+ return kept;
601
+ }
602
+ }
603
+
604
+ /**
605
+ * A private tag has an odd group number and an element at or above 0x0010 (the
606
+ * first usable private creator slot). Group-length (0x0000) and reserved low
607
+ * elements fall through to standard handling.
608
+ */
609
+ function isPrivateTag(tag) {
610
+ const group = parseInt(tag.slice(0, 4), 16);
611
+ const elem = parseInt(tag.slice(4, 8), 16);
612
+ return (group & 1) === 1 && elem >= 0x0010;
613
+ }
614
+
615
+ /** Two-hex-digit uppercase, e.g. 0x10 -> "10". */
616
+ function hex2(n) {
617
+ return n.toString(16).toUpperCase().padStart(2, "0");
618
+ }
619
+
620
+ /**
621
+ * Block-relative key for a private data element (§18.2): the registered private
622
+ * name when the (creator, offset) is known in the private dictionary and the
623
+ * name is meaningful and non-colliding; otherwise the numeric block-relative
624
+ * offset. Registered names stay scoped to the creator group.
625
+ */
626
+ function privateKeyFor(tag, creator, offset, group) {
627
+ const numeric = hex2(offset);
628
+ const reg = core.lookupPrivateTag(
629
+ `(${tag.slice(0, 4)},"${creator}",${numeric})`
630
+ );
631
+ if (reg && reg.name && reg.name !== "Unknown" && !(reg.name in group)) {
632
+ return reg.name;
633
+ }
634
+ return numeric;
635
+ }
636
+
637
+ /**
638
+ * §16 precision retention (raw-retention default "inexact only", §27). A numeric
639
+ * VR value (IS/DS) decoded to a JS number has lost precision when the number's
640
+ * shortest decimal cannot reproduce the source string (an over-length decimal,
641
+ * or an integer beyond the safe range). In that case retain the original string.
642
+ * This is VR-agnostic: it fires only when a number and its source string
643
+ * disagree, so normal values keep their number.
644
+ */
645
+ function retainPrecision(vr, value, raw) {
646
+ if (typeof value !== "number" || typeof raw !== "string") {
647
+ return value;
648
+ }
649
+ const source = raw.trim();
650
+ if (source === "" || !Number.isFinite(value)) {
651
+ return value;
652
+ }
653
+ if (canonicalDecimal(source) === canonicalDecimal(value.toString())) {
654
+ return value; // recoverable from the number -> no loss
655
+ }
656
+ return source;
657
+ }
658
+
659
+ /**
660
+ * Canonical decimal form for comparing whether two decimal strings denote the
661
+ * same number, ignoring formatting (sign, leading/trailing zeros). Exponent
662
+ * notation is left intact, so a number serialized in exponent form that differs
663
+ * from a fixed-notation source compares unequal (conservatively retained).
664
+ */
665
+ function canonicalDecimal(s) {
666
+ let str = s.trim().replace(/^\+/, "");
667
+ if (/[eE]/.test(str)) {
668
+ return str;
669
+ }
670
+ let neg = false;
671
+ if (str.startsWith("-")) {
672
+ neg = true;
673
+ str = str.slice(1);
674
+ }
675
+ let [int = "", frac = ""] = str.split(".");
676
+ int = int.replace(/^0+(?=\d)/, "");
677
+ frac = frac.replace(/0+$/, "");
678
+ if (int === "") {
679
+ int = "0";
680
+ }
681
+ const body = frac ? `${int}.${frac}` : int;
682
+ return neg && body !== "0" ? `-${body}` : body;
683
+ }
684
+
685
+ /** Shape a private data value with no VM info: scalar if one value, else array. */
686
+ function privateShape(values) {
687
+ if (values.length === 0) {
688
+ return null;
689
+ }
690
+ return values.length === 1 ? values[0] : values.slice();
691
+ }
692
+
693
+ /**
694
+ * Add Person Name accessors (§17): a non-enumerable toString() returning the raw
695
+ * PN string and toJSON() keeping the DICOM JSON model. Component access
696
+ * (`.Alphabetic`) works directly because the value IS the {Alphabetic,...}
697
+ * object (VM 1) or an array of them (VM n). Reuses dcmjs's shared helper.
698
+ */
699
+ function addPersonNameAccessors(shaped) {
700
+ if (typeof shaped === "string") {
701
+ shaped = new String(shaped);
702
+ }
703
+ if (shaped && typeof shaped === "object") {
704
+ return core.dicomJson.pnAddValueAccessors(shaped);
705
+ }
706
+ return shaped;
707
+ }
708
+
709
+ /**
710
+ * fromDicomWebJson — slice C: a DICOMweb JSON (DICOM JSON model) ->
711
+ * event-stream generator.
712
+ *
713
+ * Walks a parsed DICOMweb JSON object and emits the event-stream contract,
714
+ * proving the source-agnostic claim (§4.4): the same contract a Part 10 reader
715
+ * produces is produced here from a third source. Implemented as a low-allocation
716
+ * visitor that calls listener callbacks directly, without building intermediate
717
+ * event objects (§24.1).
718
+ *
719
+ * Values are emitted AS-IS — Person Names stay as DICOMweb `{ Alphabetic }`
720
+ * objects, numbers stay numbers. Cross-source value canonicalization (PN proxy,
721
+ * IS/DS normalization, §17/§28) belongs to the naturalized listener (slice D).
722
+ * The two binary forms are handled per spec:
723
+ * - `BulkDataURI` -> bulkDataReference (nothing fetched, §21)
724
+ * - `InlineBinary` -> base64 decoded to a buffer fragment (§22)
725
+ *
726
+ * @param {Object} json - DICOM JSON model: { "ggggeeee": { vr, Value | BulkDataURI | InlineBinary }, ... }
727
+ * @param {import("./EventStreamListener").EventStreamListener} listener
728
+ */
729
+ async function fromDicomWebJson(json, listener) {
730
+ const tags = Object.keys(json);
731
+ const metaTags = tags.filter(isMetaTag);
732
+ const bodyTags = tags.filter(t => !isMetaTag(t));
733
+
734
+ listener.startDataSet({ transferSyntaxUID: transferSyntaxOf$1(json) });
735
+
736
+ if (metaTags.length) {
737
+ listener.startFileMetaInformation();
738
+ for (const tag of metaTags) {
739
+ emitAttribute(listener, tag, json[tag]);
740
+ }
741
+ listener.endFileMetaInformation();
742
+ }
743
+
744
+ for (const tag of bodyTags) {
745
+ emitAttribute(listener, tag, json[tag]);
746
+ // Top-level element boundary: a defined backpressure checkpoint.
747
+ await listener.awaitDrain();
748
+ }
749
+
750
+ listener.endDataSet();
751
+ }
752
+
753
+ function emitAttribute(listener, tag, attr) {
754
+ if (!attr) {
755
+ return;
756
+ }
757
+ const vr = attr.vr;
758
+
759
+ if (vr === "SQ") {
760
+ listener.startSequence(tag, { vr });
761
+ for (const item of attr.Value || []) {
762
+ listener.startItem({});
763
+ for (const childTag of Object.keys(item)) {
764
+ emitAttribute(listener, childTag, item[childTag]);
765
+ }
766
+ listener.endItem();
767
+ }
768
+ listener.endSequence();
769
+ return;
770
+ }
771
+
772
+ if (attr.BulkDataURI !== undefined) {
773
+ listener.startElement(tag, { vr });
774
+ listener.bulkDataReference({ uri: attr.BulkDataURI });
775
+ listener.endElement();
776
+ return;
777
+ }
778
+
779
+ if (attr.InlineBinary !== undefined) {
780
+ listener.startElement(tag, { vr });
781
+ listener.startBinary({ encapsulated: false });
782
+ listener.binaryFragment(base64ToArrayBuffer(attr.InlineBinary));
783
+ listener.endBinary();
784
+ listener.endElement();
785
+ return;
786
+ }
787
+
788
+ listener.startElement(tag, { vr });
789
+ let index = 0;
790
+ for (const v of attr.Value || []) {
791
+ listener.value(v, { index: index++ });
792
+ }
793
+ listener.endElement();
794
+ }
795
+
796
+ function transferSyntaxOf$1(json) {
797
+ const ts = json["00020010"];
798
+ return ts && ts.Value ? ts.Value[0] : undefined;
799
+ }
800
+
801
+ function isMetaTag(tag) {
802
+ return tag.slice(0, 4) === "0002";
803
+ }
804
+
805
+ /** Decode a base64 string into an ArrayBuffer (Node and browser). */
806
+ function base64ToArrayBuffer(b64) {
807
+ if (typeof Buffer !== "undefined") {
808
+ const buf = Buffer.from(b64, "base64");
809
+ return buf.buffer.slice(
810
+ buf.byteOffset,
811
+ buf.byteOffset + buf.byteLength
812
+ );
813
+ }
814
+ const binary = atob(b64);
815
+ const bytes = new Uint8Array(binary.length);
816
+ for (let i = 0; i < binary.length; i++) {
817
+ bytes[i] = binary.charCodeAt(i);
818
+ }
819
+ return bytes.buffer;
820
+ }
821
+
822
+ /**
823
+ * fromDataSet — the reference event-stream generator for slice A.
824
+ *
825
+ * Walks a parsed dcmjs dataset (a `{ meta, dict }` shape — e.g. the DicomDict
826
+ * returned by `DicomMessage.readFile`, produced by the lazy core over
827
+ * `@dcmjs-org/parser`) and pushes the event-stream contract to a listener. It
828
+ * reuses the lazy core's already-decoded values rather than re-decoding raw
829
+ * offsets, which keeps slice A decoupled from the Part 10 byte parser (that
830
+ * production "bytes -> events" generator is slice B). This generator exercises
831
+ * the spec §32 "tag / naturalized source -> event stream" path and proves the
832
+ * vocabulary can carry a real dataset losslessly.
833
+ *
834
+ * Async by design: structural/value callbacks are synchronous, but the
835
+ * generator awaits `listener.awaitDrain()` at the defined backpressure
836
+ * checkpoints — top-level element boundaries and between binary fragments.
837
+ *
838
+ * @param {{ meta?: Object, dict?: Object }} dataset
839
+ * @param {import("./EventStreamListener").EventStreamListener} listener
840
+ */
841
+
842
+ async function fromDataSet(dataset, listener) {
843
+ const meta = dataset.meta || null;
844
+ const dict = dataset.dict || dataset;
845
+
846
+ listener.startDataSet({
847
+ transferSyntaxUID: transferSyntaxOf(meta)
848
+ });
849
+
850
+ if (meta && Object.keys(meta).length) {
851
+ listener.startFileMetaInformation();
852
+ for (const tag of Object.keys(meta)) {
853
+ emitEntry(listener, tag, meta[tag]);
854
+ }
855
+ listener.endFileMetaInformation();
856
+ }
857
+
858
+ for (const tag of Object.keys(dict)) {
859
+ emitEntry(listener, tag, dict[tag]);
860
+ // Top-level element boundary: a defined backpressure checkpoint.
861
+ await listener.awaitDrain();
862
+ }
863
+
864
+ listener.endDataSet();
865
+ }
866
+
867
+ function transferSyntaxOf(meta) {
868
+ const ts = meta && meta["00020010"];
869
+ return ts && ts.Value ? ts.Value[0] : undefined;
870
+ }
871
+
872
+ /** Emit one tag entry (element, sequence, or binary) and its children.
873
+ * Exported for fromPart10's §6.2.2 UN-sequence emission (issue #363). */
874
+ function emitEntry(listener, tag, entry) {
875
+ if (!entry) {
876
+ return;
877
+ }
878
+ const values = entry.Value || [];
879
+
880
+ if (entry.vr === "SQ") {
881
+ listener.startSequence(tag, { vr: entry.vr, length: entry.length });
882
+ for (const item of values) {
883
+ listener.startItem({ length: item && item._length });
884
+ for (const childTag of Object.keys(item)) {
885
+ emitEntry(listener, childTag, item[childTag]);
886
+ }
887
+ listener.endItem();
888
+ }
889
+ listener.endSequence();
890
+ return;
891
+ }
892
+
893
+ if (entry.InlineBinary !== undefined || values.some(isInlineBinary)) {
894
+ emitInlineBinary(listener, tag, entry, values);
895
+ return;
896
+ }
897
+
898
+ if (isBinary(values)) {
899
+ listener.startElement(tag, { vr: entry.vr, length: entry.length });
900
+ listener.startBinary({ encapsulated: !!entry.encapsulatedPixelData });
901
+ for (const fragment of values) {
902
+ listener.binaryFragment(fragment);
903
+ }
904
+ listener.endBinary();
905
+ listener.endElement();
906
+ return;
907
+ }
908
+
909
+ listener.startElement(tag, { vr: entry.vr, length: entry.length });
910
+ // _rawValue (when present on lazy/eager dict entries) carries the source
911
+ // string for precision-preserving retention (§16/§27).
912
+ const rawValues = entry._rawValue;
913
+ let index = 0;
914
+ for (const v of values) {
915
+ if (isBulkDataReference(v)) {
916
+ listener.bulkDataReference({ uri: v.BulkDataURI });
917
+ } else {
918
+ listener.value(v, {
919
+ index,
920
+ rawValue: Array.isArray(rawValues)
921
+ ? rawValues[index]
922
+ : undefined
923
+ });
924
+ }
925
+ index++;
926
+ }
927
+ listener.endElement();
928
+ }
929
+
930
+ /**
931
+ * Emit an entry that holds {InlineBinary} wrappers as binary events.
932
+ *
933
+ * {InlineBinary} wrappers are the naturalized binary form produced by both
934
+ * NaturalizedListener and DicomMetaDictionary.naturalizeDataset (§22). They
935
+ * are unwrapped to binary events exactly as fromDicomWebJson does; without
936
+ * this the wrapper object reaches BinaryRepresentation.writeBytes and throws
937
+ * (the UN naturalize→write round-trip crash). The wrapper may sit on the
938
+ * entry itself (no Value array) or inside Value; its content may be an
939
+ * ArrayBuffer, a typed-array view, a base64 string, or an array of fragments
940
+ * in any of those forms.
941
+ */
942
+ function emitInlineBinary(listener, tag, entry, values) {
943
+ const wrappers = entry.InlineBinary !== undefined ? [entry] : values;
944
+ listener.startElement(tag, { vr: entry.vr, length: entry.length });
945
+ listener.startBinary({ encapsulated: !!entry.encapsulatedPixelData });
946
+ for (const w of wrappers) {
947
+ const inline = isInlineBinary(w) ? w.InlineBinary : w;
948
+ for (const fragment of Array.isArray(inline) ? inline : [inline]) {
949
+ listener.binaryFragment(toBinaryFragment(fragment));
950
+ }
951
+ }
952
+ listener.endBinary();
953
+ listener.endElement();
954
+ }
955
+
956
+ function isBinary(values) {
957
+ return values.some(v => v instanceof ArrayBuffer || ArrayBuffer.isView(v));
958
+ }
959
+
960
+ /** True for a naturalized binary wrapper: { InlineBinary: <content> }. */
961
+ function isInlineBinary(v) {
962
+ return (
963
+ v &&
964
+ typeof v === "object" &&
965
+ v.InlineBinary !== undefined &&
966
+ !(v instanceof ArrayBuffer) &&
967
+ !ArrayBuffer.isView(v)
968
+ );
969
+ }
970
+
971
+ /** Coerce one InlineBinary fragment (buffer, view, or base64) to bytes. */
972
+ function toBinaryFragment(fragment) {
973
+ if (typeof fragment === "string") {
974
+ return base64ToArrayBuffer(fragment);
975
+ }
976
+ return fragment;
977
+ }
978
+
979
+ function isBulkDataReference(v) {
980
+ return (
981
+ v &&
982
+ typeof v === "object" &&
983
+ typeof v.BulkDataURI === "string" &&
984
+ !(v instanceof ArrayBuffer) &&
985
+ !ArrayBuffer.isView(v)
986
+ );
987
+ }
988
+
989
+ /**
990
+ * createEventAsyncIterable — the pull adapter of the hybrid contract.
991
+ *
992
+ * The push/callback listener is canonical; this wraps a generator run as an
993
+ * async-iterable so ergonomic consumers can `for await (const ev of ...)`.
994
+ * Each yielded event is `{ type, args }` where `type` is a vocabulary method
995
+ * name and `args` is the argument array.
996
+ *
997
+ * Backpressure is real: the bridge installs a drain gate on the listener, so a
998
+ * slow consumer suspends the generator at its checkpoints once the internal
999
+ * queue exceeds `highWaterMark`. Events are freshly allocated (not pooled) so
1000
+ * consumers may retain them safely.
1001
+ *
1002
+ * @param {(listener: EventStreamListener) => Promise<void>} run - drives the listener
1003
+ * @param {{ highWaterMark?: number }} [options]
1004
+ * @returns {AsyncIterable<{type: string, args: any[]}>}
1005
+ */
1006
+ function createEventAsyncIterable(run, { highWaterMark = 64 } = {}) {
1007
+ return {
1008
+ [Symbol.asyncIterator]() {
1009
+ const queue = [];
1010
+ let finished = false;
1011
+ let cancelled = false;
1012
+ let failure = null;
1013
+ let onItem = null; // resolve a waiting consumer
1014
+ let onSpace = null; // {resolve, reject} of a suspended producer
1015
+
1016
+ const cancellation = () => {
1017
+ const err = new Error("event iteration cancelled");
1018
+ err.name = "EventIterationCancelled";
1019
+ return err;
1020
+ };
1021
+ const wakeConsumer = () => {
1022
+ if (onItem) {
1023
+ const r = onItem;
1024
+ onItem = null;
1025
+ r();
1026
+ }
1027
+ };
1028
+ const wakeProducer = () => {
1029
+ if (onSpace && queue.length < highWaterMark) {
1030
+ const r = onSpace;
1031
+ onSpace = null;
1032
+ r.resolve();
1033
+ }
1034
+ };
1035
+
1036
+ // A capture filter enqueues one event per vocabulary call.
1037
+ const captureFilter = {};
1038
+ for (const name of EVENT_STREAM_VOCABULARY) {
1039
+ captureFilter[name] = function (next, ...args) {
1040
+ queue.push({ type: name, args });
1041
+ wakeConsumer();
1042
+ return next(...args);
1043
+ };
1044
+ }
1045
+
1046
+ const listener = new EventStreamListener(captureFilter);
1047
+ listener.setDrain(() => {
1048
+ if (cancelled) {
1049
+ return Promise.reject(cancellation());
1050
+ }
1051
+ return queue.length < highWaterMark
1052
+ ? Promise.resolve()
1053
+ : new Promise((resolve, reject) => {
1054
+ onSpace = { resolve, reject };
1055
+ });
1056
+ });
1057
+
1058
+ Promise.resolve()
1059
+ .then(() => run(listener))
1060
+ .then(
1061
+ () => {
1062
+ finished = true;
1063
+ wakeConsumer();
1064
+ },
1065
+ err => {
1066
+ // A rejection we caused by cancelling is a clean end,
1067
+ // not a stream failure.
1068
+ if (
1069
+ !cancelled ||
1070
+ err?.name !== "EventIterationCancelled"
1071
+ ) {
1072
+ failure = err || new Error("event stream failed");
1073
+ }
1074
+ finished = true;
1075
+ wakeConsumer();
1076
+ }
1077
+ );
1078
+
1079
+ return {
1080
+ async next() {
1081
+ while (queue.length === 0 && !finished) {
1082
+ await new Promise(resolve => {
1083
+ onItem = resolve;
1084
+ });
1085
+ }
1086
+ if (queue.length > 0) {
1087
+ const value = queue.shift();
1088
+ wakeProducer();
1089
+ return { value, done: false };
1090
+ }
1091
+ if (failure) {
1092
+ throw failure;
1093
+ }
1094
+ return { value: undefined, done: true };
1095
+ },
1096
+ // Called by `break`/`return` out of a for-await loop. Without
1097
+ // it a producer suspended in awaitDrain waits forever on a
1098
+ // consumer that is gone.
1099
+ async return(value) {
1100
+ cancelled = true;
1101
+ queue.length = 0;
1102
+ if (onSpace) {
1103
+ const r = onSpace;
1104
+ onSpace = null;
1105
+ r.reject(cancellation());
1106
+ }
1107
+ return { value, done: true };
1108
+ }
1109
+ };
1110
+ }
1111
+ };
1112
+ }
1113
+
1114
+ /**
1115
+ * Shared emit helpers for byte-level event sources.
1116
+ *
1117
+ * These route a decoded element ({ values, rawValues }) to the correct
1118
+ * listener events. They lived in the tokenizer-backed fromPart10 module;
1119
+ * with the vendored tokenizer removed they are a standalone module the
1120
+ * streaming reader (and the thin fromPart10 wrapper) share.
1121
+ */
1122
+
1123
+ /**
1124
+ * Emits a decoded leaf element. Sequence-shaped decodes yield item dicts —
1125
+ * those are emitted as sequence events (matching the eager dict shape);
1126
+ * everything else routes through emitValues.
1127
+ *
1128
+ * Two decodes are sequence-shaped: (a) UN with undefined length parsed as an
1129
+ * implicit-VR sequence (PS3.5 §6.2.2, issue #363), and (b) defined-length UN
1130
+ * whose dictionary VR is SQ (ParsedUnknownValue re-parses the value as a
1131
+ * sequence — corpus shape "EVRLE SQ as UN"). Both decode to item dicts in
1132
+ * `values` and must be emitted as sequence events; emitting them through the
1133
+ * scalar value() path crashed on rawValues[index] (the corpus bare-TypeError
1134
+ * cluster).
1135
+ */
1136
+ function emitDecodedLeaf(
1137
+ listener,
1138
+ tag,
1139
+ vrInstance,
1140
+ el,
1141
+ values,
1142
+ rawValues
1143
+ ) {
1144
+ // Sequence-shaped decodes (see JSDoc).
1145
+ if (
1146
+ (vrInstance.type === "SQ" ||
1147
+ (vrInstance.type === "UN" && el.hadUndefinedLength)) &&
1148
+ Array.isArray(values) &&
1149
+ values.every(isItemDictLike)
1150
+ ) {
1151
+ listener.startSequence(tag, { vr: "SQ", length: el.length });
1152
+ for (const itemDict of values) {
1153
+ listener.startItem({});
1154
+ for (const childTag of Object.keys(itemDict)) {
1155
+ emitEntry(listener, childTag, itemDict[childTag]);
1156
+ }
1157
+ listener.endItem();
1158
+ }
1159
+ listener.endSequence();
1160
+ return;
1161
+ }
1162
+ emitValues(listener, tag, vrInstance, el, values, rawValues);
1163
+ }
1164
+
1165
+ /**
1166
+ * Route decoded {values, rawValues} to binary or scalar listener events.
1167
+ *
1168
+ * The decoded shapes are normalized first: some VR reads legitimately yield
1169
+ * a bare value or no rawValues array (classic stores these shapes untouched
1170
+ * in the dict; the event stream must not crash on them — corpus
1171
+ * bare-TypeError cluster).
1172
+ */
1173
+ function emitValues(listener, tag, vrInstance, el, values, rawValues) {
1174
+ // Normalize bare / missing values to a list (see JSDoc).
1175
+ const list = Array.isArray(values)
1176
+ ? values
1177
+ : values === undefined || values === null
1178
+ ? []
1179
+ : [values];
1180
+ if (list.some(isBufferLike)) {
1181
+ listener.startElement(tag, { vr: vrInstance.type, length: el.length });
1182
+ listener.startBinary({ encapsulated: false });
1183
+ for (const buf of list) {
1184
+ listener.binaryFragment(buf);
1185
+ }
1186
+ listener.endBinary();
1187
+ listener.endElement();
1188
+ return;
1189
+ }
1190
+
1191
+ listener.startElement(tag, { vr: vrInstance.type, length: el.length });
1192
+ let index = 0;
1193
+ for (const v of list) {
1194
+ listener.value(v, {
1195
+ index,
1196
+ rawValue: Array.isArray(rawValues) ? rawValues[index] : undefined
1197
+ });
1198
+ index++;
1199
+ }
1200
+ listener.endElement();
1201
+ }
1202
+
1203
+ function isItemDictLike(v) {
1204
+ return (
1205
+ v &&
1206
+ typeof v === "object" &&
1207
+ !(v instanceof ArrayBuffer) &&
1208
+ !ArrayBuffer.isView(v) &&
1209
+ Object.keys(v).every(k => /^[0-9A-Fx]{8,9}$/i.test(k))
1210
+ );
1211
+ }
1212
+
1213
+ function isBufferLike(v) {
1214
+ return v instanceof ArrayBuffer || ArrayBuffer.isView(v);
1215
+ }
1216
+
1217
+ /**
1218
+ * Shared element-decode core extracted from src/lazy/LazyDicomReader.js.
1219
+ *
1220
+ * All functions operate on two read-only input shapes instead of the mutable
1221
+ * `ctx` used by the lazy reader:
1222
+ *
1223
+ * window = { arrayBuffer, baseOffset, syntax, littleEndian, implicit, decoder }
1224
+ * A fully-resolved byte region. Callers construct a *meta window*
1225
+ * (original buffer, EXPLICIT_LITTLE_ENDIAN, littleEndian=true,
1226
+ * implicit=false, decoder=null) or a *body window* (post-inflate
1227
+ * buffer, negotiated syntax/endianness/implicitness, active decoder).
1228
+ * There is no `isMeta` parameter anywhere in this module: callers
1229
+ * select the correct window.
1230
+ *
1231
+ * policy = { forceStoreRaw, noCopy, ignoreErrors }
1232
+ *
1233
+ * Every function body that reaches DicomMessage / Tag accesses them at call
1234
+ * time, never at module-evaluation time, to honour the circular-import
1235
+ * discipline of the wider codebase.
1236
+ */
1237
+
1238
+ // ──────────────────────────────────────────────────────────────────────────────
1239
+ // Internal helpers (not exported)
1240
+ // ──────────────────────────────────────────────────────────────────────────────
1241
+
1242
+ // ──────────────────────────────────────────────────────────────────────────────
1243
+ // Exported functions
1244
+ // ──────────────────────────────────────────────────────────────────────────────
1245
+
1246
+ /**
1247
+ * Resolves the ValueRepresentation instance for a parser element,
1248
+ * replicating DicomMessage._readTag's VR resolution rules
1249
+ * (src/DicomMessage.js, explicit + implicit branches).
1250
+ *
1251
+ * THIS IS THE SINGLE CANONICAL IMPLICIT-VR CONTRACT (AD-1). Every read
1252
+ * path — eager, lazy, fromPart10, fromPart10Stream — resolves implicit
1253
+ * VRs here, with eager parity: a DEFINED-length dictionary-miss element
1254
+ * resolves to UN (or OW/LO by tag rules) and is NEVER data-peek-promoted
1255
+ * to SQ, regardless of its value bytes; an UNDEFINED-length dictionary
1256
+ * miss resolves to SQ by the length rule. The parser's el.items (its
1257
+ * framing peek) is metadata only and must not influence VR resolution.
1258
+ *
1259
+ * `window.implicit` is already resolved by the caller: a meta window
1260
+ * always carries implicit=false; a body window carries the negotiated value.
1261
+ * The lazy source computed `ctx.implicit && !isMeta`; here the caller
1262
+ * selects the window instead.
1263
+ *
1264
+ * Uses DicomMetaDictionary.lookupTag, ValueRepresentation.parseUnknownVr /
1265
+ * createByTypeString, Tag — all accessed inside the function body.
1266
+ */
1267
+ function resolveVrInstance(el, window) {
1268
+ const implicit = window.implicit;
1269
+
1270
+ if (!implicit) {
1271
+ const vrType = el.vr;
1272
+ if (vrType === "UN") {
1273
+ const tag = new core.Tag(el.tagValue);
1274
+ const elementData = core.DicomMetaDictionary.lookupTag(tag);
1275
+ if (elementData && elementData.vr) {
1276
+ // UN with a known dictionary VR: eager re-parses the value
1277
+ // as the dictionary VR via ParsedUnknownValue.
1278
+ let dictVr = elementData.vr;
1279
+ if (dictVr === "xs") {
1280
+ dictVr = resolveXsVr(window);
1281
+ }
1282
+ return core.ValueRepresentation.parseUnknownVr(dictVr);
1283
+ }
1284
+ }
1285
+ return core.ValueRepresentation.createByTypeString(vrType);
1286
+ }
1287
+
1288
+ // Implicit VR: dictionary lookup with _readTag's fallback rules.
1289
+ const tag = new core.Tag(el.tagValue);
1290
+ const elementData = core.DicomMetaDictionary.lookupTag(tag);
1291
+ let vrType;
1292
+ if (elementData) {
1293
+ vrType = elementData.vr;
1294
+ if (vrType === "xs") {
1295
+ vrType = resolveXsVr(window);
1296
+ }
1297
+ } else if (el.hadUndefinedLength) {
1298
+ // eager: length == UNDEFINED_LENGTH (the parser corrects element
1299
+ // .length for undefined-length elements, so use the flag)
1300
+ vrType = "SQ";
1301
+ } else if (tag.isPixelDataTag()) {
1302
+ vrType = "OW";
1303
+ } else if (tag.isPrivateCreator()) {
1304
+ vrType = "LO";
1305
+ } else {
1306
+ vrType = "UN";
1307
+ }
1308
+ return core.ValueRepresentation.createByTypeString(vrType);
1309
+ }
1310
+
1311
+ /**
1312
+ * Resolves the dictionary meta-VR "xs" ("US or SS") by PixelRepresentation
1313
+ * (PS3.5): SS when (0028,0103) is 1, US otherwise — including when the
1314
+ * window carries no pixelRepresentation (parity with DicomMessage._readTag,
1315
+ * fixed in this arc for issue #368). Sources thread the parsed
1316
+ * (0028,0103) value onto their read window as `pixelRepresentation`;
1317
+ * (0028,0103) precedes every xs tag in tag order.
1318
+ */
1319
+ function resolveXsVr(window) {
1320
+ return window.pixelRepresentation === 1 ? "SS" : "US";
1321
+ }
1322
+
1323
+ /**
1324
+ * True when resolveVrInstance produced a ParsedUnknownValue (UN element with
1325
+ * a known dictionary VR): those are per-call instances, while every plain VR
1326
+ * resolves to the shared VRinstances singleton.
1327
+ */
1328
+ function isParsedUnknownVr(vrInstance) {
1329
+ return (
1330
+ vrInstance !== core.ValueRepresentation.createByTypeString(vrInstance.type)
1331
+ );
1332
+ }
1333
+
1334
+ /**
1335
+ * Verbatim replication of DicomMessage._readTag's value-shaping block
1336
+ * (src/DicomMessage.js:380-402): string VM splitting, the SQ and OW/OB
1337
+ * passthroughs and the array-or-push fallback (which yields
1338
+ * `_rawValue: [undefined]` for non-raw-storing VRs like UN/OF/OD - a quirk
1339
+ * the lazy core must reproduce).
1340
+ *
1341
+ * Uses the canonical singleVRs exported from @dcmjs-org/core (includes LT).
1342
+ * Arg order is (vr, rawValue, value) — same as the source.
1343
+ */
1344
+ function shapeReadValues(vr, rawValue, value) {
1345
+ let values = [];
1346
+ let rawValues = [];
1347
+ if (!vr.isBinary() && core.singleVRs.indexOf(vr.type) == -1) {
1348
+ rawValues = rawValue;
1349
+ values = value;
1350
+ if (typeof value === "string") {
1351
+ const delimiterChar = String.fromCharCode(core.VM_DELIMITER);
1352
+ rawValues = vr.dropPadByte(rawValue.split(delimiterChar));
1353
+ values = vr.dropPadByte(value.split(delimiterChar));
1354
+ }
1355
+ } else if (vr.type == "SQ") {
1356
+ rawValues = rawValue;
1357
+ values = value;
1358
+ } else if (vr.type == "OW" || vr.type == "OB") {
1359
+ rawValues = rawValue;
1360
+ values = value;
1361
+ } else {
1362
+ Array.isArray(value) ? (values = value) : values.push(value);
1363
+ Array.isArray(rawValue)
1364
+ ? (rawValues = rawValue)
1365
+ : rawValues.push(rawValue);
1366
+ }
1367
+ return { values, rawValues };
1368
+ }
1369
+
1370
+ /**
1371
+ * Constructs a ReadBufferStream over the element's data bytes within the
1372
+ * given window, mirroring the stream construction in materializeElement
1373
+ * (src/lazy/LazyDicomReader.js:565-575).
1374
+ *
1375
+ * start = window.baseOffset + el.dataOffset
1376
+ * stop = start + el.length
1377
+ *
1378
+ * policy.noCopy controls whether getBuffer() returns a Uint8Array (true) or
1379
+ * an ArrayBuffer (false), exactly as the source does. When window.decoder is
1380
+ * non-null the stream's decoder is set before returning.
1381
+ * NOTE: callers using a meta window must pass policy.noCopy = false (the lazy
1382
+ * source always forced noCopy off for meta reads).
1383
+ */
1384
+ function buildElementStream(window, el, policy) {
1385
+ const start = window.baseOffset + el.dataOffset;
1386
+ const stream = new core.ReadBufferStream(
1387
+ window.arrayBuffer,
1388
+ window.littleEndian,
1389
+ {
1390
+ start,
1391
+ stop: start + effectiveElementLength(window, el, true),
1392
+ // eager's body stream carries noCopy (getBuffer then returns
1393
+ // Uint8Array instead of ArrayBuffer); its meta stream comes from
1394
+ // stream.more(), which drops it
1395
+ noCopy: policy.noCopy
1396
+ }
1397
+ );
1398
+ if (window.decoder) {
1399
+ stream.setDecoder(window.decoder);
1400
+ }
1401
+ return stream;
1402
+ }
1403
+
1404
+ /**
1405
+ * Corrective guard: a defined length that overruns the underlying buffer is
1406
+ * a corrupt length (or a derailed walk). Historic (and test-pinned) leniency
1407
+ * reads truncated trailing elements, so the length is CLAMPED to the bytes
1408
+ * actually available — but no longer silently (the corruption is logged, and
1409
+ * phantom multi-GB allocations from garbage lengths are avoided). Parity
1410
+ * with the classic reader's overrun clamp in DicomMessage._readTag.
1411
+ */
1412
+ function effectiveElementLength(window, el, warn) {
1413
+ const available =
1414
+ window.arrayBuffer.byteLength - (window.baseOffset + el.dataOffset);
1415
+ if (
1416
+ el.length === undefined ||
1417
+ el.length === core.UNDEFINED_LENGTH ||
1418
+ el.length <= available
1419
+ ) {
1420
+ return el.length;
1421
+ }
1422
+ if (warn) {
1423
+ core.log.warn(
1424
+ `decodeCore: element ${el.tag || ""} declares ${el.length} ` +
1425
+ `bytes but only ${Math.max(available, 0)} remain in the ` +
1426
+ `buffer; clamping to the remaining bytes`
1427
+ );
1428
+ }
1429
+ return Math.max(available, 0);
1430
+ }
1431
+
1432
+ /**
1433
+ * Decodes the value phase of a defined-length element, mirroring the tail of
1434
+ * materializeElement (src/lazy/LazyDicomReader.js:557-598): the binary
1435
+ * multi-read loop (oversized binary values), or a single vr.read() followed
1436
+ * by shapeReadValues for everything else.
1437
+ *
1438
+ * Callers must already have built the stream via buildElementStream or have
1439
+ * established that the element is defined-length (not undefined-length, not
1440
+ * a sequence, not encapsulated pixel data). Use classifyElement to determine
1441
+ * the routing before calling.
1442
+ */
1443
+ function decodeElementValues(window, el, vrInstance, policy) {
1444
+ const vr = vrInstance;
1445
+ // Clamped for buffer-overrunning corrupt lengths (see
1446
+ // effectiveElementLength); buildElementStream applies (and logs) the
1447
+ // same clamp for the stream's stop offset.
1448
+ const length = effectiveElementLength(window, el, false);
1449
+ const stream = buildElementStream(window, el, policy);
1450
+ return readValues(window, vr, stream, length, policy);
1451
+ }
1452
+
1453
+ /**
1454
+ * Decodes the value of an undefined-length element that is not a streamed
1455
+ * sequence and not encapsulated pixel data (classifyElement "eagerWindow").
1456
+ * The value bytes are [dataOffset, endOffset) of the window; endOffset is the
1457
+ * end of the closing delimiter. The VR reads with UNDEFINED_LENGTH, so the
1458
+ * result is the same as DicomMessage._readTag gives for the element.
1459
+ *
1460
+ * Returns { values, rawValues } in the same shape as decodeElementValues.
1461
+ */
1462
+ function decodeUndefinedLengthValues(window, el, vrInstance, policy) {
1463
+ const stream = new core.ReadBufferStream(
1464
+ window.arrayBuffer,
1465
+ window.littleEndian,
1466
+ {
1467
+ start: window.baseOffset + el.dataOffset,
1468
+ stop: window.baseOffset + el.endOffset,
1469
+ noCopy: policy.noCopy
1470
+ }
1471
+ );
1472
+ if (window.decoder) {
1473
+ stream.setDecoder(window.decoder);
1474
+ }
1475
+ return readValues(window, vrInstance, stream, core.UNDEFINED_LENGTH, policy);
1476
+ }
1477
+
1478
+ /**
1479
+ * The value read of DicomMessage._readTag: the binary multi-read loop for
1480
+ * oversized binary values, or one vr.read() followed by shapeReadValues.
1481
+ */
1482
+ function readValues(window, vr, stream, length, policy) {
1483
+ const readOptions = { forceStoreRaw: policy.forceStoreRaw };
1484
+
1485
+ if (vr.isBinary() && length > vr.maxLength && !vr.noMultiple) {
1486
+ const values = [];
1487
+ const rawValues = [];
1488
+ const times = length / vr.maxLength;
1489
+ let i = 0;
1490
+ while (i++ < times) {
1491
+ const { rawValue, value } = vr.read(
1492
+ stream,
1493
+ vr.maxLength,
1494
+ window.syntax,
1495
+ readOptions
1496
+ );
1497
+ rawValues.push(rawValue);
1498
+ values.push(value);
1499
+ }
1500
+ return { values, rawValues };
1501
+ }
1502
+ const { rawValue, value } =
1503
+ vr.read(stream, length, window.syntax, readOptions) || {};
1504
+ return shapeReadValues(vr, rawValue, value);
1505
+ }
1506
+
1507
+ /**
1508
+ * Resolves the dataset decoder from SpecificCharacterSet (00080005) with
1509
+ * the exact eager semantics of DicomMessage._read (src/DicomMessage.js:77-105):
1510
+ * encodingMapping lookup, warn-or-throw per policy.ignoreErrors for unsupported
1511
+ * or multiple charsets, and the entry Value rewritten to ["ISO_IR 192"] while
1512
+ * _rawValue keeps the original.
1513
+ *
1514
+ * Side-effect-free version of resolveCharacterSet in LazyDicomReader: instead
1515
+ * of assigning ctx.decoder the resolved TextDecoder is RETURNED in the result
1516
+ * object. The caller is responsible for setting it on the body window.
1517
+ *
1518
+ * Returns { decoder, vrInstance, originalValues, seedState } or null if csEl
1519
+ * is absent.
1520
+ *
1521
+ * decoder — the resolved TextDecoder, or null when the charset is
1522
+ * unsupported under ignoreErrors=true.
1523
+ * vrInstance — the resolved VR for the charset element.
1524
+ * originalValues — the values as stored in the file, BEFORE the ISO_IR 192
1525
+ * rewrite (consumed by the charsetPassthroughSafe check).
1526
+ * seedState — { values: ["ISO_IR 192"], rawValues } — the seed for the
1527
+ * 00080005 lazy entry (eager quirk: rewrites Value to UTF-8).
1528
+ */
1529
+ function resolveCharacterSet(window, csEl, policy) {
1530
+ if (!csEl) {
1531
+ return null;
1532
+ }
1533
+ const vrInstance = resolveVrInstance(csEl, window);
1534
+ // Read with the default (latin1) decoder, exactly like the eager loop
1535
+ // does before it reaches the setDecoder call.
1536
+ const { values, rawValues } = decodeElementValues(
1537
+ window,
1538
+ csEl,
1539
+ vrInstance,
1540
+ policy
1541
+ );
1542
+
1543
+ // Shared charset resolution (single charsets, ISO 2022 code extensions,
1544
+ // error policy) — src/charset/iso2022.js. Same eager error semantics:
1545
+ // throws when ignoreErrors=false, warns and degrades to a null decoder
1546
+ // when ignoreErrors=true.
1547
+ const decoder = core.resolveCharsetDecoder(values, {
1548
+ ignoreErrors: policy.ignoreErrors
1549
+ });
1550
+
1551
+ return {
1552
+ decoder,
1553
+ vrInstance,
1554
+ // the values as stored in the file, BEFORE the ISO_IR 192 rewrite
1555
+ // (consumed by the charsetPassthroughSafe computation)
1556
+ originalValues: values,
1557
+ seedState: {
1558
+ // change SpecificCharacterSet to UTF-8 (eager quirk, kept)
1559
+ values: ["ISO_IR 192"],
1560
+ rawValues
1561
+ }
1562
+ };
1563
+ }
1564
+
1565
+ /**
1566
+ * src/eventStream/fromPart10Stream.js
1567
+ *
1568
+ * fromPart10Stream — chunked bytes → events source (slice K, stage 2).
1569
+ *
1570
+ * This is the public entry point for the bounded-memory streaming path.
1571
+ * Input is normalized into an AsyncIterable and fed into a ReadBufferStream
1572
+ * concurrently with parsing.
1573
+ *
1574
+ * The **preamble + File Meta Information phase** is genuinely incremental (K2+):
1575
+ * FMI elements are decoded on-the-fly as bytes arrive, so `startFileMetaInformation` /
1576
+ * per-element events / `endFileMetaInformation` are emitted before body bytes finish.
1577
+ *
1578
+ * The **body phase** streams natively for all transfer syntaxes (K3+ native paths):
1579
+ * defined-length, undefined-length, and encapsulated fragments stream directly
1580
+ * from the source. Deflate-compressed bodies (K5) inflate incrementally via
1581
+ * chunked pako.Inflate into a zero-based bodyStream, avoiding full-buffer copies.
1582
+ *
1583
+ * Both streams use clearBuffers=true with per-top-level-element consume() so that
1584
+ * chunk memory is released as the parse advances (bounded-memory streaming). A
1585
+ * bare (meta-less) dataset streams through the same body loop, behind the
1586
+ * allowMissingHeader opt-in.
1587
+ *
1588
+ * Decision D-E: noCopy is intentionally unsupported (see JSDoc above).
1589
+ */
1590
+
1591
+
1592
+ // ---------------------------------------------------------------------------
1593
+ // Public API
1594
+ // ---------------------------------------------------------------------------
1595
+
1596
+ /**
1597
+ * K5b: how far (in retained, unconsumed bytes) the raw feed loop may run
1598
+ * ahead of the parse before throttling itself. Pending demand always wins —
1599
+ * a consumer blocked in ensureAvailable wakes the feed regardless of the
1600
+ * watermark — so an element or fragment larger than this still accumulates
1601
+ * fully and the gate cannot deadlock. Overridable per call via
1602
+ * `options.feedHighWater`.
1603
+ *
1604
+ * Without this throttle, a listener stalled on its drain gate (e.g. a write
1605
+ * sink flushing a fragment to disk) lets the feed buffer the entire remaining
1606
+ * input. Parse settlement (parseState) wakes the gate on early exit or error.
1607
+ */
1608
+ const FEED_HIGH_WATER = 4 * 1024 * 1024;
1609
+
1610
+ /**
1611
+ * pako.Inflate chunkSize for the K5 deflate relay: controls when pako calls
1612
+ * onData. The default is 64 KiB (pako 2.x source: 1024*64) — large enough
1613
+ * that typical DICOM deflate bodies never fill a single chunk before the
1614
+ * stream is finalised, so onData would never fire mid-stream. 16 KiB keeps
1615
+ * the buffer small enough to ensure onData fires for every 16 KiB of
1616
+ * inflated output, giving the body loop bytes to parse before the raw stream
1617
+ * ends.
1618
+ */
1619
+ const INFLATE_CHUNK_SIZE = 16384;
1620
+
1621
+ /**
1622
+ * K5 relay throttle (ED-1): pause the relay while the body loop holds more
1623
+ * than RELAY_HIGH_WATER inflated bytes and has no pending demand — otherwise
1624
+ * a fast feed + slow listener grows bodyStream without bound (the
1625
+ * relay-balloon risk).
1626
+ */
1627
+ const RELAY_HIGH_WATER = 16384;
1628
+
1629
+ /**
1630
+ * K5 relay sub-slice size (ED-1). Because DEFLATE can expand >100× (a whole
1631
+ * file's output can hide in a few hundred compressed bytes), pausing between
1632
+ * network chunks is not enough: raw bytes are fed to the inflater in
1633
+ * RELAY_RAW_SLICE sub-slices with a retention check between each, bounding
1634
+ * the overshoot to one sub-slice's expansion.
1635
+ */
1636
+ const RELAY_RAW_SLICE = 128;
1637
+
1638
+ /**
1639
+ * fromPart10Stream — parse a chunked DICOM Part 10 byte source into events.
1640
+ *
1641
+ * Accepted `input` forms (all normalized to AsyncIterable internally):
1642
+ *
1643
+ * 1. `ArrayBuffer | Uint8Array`
1644
+ * Degenerate single-chunk input. Re-runnable: each call starts fresh.
1645
+ *
1646
+ * 2. `AsyncIterable<Uint8Array | ArrayBuffer | Buffer>`
1647
+ * Streamed chunks (async generators, Node.js Readable streams in
1648
+ * object mode, etc.). Single-use: the iterator is exhausted on the
1649
+ * first call and cannot be rewound.
1650
+ *
1651
+ * 3. WHATWG `ReadableStream`
1652
+ * Adapted to AsyncIterable via `Symbol.asyncIterator` (Node ≥ 16.14).
1653
+ * A reader-loop fallback is provided for environments where ReadableStream
1654
+ * does not implement AsyncIterable (older browsers / Node builds). No
1655
+ * additional dependencies are required.
1656
+ *
1657
+ * NOTE — `noCopy` is intentionally NOT accepted. The streaming source forces
1658
+ * noCopy semantics OFF because zero-copy views alias chunk memory that
1659
+ * `consume()` releases when the incremental loop (K3-K5) is in place
1660
+ * (decision D-E).
1661
+ *
1662
+ * @param {ArrayBuffer|Uint8Array|AsyncIterable|ReadableStream} input
1663
+ * @param {import("./EventStreamListener").EventStreamListener} listener
1664
+ * @param {Object} [options]
1665
+ * @param {boolean} [options.forceStoreRaw] Thread to the decode core.
1666
+ * @param {boolean} [options.ignoreErrors] Thread to the decode core.
1667
+ * @param {number} [options.feedHighWater] K5b feed throttle watermark in
1668
+ * bytes (default {@link FEED_HIGH_WATER}); see the constant's JSDoc.
1669
+ * @returns {Promise<void>}
1670
+ */
1671
+ function fromPart10Stream(input, listener, options = {}) {
1672
+ // Settlement handshake for the K5b feed gate: when the parse settles
1673
+ // (success OR error, from any of the many exit points), a throttled feed
1674
+ // must wake and wind down instead of waiting forever for consumer
1675
+ // activity that will never come.
1676
+ const parseState = { done: false, resolveDone: null };
1677
+ parseState.donePromise = new Promise(
1678
+ resolve => (parseState.resolveDone = resolve)
1679
+ );
1680
+ return fromPart10StreamImpl(input, listener, options, parseState).finally(
1681
+ () => {
1682
+ parseState.done = true;
1683
+ parseState.resolveDone();
1684
+ }
1685
+ );
1686
+ }
1687
+
1688
+ /**
1689
+ * The parse behind {@link fromPart10Stream}. It runs in four phases:
1690
+ *
1691
+ * 1. Preamble detection ({@link detectPreamble}); a bare dataset gets its
1692
+ * body syntax from {@link detectBareSyntax} and skips phase 2.
1693
+ * 2. Incremental FMI parse ({@link readFileMetaInformation}).
1694
+ * 3. Emission of the collected FMI events, after startDataSet.
1695
+ * 4. The body phase (K4 — fully incremental element loop).
1696
+ *
1697
+ * K4: the raw `stream` uses clearBuffers:true — the incremental body loop
1698
+ * consume()s each completed top-level element, so chunk memory is released
1699
+ * as the parse advances (bounded-memory streaming). The deflate relay
1700
+ * consumes the raw stream itself as it advances.
1701
+ *
1702
+ * Body phase: every structure now streams natively, in source order, bounded
1703
+ * only by the element currently being decoded:
1704
+ *
1705
+ * - Defined-length leaves and SQ: emitted directly (K3 behavior).
1706
+ * - Undefined-length SQ / items: parsed delimiter-driven; the subtree is
1707
+ * buffered ONLY long enough to backfill the buffered-parity content-span
1708
+ * length payload on startSequence/startItem (unknown until the closing
1709
+ * FFFE,E0DD / FFFE,E00D is reached), then flushed.
1710
+ * - Encapsulated pixel data: fragments streamed one at a time (the Basic
1711
+ * Offset Table item is skipped, matching buffered fromPart10).
1712
+ * - Undefined-length non-SQ leaves ("eagerWindow"): the value is bounded
1713
+ * by a delimiter scan ({@link skipUndefinedSequence}) and decoded via
1714
+ * decodeUndefinedLengthValues.
1715
+ *
1716
+ * The K3 tail-fallback (walkBodyTail / TailFallbackSignal / EventBuffer-for-
1717
+ * atomicity) is deleted: nothing can fall back mid-subtree anymore because
1718
+ * deflate is decided BEFORE the body loop. The only remaining buffered path
1719
+ * is deflate (K5). Chunk release is LIVE (clearBuffers:true + consume()).
1720
+ *
1721
+ * K5 deflate: a relay coroutine (runInflateRelay) reads compressed bytes from
1722
+ * `stream` (raw space, fixed at metaEndOffset after FMI parsing) and pushes
1723
+ * them through pako.Inflate into `bodyStream` (inflated/zero-based space).
1724
+ * The body element loop reads from `bsrc`, which is `bodyStream` for deflate
1725
+ * and `stream` for everything else. This is the ONLY branch that decides
1726
+ * which offset space the body loop operates in.
1727
+ *
1728
+ * Offset-space invariant: `stream` coordinates are always raw/compressed;
1729
+ * `bodyStream` coordinates are always inflated/zero-based. The two spaces are
1730
+ * NEVER mixed: body element offsets, `ensureAbs` calls, `slice` calls, and
1731
+ * `consume` calls all operate exclusively on whichever `bsrc` resolves to.
1732
+ * The relay is the sole owner of `stream` during the body phase.
1733
+ *
1734
+ * K5 top-level body element loop: every element (defined or undefined
1735
+ * length, leaf or SQ or encapsulated) is read and emitted incrementally by
1736
+ * parseOneElement. After each top-level element completes, consume()
1737
+ * releases the chunks it no longer needs. For deflate, `bsrc` is bodyStream
1738
+ * (inflated space, zero-based); the relay concurrently pushes inflated
1739
+ * chunks. For all other paths, `bsrc` is stream (raw space).
1740
+ */
1741
+ async function fromPart10StreamImpl(input, listener, options, parseState) {
1742
+ const iterable = normalizeInput(input);
1743
+
1744
+ // K4: clearBuffers releases chunks as the parse advances (see JSDoc).
1745
+ const stream = new core.ReadBufferStream(null, true, { clearBuffers: true });
1746
+
1747
+ // Feed runs unawaited so the FMI parse can proceed concurrently.
1748
+ const feedHighWater = options.feedHighWater ?? FEED_HIGH_WATER;
1749
+ let feedError = null;
1750
+ const feedPromise = runFeed();
1751
+
1752
+ /**
1753
+ * Feed loop: copies each source chunk into `stream`, then completes it.
1754
+ * K5b: the loop throttles against the parse loop at `feedHighWater`
1755
+ * retained bytes (see {@link FEED_HIGH_WATER}). Pending demand always
1756
+ * wins so a starved consumer can never deadlock; parse settlement
1757
+ * (parseState) wakes the gate on early exit or error. A source error is
1758
+ * stored in `feedError` for the parse to rethrow.
1759
+ */
1760
+ async function runFeed() {
1761
+ try {
1762
+ for await (const chunk of iterable) {
1763
+ stream.addBuffer(toArrayBuffer(chunk));
1764
+ // K5b: throttle against the parse loop (see JSDoc).
1765
+ while (
1766
+ !parseState.done &&
1767
+ stream.getBufferMemoryInfo().totalSize > feedHighWater &&
1768
+ !stream.hasPendingDemand()
1769
+ ) {
1770
+ await Promise.race([
1771
+ stream.awaitConsumerActivity(),
1772
+ parseState.donePromise
1773
+ ]);
1774
+ }
1775
+ }
1776
+ stream.setComplete();
1777
+ } catch (e) {
1778
+ feedError = e;
1779
+ // Unblock any stream.ensureAvailable() waiters so the parse
1780
+ // can observe the error and propagate it.
1781
+ stream.setComplete();
1782
+ }
1783
+ }
1784
+
1785
+ const policy = {
1786
+ forceStoreRaw: !!options.forceStoreRaw,
1787
+ noCopy: false,
1788
+ ignoreErrors: !!options.ignoreErrors
1789
+ };
1790
+
1791
+ // ---- Phase 1: Preamble detection (incremental) ----
1792
+ let fmiElements = [];
1793
+ let transferSyntaxUID;
1794
+ let rawTransferSyntaxUID;
1795
+ if (await detectPreamble(stream)) {
1796
+ // A bare dataset has no FMI; its body starts at byte 0.
1797
+ transferSyntaxUID = await detectBareSyntax(stream, options);
1798
+ rawTransferSyntaxUID = transferSyntaxUID;
1799
+ } else {
1800
+ // ---- Phase 2: Incremental FMI parse ----
1801
+ ({ fmiElements, transferSyntaxUID, rawTransferSyntaxUID } =
1802
+ await readFileMetaInformation(stream, policy));
1803
+ }
1804
+
1805
+ // ---- Phase 3: Emit collected FMI events ----
1806
+ //
1807
+ // Now that we know the TransferSyntaxUID we can emit startDataSet with
1808
+ // the correct TS before the FMI bracket and element events.
1809
+
1810
+ listener.startDataSet({ transferSyntaxUID });
1811
+
1812
+ if (fmiElements.length > 0) {
1813
+ listener.startFileMetaInformation();
1814
+ for (const el of fmiElements) {
1815
+ emitFmiElement(listener, el);
1816
+ }
1817
+ listener.endFileMetaInformation();
1818
+ }
1819
+
1820
+ // ---- Phase 4: Body phase (K4 — fully incremental; see JSDoc) ----
1821
+
1822
+ let bodyStream = null;
1823
+ let inflateError = null;
1824
+ let relayPromise = Promise.resolve();
1825
+
1826
+ // F6: the body-loop catch below awaits relayPromise, so the relay must
1827
+ // never park on consumer activity that a failed body loop will never
1828
+ // produce. The catch resolves this deferred BEFORE awaiting the relay,
1829
+ // and the relay races it inside its throttle gate and winds down.
1830
+ let bodyFailed = false;
1831
+ let signalBodyFailed = null;
1832
+ const bodyFailedPromise = new Promise(
1833
+ resolve => (signalBodyFailed = resolve)
1834
+ );
1835
+
1836
+ if (rawTransferSyntaxUID === core.DEFLATED_EXPLICIT_LITTLE_ENDIAN) {
1837
+ bodyStream = new core.ReadBufferStream(null, true, { clearBuffers: true });
1838
+
1839
+ // `stream.offset` is fixed at metaEndOffset throughout the body phase
1840
+ // for the deflate path — the body parser reads from bodyStream, never
1841
+ // from stream. This keeps raw-space and inflated-space counters separate.
1842
+ const relayStartPos = stream.offset; // == metaEndOffset
1843
+
1844
+ relayPromise = runInflateRelay(relayStartPos);
1845
+ }
1846
+
1847
+ /**
1848
+ * K5 deflate relay: reads compressed bytes from `stream` starting at
1849
+ * `relayStartPos`, inflates them (raw DEFLATE, chunk size
1850
+ * {@link INFLATE_CHUNK_SIZE}) and appends the output to `bodyStream`.
1851
+ * Sets `inflateError` on a decompress failure, or copies `feedError`
1852
+ * there when the raw stream failed, then completes `bodyStream`.
1853
+ *
1854
+ * Throttle (ED-1, see {@link RELAY_HIGH_WATER} and
1855
+ * {@link RELAY_RAW_SLICE}): after each raw sub-slice, the relay waits for
1856
+ * the body loop to consume below the watermark before it inflates more.
1857
+ * A consumer blocked on ensureAvailable (pending demand) always wins — the
1858
+ * relay resumes immediately. A body loop that FAILED (listener threw)
1859
+ * produces no consumer activity ever again, so the gate also races the
1860
+ * bodyFailed deferred and winds down (F6).
1861
+ */
1862
+ async function runInflateRelay(relayStartPos) {
1863
+ const inflater = new pako.Inflate({
1864
+ raw: true,
1865
+ chunkSize: INFLATE_CHUNK_SIZE
1866
+ });
1867
+ inflater.onData = chunk => {
1868
+ // chunk is a Uint8Array (pako 2.x). Slice to an owned
1869
+ // ArrayBuffer so bodyStream's view doesn't alias pako's buffer.
1870
+ bodyStream.addBuffer(
1871
+ chunk.buffer.slice(
1872
+ chunk.byteOffset,
1873
+ chunk.byteOffset + chunk.byteLength
1874
+ )
1875
+ );
1876
+ };
1877
+
1878
+ let relayPos = relayStartPos;
1879
+ for (;;) {
1880
+ // Wait for at least one new byte at relayPos, or raw stream done.
1881
+ // stream.offset stays fixed (== metaEndOffset), so:
1882
+ // need = relayPos + 1 - stream.offset = bytes to advance past offset.
1883
+ const need = relayPos + 1 - stream.offset;
1884
+ await stream.ensureAvailable(need);
1885
+
1886
+ // Synchronous snapshot after the await (JS single-threaded:
1887
+ // no feed-loop interleaving between these two reads).
1888
+ const nowEnd = stream.endOffset;
1889
+ const done = stream.isComplete;
1890
+
1891
+ if (nowEnd > relayPos) {
1892
+ const rawSlice = new Uint8Array(stream.slice(relayPos, nowEnd));
1893
+ relayPos = nowEnd;
1894
+ // Release raw chunks that the relay has fully passed.
1895
+ stream.consume(relayPos);
1896
+ // isLast: feed loop called setComplete() — no more chunks.
1897
+ const isLast = done;
1898
+ for (let s = 0; s < rawSlice.length; s += RELAY_RAW_SLICE) {
1899
+ const subEnd = Math.min(
1900
+ s + RELAY_RAW_SLICE,
1901
+ rawSlice.length
1902
+ );
1903
+ const subLast = isLast && subEnd === rawSlice.length;
1904
+ inflater.push(rawSlice.subarray(s, subEnd), subLast);
1905
+ if (inflater.err) {
1906
+ // pako 2.x stores the error message in inflater.msg.
1907
+ inflateError = new Error(
1908
+ `fromPart10Stream: deflate decompress failed: ${inflater.msg}`
1909
+ );
1910
+ bodyStream.setComplete(); // unblock waiting body parser
1911
+ return;
1912
+ }
1913
+ if (subLast) break;
1914
+ // Throttle below the watermark; races bodyFailed (F6).
1915
+ while (
1916
+ !bodyFailed &&
1917
+ bodyStream.getBufferMemoryInfo().totalSize >
1918
+ RELAY_HIGH_WATER &&
1919
+ !bodyStream.hasPendingDemand()
1920
+ ) {
1921
+ await Promise.race([
1922
+ bodyStream.awaitConsumerActivity(),
1923
+ bodyFailedPromise
1924
+ ]);
1925
+ }
1926
+ if (bodyFailed) {
1927
+ bodyStream.setComplete();
1928
+ return;
1929
+ }
1930
+ }
1931
+ if (isLast) break;
1932
+ } else {
1933
+ // No new bytes — stream must be isComplete (OR-complete).
1934
+ // Finalize: push empty batch with isLast=true.
1935
+ inflater.push(new Uint8Array(0), true);
1936
+ if (inflater.err) {
1937
+ inflateError = new Error(
1938
+ `fromPart10Stream: deflate decompress failed: ${inflater.msg}`
1939
+ );
1940
+ }
1941
+ break;
1942
+ }
1943
+ }
1944
+
1945
+ // Propagate a feed error if the raw stream failed (e.g. network
1946
+ // error mid-stream). Prefer inflate error if both occurred.
1947
+ if (!inflateError && feedError) {
1948
+ inflateError = feedError;
1949
+ }
1950
+
1951
+ bodyStream.setComplete();
1952
+ }
1953
+
1954
+ // Body source: inflated bodyStream for deflate, raw stream for everything else.
1955
+ // ALL body helper functions and the body loop use `bsrc` exclusively.
1956
+ const bsrc = bodyStream ?? stream;
1957
+
1958
+ // Body transfer syntax characteristics — drive all element reads.
1959
+ const bodyLittleEndian = transferSyntaxUID !== core.EXPLICIT_BIG_ENDIAN;
1960
+ const bodyImplicit = transferSyntaxUID === core.IMPLICIT_LITTLE_ENDIAN;
1961
+
1962
+ // Chunk release is LIVE for all paths: clearBuffers=true on both `stream`
1963
+ // (non-deflate) and `bodyStream` (deflate). The relay releases raw chunks
1964
+ // as it advances; the body loop releases inflated (or native) chunks below.
1965
+ const releaseEnabled = true;
1966
+
1967
+ const UNDEFINED_LEN = 0xffffffff;
1968
+ const EMPTY_WIN = {
1969
+ implicit: bodyImplicit};
1970
+
1971
+ /**
1972
+ * Byte-order helpers for body elements (tag, VR, length). They use `bsrc`
1973
+ * (bodyStream for deflate, stream for everything else) so that they
1974
+ * operate in the correct offset space.
1975
+ *
1976
+ * FFFE-family item/delimiter tags (FFFE,E000 / FFFE,E00D / FFFE,E0DD) and
1977
+ * their length fields are read in the body transfer-syntax byte order,
1978
+ * exactly as the buffered fromPart10 reads them via Tag.readTag →
1979
+ * readUint16, which honors stream.isLittleEndian. They are NOT
1980
+ * unconditionally little-endian: in an Explicit Big Endian dataset the
1981
+ * item bytes on wire are big-endian (FF FE for the group, E0 00 for the
1982
+ * element, etc.) and must be read as BE.
1983
+ */
1984
+ const getU16 = abs => bsrc.view.getUint16(abs, bodyLittleEndian);
1985
+ /** 32-bit form of {@link getU16}, in the body byte order. */
1986
+ const getU32 = abs => bsrc.view.getUint32(abs, bodyLittleEndian);
1987
+
1988
+ /** Convert (group, element) numbers to clean DICOM tag string "GGGGEEEE". */
1989
+ function bodyTagStr(g, e) {
1990
+ return (
1991
+ g.toString(16).padStart(4, "0").toUpperCase() +
1992
+ e.toString(16).padStart(4, "0").toUpperCase()
1993
+ );
1994
+ }
1995
+
1996
+ /**
1997
+ * EventBuffer — records listener events as lambdas so an undefined-length
1998
+ * SQ / item subtree can be replayed AFTER its closing delimiter is reached,
1999
+ * once the content-span length payload is known (buffered fromPart10 emits
2000
+ * that computed span, not the on-wire 0xFFFFFFFF). Values are baked into the
2001
+ * lambdas at decode time, so charset scoping and fresh-copy semantics are
2002
+ * unaffected by the deferred flush. awaitDrain is a local no-op during
2003
+ * buffering (backpressure is applied by the real listener after the flush).
2004
+ */
2005
+ class EventBuffer {
2006
+ constructor() {
2007
+ this._q = [];
2008
+ }
2009
+ startElement(tag, info) {
2010
+ this._q.push(l => l.startElement(tag, info));
2011
+ }
2012
+ endElement() {
2013
+ this._q.push(l => l.endElement());
2014
+ }
2015
+ value(v, opts) {
2016
+ this._q.push(l => l.value(v, opts));
2017
+ }
2018
+ startBinary(opts) {
2019
+ this._q.push(l => l.startBinary(opts));
2020
+ }
2021
+ binaryFragment(buf) {
2022
+ this._q.push(l => l.binaryFragment(buf));
2023
+ }
2024
+ endBinary() {
2025
+ this._q.push(l => l.endBinary());
2026
+ }
2027
+ startSequence(tag, info) {
2028
+ this._q.push(l => l.startSequence(tag, info));
2029
+ }
2030
+ endSequence() {
2031
+ this._q.push(l => l.endSequence());
2032
+ }
2033
+ startItem(info) {
2034
+ this._q.push(l => l.startItem(info));
2035
+ }
2036
+ endItem() {
2037
+ this._q.push(l => l.endItem());
2038
+ }
2039
+ awaitDrain() {} // no-op during buffering
2040
+ /** Replay all buffered events to `realListener`. */
2041
+ flushTo(realListener) {
2042
+ for (const fn of this._q) fn(realListener);
2043
+ }
2044
+ }
2045
+
2046
+ /**
2047
+ * Ensure the bytes up to absolute offset `absEnd` are present, then re-check
2048
+ * strict availability (ensureAvailable resolves at EOF too — OR-complete
2049
+ * semantics). Returns true only when the bytes are genuinely available.
2050
+ */
2051
+ async function ensureAbs(absEnd) {
2052
+ // Operate on `bsrc`: bodyStream (inflated, zero-based) for deflate,
2053
+ // stream (raw) for everything else. Never mix offset spaces.
2054
+ const need = absEnd - bsrc.offset;
2055
+ if (need > 0) {
2056
+ await bsrc.ensureAvailable(need);
2057
+ }
2058
+ return absEnd <= bsrc.endOffset;
2059
+ }
2060
+
2061
+ // ---- Undefined-length structural end-finders (element-aware skip, no emission) ----
2062
+
2063
+ /**
2064
+ * Skip an undefined-length sequence's items, returning
2065
+ * `{ contentEnd, end }`: `contentEnd` is the offset of the closing
2066
+ * FFFE,E0DD (the parser's content-span end == element.length base), `end`
2067
+ * is the offset just past it. Mirrors readSQElementUndefinedLength*.
2068
+ *
2069
+ * DICOM PS3.5 permits undefined length (0xFFFFFFFF) ONLY for SQ elements,
2070
+ * items, and encapsulated pixel data. The only non-SQ undefined-length
2071
+ * element dcmjs decodes cleanly (classifyElement "eagerWindow", via
2072
+ * decodeUndefinedLengthValues) is explicit-VR UN of undefined length (and private
2073
+ * implicit undefined-length elements), which the offsets parser routes
2074
+ * through readSequenceItemsImplicit. These end at the SEQUENCE delimiter
2075
+ * FFFE,E0DD, NOT at an item delimiter.
2076
+ *
2077
+ * For non-conformant text VRs (UT/UC/UR) with undefined length, the two
2078
+ * paths DELIBERATELY diverge (empirically verified; pinned in the K4 test
2079
+ * suite):
2080
+ * - buffered fromPart10 — readEncodedString clamps the 0xFFFFFFFF read
2081
+ * to the actual buffer size, bleeds past any FFFE,E00D delimiter and
2082
+ * returns a garbage string containing all remaining bytes (no throw);
2083
+ * any element following the delimiter is silently consumed into the
2084
+ * string value.
2085
+ * - fromPart10Stream — emitUndefinedLeaf's skipUndefinedSequence sees
2086
+ * the non-FFFE value bytes as malformed (not FFFE,E0DD / FFFE,E000),
2087
+ * stops the window at the value start; the body loop then re-parses
2088
+ * the value bytes as a DICOM element, producing a truncation throw.
2089
+ *
2090
+ * This loud-failure divergence is DELIBERATE: stream fails loudly on
2091
+ * non-conformant data that buffered silently mishandles.
2092
+ *
2093
+ * For binary VRs (OB/OW/etc.) with undefined length, both paths throw
2094
+ * (buffered: "Item tag not found after undefined binary length"; stream:
2095
+ * similar truncation), so no path-divergence arises there.
2096
+ *
2097
+ * These scanners mirror the parser's sequence walk (FFFE,E0DD) with
2098
+ * nested item-delimiter (FFFE,E00D) handling. skipUndefinedItem is
2099
+ * ELEMENT-AWARE — it steps whole element headers/values via
2100
+ * skipOneElementEnd — not a 2-byte byte-scan like findItemDelimitationItem.
2101
+ */
2102
+ async function skipUndefinedSequence(fromAbs) {
2103
+ let pos = fromAbs;
2104
+ for (;;) {
2105
+ if (!(await ensureAbs(pos + 8))) {
2106
+ return { contentEnd: bsrc.endOffset, end: bsrc.endOffset };
2107
+ }
2108
+ const g = getU16(pos);
2109
+ const e = getU16(pos + 2);
2110
+ if (g === 0xfffe && e === 0xe0dd) {
2111
+ return { contentEnd: pos, end: pos + 8 };
2112
+ }
2113
+ if (g !== 0xfffe || e !== 0xe000) {
2114
+ return { contentEnd: pos, end: pos }; // malformed — stop
2115
+ }
2116
+ const itemLength = getU32(pos + 4);
2117
+ pos += 8;
2118
+ pos =
2119
+ itemLength === UNDEFINED_LEN
2120
+ ? await skipUndefinedItem(pos)
2121
+ : pos + itemLength;
2122
+ }
2123
+ }
2124
+
2125
+ /**
2126
+ * Skip an undefined-length item's elements, returning the offset just past
2127
+ * its FFFE,E00D delimiter (findItemDelimitationItem semantics, but element-
2128
+ * aware so nested defined-length values are stepped over correctly).
2129
+ */
2130
+ async function skipUndefinedItem(fromAbs) {
2131
+ let pos = fromAbs;
2132
+ for (;;) {
2133
+ if (!(await ensureAbs(pos + 8))) return bsrc.endOffset;
2134
+ const g = getU16(pos);
2135
+ const e = getU16(pos + 2);
2136
+ if (g === 0xfffe && e === 0xe00d) return pos + 8;
2137
+ pos = await skipOneElementEnd(pos);
2138
+ }
2139
+ }
2140
+
2141
+ /** Skip a single element header + value, recursing into nested structures. */
2142
+ async function skipOneElementEnd(fromAbs) {
2143
+ let pos = fromAbs;
2144
+ if (!(await ensureAbs(pos + 8))) return bsrc.endOffset;
2145
+ pos += 4; // tag
2146
+ let valueLength;
2147
+ if (bodyImplicit) {
2148
+ valueLength = bsrc.view.getUint32(pos, true);
2149
+ pos += 4;
2150
+ } else {
2151
+ const vr =
2152
+ String.fromCharCode(bsrc.view.getUint8(pos)) +
2153
+ String.fromCharCode(bsrc.view.getUint8(pos + 1));
2154
+ pos += 2;
2155
+ if (core.ValueRepresentation.createByTypeString(vr).isLength32()) {
2156
+ if (!(await ensureAbs(pos + 6))) return bsrc.endOffset;
2157
+ pos += 2; // reserved
2158
+ valueLength = getU32(pos);
2159
+ pos += 4;
2160
+ } else {
2161
+ valueLength = getU16(pos);
2162
+ pos += 2;
2163
+ }
2164
+ }
2165
+ if (valueLength === UNDEFINED_LEN) {
2166
+ return (await skipUndefinedSequence(pos)).end;
2167
+ }
2168
+ if (!(await ensureAbs(pos + valueLength))) return bsrc.endOffset;
2169
+ return pos + valueLength;
2170
+ }
2171
+
2172
+ /**
2173
+ * Read ONE element header at `elemStartAbs` (the caller has verified it is
2174
+ * not a delimiter tag) and route it by classification, emitting into
2175
+ * `target`. Returns the (possibly charset-updated) decoder for the caller
2176
+ * to thread into the next element. Mirrors decodeCore.classifyElement.
2177
+ *
2178
+ * Defined length: resolveVrInstance is the single canonical implicit-VR
2179
+ * contract (AD-1) — dictionary-miss elements resolve to UN and are never
2180
+ * data-peek-promoted to SQ (eager parity). Only dictionary-known SQs take
2181
+ * the sequence path.
2182
+ *
2183
+ * Undefined length: the element is classified as SQ
2184
+ * ({@link isUndefinedLengthSequence}), encapsulated pixel data, or an
2185
+ * eagerWindow leaf, matching decodeCore.classifyElement + the parser's SQ
2186
+ * resolution.
2187
+ */
2188
+ async function parseOneElement(target, elemStartAbs, currentDecoder) {
2189
+ bsrc.offset = elemStartAbs;
2190
+ const elGroup = getU16(elemStartAbs);
2191
+ const elElement = getU16(elemStartAbs + 2);
2192
+ bsrc.offset = elemStartAbs + 4;
2193
+ const tagStr = bodyTagStr(elGroup, elElement);
2194
+
2195
+ let vrStr = null;
2196
+ let valueLength;
2197
+ if (bodyImplicit) {
2198
+ if (!(await ensureAbs(bsrc.offset + 4))) {
2199
+ throw new Error(
2200
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing implicit length`
2201
+ );
2202
+ }
2203
+ // Implicit is always LITTLE_ENDIAN regardless of body TS.
2204
+ valueLength = bsrc.view.getUint32(bsrc.offset, true);
2205
+ bsrc.offset += 4;
2206
+ } else {
2207
+ if (!(await ensureAbs(bsrc.offset + 2))) {
2208
+ throw new Error(
2209
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing VR bytes`
2210
+ );
2211
+ }
2212
+ vrStr =
2213
+ String.fromCharCode(bsrc.view.getUint8(bsrc.offset)) +
2214
+ String.fromCharCode(bsrc.view.getUint8(bsrc.offset + 1));
2215
+ bsrc.offset += 2;
2216
+ const vrForLen = core.ValueRepresentation.createByTypeString(vrStr);
2217
+ if (vrForLen.isLength32()) {
2218
+ if (!(await ensureAbs(bsrc.offset + 6))) {
2219
+ throw new Error(
2220
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing extended length`
2221
+ );
2222
+ }
2223
+ bsrc.offset += 2; // reserved
2224
+ valueLength = getU32(bsrc.offset);
2225
+ bsrc.offset += 4;
2226
+ } else {
2227
+ if (!(await ensureAbs(bsrc.offset + 2))) {
2228
+ throw new Error(
2229
+ `fromPart10Stream: truncated at ${elemStartAbs}: missing 2-byte length`
2230
+ );
2231
+ }
2232
+ valueLength = getU16(bsrc.offset);
2233
+ bsrc.offset += 2;
2234
+ }
2235
+ }
2236
+
2237
+ const valueStartAbs = bsrc.offset;
2238
+ const undef = valueLength === UNDEFINED_LEN;
2239
+ const elLike = {
2240
+ vr: vrStr,
2241
+ tagValue: ((elGroup << 16) | elElement) >>> 0,
2242
+ dataOffset: 0,
2243
+ length: valueLength,
2244
+ hadUndefinedLength: undef
2245
+ };
2246
+ let vrInstance = resolveVrInstance(elLike, EMPTY_WIN);
2247
+
2248
+ if (!undef) {
2249
+ // Only dictionary-known SQs take the sequence path (AD-1).
2250
+ if (vrInstance.type === "SQ") {
2251
+ await emitSequence(
2252
+ target,
2253
+ tagStr,
2254
+ valueStartAbs,
2255
+ valueLength,
2256
+ currentDecoder
2257
+ );
2258
+ return currentDecoder;
2259
+ }
2260
+ return await emitDefinedLeaf(
2261
+ target,
2262
+ tagStr,
2263
+ elLike,
2264
+ vrInstance,
2265
+ valueLength,
2266
+ valueStartAbs,
2267
+ currentDecoder
2268
+ );
2269
+ }
2270
+
2271
+ // Undefined length: classify SQ / encapsulated / eagerWindow leaf.
2272
+ const treatAsSq = await isUndefinedLengthSequence(
2273
+ elLike,
2274
+ vrInstance,
2275
+ valueStartAbs
2276
+ );
2277
+ if (treatAsSq) {
2278
+ await emitSequence(
2279
+ target,
2280
+ tagStr,
2281
+ valueStartAbs,
2282
+ UNDEFINED_LEN,
2283
+ currentDecoder
2284
+ );
2285
+ return currentDecoder;
2286
+ }
2287
+ if (tagStr === "7FE00010" && !isParsedUnknownVr(vrInstance)) {
2288
+ await emitEncapsulated(target, tagStr, vrInstance, valueStartAbs);
2289
+ return currentDecoder;
2290
+ }
2291
+ await emitUndefinedLeaf(
2292
+ target,
2293
+ tagStr,
2294
+ valueStartAbs,
2295
+ elLike,
2296
+ vrInstance,
2297
+ currentDecoder
2298
+ );
2299
+ return currentDecoder;
2300
+ }
2301
+
2302
+ /**
2303
+ * Decide whether an undefined-length element streams as a sequence.
2304
+ * Explicit VR: true when the resolved VR is SQ. Implicit VR: true for a
2305
+ * dictionary-known SQ (no peek); a dictionary-unknown element that
2306
+ * resolved to SQ (hadUndefinedLength fallback) is peeked for an
2307
+ * FFFE,E000 / FFFE,E0DD first tag.
2308
+ *
2309
+ * The peek is ROUTING-ONLY (AD-1): it chooses between streamed
2310
+ * emitSequence and the delimiter-scanned eager-window leaf, both of which
2311
+ * yield eager-SQ semantics for undefined-length dictionary-miss elements
2312
+ * (resolveVrInstance's length rule). The semantic contract itself never
2313
+ * data-peek-promotes defined-length elements.
2314
+ */
2315
+ async function isUndefinedLengthSequence(
2316
+ elLike,
2317
+ vrInstance,
2318
+ valueStartAbs
2319
+ ) {
2320
+ let treatAsSq = false;
2321
+ if (vrInstance.type === "SQ") {
2322
+ if (!bodyImplicit) {
2323
+ treatAsSq = true; // explicit VR SQ
2324
+ } else {
2325
+ const dictVr = resolveVrInstance(
2326
+ { ...elLike, hadUndefinedLength: false },
2327
+ EMPTY_WIN
2328
+ );
2329
+ if (dictVr.type === "SQ") {
2330
+ treatAsSq = true;
2331
+ } else if (await ensureAbs(valueStartAbs + 4)) {
2332
+ const pg = bsrc.view.getUint16(valueStartAbs, true);
2333
+ const pe = bsrc.view.getUint16(valueStartAbs + 2, true);
2334
+ treatAsSq =
2335
+ pg === 0xfffe && (pe === 0xe000 || pe === 0xe0dd);
2336
+ }
2337
+ }
2338
+ }
2339
+ return treatAsSq;
2340
+ }
2341
+
2342
+ /**
2343
+ * Defined-length leaf element: decode the value and emit directly. Returns
2344
+ * the decoder to thread onward (updated when this is (0008,0005)).
2345
+ *
2346
+ * (0028,0103) PixelRepresentation drives the "xs" (US-or-SS) meta-VR
2347
+ * resolution of subsequent elements (issue #368). EMPTY_WIN is the window
2348
+ * handed to resolveVrInstance and is created per parse, so the in-place
2349
+ * update is private to this stream.
2350
+ */
2351
+ async function emitDefinedLeaf(
2352
+ target,
2353
+ tagStr,
2354
+ elLike,
2355
+ vrInstance,
2356
+ valueLength,
2357
+ valueStartAbs,
2358
+ decoder
2359
+ ) {
2360
+ const valueEndAbs = valueStartAbs + valueLength;
2361
+ if (valueLength > 0 && !(await ensureAbs(valueEndAbs))) {
2362
+ throw new Error(
2363
+ `fromPart10Stream: truncated: element at ${valueStartAbs} ` +
2364
+ `declares ${valueLength} bytes but stream ended`
2365
+ );
2366
+ }
2367
+ const valueAB = bsrc.slice(valueStartAbs, valueEndAbs);
2368
+ const win = {
2369
+ arrayBuffer: valueAB,
2370
+ baseOffset: 0,
2371
+ syntax: transferSyntaxUID,
2372
+ littleEndian: bodyLittleEndian,
2373
+ implicit: bodyImplicit,
2374
+ decoder
2375
+ };
2376
+ const { values, rawValues } = decodeElementValues(
2377
+ win,
2378
+ elLike,
2379
+ vrInstance,
2380
+ policy
2381
+ );
2382
+ let newDecoder = decoder;
2383
+ // (0008,0005) SpecificCharacterSet sets the decoder for subsequent
2384
+ // elements in this scope (top-level body or the current SQ item).
2385
+ if (tagStr === "00080005") {
2386
+ const csResult = resolveCharacterSet(win, elLike, policy);
2387
+ newDecoder = csResult?.decoder ?? null;
2388
+ }
2389
+ // (0028,0103) drives "xs" VR resolution (issue #368; see JSDoc).
2390
+ if (tagStr === "00280103" && values && values.length) {
2391
+ EMPTY_WIN.pixelRepresentation = values[0];
2392
+ }
2393
+ emitValues(target, tagStr, vrInstance, elLike, values, rawValues);
2394
+ bsrc.offset = valueEndAbs;
2395
+ return newDecoder;
2396
+ }
2397
+
2398
+ /**
2399
+ * Emit a sequence (defined or undefined length) into `target`.
2400
+ * `dataOffsetAbs` is the absolute offset of the sequence's first content
2401
+ * byte. Defined-length sequences emit directly with the declared length;
2402
+ * undefined-length sequences buffer their items so the content-span length
2403
+ * payload (parity with buffered fromPart10) can be backfilled at the
2404
+ * closing FFFE,E0DD.
2405
+ */
2406
+ async function emitSequence(
2407
+ target,
2408
+ tagStr,
2409
+ dataOffsetAbs,
2410
+ declaredLength,
2411
+ outerDecoder
2412
+ ) {
2413
+ if (declaredLength !== UNDEFINED_LEN) {
2414
+ const sqEndAbs = dataOffsetAbs + declaredLength;
2415
+ target.startSequence(tagStr, { vr: "SQ", length: declaredLength });
2416
+ await parseSqItems(target, sqEndAbs, false, outerDecoder);
2417
+ target.endSequence();
2418
+ bsrc.offset = sqEndAbs;
2419
+ } else {
2420
+ const buf = new EventBuffer();
2421
+ const delimStart = await parseSqItems(buf, -1, true, outerDecoder);
2422
+ const contentSpan = delimStart - dataOffsetAbs;
2423
+ target.startSequence(tagStr, { vr: "SQ", length: contentSpan });
2424
+ buf.flushTo(target);
2425
+ target.endSequence();
2426
+ // bsrc.offset already advanced past FFFE,E0DD by parseSqItems.
2427
+ }
2428
+ }
2429
+
2430
+ /**
2431
+ * Encapsulated pixel data: stream fragments one at a time. The first item is
2432
+ * the Basic Offset Table — its header is read and its bytes skipped (buffered
2433
+ * fromPart10 keeps it in element.basicOffsetTable and does NOT emit it as a
2434
+ * fragment). The startElement length payload is the on-wire 0xFFFFFFFF
2435
+ * (the computed span is unknown until the closing delimiter, which would
2436
+ * defeat fragment streaming) — a documented delta from buffered fromPart10.
2437
+ *
2438
+ * The Basic Offset Table item (FFFE,E000) offsets are surfaced on
2439
+ * startBinary so BOT-aware listeners can merge fragments per frame window
2440
+ * (issue #204).
2441
+ *
2442
+ * K6: per-fragment release (see {@link releaseConsumedChunks}) bounds
2443
+ * peak memory to (largest fragment + chunk size + fixed slack) rather than
2444
+ * the full pixel-data element. The fragment bytes were already copied
2445
+ * into an owned ArrayBuffer by bsrc.slice(), so aliasing is safe to
2446
+ * discard. Without this, the whole encapsulated element accumulates in
2447
+ * the stream buffer until the post-element consume() in the body loop
2448
+ * fires.
2449
+ */
2450
+ async function emitEncapsulated(target, tagStr, vrInstance, dataOffsetAbs) {
2451
+ target.startElement(tagStr, {
2452
+ vr: vrInstance.type,
2453
+ length: UNDEFINED_LEN
2454
+ });
2455
+ bsrc.offset = dataOffsetAbs;
2456
+
2457
+ // Basic Offset Table: surface offsets (issue #204), then skip bytes.
2458
+ if (!(await ensureAbs(bsrc.offset + 8))) {
2459
+ throw new Error(
2460
+ `fromPart10Stream: truncated: encapsulated BOT header at ${bsrc.offset}`
2461
+ );
2462
+ }
2463
+ const botLen = getU32(bsrc.offset + 4);
2464
+ bsrc.offset += 8;
2465
+ const startBinaryInfo = { encapsulated: true };
2466
+ if (botLen > 0) {
2467
+ if (!(await ensureAbs(bsrc.offset + botLen))) {
2468
+ throw new Error(
2469
+ `fromPart10Stream: truncated: encapsulated BOT (${botLen} bytes)`
2470
+ );
2471
+ }
2472
+ const botCount = Math.floor(botLen / 4);
2473
+ if (botCount > 0) {
2474
+ const basicOffsetTable = new Array(botCount);
2475
+ for (let i = 0; i < botCount; i++) {
2476
+ basicOffsetTable[i] = getU32(bsrc.offset + i * 4);
2477
+ }
2478
+ startBinaryInfo.basicOffsetTable = basicOffsetTable;
2479
+ }
2480
+ bsrc.offset += botLen;
2481
+ }
2482
+ target.startBinary(startBinaryInfo);
2483
+
2484
+ for (;;) {
2485
+ if (!(await ensureAbs(bsrc.offset + 8))) {
2486
+ throw new Error(
2487
+ `fromPart10Stream: truncated: encapsulated item header at ${bsrc.offset}`
2488
+ );
2489
+ }
2490
+ const g = getU16(bsrc.offset);
2491
+ const e = getU16(bsrc.offset + 2);
2492
+ if (g === 0xfffe && e === 0xe0dd) {
2493
+ bsrc.offset += 8; // sequence-delimiter tag + 4-byte length
2494
+ break;
2495
+ }
2496
+ if (g !== 0xfffe || e !== 0xe000) {
2497
+ break; // unexpected tag — stop gracefully
2498
+ }
2499
+ const fragLen = getU32(bsrc.offset + 4);
2500
+ bsrc.offset += 8;
2501
+ const fragStart = bsrc.offset;
2502
+ const fragEnd = fragStart + fragLen;
2503
+ if (!(await ensureAbs(fragEnd))) {
2504
+ throw new Error(
2505
+ `fromPart10Stream: truncated: pixel-data fragment (${fragLen} bytes) at ${fragStart}`
2506
+ );
2507
+ }
2508
+ // Fresh copy — the emitted buffer must not alias released chunks.
2509
+ target.binaryFragment(bsrc.slice(fragStart, fragEnd));
2510
+ bsrc.offset = fragEnd;
2511
+ await target.awaitDrain(); // backpressure between fragments
2512
+ // K6: per-fragment release (see JSDoc).
2513
+ {
2514
+ releaseConsumedChunks();
2515
+ }
2516
+ }
2517
+ target.endBinary();
2518
+ target.endElement();
2519
+ }
2520
+
2521
+ /**
2522
+ * Release every `bsrc` chunk fully behind the current position, then
2523
+ * report the buffer memory state to `options.onConsume`. For the deflate
2524
+ * path (bodyStream active), the report also includes the raw stream
2525
+ * memory state, so tests can verify both streams release chunks
2526
+ * concurrently.
2527
+ */
2528
+ function releaseConsumedChunks() {
2529
+ bsrc.consume(bsrc.offset);
2530
+ const info = bsrc.getBufferMemoryInfo();
2531
+ if (bodyStream) {
2532
+ info.rawStreamInfo = stream.getBufferMemoryInfo();
2533
+ }
2534
+ options.onConsume?.(info);
2535
+ }
2536
+
2537
+ /**
2538
+ * Undefined-length non-SQ leaf ("eagerWindow"): bound the value by
2539
+ * walking the structure to its closing sequence delimiter, copy the value
2540
+ * bytes, and decode via decodeUndefinedLengthValues. The emitted length
2541
+ * payload is the content span (delimiter offset minus the data offset),
2542
+ * for parity with buffered. See {@link skipUndefinedSequence} for the
2543
+ * deliberate divergence on non-conformant undefined-length UT/UC/UR.
2544
+ */
2545
+ async function emitUndefinedLeaf(
2546
+ target,
2547
+ tagStr,
2548
+ valueStartAbs,
2549
+ elLike,
2550
+ vrInstance,
2551
+ decoder
2552
+ ) {
2553
+ const { contentEnd, end } = await skipUndefinedSequence(valueStartAbs);
2554
+ const win = {
2555
+ arrayBuffer: bsrc.slice(valueStartAbs, end),
2556
+ baseOffset: 0,
2557
+ syntax: transferSyntaxUID,
2558
+ littleEndian: bodyLittleEndian,
2559
+ decoder
2560
+ };
2561
+ const valueEl = {
2562
+ ...elLike,
2563
+ dataOffset: 0,
2564
+ endOffset: end - valueStartAbs,
2565
+ length: contentEnd - valueStartAbs
2566
+ };
2567
+ const { values, rawValues } = decodeUndefinedLengthValues(
2568
+ win,
2569
+ valueEl,
2570
+ vrInstance,
2571
+ policy
2572
+ );
2573
+ emitDecodedLeaf(target, tagStr, vrInstance, valueEl, values, rawValues);
2574
+ bsrc.offset = end;
2575
+ }
2576
+
2577
+ /**
2578
+ * Parse the items of a sequence into `target`.
2579
+ * - Defined-length SQ (`undefinedSeq=false`): items until `sqEndAbs`.
2580
+ * - Undefined-length SQ (`undefinedSeq=true`, `sqEndAbs` ignored): items
2581
+ * until the sequence delimiter (FFFE,E0DD); returns the absolute offset
2582
+ * of that delimiter (the parser's content-span end).
2583
+ * `outerDecoder` is the parent-scope charset decoder inherited by items.
2584
+ */
2585
+ async function parseSqItems(target, sqEndAbs, undefinedSeq, outerDecoder) {
2586
+ while (undefinedSeq || bsrc.offset < sqEndAbs) {
2587
+ if (!(await ensureAbs(bsrc.offset + 8))) {
2588
+ if (undefinedSeq) return bsrc.offset; // EOF before delimiter
2589
+ throw new Error(
2590
+ `fromPart10Stream: truncated: SQ item header at ${bsrc.offset}`
2591
+ );
2592
+ }
2593
+ const itemStart = bsrc.offset;
2594
+ const itemGroup = getU16(itemStart);
2595
+ const itemElement = getU16(itemStart + 2);
2596
+
2597
+ if (itemGroup === 0xfffe && itemElement === 0xe0dd) {
2598
+ bsrc.offset = itemStart + 8; // consume seq-delimiter + length
2599
+ return itemStart;
2600
+ }
2601
+ if (itemGroup !== 0xfffe || itemElement !== 0xe000) {
2602
+ return itemStart; // unexpected tag — stop gracefully
2603
+ }
2604
+ const itemLength = getU32(itemStart + 4);
2605
+ bsrc.offset = itemStart + 8; // past item header
2606
+ const itemDataOffset = bsrc.offset;
2607
+
2608
+ if (itemLength !== UNDEFINED_LEN) {
2609
+ const itemEndAbs = itemDataOffset + itemLength;
2610
+ target.startItem({ length: itemLength });
2611
+ await parseItemElements(
2612
+ target,
2613
+ itemEndAbs,
2614
+ false,
2615
+ outerDecoder
2616
+ );
2617
+ target.endItem();
2618
+ bsrc.offset = itemEndAbs;
2619
+ } else {
2620
+ // Undefined-length item: buffer to backfill the parser's item
2621
+ // span (data offset → past the closing item delimiter).
2622
+ const ibuf = new EventBuffer();
2623
+ const delimStart = await parseItemElements(
2624
+ ibuf,
2625
+ -1,
2626
+ true,
2627
+ outerDecoder
2628
+ );
2629
+ const itemSpan = delimStart + 8 - itemDataOffset;
2630
+ target.startItem({ length: itemSpan });
2631
+ ibuf.flushTo(target);
2632
+ target.endItem();
2633
+ }
2634
+ }
2635
+ return bsrc.offset;
2636
+ }
2637
+
2638
+ /**
2639
+ * Parse the elements of a single sequence item into `target`.
2640
+ * - Defined-length item (`undefinedItem=false`): elements until
2641
+ * `itemEndAbs`.
2642
+ * - Undefined-length item (`undefinedItem=true`, `itemEndAbs` ignored):
2643
+ * elements until the item delimiter (FFFE,E00D); returns the absolute
2644
+ * offset of that delimiter.
2645
+ * Per-item charset scoping: this item's own (0008,0005) overrides
2646
+ * `parentDecoder` for subsequent elements in its subtree.
2647
+ */
2648
+ async function parseItemElements(
2649
+ target,
2650
+ itemEndAbs,
2651
+ undefinedItem,
2652
+ parentDecoder
2653
+ ) {
2654
+ let itemDecoder = parentDecoder;
2655
+ while (undefinedItem || bsrc.offset < itemEndAbs) {
2656
+ if (!(await ensureAbs(bsrc.offset + 4))) {
2657
+ if (undefinedItem) return bsrc.offset;
2658
+ throw new Error(
2659
+ `fromPart10Stream: truncated: item element header at ${bsrc.offset}`
2660
+ );
2661
+ }
2662
+ const elemStart = bsrc.offset;
2663
+ const g = getU16(elemStart);
2664
+ const e = getU16(elemStart + 2);
2665
+ if (g === 0xfffe && e === 0xe00d) {
2666
+ // Item delimiter: consume tag + 4-byte length.
2667
+ if (!(await ensureAbs(elemStart + 8)) && undefinedItem) {
2668
+ return elemStart;
2669
+ }
2670
+ bsrc.offset = elemStart + 8;
2671
+ return elemStart;
2672
+ }
2673
+ itemDecoder = await parseOneElement(target, elemStart, itemDecoder);
2674
+ }
2675
+ return bsrc.offset;
2676
+ }
2677
+
2678
+ // ---- K5 top-level body element loop (see fromPart10StreamImpl JSDoc) ----
2679
+ let bodyDecoder = null; // resolved when (0008,0005) is first seen in body
2680
+
2681
+ try {
2682
+ bodyLoop: for (;;) {
2683
+ // --- Read next element tag (4 bytes) ---
2684
+ if (!(await ensureAbs(bsrc.offset + 4))) break bodyLoop; // clean EOF
2685
+
2686
+ const elemStartAbs = bsrc.offset;
2687
+ const elGroup = getU16(elemStartAbs);
2688
+
2689
+ // Defensive: stray top-level FFFE delimiter tags are malformed for a
2690
+ // well-formed Part 10 body; skip them so the next real element frames
2691
+ // correctly (native SQ/encapsulated handlers already consume their own
2692
+ // delimiters, so this is only reached on malformed input).
2693
+ if (elGroup === 0xfffe) {
2694
+ if (!(await ensureAbs(elemStartAbs + 8))) break bodyLoop;
2695
+ bsrc.offset = elemStartAbs + 8;
2696
+ continue bodyLoop;
2697
+ }
2698
+
2699
+ bodyDecoder = await parseOneElement(
2700
+ listener,
2701
+ elemStartAbs,
2702
+ bodyDecoder
2703
+ );
2704
+ await listener.awaitDrain();
2705
+ if (releaseEnabled) {
2706
+ releaseConsumedChunks();
2707
+ }
2708
+ }
2709
+ } catch (bodyErr) {
2710
+ // F6: wake a relay parked on consumer activity BEFORE awaiting it,
2711
+ // or the two awaits deadlock each other and the promise never settles.
2712
+ bodyFailed = true;
2713
+ signalBodyFailed();
2714
+ // Wait for the relay to settle so inflateError is populated (if any).
2715
+ await relayPromise;
2716
+ // Prioritize the root cause over the symptom: an inflate or source
2717
+ // (feed) error explains the truncated read the body loop tripped on.
2718
+ throw inflateError ?? feedError ?? bodyErr;
2719
+ }
2720
+
2721
+ // Relay must finish before we inspect inflateError.
2722
+ await relayPromise;
2723
+ if (inflateError) throw inflateError;
2724
+
2725
+ // F7: the body loop treats stream-complete as a clean EOF, but the feed
2726
+ // catch also calls setComplete() when the SOURCE throws mid-transfer. A
2727
+ // clean end is only clean if the feed finished without error — otherwise
2728
+ // a truncated transfer would resolve as a well-formed shorter dataset.
2729
+ await feedPromise;
2730
+ if (feedError) throw feedError;
2731
+
2732
+ // Observable hook: fires for ALL paths (deflate and non-deflate) now that
2733
+ // the early deflate return is gone.
2734
+ options.onPhase?.("native");
2735
+
2736
+ listener.endDataSet();
2737
+ }
2738
+
2739
+ // ---------------------------------------------------------------------------
2740
+ // Preamble, bare dataset and FMI parse
2741
+ // ---------------------------------------------------------------------------
2742
+
2743
+ /**
2744
+ * Phase 1: preamble detection (incremental). Sets `stream.offset` to the
2745
+ * start of the FMI and returns false, or returns true when the input is a
2746
+ * bare dataset.
2747
+ *
2748
+ * - "DICM" at bytes 128-131 → normal Part 10, advance to offset 132
2749
+ * - First 2 bytes are group 0x0002 → PART10_NO_PREAMBLE, stay at 0
2750
+ * - Neither → bare dataset or non-DICOM input
2751
+ * (see {@link detectBareSyntax}).
2752
+ *
2753
+ * @param {ReadBufferStream} stream the raw input stream
2754
+ * @returns {Promise<boolean>} true for a bare dataset
2755
+ */
2756
+ async function detectPreamble(stream) {
2757
+ let rawDatasetFallback = false;
2758
+
2759
+ // Wait for enough bytes to check the DICM marker (requires 132 bytes:
2760
+ // 128-byte preamble + 4-byte "DICM"). ensureAvailable resolves even
2761
+ // at EOF if bytes are insufficient (OR-complete semantics), so we
2762
+ // always re-check with isAvailable(N, false) after the await.
2763
+ await stream.ensureAvailable(132);
2764
+
2765
+ if (stream.isAvailable(132, false)) {
2766
+ // We have at least 132 bytes — check for "DICM" at bytes 128-131.
2767
+ const hasDicm =
2768
+ stream.view.getUint8(128) === 0x44 && // D
2769
+ stream.view.getUint8(129) === 0x49 && // I
2770
+ stream.view.getUint8(130) === 0x43 && // C
2771
+ stream.view.getUint8(131) === 0x4d; // M
2772
+ if (hasDicm) {
2773
+ // Normal Part 10: skip preamble + DICM marker.
2774
+ stream.offset = 132;
2775
+ } else {
2776
+ // No DICM — check whether the file starts with group 0x0002.
2777
+ const firstGroup = stream.view.getUint16(0, true); // LE
2778
+ if (firstGroup === 0x0002) {
2779
+ // PART10_NO_PREAMBLE: FMI starts at byte 0.
2780
+ stream.offset = 0;
2781
+ } else {
2782
+ rawDatasetFallback = true;
2783
+ }
2784
+ }
2785
+ } else {
2786
+ // Fewer than 132 bytes available (short stream or early EOF).
2787
+ // Try to at least check the 0x0002 group in the first 2 bytes.
2788
+ await stream.ensureAvailable(4);
2789
+ if (stream.isAvailable(2, false)) {
2790
+ const firstGroup = stream.view.getUint16(0, true); // LE
2791
+ if (firstGroup === 0x0002) {
2792
+ stream.offset = 0; // PART10_NO_PREAMBLE
2793
+ } else {
2794
+ rawDatasetFallback = true;
2795
+ }
2796
+ } else {
2797
+ rawDatasetFallback = true;
2798
+ }
2799
+ }
2800
+ return rawDatasetFallback;
2801
+ }
2802
+
2803
+ /**
2804
+ * Bare (meta-less, DIMSE-style) dataset: returns the transfer syntax of the
2805
+ * body, or refuses the input (issue #93).
2806
+ *
2807
+ * The input needs an explicit opt-in: allowMissingHeader, or the tolerant
2808
+ * ignoreErrors mode. The body is Explicit Little Endian when bytes 4-5 of the
2809
+ * first element header are a valid VR code, and Implicit Little Endian
2810
+ * otherwise (the same rule as DicomMessage._detectBareSyntax). The body then
2811
+ * streams through the standard body loop from byte 0.
2812
+ *
2813
+ * Without the opt-in, the reader refuses input that is neither Part 10 nor
2814
+ * an FMI group, with the streaming reader's own error text.
2815
+ *
2816
+ * @param {ReadBufferStream} stream the raw input stream, at offset 0
2817
+ * @param {Object} options the fromPart10Stream options
2818
+ * @returns {Promise<string>} the body transfer syntax UID
2819
+ */
2820
+ async function detectBareSyntax(stream, options) {
2821
+ if (!options.allowMissingHeader && !options.ignoreErrors) {
2822
+ throw new Error(
2823
+ "fromPart10Stream: input has no DICM marker and does not start " +
2824
+ "with a File Meta Information group; pass " +
2825
+ "allowMissingHeader: true (or ignoreErrors: true) to " +
2826
+ "force-read a bare dataset"
2827
+ );
2828
+ }
2829
+ stream.offset = 0;
2830
+ await stream.ensureAvailable(8);
2831
+ if (!stream.isAvailable(8, false)) {
2832
+ return core.EXPLICIT_LITTLE_ENDIAN;
2833
+ }
2834
+ const vrStr =
2835
+ String.fromCharCode(stream.view.getUint8(4)) +
2836
+ String.fromCharCode(stream.view.getUint8(5));
2837
+ return core.VALID_VRS.has(vrStr)
2838
+ ? core.EXPLICIT_LITTLE_ENDIAN
2839
+ : core.IMPLICIT_LITTLE_ENDIAN;
2840
+ }
2841
+
2842
+ /**
2843
+ * Phase 2: incremental FMI parse, from `stream.offset` to the end of the
2844
+ * File Meta Information. Leaves `stream.offset` at the first body byte.
2845
+ *
2846
+ * FMI is always EXPLICIT_LITTLE_ENDIAN regardless of the body TS. The decoded
2847
+ * FMI elements (tag, VR, values, rawValues) are accumulated into an array so
2848
+ * that the caller can emit startDataSet *after* it knows the
2849
+ * TransferSyntaxUID from (0002,0010) — the listener must receive
2850
+ * startDataSet with the correct TS before any FMI events.
2851
+ *
2852
+ * Two forms of the TS are returned. `rawTransferSyntaxUID` is the raw
2853
+ * (un-normalised) TS read from (0002,0010): it is used for the K5 deflate
2854
+ * detection because _normalizeSyntax maps deflate → ELE, which would prevent
2855
+ * bodyStream from being created (K5 root bug). `transferSyntaxUID`
2856
+ * (normalised) is kept for listener.startDataSet and body-parsing parity with
2857
+ * the eager reader, which normalises the same way. Both default to
2858
+ * EXPLICIT_LITTLE_ENDIAN when (0002,0010) is absent.
2859
+ *
2860
+ * @param {ReadBufferStream} stream the raw input stream
2861
+ * @param {Object} policy the decode policy
2862
+ * @returns {Promise<{fmiElements: Array<{tag:string, vrStr:string, length:number, values:any[], rawValues:any[]}>, transferSyntaxUID: string, rawTransferSyntaxUID: string}>}
2863
+ */
2864
+ async function readFileMetaInformation(stream, policy) {
2865
+ const fmiElements = [];
2866
+ let transferSyntaxUID = core.EXPLICIT_LITTLE_ENDIAN; // default if 0002,0010 absent
2867
+ let rawTransferSyntaxUID = core.EXPLICIT_LITTLE_ENDIAN;
2868
+
2869
+ // We need at least 8 bytes for the smallest possible FMI header.
2870
+ await stream.ensureAvailable(8);
2871
+
2872
+ // Determine whether (0002,0000) FileMetaInformationGroupLength is present.
2873
+ // If present, we know the exact end-of-FMI offset; otherwise we stop
2874
+ // when the first non-0002 group tag appears (AsyncDicomReader.readMeta
2875
+ // §233–240 fallback).
2876
+ let metaEndOffset = null; // null → no fixed bound
2877
+
2878
+ if (
2879
+ stream.isAvailable(8, false) &&
2880
+ stream.view.getUint16(stream.offset, true) === 0x0002 &&
2881
+ stream.view.getUint16(stream.offset + 2, true) === 0x0000
2882
+ ) ;
2883
+
2884
+ // ---- FMI element loop ----
2885
+ while (true) {
2886
+ // Fixed-bound termination: used when (0002,0000) was found.
2887
+ if (metaEndOffset !== null && stream.offset >= metaEndOffset) break;
2888
+
2889
+ // Wait for enough bytes to read a minimal element header (8 bytes:
2890
+ // 4-byte tag + 2-byte VR + 2-byte length). If the stream ends
2891
+ // before we get 8 bytes (unlikely for valid FMI), we stop.
2892
+ await stream.ensureAvailable(8);
2893
+
2894
+ // EOF or insufficient data: stop FMI loop gracefully.
2895
+ if (!stream.isAvailable(4, false)) break;
2896
+
2897
+ // Peek at the next element's group tag (LE uint16).
2898
+ // For the no-group-length fallback: stop as soon as group != 0x0002.
2899
+ const peekGroup = stream.view.getUint16(stream.offset, true);
2900
+ if (peekGroup !== 0x0002) break; // body starts here
2901
+
2902
+ // Confirm we have at least a full 8-byte header before committing.
2903
+ if (!stream.isAvailable(8, false)) break;
2904
+
2905
+ // ---- Read element header (Explicit Little Endian) ----
2906
+ const elGroup = stream.readUint16(); // always 0x0002
2907
+ const elElement = stream.readUint16();
2908
+ // Build DICOM clean tag string: "GGGGEEEE" (uppercase hex, 8 chars)
2909
+ const tagStr =
2910
+ elGroup.toString(16).padStart(4, "0").toUpperCase() +
2911
+ elElement.toString(16).padStart(4, "0").toUpperCase();
2912
+
2913
+ // VR: 2 ASCII bytes
2914
+ const vrStr =
2915
+ String.fromCharCode(stream.view.getUint8(stream.offset)) +
2916
+ String.fromCharCode(stream.view.getUint8(stream.offset + 1));
2917
+ stream.offset += 2;
2918
+
2919
+ // Length: 2 bytes (standard VR) or 2 reserved + 4 bytes (extended VR)
2920
+ let valueLength;
2921
+ // Resolve VR instance to determine header framing via isLength32()
2922
+ // createByTypeString handles invalid VR strings by falling back to UN.
2923
+ const vrForHeader = core.ValueRepresentation.createByTypeString(vrStr);
2924
+ if (vrForHeader.isLength32()) {
2925
+ // Extended form: need 2 more bytes (reserved) + 4 bytes (length32)
2926
+ await stream.ensureAvailable(6);
2927
+ if (!stream.isAvailable(6, false)) break; // truncated
2928
+ stream.offset += 2; // skip reserved (0x0000)
2929
+ valueLength = stream.readUint32();
2930
+ } else {
2931
+ // Standard form: length is already in the next 2 bytes
2932
+ await stream.ensureAvailable(2);
2933
+ if (!stream.isAvailable(2, false)) break; // truncated
2934
+ valueLength = stream.readUint16();
2935
+ }
2936
+
2937
+ // Set metaEndOffset after reading the FileMetaInformationGroupLength
2938
+ // value (0002,0000) UL. The bound is relative to the END of this
2939
+ // element (i.e., the first byte AFTER the UL value bytes).
2940
+ const isGroupLengthTag = elGroup === 0x0002 && elElement === 0x0000;
2941
+
2942
+ // Wait for value bytes
2943
+ await stream.ensureAvailable(valueLength);
2944
+
2945
+ if (!stream.isAvailable(valueLength, false)) {
2946
+ // Stream ended mid-value: best-effort stop (truncated FMI)
2947
+ break;
2948
+ }
2949
+
2950
+ // Extract value bytes into a fresh ArrayBuffer (copy is acceptable
2951
+ // for FMI — FMI is at most a few hundred bytes).
2952
+ const valueStart = stream.offset;
2953
+ const valueAB = stream.slice(valueStart, valueStart + valueLength);
2954
+
2955
+ const { values, rawValues } = decodeFmiValue(
2956
+ valueAB,
2957
+ elGroup,
2958
+ elElement,
2959
+ vrStr,
2960
+ valueLength,
2961
+ policy
2962
+ );
2963
+
2964
+ // Capture TransferSyntaxUID for startDataSet and body-phase delegation.
2965
+ // Matches seedReadContext's normalization (core normalizeSyntax).
2966
+ if (tagStr === "00020010" && values[0]) {
2967
+ rawTransferSyntaxUID = values[0];
2968
+ transferSyntaxUID = core.normalizeSyntax(values[0]);
2969
+ }
2970
+
2971
+ // Set meta end offset from (0002,0000) FileMetaInformationGroupLength
2972
+ if (isGroupLengthTag && values[0] !== undefined) {
2973
+ // values[0] is the UL integer: bytes after THIS element
2974
+ metaEndOffset = valueStart + valueLength + values[0];
2975
+ }
2976
+
2977
+ fmiElements.push({
2978
+ tag: tagStr,
2979
+ vrStr,
2980
+ length: valueLength,
2981
+ values,
2982
+ rawValues
2983
+ });
2984
+
2985
+ // Advance stream past the value bytes
2986
+ stream.offset = valueStart + valueLength;
2987
+ }
2988
+
2989
+ return { fmiElements, transferSyntaxUID, rawTransferSyntaxUID };
2990
+ }
2991
+
2992
+ /**
2993
+ * Decode one FMI element value through decodeCore, over a minimal
2994
+ * Explicit Little Endian read window that holds only the value bytes.
2995
+ *
2996
+ * The `elLike` object is the minimal shape decodeCore.resolveVrInstance and
2997
+ * decodeCore.decodeElementValues require:
2998
+ * - vr — VR string (e.g. "UI", "UL", "OB")
2999
+ * - tagValue — numeric tag (group << 16) | element, for UN dictionary lookup
3000
+ * - dataOffset — byte offset of value within the window.arrayBuffer
3001
+ * - length — value byte count
3002
+ * - hadUndefinedLength — always false for FMI elements (PS3.5 §7.1)
3003
+ *
3004
+ * @param {ArrayBuffer} valueAB a fresh copy of the value bytes
3005
+ * @param {number} elGroup the tag group
3006
+ * @param {number} elElement the tag element
3007
+ * @param {string} vrStr the on-wire VR string
3008
+ * @param {number} valueLength the value byte count
3009
+ * @param {Object} policy the decode policy
3010
+ * @returns {{values: any[], rawValues: any[]}}
3011
+ */
3012
+ function decodeFmiValue(
3013
+ valueAB,
3014
+ elGroup,
3015
+ elElement,
3016
+ vrStr,
3017
+ valueLength,
3018
+ policy
3019
+ ) {
3020
+ const fakeWindow = {
3021
+ arrayBuffer: valueAB,
3022
+ baseOffset: 0,
3023
+ syntax: core.EXPLICIT_LITTLE_ENDIAN,
3024
+ littleEndian: true,
3025
+ implicit: false,
3026
+ decoder: null
3027
+ };
3028
+ const elLike = {
3029
+ vr: vrStr,
3030
+ tagValue: (elGroup << 16) | elElement,
3031
+ dataOffset: 0,
3032
+ length: valueLength,
3033
+ hadUndefinedLength: false
3034
+ };
3035
+
3036
+ const vrInstance = resolveVrInstance(elLike, fakeWindow);
3037
+ return decodeElementValues(fakeWindow, elLike, vrInstance, policy);
3038
+ }
3039
+
3040
+ // ---------------------------------------------------------------------------
3041
+ // FMI element emission
3042
+ // ---------------------------------------------------------------------------
3043
+
3044
+ /**
3045
+ * Emit a single FMI element's events into `listener`.
3046
+ *
3047
+ * Mirrors fromPart10's `emitValues` logic:
3048
+ * - Buffer-valued VRs (OB, OW, OD, …) → startBinary / binaryFragment / endBinary
3049
+ * - Everything else → one or more value() calls
3050
+ *
3051
+ * FMI elements are never sequences (SQ) or undefined-length elements, so
3052
+ * those branches from the full emitElement are not needed here.
3053
+ */
3054
+ function emitFmiElement(listener, el) {
3055
+ const { tag, vrStr, length, values, rawValues } = el;
3056
+
3057
+ const hasBuffer = values.some(
3058
+ v => v instanceof ArrayBuffer || ArrayBuffer.isView(v)
3059
+ );
3060
+
3061
+ listener.startElement(tag, { vr: vrStr, length });
3062
+
3063
+ if (hasBuffer) {
3064
+ listener.startBinary({ encapsulated: false });
3065
+ for (const buf of values) {
3066
+ listener.binaryFragment(buf);
3067
+ }
3068
+ listener.endBinary();
3069
+ } else {
3070
+ let index = 0;
3071
+ for (const v of values) {
3072
+ listener.value(v, { index, rawValue: rawValues[index] });
3073
+ index++;
3074
+ }
3075
+ }
3076
+
3077
+ listener.endElement();
3078
+ }
3079
+
3080
+ // ---------------------------------------------------------------------------
3081
+ // Input normalization
3082
+ // ---------------------------------------------------------------------------
3083
+
3084
+ /**
3085
+ * Normalize `input` to an `AsyncIterable<Uint8Array | ArrayBuffer>`.
3086
+ *
3087
+ * Dispatch order:
3088
+ * 1. ArrayBuffer / TypedArray → single-item async iterable
3089
+ * 2. WHATWG ReadableStream → AsyncIterable (native) or reader-loop adapter
3090
+ * 3. AsyncIterable (generator, etc.) → returned as-is
3091
+ *
3092
+ * @param {*} input
3093
+ * @returns {AsyncIterable<Uint8Array|ArrayBuffer>}
3094
+ */
3095
+ function normalizeInput(input) {
3096
+ // Case 1: flat buffer — degenerate single-chunk
3097
+ if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {
3098
+ return singleChunkIterable(input);
3099
+ }
3100
+
3101
+ // Case 2: WHATWG ReadableStream
3102
+ if (isWhatwgReadableStream(input)) {
3103
+ // Modern Node (≥ 16.14) and modern browsers expose Symbol.asyncIterator
3104
+ // on ReadableStream natively — use it directly.
3105
+ if (Symbol.asyncIterator in input) {
3106
+ return input;
3107
+ }
3108
+ // Fallback for environments where ReadableStream is defined but not
3109
+ // yet AsyncIterable (older browsers, certain polyfills).
3110
+ return readableStreamToAsyncIterable(input);
3111
+ }
3112
+
3113
+ // Case 3: AsyncIterable (async generators, Node.js streams, etc.)
3114
+ if (input != null && typeof input[Symbol.asyncIterator] === "function") {
3115
+ return input;
3116
+ }
3117
+
3118
+ throw new TypeError(
3119
+ "fromPart10Stream: `input` must be an ArrayBuffer, Uint8Array, " +
3120
+ "AsyncIterable<Uint8Array|ArrayBuffer>, or a WHATWG ReadableStream. " +
3121
+ `Got: ${Object.prototype.toString.call(input)}`
3122
+ );
3123
+ }
3124
+
3125
+ /** True if `input` is a WHATWG ReadableStream (works in browser and Node). */
3126
+ function isWhatwgReadableStream(input) {
3127
+ return (
3128
+ typeof ReadableStream !== "undefined" && input instanceof ReadableStream
3129
+ );
3130
+ }
3131
+
3132
+ /** Single-item async iterable that yields `buffer` as a Uint8Array chunk. */
3133
+ async function* singleChunkIterable(buffer) {
3134
+ yield buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
3135
+ }
3136
+
3137
+ /**
3138
+ * Adapter: wrap a WHATWG ReadableStream in an async generator for
3139
+ * environments where the stream does not implement Symbol.asyncIterator.
3140
+ * This is dependency-free and works in both browser and Node.
3141
+ */
3142
+ async function* readableStreamToAsyncIterable(stream) {
3143
+ const reader = stream.getReader();
3144
+ try {
3145
+ for (;;) {
3146
+ const { done, value } = await reader.read();
3147
+ if (done) break;
3148
+ yield value;
3149
+ }
3150
+ } finally {
3151
+ reader.releaseLock();
3152
+ }
3153
+ }
3154
+
3155
+ // ---------------------------------------------------------------------------
3156
+ // Chunk helpers
3157
+ // ---------------------------------------------------------------------------
3158
+
3159
+ /**
3160
+ * Coerce a chunk from the async iterable to an ArrayBuffer for
3161
+ * `stream.addBuffer()`. Handles Uint8Array, Buffer (Node), other typed
3162
+ * arrays, and plain ArrayBuffers.
3163
+ *
3164
+ * @param {Uint8Array|ArrayBuffer} chunk
3165
+ * @returns {ArrayBuffer}
3166
+ */
3167
+ function toArrayBuffer(chunk) {
3168
+ if (chunk instanceof ArrayBuffer) return chunk;
3169
+ if (ArrayBuffer.isView(chunk)) {
3170
+ // Typed array (Uint8Array, Buffer, etc.): slice to own ArrayBuffer.
3171
+ return chunk.buffer.slice(
3172
+ chunk.byteOffset,
3173
+ chunk.byteOffset + chunk.byteLength
3174
+ );
3175
+ }
3176
+ throw new TypeError(
3177
+ `fromPart10Stream: expected Uint8Array|ArrayBuffer chunk from iterable, ` +
3178
+ `got ${Object.prototype.toString.call(chunk)}`
3179
+ );
3180
+ }
3181
+
3182
+ /**
3183
+ * fromPart10 — whole-buffer Part 10 bytes → event stream.
3184
+ *
3185
+ * A thin wrapper: the buffer is fed to the streaming reader as a single
3186
+ * chunk. Earlier drafts of the rewrite implemented this on a vendored
3187
+ * copy of the dicom-parser tokenizer; that package is removed from 1.0,
3188
+ * so the streaming reader's tokenizer is the only one in the library and
3189
+ * this wrapper keeps the buffered entry point working unchanged.
3190
+ *
3191
+ * @param {ArrayBuffer|ArrayBufferView} buffer - complete Part 10 bytes
3192
+ * @param {EventStreamListener} listener - the event consumer
3193
+ * @param {object} [options] - forwarded to fromPart10Stream
3194
+ */
3195
+ async function fromPart10(buffer, listener, options = {}) {
3196
+ const bytes =
3197
+ buffer instanceof Uint8Array
3198
+ ? buffer
3199
+ : ArrayBuffer.isView(buffer)
3200
+ ? new Uint8Array(
3201
+ buffer.buffer,
3202
+ buffer.byteOffset,
3203
+ buffer.byteLength
3204
+ )
3205
+ : new Uint8Array(buffer);
3206
+ await fromPart10Stream(bytes, listener, options);
3207
+ }
3208
+
3209
+ exports.CONTRACT_VERSION = CONTRACT_VERSION;
3210
+ exports.CollectorListener = CollectorListener;
3211
+ exports.EVENT_STREAM_VOCABULARY = EVENT_STREAM_VOCABULARY;
3212
+ exports.EventStreamListener = EventStreamListener;
3213
+ exports.NaturalizedListener = NaturalizedListener;
3214
+ exports.base64ToArrayBuffer = base64ToArrayBuffer;
3215
+ exports.createEventAsyncIterable = createEventAsyncIterable;
3216
+ exports.emitDecodedLeaf = emitDecodedLeaf;
3217
+ exports.emitEntry = emitEntry;
3218
+ exports.emitValues = emitValues;
3219
+ exports.fromDataSet = fromDataSet;
3220
+ exports.fromDicomWebJson = fromDicomWebJson;
3221
+ exports.fromPart10 = fromPart10;
3222
+ exports.fromPart10Stream = fromPart10Stream;
3223
+ exports.mergeFragmentsPerBotWindow = mergeFragmentsPerBotWindow;
3224
+ //# sourceMappingURL=index.cjs.map