Skip to content

feat: @dcmjs-org/dicomdir assembly — DICOMDIR reading and writing - #575

Merged
wayfarer3130 merged 10 commits into
1.0-betafrom
release/1.0-beta-dicomdir
Oct 19, 2026
Merged

wayfarer3130 merged 10 commits into
1.0-betafrom
release/1.0-beta-dicomdir

Conversation

@awatson1978

@awatson1978 awatson1978 commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

This is the assembly PR for the dicomdir package: it brings release/1.0-beta-dicomdir into 1.0-beta, carrying wave PR #573 and its follow-up #580 on top of the core branch. Like the other assemblies (#542, #543) it's open as a draft on purpose — please don't merge it yet; the landing order in RELEASE_PLAN.md section 6 means the assemblies go in deliberately, not as soon as they're green.

What this is in plain terms. A DICOMDIR is the index file at the root of a patient CD, DVD, or USB stick — the Media Storage Directory of PS3.10 / PS3.3 Annex F. It's what lets a workstation show the patients, studies, and series on the disc without opening every file. @dcmjs-org/dicomdir builds and writes one: you hand writeDicomDir a flat list of file-set entries (one per file on the media, with its path, SOP identity, and patient/study/series attributes), and it builds the PATIENT → STUDY → SERIES → leaf directory record hierarchy, computes the real byte offsets that chain the records together, and serializes the complete Part 10 file in a single pass. The interesting engineering fact is in how those offsets are computed: every DICOMDIR offset attribute is VR UL — a fixed four bytes — so the values never affect the layout, and one measurement pass with placeholder zeros yields the exact offsets of the final file. No patch-and-rewrite, no buffer scanning.

The package depends on @dcmjs-org/core and nothing else at runtime — and that claim is now enforced, not just implied by the imports. The v2 code this was ported from leaned on what is now @dcmjs-org/legacy in two places (size measurement through DicomMessage.write, and serialization through DicomDict.write); both were rebuilt on core's writeDataSet/writeTagObject primitives — the exact functions those legacy statics delegate to — and I verified the inlined Part 10 envelope byte-identical against legacy DicomDict.write on the same denaturalized { meta, dict } before relying on the argument (details in #573). Then, while verifying this PR's worked example in a clean process, I found core's sequence writer still reached for the late-bound DicomMessage that only legacy registers — so the package worked only when legacy happened to be loaded. #580 fixes that at the root (core's writeCore.js registers writeDataSet into the sequence writer's seam at load) and adds a standalone regression test that imports nothing from legacy and checks the written bytes directly.

A worked example (run on this branch, in a process with no legacy engine loaded — that's exactly what packages/dicomdir/test/standalone.test.js pins):

import { writeDicomDir } from "@dcmjs-org/dicomdir";

const arrayBuffer = writeDicomDir(
    [
        {
            referencedFileID: ["DICOM", "IM000001"],
            sopClassUid: "1.2.840.10008.5.1.4.1.1.4",
            sopInstanceUid: "1.2.3.4.100",
            transferSyntaxUid: "1.2.840.10008.1.2.1",
            patient: { PatientID: "998877", PatientName: "DOE^JANE" },
            study: { StudyInstanceUID: "1.2.3.4" },
            series: { SeriesInstanceUID: "1.2.3.4.5", Modality: "MR" },
            instance: { InstanceNumber: 1 }
        }
    ],
    { fileSetID: "MY_CD" }
);
// arrayBuffer is a complete DICOMDIR; write it to the media root.

And reading one back — a DICOMDIR is an ordinary Part 10 file, so any engine reader handles it; here's the streaming path (run on this branch, output verbatim):

import { fromPart10, NaturalizedListener } from "@dcmjs-org/parser";

const listener = new NaturalizedListener();
await fromPart10(arrayBuffer, listener); // or fromPart10Stream for media too big to buffer

const dir = listener.result;
dir.DirectoryRecordSequence.map(r => r.DirectoryRecordType);
// ["PATIENT", "STUDY", "SERIES", "IMAGE"]

const image = dir.DirectoryRecordSequence[3];
image.ReferencedFileID;                // ["DICOM", "IM000001"]
image.ReferencedSOPInstanceUIDInFile;  // "1.2.3.4.100"
// and the meta group confirms what it is:
// MediaStorageSOPClassUID "1.2.840.10008.1.3.10" (Media Storage Directory)

To be plain about scope: the package exports the builder and writer; there is no dedicated DICOMDIR read API in it, because reading needs nothing special — the records come back as the DirectoryRecordSequence shown above through either engine. If a convenience walker (offset-chasing the lower/next record chains for you) turns out to be wanted, it would be a small additive follow-up here.

buildDicomDirDataset is also exported for inspecting the record tree before serialization.

What's in it. Two PRs. #573 is the port: a scaffold commit (package.json + README), a verbatim v2 commit (three source files and the 16-test suite, byte-for-byte from v2.0-development's src/media/), and the hand-written rewiring onto @dcmjs-org/core. #580 is the standalone fix described above — a small core seam (setWriteDataSet, mirroring the existing DicomMessage seam) plus the no-legacy regression test. Hand-written totals are declared in each PR (~120 and ~100 lines); the ported lines are exempt per the budget convention.

