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

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