dcmnorm 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dcmnorm.js ADDED
@@ -0,0 +1,525 @@
1
+ "use strict";
2
+ // The `dcmnorm` package entry point: everything the native addon exports (index.js, generated by
3
+ // napi-rs), plus the typed dataset API of #6 - read / toDicomJson / write / renderPixels /
4
+ // transcodeTo, `DicomDataset`, typed errors, and the generated Tag / VR / TransferSyntax /
5
+ // SOPClassUID constants (dicom-constants.js). The dataset functions wrap the addon's `dataset*`
6
+ // internals; see README.md "Typed datasets".
7
+
8
+ const native = require("./index.js");
9
+ const constants = require("./dicom-constants.js");
10
+
11
+ const { VR_KIND, TRANSFER_SYNTAX_INFO, SOP_CLASS_NAMES } = constants;
12
+
13
+ // ---------------------------------------------------------------------------------------------
14
+ // Errors
15
+ // ---------------------------------------------------------------------------------------------
16
+
17
+ /** Every dataset API failure. `kind` is the native classification; `code` is `ERR_DCMNORM_<KIND>`. */
18
+ class DcmnormError extends Error {
19
+ constructor(message, info = {}) {
20
+ super(message);
21
+ this.name = new.target.name;
22
+ this.kind = info.kind || "Other";
23
+ this.code = "ERR_DCMNORM_" + this.kind.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
24
+ this.sourceTransferSyntaxUid = info.sourceTransferSyntaxUid ?? null;
25
+ this.targetTransferSyntaxUid = info.targetTransferSyntaxUid ?? null;
26
+ this.frameIndex = info.frameIndex ?? null;
27
+ }
28
+ }
29
+ class InvalidDicomError extends DcmnormError {}
30
+ class UnsupportedTransferSyntaxError extends DcmnormError {}
31
+ class DecodeError extends DcmnormError {}
32
+ class EncodeError extends DcmnormError {}
33
+ class RenderError extends DcmnormError {}
34
+ class DimseError extends DcmnormError {}
35
+
36
+ const ERROR_CLASSES = {
37
+ InvalidDicom: InvalidDicomError,
38
+ UnsupportedTransferSyntax: UnsupportedTransferSyntaxError,
39
+ Decode: DecodeError,
40
+ Encode: EncodeError,
41
+ Render: RenderError,
42
+ Dimse: DimseError,
43
+ };
44
+
45
+ function unwrap(result) {
46
+ if (result.error) {
47
+ const ErrorClass = ERROR_CLASSES[result.error.kind] || DcmnormError;
48
+ throw new ErrorClass(result.error.message, result.error);
49
+ }
50
+ return result;
51
+ }
52
+
53
+ // ---------------------------------------------------------------------------------------------
54
+ // Sources
55
+ // ---------------------------------------------------------------------------------------------
56
+
57
+ function isBytes(value) {
58
+ return Buffer.isBuffer(value) || value instanceof Uint8Array;
59
+ }
60
+
61
+ /**
62
+ * A source as [path, bytes]: a path string, a Buffer / Uint8Array, or a readable stream / async
63
+ * iterable of chunks (collected into one Buffer: the native reader needs the bytes).
64
+ */
65
+ async function sourceArgs(source) {
66
+ if (typeof source === "string") return [source, null];
67
+ if (source instanceof URL) return [require("url").fileURLToPath(source), null];
68
+ if (isBytes(source)) return [null, Buffer.isBuffer(source) ? source : Buffer.from(source.buffer, source.byteOffset, source.byteLength)];
69
+ if (source && typeof source[Symbol.asyncIterator] === "function") {
70
+ const chunks = [];
71
+ for await (const chunk of source) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk));
72
+ return [null, Buffer.concat(chunks)];
73
+ }
74
+ throw new TypeError("a DICOM source is a path, a Buffer/Uint8Array or a readable stream");
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------------------------
78
+ // The binary data set form (src/dicom_io/dataset_tree.rs: encode_document / decode_document)
79
+ // ---------------------------------------------------------------------------------------------
80
+
81
+ const KIND_NAMES = ["empty", "strings", "ints", "doubles", "tags", "bytes", "bulkData", "fragments", "sequence"];
82
+
83
+ function decodeDocument(buffer, source) {
84
+ let pos = 0;
85
+ const u8 = () => buffer[pos++];
86
+ const u32 = () => {
87
+ const v = buffer.readUInt32BE(pos);
88
+ pos += 4;
89
+ return v;
90
+ };
91
+ const str = () => {
92
+ const n = u32();
93
+ const s = buffer.toString("utf8", pos, pos + n);
94
+ pos += n;
95
+ return s;
96
+ };
97
+ const take = (n) => {
98
+ const b = Buffer.from(buffer.subarray(pos, pos + n));
99
+ pos += n;
100
+ return b;
101
+ };
102
+ const tree = () => {
103
+ const count = u32();
104
+ const elements = new Map();
105
+ for (let i = 0; i < count; i++) {
106
+ const tag = u32();
107
+ const vr = String.fromCharCode(u8(), u8());
108
+ const kind = u8();
109
+ let value;
110
+ switch (kind) {
111
+ case 0: value = null; break;
112
+ case 1: { const n = u32(); value = []; for (let j = 0; j < n; j++) value.push(str()); break; }
113
+ case 2: { const n = u32(); value = []; for (let j = 0; j < n; j++) { value.push(Number(buffer.readBigInt64BE(pos))); pos += 8; } break; }
114
+ case 3: { const n = u32(); value = []; for (let j = 0; j < n; j++) { value.push(buffer.readDoubleBE(pos)); pos += 8; } break; }
115
+ case 4: { const n = u32(); value = []; for (let j = 0; j < n; j++) value.push(u32()); break; }
116
+ case 5: value = take(u32()); break;
117
+ case 6: {
118
+ const offset = Number(buffer.readBigUInt64BE(pos));
119
+ const length = Number(buffer.readBigInt64BE(pos + 8));
120
+ pos += 16;
121
+ value = Object.freeze({ tag, vr, offset, length });
122
+ break;
123
+ }
124
+ case 7: {
125
+ const n = u32();
126
+ const offsetTable = [];
127
+ for (let j = 0; j < n; j++) offsetTable.push(u32());
128
+ const m = u32();
129
+ const fragments = [];
130
+ for (let j = 0; j < m; j++) fragments.push(take(u32()));
131
+ value = { offsetTable, fragments };
132
+ break;
133
+ }
134
+ case 8: { const n = u32(); value = []; for (let j = 0; j < n; j++) value.push(new DicomDataset(tree())); break; }
135
+ default: throw new Error(`unknown value kind ${kind} in the binary data set`);
136
+ }
137
+ elements.set(tag, Object.freeze({ tag, vr, type: KIND_NAMES[kind], value }));
138
+ }
139
+ return elements;
140
+ };
141
+ if (buffer.toString("latin1", 0, 4) !== "DCMT" || buffer[4] !== 1) throw new Error("not a binary data set");
142
+ pos = 5;
143
+ const transferSyntaxUid = str();
144
+ const meta = tree();
145
+ const dataset = tree();
146
+ return new DicomDataset(dataset, { fileMeta: new DicomDataset(meta), transferSyntaxUid: transferSyntaxUid || null, source });
147
+ }
148
+
149
+ function encodeDocument(dataset) {
150
+ const parts = [];
151
+ const u32 = (v) => { const b = Buffer.alloc(4); b.writeUInt32BE(v >>> 0); parts.push(b); };
152
+ const str = (s) => { const b = Buffer.from(s, "utf8"); u32(b.length); parts.push(b); };
153
+ const tree = (ds) => {
154
+ u32(ds.size);
155
+ for (const e of ds) {
156
+ u32(e.tag);
157
+ parts.push(Buffer.from(e.vr, "latin1"));
158
+ const kind = KIND_NAMES.indexOf(e.type);
159
+ parts.push(Buffer.from([kind]));
160
+ const v = e.value;
161
+ switch (e.type) {
162
+ case "empty": break;
163
+ case "strings": u32(v.length); v.forEach(str); break;
164
+ case "ints": { u32(v.length); const b = Buffer.alloc(8 * v.length); v.forEach((x, i) => b.writeBigInt64BE(BigInt(Math.trunc(x)), 8 * i)); parts.push(b); break; }
165
+ case "doubles": { u32(v.length); const b = Buffer.alloc(8 * v.length); v.forEach((x, i) => b.writeDoubleBE(x, 8 * i)); parts.push(b); break; }
166
+ case "tags": u32(v.length); v.forEach(u32); break;
167
+ case "bytes": u32(v.length); parts.push(Buffer.from(v)); break;
168
+ case "bulkData": { const b = Buffer.alloc(16); b.writeBigUInt64BE(BigInt(v.offset)); b.writeBigInt64BE(BigInt(v.length), 8); parts.push(b); break; }
169
+ case "fragments": u32(v.offsetTable.length); v.offsetTable.forEach(u32); u32(v.fragments.length); v.fragments.forEach((f) => { u32(f.length); parts.push(Buffer.from(f)); }); break;
170
+ case "sequence": u32(v.length); v.forEach(tree); break;
171
+ default: throw new Error(`unknown value type ${e.type}`);
172
+ }
173
+ }
174
+ };
175
+ parts.push(Buffer.from("DCMT", "latin1"), Buffer.from([1]));
176
+ str(dataset.transferSyntaxUid || "");
177
+ tree(dataset.fileMeta);
178
+ tree(dataset);
179
+ return Buffer.concat(parts);
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------------------------
183
+ // DicomDataset
184
+ // ---------------------------------------------------------------------------------------------
185
+
186
+ function hex8(tag) {
187
+ return (tag >>> 0).toString(16).toUpperCase().padStart(8, "0");
188
+ }
189
+
190
+ function formatNumber(v) {
191
+ return Number.isInteger(v) ? String(v) : String(v);
192
+ }
193
+
194
+ function parseNumber(text) {
195
+ const v = Number(String(text).trim());
196
+ return Number.isNaN(v) ? undefined : v;
197
+ }
198
+
199
+ /** A PN value split into groups (alphabetic, ideographic, phonetic) and components. */
200
+ class PersonName {
201
+ constructor(value) {
202
+ this.value = value || "";
203
+ const groups = this.value.split("=");
204
+ const group = (text = "") => {
205
+ const c = text.split("^");
206
+ return Object.freeze({
207
+ familyName: c[0] || "",
208
+ givenName: c[1] || "",
209
+ middleName: c[2] || "",
210
+ namePrefix: c[3] || "",
211
+ nameSuffix: c.slice(4).join("^"),
212
+ });
213
+ };
214
+ this.alphabetic = group(groups[0]);
215
+ this.ideographic = group(groups[1]);
216
+ this.phonetic = group(groups[2]);
217
+ Object.freeze(this);
218
+ }
219
+ get familyName() { return this.alphabetic.familyName; }
220
+ get givenName() { return this.alphabetic.givenName; }
221
+ toString() { return this.value; }
222
+ }
223
+
224
+ /**
225
+ * A read-only DICOM data set as plain JS values. Iterates its elements `{ tag, vr, type, value }`
226
+ * in ascending tag order; `type` is how the value is held: `strings` (text VRs, one string per
227
+ * value), `ints` (numbers; SV/UV beyond 2^53 lose precision), `doubles`, `tags`, `bytes`
228
+ * (Buffer), `bulkData` (`{ tag, vr, offset, length }`, left in the source), `fragments`,
229
+ * `sequence` (DicomDataset items) or `empty`.
230
+ */
231
+ class DicomDataset {
232
+ constructor(elements = new Map(), { fileMeta = null, transferSyntaxUid = null, source = null } = {}) {
233
+ this._elements = new Map([...elements.entries()].sort((a, b) => (a[0] >>> 0) - (b[0] >>> 0)));
234
+ this._fileMeta = fileMeta;
235
+ this.transferSyntaxUid = transferSyntaxUid;
236
+ this._source = source;
237
+ Object.freeze(this);
238
+ }
239
+
240
+ static empty() { return new DicomDataset(); }
241
+
242
+ get size() { return this._elements.size; }
243
+ [Symbol.iterator]() { return this._elements.values(); }
244
+ tags() { return [...this._elements.keys()]; }
245
+ has(tag) { return this._elements.has(tag); }
246
+ get(tag) { return this._elements.get(tag); }
247
+ vr(tag) { const e = this._elements.get(tag); return e ? e.vr : null; }
248
+
249
+ /** The File Meta Information read with the data set (not written back; `write` creates it). */
250
+ get fileMeta() { return this._fileMeta || EMPTY; }
251
+ get transferSyntax() { return TRANSFER_SYNTAX_INFO[this.transferSyntaxUid] || null; }
252
+
253
+ /** Value `index` as text, or `defaultValue` if absent or empty. */
254
+ getString(tag, defaultValue = null, index = 0) {
255
+ const e = this._elements.get(tag);
256
+ if (!e || !Array.isArray(e.value) || index >= e.value.length) return defaultValue;
257
+ const v = e.value[index];
258
+ switch (e.type) {
259
+ case "strings": return v === "" ? defaultValue : v;
260
+ case "ints": case "doubles": return formatNumber(v);
261
+ case "tags": return hex8(v);
262
+ default: return defaultValue;
263
+ }
264
+ }
265
+
266
+ /** Every value as text; null if absent. */
267
+ getStrings(tag) {
268
+ const e = this._elements.get(tag);
269
+ if (!e) return null;
270
+ switch (e.type) {
271
+ case "strings": return [...e.value];
272
+ case "ints": case "doubles": return e.value.map(formatNumber);
273
+ case "tags": return e.value.map(hex8);
274
+ default: return [];
275
+ }
276
+ }
277
+
278
+ /** Value `index` as a number (IS/DS parsed), or `defaultValue`. */
279
+ getNumber(tag, defaultValue = null, index = 0) {
280
+ const e = this._elements.get(tag);
281
+ if (!e || !Array.isArray(e.value) || index >= e.value.length) return defaultValue;
282
+ if (e.type === "strings") {
283
+ const v = parseNumber(e.value[index]);
284
+ return v === undefined || e.value[index] === "" ? defaultValue : v;
285
+ }
286
+ return e.type === "ints" || e.type === "doubles" || e.type === "tags" ? e.value[index] : defaultValue;
287
+ }
288
+
289
+ /** dcm4che-style: an integer (IS parsed; DS truncated). */
290
+ getInt(tag, defaultValue = null, index = 0) {
291
+ const v = this.getNumber(tag, null, index);
292
+ return v === null ? defaultValue : Math.trunc(v);
293
+ }
294
+
295
+ getFloat(tag, defaultValue = null, index = 0) {
296
+ return this.getNumber(tag, defaultValue, index);
297
+ }
298
+
299
+ /** Every value as a number; null if absent (throws on an unparseable value). */
300
+ getNumbers(tag) {
301
+ const e = this._elements.get(tag);
302
+ if (!e) return null;
303
+ if (e.type === "strings") {
304
+ return e.value.map((s) => {
305
+ const v = parseNumber(s);
306
+ if (v === undefined) throw new TypeError(`'${s}' is not a number`);
307
+ return v;
308
+ });
309
+ }
310
+ return e.type === "ints" || e.type === "doubles" || e.type === "tags" ? [...e.value] : [];
311
+ }
312
+
313
+ getInts(tag) { const v = this.getNumbers(tag); return v && v.map(Math.trunc); }
314
+ getFloats(tag) { return this.getNumbers(tag); }
315
+
316
+ /** A binary value that was read (a copy), or null (absent, or left in the source). */
317
+ getBytes(tag) {
318
+ const e = this._elements.get(tag);
319
+ if (!e) return null;
320
+ if (e.type === "bytes") return Buffer.from(e.value);
321
+ if (e.type === "empty") return Buffer.alloc(0);
322
+ return null;
323
+ }
324
+
325
+ getBulkDataRef(tag) { const e = this._elements.get(tag); return e && e.type === "bulkData" ? e.value : null; }
326
+ getSequence(tag) { const e = this._elements.get(tag); return e && e.type === "sequence" ? [...e.value] : null; }
327
+ getNestedDataset(tag, index = 0) { const s = this.getSequence(tag); return s && index < s.length ? s[index] : null; }
328
+ getPersonName(tag, index = 0) { const v = this.getString(tag, null, index); return v === null ? null : new PersonName(v); }
329
+
330
+ get numberOfFrames() { return Math.max(1, this.getInt(constants.Tag.NumberOfFrames, 1)); }
331
+ get frameTimeMillis() { return this.getNumber(constants.Tag.FrameTime, null); }
332
+ get frameTimeVector() { return this.has(constants.Tag.FrameTimeVector) ? this.getNumbers(constants.Tag.FrameTimeVector) : null; }
333
+
334
+ /** Vertical / horizontal pixel size: PixelAspectRatio, else the PixelSpacing ratio, else 1. */
335
+ get pixelAspectRatio() {
336
+ for (const tag of [constants.Tag.PixelAspectRatio, constants.Tag.PixelSpacing]) {
337
+ const v = this.has(tag) ? this.getNumbers(tag) : null;
338
+ if (v && v.length === 2 && v[0] > 0 && v[1] > 0) return v[0] / v[1];
339
+ }
340
+ return 1;
341
+ }
342
+
343
+ toBuilder() { return new DicomDatasetBuilder(this); }
344
+ }
345
+
346
+ const EMPTY = new DicomDataset();
347
+
348
+ /** Builds a modified copy of a DicomDataset; bulk data references stay references. */
349
+ class DicomDatasetBuilder {
350
+ constructor(from) {
351
+ this._elements = new Map(from._elements);
352
+ this._fileMeta = from._fileMeta;
353
+ this._transferSyntaxUid = from.transferSyntaxUid;
354
+ this._source = from._source;
355
+ }
356
+
357
+ _put(tag, vr, type, value) {
358
+ if (tag >>> 16 === 0x0002) throw new Error("File Meta Information is created by write(), not set in the data set");
359
+ this._elements.set(tag, Object.freeze({ tag, vr, type, value }));
360
+ return this;
361
+ }
362
+
363
+ _vr(tag) {
364
+ const vr = native.vrOf(tag);
365
+ if (!vr) throw new Error(`${hex8(tag)} is not in the dictionary: give its VR`);
366
+ return vr;
367
+ }
368
+
369
+ /** Text values for any VR (a binary VR parses them when written): `set(tag, vr, ...values)`,
370
+ * or `set(tag, [values])` with the dictionary VR. */
371
+ set(tag, vr, ...values) {
372
+ if (Array.isArray(vr)) return this.set(tag, this._vr(tag), ...vr);
373
+ if (!(vr in VR_KIND)) throw new TypeError(`unknown VR ${vr}: set(tag, vr, ...values) or set(tag, [values])`);
374
+ if (vr === "SQ") throw new Error("use setSequence for SQ");
375
+ return values.length === 0 ? this._put(tag, vr, "empty", null) : this._put(tag, vr, "strings", values.map((v) => (v == null ? "" : String(v))));
376
+ }
377
+ setInt(tag, vr, ...values) { return this._put(tag, vr, values.length ? "ints" : "empty", values.length ? values.map(Math.trunc) : null); }
378
+ setDouble(tag, vr, ...values) { return this._put(tag, vr, values.length ? "doubles" : "empty", values.length ? [...values] : null); }
379
+ setTags(tag, ...tags) { return this._put(tag, "AT", tags.length ? "tags" : "empty", tags.length ? tags.map((t) => t >>> 0) : null); }
380
+ setBytes(tag, vr, bytes) { return this._put(tag, vr, bytes.length ? "bytes" : "empty", bytes.length ? Buffer.from(bytes) : null); }
381
+ setNull(tag, vr) { return this._put(tag, vr, "empty", null); }
382
+ setSequence(tag, items) { return this._put(tag, "SQ", "sequence", Object.freeze([...items])); }
383
+ addSequenceItem(tag, item) {
384
+ const e = this._elements.get(tag);
385
+ return this.setSequence(tag, [...(e && e.type === "sequence" ? e.value : []), item]);
386
+ }
387
+ editSequenceItem(tag, index, edit) {
388
+ const e = this._elements.get(tag);
389
+ if (!e || e.type !== "sequence" || index < 0 || index >= e.value.length) throw new RangeError(`${hex8(tag)} has no item ${index}`);
390
+ const builder = e.value[index].toBuilder();
391
+ edit(builder);
392
+ const items = [...e.value];
393
+ items[index] = builder.build();
394
+ return this.setSequence(tag, items);
395
+ }
396
+ removeSequenceItem(tag, index) {
397
+ const e = this._elements.get(tag);
398
+ if (!e || e.type !== "sequence" || index < 0 || index >= e.value.length) throw new RangeError(`${hex8(tag)} has no item ${index}`);
399
+ return this.setSequence(tag, e.value.filter((_, i) => i !== index));
400
+ }
401
+ remove(tag) { this._elements.delete(tag); return this; }
402
+ removePrivateTags() { for (const tag of [...this._elements.keys()]) if ((tag >>> 16) & 1) this._elements.delete(tag); return this; }
403
+ build() {
404
+ return new DicomDataset(this._elements, { fileMeta: this._fileMeta, transferSyntaxUid: this._transferSyntaxUid, source: this._source });
405
+ }
406
+ }
407
+
408
+ // ---------------------------------------------------------------------------------------------
409
+ // The API
410
+ // ---------------------------------------------------------------------------------------------
411
+
412
+ /**
413
+ * Read a DICOM object into a DicomDataset. `source`: a path, a Buffer/Uint8Array, or a readable
414
+ * stream (collected first). Options: `untilPixelData` (stop at the PixelData header),
415
+ * `loadBulkData` (read bulk values instead of leaving them as references).
416
+ */
417
+ async function read(source, options = {}) {
418
+ const [path, bytes] = await sourceArgs(source);
419
+ const result = unwrap(await native.datasetRead(path, bytes, !!options.untilPixelData, !!options.loadBulkData));
420
+ return decodeDocument(result.data, path !== null ? { path } : { bytes });
421
+ }
422
+
423
+ const PLACEHOLDER = /"dcmnorm-bulk:([0-9A-F]{8}):([A-Z]{2}):(\d+):(-?\d+)"/g;
424
+
425
+ function jsonOptions(options) {
426
+ return {
427
+ includeTags: options.includeTags,
428
+ excludeTags: options.excludeTags,
429
+ bulkData: options.bulkData,
430
+ bulkDataUriBase: options.bulkDataUriBase,
431
+ includeFileMeta: options.includeFileMeta,
432
+ keywordAndVm: options.keywordAndVM,
433
+ placeholderUris: typeof options.bulkDataUriBuilder === "function",
434
+ };
435
+ }
436
+
437
+ function applyUriBuilder(json, builder) {
438
+ if (typeof builder !== "function") return json;
439
+ return json.replace(PLACEHOLDER, (_, tag, vr, offset, length) => {
440
+ const uri = builder(Object.freeze({ tag: parseInt(tag, 16), vr, offset: Number(offset), length: Number(length) }));
441
+ if (typeof uri !== "string") throw new TypeError("bulkDataUriBuilder must return a string");
442
+ return JSON.stringify(uri);
443
+ });
444
+ }
445
+
446
+ /**
447
+ * PS3.18 Annex F DICOM JSON of a source or a DicomDataset, as a string. Options: `includeTags`,
448
+ * `excludeTags`, `bulkData` ('uri' default | 'inline'), `bulkDataUriBase`,
449
+ * `bulkDataUriBuilder(ref) => string`, `includeFileMeta`, `keywordAndVM`.
450
+ */
451
+ async function toDicomJson(source, options = {}) {
452
+ let result;
453
+ if (source instanceof DicomDataset) {
454
+ const s = source._source || {};
455
+ result = unwrap(await native.datasetDocumentToJson(encodeDocument(source), s.path ?? null, s.bytes ?? null, jsonOptions(options)));
456
+ } else {
457
+ const [path, bytes] = await sourceArgs(source);
458
+ result = unwrap(await native.datasetSourceToJson(path, bytes, jsonOptions(options)));
459
+ }
460
+ return applyUriBuilder(result.text, options.bulkDataUriBuilder);
461
+ }
462
+
463
+ /**
464
+ * Write a DicomDataset as a DICOM file to `outputPath`, or (outputPath null) resolve to its bytes.
465
+ * File Meta Information is created for it; bulk data references are read natively from the source
466
+ * it was read from (or `options.bulkDataSource`: a path or Buffer). `options.transferSyntax`
467
+ * transcodes.
468
+ */
469
+ async function write(dataset, outputPath = null, options = {}) {
470
+ let s = dataset._source || {};
471
+ if (options.bulkDataSource !== undefined) {
472
+ s = typeof options.bulkDataSource === "string" ? { path: options.bulkDataSource } : { bytes: Buffer.from(options.bulkDataSource) };
473
+ }
474
+ const result = unwrap(
475
+ await native.datasetWrite(encodeDocument(dataset), s.path ?? null, s.bytes ?? null, outputPath, options.transferSyntax ?? null),
476
+ );
477
+ return outputPath === null ? result.data : undefined;
478
+ }
479
+
480
+ /** `write(dataset, null, options)`: the file's bytes. */
481
+ function toBuffer(dataset, options = {}) {
482
+ return write(dataset, null, options);
483
+ }
484
+
485
+ /**
486
+ * Render frame `frameIndex` to 8-bit display pixels - no image encoding: resolves to
487
+ * `{ width, height, channels, pixels, overlays, selectedOverlayIndex }`, `pixels` a Buffer of
488
+ * `width * height * channels` bytes (1 channel gray, 3 RGB interleaved), rows top to bottom.
489
+ * Params: `windowCenter`/`windowWidth`, `voiLut`, `modalityLut`, `iccProfile`, `outputWidth`,
490
+ * `outputHeight`, `showOverlays`, `overlayIndex`, `overlayColor`.
491
+ */
492
+ async function renderPixels(source, frameIndex = 0, params = {}) {
493
+ const [path, bytes] = await sourceArgs(source);
494
+ const result = unwrap(await native.datasetRenderPixels(path, bytes, frameIndex, params));
495
+ return result.rendered;
496
+ }
497
+
498
+ /** Transcode a source to `transferSyntaxUid`: to `outputPath`, or (null) resolve to the bytes. */
499
+ async function transcodeTo(source, transferSyntaxUid, outputPath = null) {
500
+ const [path, bytes] = await sourceArgs(source);
501
+ const result = unwrap(await native.datasetTranscode(path, bytes, outputPath, transferSyntaxUid));
502
+ return outputPath === null ? result.data : undefined;
503
+ }
504
+
505
+ module.exports = {
506
+ ...native,
507
+ ...constants,
508
+ DcmnormError,
509
+ InvalidDicomError,
510
+ UnsupportedTransferSyntaxError,
511
+ DecodeError,
512
+ EncodeError,
513
+ RenderError,
514
+ DimseError,
515
+ DicomDataset,
516
+ DicomDatasetBuilder,
517
+ PersonName,
518
+ read,
519
+ toDicomJson,
520
+ write,
521
+ toBuffer,
522
+ renderPixels,
523
+ transcodeTo,
524
+ sopClassName: (uid) => SOP_CLASS_NAMES[uid] ?? null,
525
+ };