Test evidence. The 17 tests in packages/dicomdir/test/ are fully synthetic — no fixtures. They prove the property that matters by checking the written bytes themselves: every nonzero offset value must land exactly on an FFFE,E000 item tag, the next/lower chains plus the first-root offset must address every record exactly once, the write must be deterministic, and the whole thing must work with no eager engine wired. Full suite on the branch tip: 861 passed / 12 skipped / 873 total (the 844-test core baseline plus these 17), on Node 22 and 24. CI from the merged PRs: #573 tests + build, #580 tests + build, lint/format.

GitHub issues. Honestly: none. I searched the tracker for DICOMDIR and found nothing but the 1.0 RFC (#517) this whole effort serves — dcmjs never had a DICOMDIR builder, so there was no backlog to fix. This is new capability, ported from the v2 rewrite.

Breaking changes. None. The package is purely additive, and the one touch to existing code — the sequence-writer seam in #580 — routes item serialization to the very function DicomMessage.write already delegates to, so bytes are identical whichever package loads first; the full regression suite agrees.

The trunk overlap, so the diff size isn't alarming. release/1.0-beta-dicomdir was cut from the tip of release/1.0-beta-core (e5f46e4), so until the core assembly #542 merges, this PR's diff shows the whole engine stack it sits on. Once #542 is in, this shrinks to just packages/dicomdir/ plus the lockfile and the seam fix. That's the same absorb-the-trunk pattern as the earlier assemblies, and it's the other reason this stays a draft.

🤖 Generated with Claude Code

awatson1978 and others added 6 commits October 2, 2026 12:21
package.json modeled on @dcmjs-org/core's (version 0.0.0, publishable,
MIT, main ./src/index.js, repository directory), depending on
@dcmjs-org/core at runtime and on @dcmjs-org/legacy only as a
devDependency for test readback. Plus a short README with a usage
sample.

Co-Authored-By: Claude Fable 5 <[email protected]>
src/media/dicomdir.js, src/media/directoryOffsets.js, and
src/media/index.js from the v2.0-development branch land as
packages/dicomdir/src/{dicomdir,directoryOffsets,index}.js, and
test/dicomdir.test.js as packages/dicomdir/test/dicomdir.test.js —
byte-for-byte v2 content. Imports still point at the v2 tree; the next
commit rewires them onto @dcmjs-org/core and replaces the DicomDict
dependency.

Co-Authored-By: Claude Fable 5 <[email protected]>
The two legacy imports the v2 code carried are gone, keeping the hard
rule that this package never depends on @dcmjs-org/legacy:

- directoryOffsets.js measured element sizes through DicomMessage.write
  and DicomMessage.writeTagObject; it now calls core's writeDataSet and
  writeTagObject directly — the exact functions those statics are
  one-line delegates to, so measured sizes are unchanged.
- dicomdir.js built a DicomDict and called dicomDict.write(); the Part
  10 envelope (preamble + DICM, meta group behind its group length,
  then the body) is now inlined as writePart10 on the same core
  primitives, minus the deflate branch a DICOMDIR can never take.
  Verified byte-identical against legacy DicomDict.write on the same
  denaturalized { meta, dict }.

The test readback oracle rewires from the root dcmjs facade to
DicomMessage from @dcmjs-org/legacy (devDependency) plus
DicomMetaDictionary and validationLog from @dcmjs-org/core, and the
local EXPLICIT_LITTLE_ENDIAN constant gives way to core's export.

Full suite: 860 passed, 12 skipped, 872 total.

Co-Authored-By: Claude Fable 5 <[email protected]>
feat: port the DICOMDIR builder into packages/dicomdir
Writing a DICOMDIR from @dcmjs-org/dicomdir alone threw: core's
SequenceOfItems.writeBytes serialized each item through the late-bound
DicomMessage, which only @dcmjs-org/legacy (or the dcmjs wrapper)
registers — so the package's hard no-legacy rule held in its imports
but not at runtime. The committed suite never saw it because its
readback oracle imports legacy, wiring the seam as a side effect.

