dicom-synth 1.0.0 → 1.1.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.
@@ -0,0 +1,386 @@
1
+ // src/collection/writer.ts
2
+ import { mkdirSync as mkdirSync2 } from "node:fs";
3
+ import { writeFile } from "node:fs/promises";
4
+ import { resolve as resolve2 } from "node:path";
5
+
6
+ // src/loadDcmjs.ts
7
+ import dcmjsDefaultImport, * as dcmjsNamespace from "dcmjs";
8
+ function loadDcmjs() {
9
+ if (dcmjsNamespace.data?.DicomDict) {
10
+ return dcmjsNamespace;
11
+ }
12
+ const d = dcmjsDefaultImport;
13
+ if (d?.data?.DicomDict) {
14
+ return d;
15
+ }
16
+ if (d?.default?.data?.DicomDict) {
17
+ return d.default;
18
+ }
19
+ throw new Error(
20
+ "dcmjs failed to load (missing data.DicomDict). Install dcmjs >= 0.29."
21
+ );
22
+ }
23
+ var dcmjs = loadDcmjs();
24
+
25
+ // src/nonStandardDicom/dicomdir.ts
26
+ import { mkdirSync, writeFileSync } from "node:fs";
27
+ import { resolve } from "node:path";
28
+ var DICOMDIR_SOP_CLASS_UID = "1.2.840.10008.1.3.10";
29
+ function buildDicomdirBuffer() {
30
+ const uid = DICOMDIR_SOP_CLASS_UID;
31
+ const buf = Buffer.alloc(256, 0);
32
+ buf.write("DICM", 128, 4, "ascii");
33
+ let off = 132;
34
+ buf.writeUInt16LE(2, off);
35
+ off += 2;
36
+ buf.writeUInt16LE(2, off);
37
+ off += 2;
38
+ buf.write("UI", off, 2, "ascii");
39
+ off += 2;
40
+ buf.writeUInt16LE(uid.length, off);
41
+ off += 2;
42
+ buf.write(uid, off, uid.length, "ascii");
43
+ off += uid.length;
44
+ return buf.subarray(0, off);
45
+ }
46
+
47
+ // src/schema/validate.ts
48
+ var MAX_PIXEL_BYTES = 512 * 1024 * 1024;
49
+ var HEX_TAG_RE = /^[0-9a-fA-F]{8}$/;
50
+
51
+ // src/syntheticFixtures/generator.ts
52
+ var CT_SOP_CLASS = "1.2.840.10008.5.1.4.1.1.2";
53
+ var TRANSFER_SYNTAX_UID = {
54
+ "explicit-vr-little-endian": "1.2.840.10008.1.2.1",
55
+ "implicit-vr-little-endian": "1.2.840.10008.1.2"
56
+ };
57
+ function buildTagToKeyword() {
58
+ const map = /* @__PURE__ */ new Map();
59
+ const nm = dcmjs.data?.DicomMetaDictionary?.nameMap;
60
+ if (!nm) return map;
61
+ for (const [keyword, info] of Object.entries(nm)) {
62
+ if (info?.tag) {
63
+ const hex = info.tag.replace(/[(,)]/g, "").toUpperCase();
64
+ if (hex.length === 8) map.set(hex, keyword);
65
+ }
66
+ }
67
+ return map;
68
+ }
69
+ var tagToKeyword = buildTagToKeyword();
70
+ function applyTagOverrides(dataset, tags) {
71
+ if (!tags) return;
72
+ for (const [key, value] of Object.entries(tags)) {
73
+ if (HEX_TAG_RE.test(key)) {
74
+ const keyword = tagToKeyword.get(key.toUpperCase());
75
+ if (keyword) {
76
+ dataset[keyword] = value;
77
+ } else {
78
+ console.warn(`dicom-synth: unknown hex tag "${key}" \u2014 skipping`);
79
+ }
80
+ } else {
81
+ dataset[key] = value;
82
+ }
83
+ }
84
+ }
85
+ function buildMeta(uid, transferSyntax = "explicit-vr-little-endian") {
86
+ return {
87
+ FileMetaInformationVersion: new Uint8Array([0, 1]).buffer,
88
+ MediaStorageSOPClassUID: CT_SOP_CLASS,
89
+ MediaStorageSOPInstanceUID: uid.sop,
90
+ TransferSyntaxUID: TRANSFER_SYNTAX_UID[transferSyntax],
91
+ ImplementationClassUID: "1.2.3.4",
92
+ ImplementationVersionName: "SYNTH"
93
+ };
94
+ }
95
+ function buildBaseCtDataset(uid) {
96
+ return {
97
+ PatientName: "SYNTH^SUBJECT",
98
+ PatientID: "SYNTH_PID",
99
+ Modality: "CT",
100
+ SOPClassUID: CT_SOP_CLASS,
101
+ SOPInstanceUID: uid.sop,
102
+ SeriesInstanceUID: uid.series,
103
+ StudyInstanceUID: uid.study,
104
+ StudyDescription: "Synthetic study",
105
+ SeriesDescription: "Synthetic series",
106
+ Rows: 1,
107
+ Columns: 1,
108
+ BitsAllocated: 16,
109
+ BitsStored: 16,
110
+ HighBit: 15,
111
+ SamplesPerPixel: 1,
112
+ PhotometricInterpretation: "MONOCHROME2",
113
+ PixelRepresentation: 0,
114
+ PixelData: new Uint8Array([0, 0]).buffer,
115
+ // Declares PixelData's VR explicitly — without it dcmjs logs
116
+ // "No value representation given for PixelData" and falls back to OW anyway.
117
+ _vrMap: { PixelData: "OW" }
118
+ };
119
+ }
120
+ function serializeDict(meta, dataset) {
121
+ const dicomDict = new dcmjs.data.DicomDict(
122
+ dcmjs.data.DicomMetaDictionary.denaturalizeDataset(
123
+ meta
124
+ )
125
+ );
126
+ dicomDict.dict = dcmjs.data.DicomMetaDictionary.denaturalizeDataset(
127
+ dataset
128
+ );
129
+ return Buffer.from(dicomDict.write({ allowInvalidVRLength: true }));
130
+ }
131
+ function buildValidCtBuffer(uid, tags, transferSyntax) {
132
+ const dataset = buildBaseCtDataset(uid);
133
+ applyTagOverrides(dataset, tags);
134
+ return serializeDict(buildMeta(uid, transferSyntax), dataset);
135
+ }
136
+ function buildInvalidUidCtBuffer(uid, tags, transferSyntax) {
137
+ const invalidUid = {
138
+ study: `2.25.invalid.study.${uid.study.slice(-6)}`,
139
+ series: `2.25.invalid.series.${uid.series.slice(-6)}`,
140
+ sop: `2.25.invalid.sop.${uid.sop.slice(-6)}`
141
+ };
142
+ const dataset = buildBaseCtDataset(invalidUid);
143
+ applyTagOverrides(dataset, tags);
144
+ return serializeDict(buildMeta(invalidUid, transferSyntax), dataset);
145
+ }
146
+ function buildVendorCtBuffer(uid, tags, transferSyntax) {
147
+ const dataset = buildBaseCtDataset(uid);
148
+ dataset.Laterality = "";
149
+ dataset.PatientWeight = "0";
150
+ applyTagOverrides(dataset, tags);
151
+ return serializeDict(buildMeta(uid, transferSyntax), dataset);
152
+ }
153
+ function buildLargeCtBuffer(uid, rows, columns, frames, tags, transferSyntax) {
154
+ const dataset = buildBaseCtDataset(uid);
155
+ dataset.Rows = rows;
156
+ dataset.Columns = columns;
157
+ dataset.NumberOfFrames = frames;
158
+ dataset.PixelData = new Uint8Array(rows * columns * frames * 2).buffer;
159
+ applyTagOverrides(dataset, tags);
160
+ return serializeDict(buildMeta(uid, transferSyntax), dataset);
161
+ }
162
+ function buildFakeSignatureBuffer() {
163
+ const buf = Buffer.alloc(200, 0);
164
+ buf.write("XXXX", 128, 4, "ascii");
165
+ return buf;
166
+ }
167
+ function buildNonDicomBuffer(content = "not dicom") {
168
+ return Buffer.from(content, "utf8");
169
+ }
170
+ function buildBufferForSpec(spec, uid) {
171
+ switch (spec.type) {
172
+ case "valid-ct":
173
+ return buildValidCtBuffer(uid, spec.tags, spec.transferSyntax);
174
+ case "invalid-uid-ct":
175
+ return buildInvalidUidCtBuffer(uid, spec.tags, spec.transferSyntax);
176
+ case "vendor-warnings-ct":
177
+ return buildVendorCtBuffer(uid, spec.tags, spec.transferSyntax);
178
+ case "large-ct":
179
+ return buildLargeCtBuffer(
180
+ uid,
181
+ spec.rows,
182
+ spec.columns,
183
+ spec.frames ?? 1,
184
+ spec.tags,
185
+ spec.transferSyntax
186
+ );
187
+ case "fake-signature":
188
+ return buildFakeSignatureBuffer();
189
+ case "non-dicom":
190
+ return buildNonDicomBuffer(spec.content);
191
+ case "dicomdir":
192
+ return buildDicomdirBuffer();
193
+ }
194
+ }
195
+
196
+ // src/syntheticFixtures/uid.ts
197
+ import { randomBytes } from "node:crypto";
198
+ var ROLE_CODE = { study: 1, series: 2, sop: 3 };
199
+ function lcg(seed) {
200
+ let s = seed >>> 0;
201
+ return () => {
202
+ s = Math.imul(1664525, s) + 1013904223 >>> 0;
203
+ return s;
204
+ };
205
+ }
206
+ function formatUid(a, b, role) {
207
+ return `2.25.${a}.${b}.${ROLE_CODE[role]}`;
208
+ }
209
+ function randomUid(role) {
210
+ const buf = randomBytes(8);
211
+ return formatUid(buf.readUInt32BE(0), buf.readUInt32BE(4), role);
212
+ }
213
+ function seededUid(next, role) {
214
+ return formatUid(next(), next(), role);
215
+ }
216
+ function makeUidGenerator(seed) {
217
+ if (seed === void 0) {
218
+ return () => ({
219
+ study: randomUid("study"),
220
+ series: randomUid("series"),
221
+ sop: randomUid("sop")
222
+ });
223
+ }
224
+ return (fileIndex) => {
225
+ const next = lcg(seed * 999983 + fileIndex * 1000003 >>> 0);
226
+ return {
227
+ study: seededUid(next, "study"),
228
+ series: seededUid(next, "series"),
229
+ sop: seededUid(next, "sop")
230
+ };
231
+ };
232
+ }
233
+
234
+ // src/syntheticFixtures/violations.ts
235
+ var dcmjsAny = dcmjs;
236
+ function parseBuffer(buffer) {
237
+ const ab = buffer.buffer.slice(
238
+ buffer.byteOffset,
239
+ buffer.byteOffset + buffer.byteLength
240
+ );
241
+ return dcmjsAny.data.DicomMessage.readFile(ab);
242
+ }
243
+ function reserialize(parsed) {
244
+ return Buffer.from(parsed.write({ allowInvalidVRLength: true }));
245
+ }
246
+ var OVERLONG_UID = `2.25.${"0".repeat(60)}`;
247
+ var VIOLATION_LEVEL = {
248
+ "uid-too-long": "tag",
249
+ "non-conformant-uid": "tag",
250
+ "vr-max-length-exceeded": "tag",
251
+ "missing-type1-tag": "tag",
252
+ "missing-meta-header": "byte",
253
+ "malformed-sq-delimiter": "byte"
254
+ };
255
+ function applyTagLevel(buffer, violations) {
256
+ if (violations.length === 0) return buffer;
257
+ let parsed;
258
+ try {
259
+ parsed = parseBuffer(buffer);
260
+ } catch {
261
+ console.warn(
262
+ "dicom-synth: could not parse buffer for tag-level violations \u2014 skipping"
263
+ );
264
+ return buffer;
265
+ }
266
+ const natural = dcmjsAny.data.DicomMetaDictionary.naturalizeDataset(
267
+ parsed.dict
268
+ );
269
+ for (const v of violations) {
270
+ switch (v) {
271
+ case "uid-too-long":
272
+ break;
273
+ case "non-conformant-uid":
274
+ natural.SOPInstanceUID = "2.25.01.234.567";
275
+ break;
276
+ case "vr-max-length-exceeded":
277
+ natural.StudyDescription = "X".repeat(65);
278
+ break;
279
+ case "missing-type1-tag":
280
+ delete natural.SOPClassUID;
281
+ break;
282
+ default:
283
+ throw new Error(
284
+ `dicom-synth: unhandled tag-level violation "${v}"`
285
+ );
286
+ }
287
+ }
288
+ parsed.dict = dcmjsAny.data.DicomMetaDictionary.denaturalizeDataset(natural);
289
+ if (violations.includes("uid-too-long")) {
290
+ ;
291
+ parsed.dict["00080018"] = {
292
+ vr: "UI",
293
+ Value: [OVERLONG_UID]
294
+ };
295
+ }
296
+ return reserialize(parsed);
297
+ }
298
+ function applyByteLevel(buffer, violations) {
299
+ let result = buffer;
300
+ for (const v of violations) {
301
+ switch (v) {
302
+ case "missing-meta-header":
303
+ result = result.subarray(132);
304
+ break;
305
+ case "malformed-sq-delimiter": {
306
+ const delimiter = Buffer.alloc(8);
307
+ delimiter.writeUInt16LE(65534, 0);
308
+ delimiter.writeUInt16LE(57565, 2);
309
+ delimiter.writeUInt32LE(4, 4);
310
+ result = Buffer.concat([result, delimiter]);
311
+ break;
312
+ }
313
+ default:
314
+ throw new Error(
315
+ `dicom-synth: unhandled byte-level violation "${v}"`
316
+ );
317
+ }
318
+ }
319
+ return result;
320
+ }
321
+ function applyViolations(buffer, violations) {
322
+ if (violations.length === 0) return buffer;
323
+ const tagViolations = violations.filter((v) => VIOLATION_LEVEL[v] === "tag");
324
+ const byteViolations = violations.filter((v) => VIOLATION_LEVEL[v] === "byte");
325
+ return applyByteLevel(applyTagLevel(buffer, tagViolations), byteViolations);
326
+ }
327
+
328
+ // src/collection/writer.ts
329
+ var NO_EXTENSION_TYPES = /* @__PURE__ */ new Set([
330
+ "fake-signature",
331
+ "non-dicom"
332
+ ]);
333
+ function filename(type, index, padWidth) {
334
+ const padded = String(index).padStart(padWidth, "0");
335
+ const base = `${type}-${padded}`;
336
+ return NO_EXTENSION_TYPES.has(type) ? base : `${base}.dcm`;
337
+ }
338
+ async function generateFile(spec, options) {
339
+ const index = options?.index ?? 0;
340
+ const padWidth = options?.padWidth ?? 3;
341
+ const uidGen = makeUidGenerator(options?.seed);
342
+ const uid = uidGen(index);
343
+ let buffer = buildBufferForSpec(spec, uid);
344
+ const violations = "violations" in spec ? spec.violations : void 0;
345
+ if (violations?.length) {
346
+ buffer = applyViolations(buffer, violations);
347
+ }
348
+ return {
349
+ filename: filename(spec.type, index, padWidth),
350
+ buffer,
351
+ type: spec.type,
352
+ index
353
+ };
354
+ }
355
+ async function* generateCollectionFromSpec(spec) {
356
+ const totalFiles = spec.entries.reduce((sum, e) => sum + (e.count ?? 1), 0);
357
+ const padWidth = String(totalFiles).length;
358
+ let globalIndex = 0;
359
+ for (const entry of spec.entries) {
360
+ const { count = 1, ...fileSpec } = entry;
361
+ for (let i = 0; i < count; i++) {
362
+ yield generateFile(fileSpec, {
363
+ index: globalIndex,
364
+ seed: spec.seed,
365
+ padWidth
366
+ });
367
+ globalIndex++;
368
+ }
369
+ }
370
+ }
371
+ async function writeCollectionFromSpec(spec, outDir) {
372
+ const root = resolve2(outDir);
373
+ mkdirSync2(root, { recursive: true });
374
+ const manifest = [];
375
+ for await (const file of generateCollectionFromSpec(spec)) {
376
+ const filePath = resolve2(root, file.filename);
377
+ await writeFile(filePath, file.buffer);
378
+ manifest.push({ path: filePath, type: file.type, index: file.index });
379
+ }
380
+ return manifest;
381
+ }
382
+ export {
383
+ generateCollectionFromSpec,
384
+ generateFile,
385
+ writeCollectionFromSpec
386
+ };