core/writeCore.js now registers writeDataSet into ValueRepresentation
at load (a direct import between the two files is a module-level CJS
cycle that breaks Tag's registration, hence the seam), and the
sequence writer calls that instead of DicomMessage.write — the exact
function DicomMessage.write delegates to, so bytes are unchanged
either way. The new packages/dicomdir/test/standalone.test.js imports
nothing from legacy (jest's per-file module registry guarantees the
seam stays unwired) and proves a full DICOMDIR write: DICM magic,
four undefined-length item headers for PATIENT/STUDY/SERIES/IMAGE,
deterministic bytes.

Full suite: 861 passed, 12 skipped, 873 total.

Co-Authored-By: Claude Fable 5 <[email protected]>
fix: let core's sequence writer run with no eager engine loaded
…ented

GHSA-vfj7-8cjw-p6xm was published 2026-10-02 with a claimed fix range of
>=3.0.4, but no such braces release exists on the registry, so there is
nothing to override to. Every path is dev tooling; braces never reaches
the published packages. Same entry the fhir staging branch already
carries (#589) — remove it the moment a patched braces ships.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 7261970)
awatson1978 and others added 2 commits October 3, 2026 10:22
Per review on #542: the guide existed to hold the staged-landing PR
descriptions to one standard, and every description is now written.
Removed rather than kept stale; git history preserves it if the team
wants it back later. The PR template keeps the one-line spirit of it.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 2a5935e)
…dicomdir

# Conflicts:
#	packages/core/src/ValueRepresentation.js
#	packages/core/src/core/writeCore.js
#	pnpm-workspace.yaml
@awatson1978
awatson1978 marked this pull request as ready for review October 19, 2026 06:35
@@ -0,0 +1,79 @@
// packages/dicomdir/test/standalone.test.js
//
// The package's reason to exist is running without the legacy engines, so

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new 1.0 dcmjs reason to exist is to run without the elgacy engine, but the dicomdir REASON is to provide dicomdir functionality to write and read dicomdir formatted directories.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy that. The package's purpose is to build and write DICOMDIRs. Running without the legacy engine is a separate promise that 1.0 makes on top of that. I've reworded the comment: this test file is here to prove the no-legacy promise, and that framing is now in the test instead of being pinned to the whole package.

Comment thread packages/dicomdir/README.md Outdated
```js
import { writeDicomDir } from "@dcmjs-org/dicomdir";

const arrayBuffer = writeDicomDir(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fine for creation, but does nothing for getting an index or "qido" type search results from a dicomdir. Writing is thus only about half the package functionality - I'm fine with that right now, but leave it as a clearly open issue on the package support.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed as #611. The idea is a reader that walks the directory tree for you, plus a way to search it the way QIDO does (give me the studies/series on this disc, find the series with this modality, and so on). I've left it as a follow-up on purpose so the write side can land first, per RELEASE_PLAN.md section 6. The README now says plainly that the read side isn't built yet and links to the issue.

@wayfarer3130 wayfarer3130 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally this is a good demonstration of the streaming support, and provides write functionality, but it looks like from the readme it only supports a single series, not multiple studies, and doesn't have any read functionality to automatically index.
I'd also like confirmation that this will create/write huge DICOM files to a dicomdir - that would confirm it is using the streaming functionality correctly. That test doesn't have to run every time, but I think it would be useful to run the video test through this at least as a "long test" option.

…y support

Addresses review on PR #575:

- README: add a two-patient/two-study example and state that grouping by
  patient/study/series is automatic. The single-entry example read as
  single-series only.
- standalone.test.js: reword the header so the no-legacy framing belongs to
  the test (which pins it), not to the package (whose purpose is building and
  writing DICOMDIRs).
- Add mediaRoundTrip.long.test.js, gated on DCMJS_LONG_TESTS: stream a
  multi-GiB video to disk, index it in a DICOMDIR, then read the media back
  via fromPart10Stream with a zero-retention listener. Verified at 3 GiB
  under a 512 MB heap cap. Pulls in @dcmjs-org/parser as a devDependency.
- README: link #611 for the follow-up read/index/QIDO API.

Co-Authored-By: Claude Fable 5 <[email protected]>
@awatson1978

Copy link
Copy Markdown
Collaborator Author

Three things from your review:

Multiple studies and series. It does handle them — the single-entry example in the README made it look more limited than it is. Internally the entries get grouped by patient, then study, then series, and the records are chained correctly at each level. The tests already cover this (one checks two patients chaining as siblings; another checks the root first/last pointers across two patient records). I've added a two-patient, two-study example to the README so this is obvious from the docs.

Huge files. Point of clarification — a DICOMDIR doesn't contain any image data. It only holds file paths and a few identifying attributes per file, so the size of writeDicomDir's output doesn't change with how big the referenced files are — the DICOMDIR written in these tests is under 4 KB no matter what it points at. The part of a real workflow that actually has to handle large files is reading the referenced files back, and that has to use the streaming reader. So I added a long test (off by default, turned on with DCMJS_LONG_TESTS=1): it writes a multi-gigabyte video file to disk, builds a DICOMDIR that indexes it, then reads the whole thing back — opens the DICOMDIR, follows the file reference to the video, and streams the video through the parser with a listener that throws the bytes away as they arrive. I ran it with a 3 GB file and the heap capped at 512 MB and it passed, which it couldn't do if the reader were holding the file in memory. (The streaming reader's memory limits are also covered on their own by the existing K5b tests under test/eventStream/.)

Reading and indexing a DICOMDIR. Agreed this is about half of what the package should eventually do. Filed as #611 and called out in the README, kept as a follow-up so the write side can land first.

@wayfarer3130
wayfarer3130 merged commit f0de337 into 1.0-beta Oct 19, 2026
10 checks passed
@wayfarer3130
wayfarer3130 deleted the release/1.0-beta-dicomdir branch October 19, 2026 17:17
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 1.0.0-beta.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants