Repository navigation
feat: dcmjs 1.0 rewrite — event streaming, bounded-memory large files, FHIR, video, DICOMDIR - #512
Closed
awatson1978 wants to merge 138 commits into
Closed
awatson1978 wants to merge 138 commits into
awatson1978 wants to merge 138 commits into
Conversation
…npm monorepo Step 1 + R0 of docs/REWIRING-PLAN.md: - pnpm workspace now includes packages/*; @dcmjs/parser is a private workspace package (vendored dicom-parser src, testImages corpus, d.ts) - all 13 mocha/chai suites ported to jest (195 tests, offline) - R0 fixes with 44 new tests: warnings.push crash fix and findAndSetUNElementLength removal, dataSet string()/text() index footguns, omitPrivateAttributes rename, stable 14-field element shape with tagValue/startOffset/endOffset spans, bulk fragment copy, scratch-buffer float reads, numeric delimiter peeks, VR lookup table - babel.config.js declares babelrcRoots so package-level .babelrc works; root .babelrc/rollup output unaffected Co-Authored-By: Claude Fable 5 <[email protected]>
- bench:parser — vendored tokenizer vs published [email protected] over the 23-file corpus; gate: geomean <= 1.10, per-file <= 1.25. Current: geomean 0.84 (vendored faster on every file, best 0.60) - gate:parser-bundle — rollup self-containment proof: 29 modules all under packages/parser/src, zero external imports, no dictionary or pako bytes, 88.5 kB ESM, side-effect-free import in a child process Co-Authored-By: Claude Fable 5 <[email protected]>
…, R1+R2)
src/lazy/LazyDicomReader.js: readFileLazy builds DicomDict over
@dcmjs/parser offset elements — getter-backed Value/_rawValue with a
windowed ReadBufferStream + the existing VR classes, eager-exact charset
handling (ISO_IR 192 rewrite, per-item decoders), implicit VR via the
dictionary as vrCallback, structural SQ wrap (no byte rescans),
encapsulated frames from fragment/BOT indexes, deflate via injected
pako inflater, untilTag/includeUntilTagValue/noCopy/forceStoreRaw
parity, ignoreErrors honored at materialization, whole-file eager
fallback for tokenizer-rejected streams.
DicomMessage.readFile gains options.core ('eager'|'lazy'); default
remains eager (DCMJS_CORE env override for CI).
Tokenizer hardening from review probes: UV/SV/OV 4-byte framing,
eager-aligned unknown-VR fallback, explicit FFFE delimiter framing,
deflate dataset stream no longer re-walks the preamble.
Gates: equivalence matrix 150/150 fixture-x-option cells; full dcmjs
suite passes identically on both cores (535 tests); parser suite 245;
bench geomean 0.84 vs published; bundle gate green.
Co-Authored-By: Claude Fable 5 <[email protected]>
…plan step 5, R4) - Tag.write writes directly into the destination stream with 16/32-bit length backpatching; temp-stream-per-element and double-copy concat removed (SR-tree writes 1.76x faster, large values 3.23x); output bytes proven identical across 22 adversarial boundary datasets incl. explicit big endian and Big16 UN substitution - passthrough: clean lazy entries (un-edited, charset-safe, same body syntax) emit verbatim source bytes; >=64KB spans as zero-copy windows; byte-identity suite over the corpus; structural SQ edit detection, non-default writeOptions disable passthrough, window-aware geometric growth (probe: 199MB -> 4KB allocated) - deflate-on-write for 1.2.840.10008.1.2.1.99 (uncompressed meta + raw-deflated ELE body) — also fixes the pre-existing bug where a deflated TSUID silently wrote an uncompressed body - SplitDataView: writableAllocated accounting, spare-capacity reuse, writeBuffer honors typed-array byteOffset (latent bug) Gates: 620 tests green on both cores; parser 245; bench geomean 0.84; bundle gate clean. Co-Authored-By: Claude Fable 5 <[email protected]>
… 6 + scoped R6) BREAKING CHANGES for 1.0: - DicomMessage.readFile defaults to the lazy offset-tokenizer core (DCMJS_CORE=eager or options.core restore the old reader); both cores pass the full 635-test suite identically - removed deprecated DicomMessage.read/readTag statics (warned since 0.24) and the legacy DICOMWEB class (use dicomweb-client) - log: named child logger 'dcmjs'; importing dcmjs no longer calls setLevel on the global loglevel root Also: - DicomMetaDictionary.nameMap is lazily built on first access (was ~5000 objects at import time) - BufferStream: readUint16Array off-by-one fixed (increment-before-test loop); shared default TextDecoder/TextEncoder singletons - SplitDataView: cached last-hit chunk index fast path for sequential streaming reads - version 1.0.0-beta.0 (not published) Gates: 635 tests green on default(lazy) and DCMJS_CORE=eager; parser 245; bench geomean 0.846; bundle gate clean; rollup build OK. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…ME for 1.0 - new @dcmjs/docs workspace package (Docusaurus 3, blog disabled, onBrokenLinks: throw): 18 pages covering getting started, the layered architecture (parser package, lazy core, writer, dictionary, streaming), guides (reading options, writing/editing rules under passthrough, naturalized datasets, character sets, deflate), migration from 0.x and from standalone dicom-parser, performance numbers and gates, contributor monorepo guide, and the 1.x roadmap with the open API decisions - content written against the actual source with verified references; production build green - README: 1.0 architecture summary, updated status/backlog, monorepo and docs commands, child-logger logging note, dictionary file fixes - pnpm-workspace: trust-policy exclusion for a docusaurus transitive dep (detect-port) and explicit allowBuilds decisions (@swc/core true, core-js false) Co-Authored-By: Claude Fable 5 <[email protected]>
…to a cookbook - migration/before-and-after.md (new): what dcmjs 0.x was and how 1.0 changed under an unchanged API — the identical usage snippet annotated under both engines, plus Unchanged / Changed semantics / Removed / Added inventory tables and the derivability rationale - migration/from-0x.md: rewritten as a before/after cookbook across ten areas (reading + error placement, ignoreErrors recipes, escape hatches, assignment-based editing with wrong/right pairs incl. in-sequence edits and the SQ structural safety net, byte-identity writing, deflate, removed APIs, logging, lazy nameMap, no-migration checklist) - every runnable example empirically executed against build/dcmjs.js with real fixtures; three doc inaccuracies found and fixed by the verifier (over-absolute 0.x round-trip claim, whole-file identity preamble caveat, ignoreErrors listed as unchanged while documented as changed) - sidebar gains the before-and-after entry; docs build green Co-Authored-By: Claude Fable 5 <[email protected]>
…docs/REWIRING-PLAN.md The roadmap page (packages/docs/docs/development/roadmap.md) now carries the full step-by-step plan toward the final JS DICOM reader/writer: vision, status table, founding decisions, the complete R0-R8 sections with per-section status, the R8 gate checklist, 1.x backlog, and the four open API decisions. docs/REWIRING-PLAN.md is removed (history in git); all references in README, test comments, src/lazy docblocks, and docs pages now point at the roadmap. Co-Authored-By: Claude Fable 5 <[email protected]>
The original 31-agent analysis report that seeded the 1.0 merge: scorecard, merge direction verdict, module-level merge map, verified performance/DevX optimization targets, and migration roadmap. The living plan derived from it is the docs-site roadmap page. Co-Authored-By: Claude Fable 5 <[email protected]>
…slice A)
Introduces the keystone of the Unified dcmjs architecture: a documented,
versioned, conformance-tested event-stream contract that every reader, writer,
listener, and filter speaks. Formalizes the implicit DicomMetadataListener model
into an explicit vocabulary (startElement/startSequence/startItem/value plus a
binary fragment sub-stream and bulkDataReference), per the Naturalized DICOM
Metadata Behavior Specification §15.1.
Design (see CLAUDE_REFACTOR_ANALYSIS.md for the decision log):
- Hybrid model: push/callback core is canonical; an async-iterator adapter sits
on top for ergonomic consumers.
- Sync structural/value callbacks (allocation-free hot path, §15.4/§24.1);
backpressure only at defined checkpoints via setDrain/awaitDrain.
- Binary = startBinary/binaryFragment/endBinary (boundaries preserved, §33) plus
bulkDataReference for unfetched URIs (§26).
- File Meta Information as a leading bracketed sub-stream; optional sourceSpan on
structural events for the future passthrough writer.
Components under src/eventStream/ (exposed as dcmjs.eventStream):
- EventStreamListener: push core + next-middleware chain + backpressure
- fromDataSet: reference generator (walks a parsed dataset, emits the contract)
- CollectorListener: rebuilds a {meta,dict} tree to validate round-trips
- asyncIterator: pull adapter with real backpressure
Verification: 79 slice-A tests (red-first), incl. corpus round-trip equivalence
over 30 fixtures (plain LE/BE/implicit, deflate, encapsulated single/multi-frame),
well-formed nesting, and loss preservation (§15.1). Full suite green on both
cores (959 tests; lazy and DCMJS_CORE=eager).
Scope: the reference generator walks the parser-derived decoded dataset (spec §32
tag-source path); the from-raw-bytes Part 10 generator is slice B, and _rawValue
raw retention is slice D.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
fromPart10(buffer, listener, options) walks @dcmjs/parser's offsets tree in source order and emits the event-stream contract directly from Part 10 bytes, reusing dcmjs's public decode primitives (ReadBufferStream, ValueRepresentation .read, encodingMapping, DicomMessage.lookupTag) plus faithful copies of the small pure helpers (resolveVrInstance, shapeReadValues). This is the genuine bytes->events path and the streaming foundation. Design (see CLAUDE_REFACTOR_ANALYSIS.md D8/D9): - Common path handled directly: explicit/implicit LE + big-endian, sequences (defined + undefined length), encapsulated pixel data as RAW fragments (§33), defined-length binary as a one-fragment sub-stream, SpecificCharacterSet. - Hard cases delegate to the lazy core for the whole file (byte-equivalent by construction): deflate transfer syntax, and undefined-length non-SQ / unknown-VR elements (detected mid-walk -> abort -> fromDataSet(readFile)). - Leaf elements route by DECODED value type (ArrayBuffer -> binary sub-stream; else value()), not by isBinary() -- which in dcmjs is true for numeric VRs (SL/SS/US/UL/FL/FD/AT/UV) that decode to numbers, not byte blobs. The trapped decode core (closures inside readFileLazy) is intentionally NOT refactored here; extracting it into a shared "one read core" module is a scheduled follow-up. Verification: synthesized explicit-LE round-trip + 31-fixture corpus gate (fromPart10 -> CollectorListener vs readFile): non-binary tags exact, binary at concatenated-fragment-byte level, group-length and SpecificCharacterSet exempt (readFile strips/rewrites them). Full suite green on both cores (990 tests). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
fromDicomWebJson(json, listener) walks the DICOM JSON model and emits the
event-stream contract as a low-allocation visitor (§24.1), proving the
source-agnostic claim (§4.4): the same contract a Part 10 reader produces is now
produced from a third source.
Design (see CLAUDE_REFACTOR_ANALYSIS.md D10): values are emitted AS-IS — Person
Names stay DICOMweb {Alphabetic} objects, numbers stay numbers — and cross-source
value canonicalization (PN proxy §17, IS/DS §28) is deferred to the naturalized
listener (slice D), keeping slice boundaries clean. Binary forms per spec:
BulkDataURI -> bulkDataReference (unfetched, §21); InlineBinary base64 -> decoded
buffer fragment (§22). File Meta (group 0002) is emitted as a leading sub-stream
when present.
Verification: vocabulary/round-trip incl. nested SQ + PN objects, both binary
forms, backpressure, and a source-agnostic structural check asserting DICOMweb
JSON and a dcmjs dict produce identical event/tag structure. Full suite green
(995 tests). The exhaustive corpus-wide cross-source value matrix is slice G.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NaturalizedListener consumes the event-stream contract and builds the
application-facing naturalized object per the Naturalized DICOM Metadata
Behavior Specification: canonical keyword keys (§5, via lookupTagHex) and
VM-driven cardinality (§7-§14). Because it consumes the source-agnostic
contract, the SAME object is produced from Part 10 bytes, a dcmjs dict, or
DICOMweb JSON -- the §4.4 payoff.
Cardinality rules: scalar VM (1/0-1) -> scalar, present-empty -> null; multi VM
(1-n, 2-n, ...) -> always list-like, present-empty -> []; single-item sequence ->
the item object with hidden length 1 (reusing the shared addAccessors proxy);
empty sequence -> []; multi-item sequence -> array. Binary fragments assemble to
{InlineBinary}; bulkDataReference -> {BulkDataURI}. Cardinality-violation policy
(§15.2) defaults to warnAndPreserve (configurable), with violations exposed on
listener.violations.
Key interpretation (D12): a sequence's declared VM ("1") constrains attribute
occurrence, NOT item count -- multi-item sequences like
PerFrameFunctionalGroupsSequence are normal, not violations. Violations apply
only to non-SQ scalar VRs exceeding their declared VM.
Deferred to D2 (per D11): PN proxy/toString sugar (§17, open spec decision),
private-tag grouping (§18), precision/raw retention (§16/§27, which needs the
contract to carry raw values). The underlying PN {Alphabetic} value already
matches across sources today.
Verification: 43 tests -- full §14 VM table, sequences, binary/meta, a
generator-agnostic corpus gate (fromPart10 vs fromDataSet naturalize identically
across all fixtures, modulo the known SpecificCharacterSet rewrite and binary
frame-grouping), and a three-source agreement check. Full suite green on both
cores (1038 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
DicomWebJsonWriter is an event-stream consumer that writes the DICOM JSON model
-- the faithful inverse of fromDicomWebJson. It makes the contract a SINK as well
as a source, so the architecture round-trips and any source can be serialized to
DICOMweb JSON.
Output per tag: { vr, Value } / { vr, BulkDataURI } / { vr, InlineBinary base64 }.
Person Names pass through as the DICOMweb {Alphabetic} objects the contract
carries. Binary source form is preserved (§25): a bulkDataReference stays a
BulkDataURI; assembled binary fragments become base64 InlineBinary.
This is E1; the heavy Part 10 byte writer (verbatim passthrough via sourceSpan,
§26 BinaryOutputMode) is E2.
Verification: JSON -> events -> JSON identity (scalars, PN, sequence, BulkDataURI,
InlineBinary), and an end-to-end round-trip bytes -> events -> DICOMweb JSON ->
events -> naturalized that equals the direct naturalize (plain/implicit LE + deep
SR). Full suite green on both cores (1043 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The recommended ergonomic API from spec §32, as thin wrappers over the generators and listeners built in slices A-E1: const events = DicomEventStream.fromPart10(bytes); const metadata = await Naturalized.from(events); // or events.toNaturalized() const json = await DicomWebJson.from(events); // or events.toDicomWebJson() DicomEventStream wraps a re-runnable run(listener) thunk with .fromPart10/.fromDicomWebJson/.fromDataSet factories and .process/.toNaturalized/.toDicomWebJson/.toDataSet/.asyncIterable methods; the §32 sink helpers Naturalized.from / DicomWebJson.from delegate to them. Sources are reusable, so one source can drive multiple sinks. Verification: 5 tests (toNaturalized from JSON and from Part 10 bytes, static vs instance equivalence, source reuse, async iteration). Full suite green (1048). Compat wrappers over legacy DicomMessage/naturalize APIs remain a follow-up. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…or slice D2a)
Resolves the spec's open §17 decision. In NaturalizedListener, PN values get
non-enumerable toString()/toJSON() via the existing dicomJson.pnAddValueAccessors:
- VM 1 -> the {Alphabetic, Ideographic, Phonetic} object itself, so
PatientName.Alphabetic works directly, and String(PatientName) returns the
raw PN string ("Wallace^Bill").
- VM n -> array of those objects, with array-level toString() joining the
component strings with the DICOM value delimiter.
Reuses dcmjs's shared PN accessor helper; no contract or generator change (PN
objects already arrive identically from all three sources). Accessors are
non-enumerable, so the generator-agnostic cross-source corpus gate is unaffected.
toJSON serializes to the DICOM JSON model (PN Value as an array of component
objects), matching dcmjs's existing convention.
First piece of D2; private-tag grouping (§18, D2b) and precision/raw retention
(§16/§27, D2c, needs a contract extension) follow.
Verification: VM-1 component access + stringification, VM-n array + delimiter
join, present-empty stays null, JSON round-trip shape. Full suite green on both
cores (1051 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…actor slice D2b)
NaturalizedListener now groups private attributes per §18. Private data elements
are nested under a "<slot>:<CREATOR>" key carrying originalTagOffset and
block-relative (low-byte) element keys (§18.1):
(0029,0010) LO "SIEMENS CSA HEADER" -> defines slot 0x10
(0029,1010) "csa-value" -> "10:SIEMENS CSA HEADER": {
originalTagOffset: 0x10, "10": "csa-value" }
Private creators are recorded per dataset level and are NOT emitted as ordinary
attributes (§18.5); private data with no identifiable creator keeps a full-tag
{ vr, Value } unknown shape (§18.4); grouping is scoped per dataset level, so
sequence items carry their own creators. Element/sequence placement is routed
through shared private-aware helpers, so private sequences group too.
Applies identically regardless of source, so the generator-agnostic cross-source
corpus gate stays green. Deferred: registered private names (§18.2), which need a
creator-qualified lookupPrivateTag; numeric block-relative keys are used for now.
Verification: grouping with block-relative keys, creatorless full-tag fallback,
per-level creator scoping in sequence items. Full suite green on both cores
(1054 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…del (§18.2)
Completes private-tag grouping (§18). The naturalized listener now resolves the
registered private name for a private data element via lookupPrivateTag with the
creator-qualified key `(gggg,"CREATOR",ee)`, and uses it as the block-relative
nested key when the entry is known, meaningful (name !== "Unknown"), and
non-colliding within the group:
(0029,0010) LO "SIEMENS CSA HEADER"
(0029,1010) -> "10:SIEMENS CSA HEADER": { CSAImageHeaderInfo: ... }
(0029,1099) -> "10:SIEMENS CSA HEADER": { "99": ... } // unregistered -> numeric
Names stay scoped to the creator group (no top-level leakage), avoiding
cross-vendor collisions. lookupPrivateTag is imported directly from the packed
private dictionary, so resolution does not depend on registerPrivatesModule
having run. Applies identically across generators, so the cross-source corpus
gate stays green.
Verification: registered-name resolution + numeric fallback for unregistered
offsets + scoping; the existing numeric-grouping test now uses an unregistered
creator. Full suite green on both cores (1055 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…actor slice D2c)
Completes the naturalized value model (D). Adds an optional rawValue payload to
the contract's value event (backward compatible) so precision-preserving
retention (§16/§27) is possible:
- fromPart10: decodeValues now returns parallel { values, rawValues } (string
splits applied to both), emitting value(v, { index, rawValue }).
- fromDataSet: emits rawValue from the dict entry's _rawValue.
- NaturalizedListener: retains the raw source string whenever a numeric value's
shortest decimal (value.toString()) cannot reproduce the source string -- a
VR-agnostic round-trip check, so normal values keep their JS number. Default
matches §27 "inexact only".
Gotcha (see CLAUDE_REFACTOR_ANALYSIS.md D14): the spec's "large integer" example
cannot be an IS (capped at 12 chars, never overflows). The real case is DS
(<=16 chars), whose double can drop the final digit; the rule is therefore
round-trip-based, not VR-specific. fromDicomWebJson carries no raw, so
JSON-sourced numbers stay numbers.
Verification: DS retention (unit + end-to-end through fromPart10 and fromDataSet),
exactly-representable decimals (incl. trailing zeros) keep their number, no-raw
keeps the number. Cross-source corpus gate stays green (both Part-10 generators
emit raw identically). Full suite green on both cores (1060 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e G)
Proves §31/§4.4 across the whole corpus: for every local fixture, the
naturalized object is built three independent ways and asserted identical:
1. raw Part 10 bytes -> fromPart10
2. parsed dcmjs dict -> fromDataSet
3. DICOMweb JSON -> fromDicomWebJson, where the JSON is itself produced from the
bytes through the writer (bytes -> events -> DicomWebJsonWriter), exercising
the contract as both source and sink.
Comparison is semantic (§31): binary leaves collapse to a placeholder
(raw-fragment vs frame grouping differs by path), single-item sequence proxies
compare structurally, SpecificCharacterSet is exempt (readFile's ISO_IR 192
rewrite). All 30 fixtures pass. Full suite green (1090 tests).
This capstone was only possible once E1 (DicomWebJsonWriter) existed to generate
DICOMweb JSON from the fixtures.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Part10Writer is an event-stream sink that produces DICOM Part 10 bytes, making
the architecture fully bidirectional. It is a thin LAYER over the canonical
encoder, not a second encoder: it collects the event stream into a tag-keyed
{ meta, dict } (reusing CollectorListener) and delegates serialization to the
proven DicomDict.write() -- every VR, undefined-length sequences, deflate,
padding, Big16, and FileMetaInformationGroupLength recompute. Exposed as
dcmjs.eventStream.Part10Writer and DicomEventStream.toPart10(writeOptions).
Architecture decision (see CLAUDE_REFACTOR_ANALYSIS.md D15): the user asked
whether a streaming encoder would replace the old writer or just duplicate it.
The existing DicomMessage.write is already the canonical byte-faithful encoder
(incl. R4 verbatim passthrough), and byte-identical Part 10 round-tripping is an
explicit non-goal of the event/naturalized path (spec §4.5), already served by
the lazy-read + passthrough-write path. So a streaming event encoder would
duplicate, not replace -- this layered reuse is the correct, non-duplicative
solution. A streaming + passthrough encoder is deferred until streaming writes of
giant datasets are a real need.
Drops any collected group-length so it isn't double-counted; forwards write
options (e.g. allowInvalidVRLength for malformed round-trips).
Verification: synthesized round-trip (scalars/PN/sequence/meta) + a 30-fixture
corpus semantic round-trip (bytes -> events -> Part 10 -> readback naturalizes
identically). Full suite green on both cores (1122 tests).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Drives NaturalizedListener with a 100k-item PerFrameFunctionalGroupsSequence (~76 ms) and a 500-deep recursive ContentSequence (~16 ms), asserting correct reconstruction at both extremes. The depth-bounded frame stack scales linearly, so the spec's §15.4 "suitable for very large datasets" requirement holds without state-by-depth pooling. Validate-first: no premature optimization; deeper allocation tuning stays a future option if a real workload demands it. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adoption ergonomics for the §32 public API: DicomEventStream.from(source) dispatches by source type so callers don't have to pick the right factory -- ArrayBuffer/typed array -> Part 10 bytes; an object with dict/meta -> parsed dataset; any other object -> the DICOM JSON model; otherwise throws. Combined with the toNaturalized/toDicomWebJson/toPart10 sinks, this is the friendly front door for migrating existing call sites onto the event architecture. Verification: from() detection for all three source kinds + throw on unknown. Full suite green on both cores (1128 tests). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Documents the four follow-ups that intentionally fall outside the incremental A–G flow and each warrant their own brainstorm → design → plan cycle: R1 legacy compat wrappers (behavior-changing, not drop-in), R2 streaming+ passthrough Part 10 encoder (a second encoder, deferred per D15 until giant streaming writes are real), R3 "one read core" extraction (risky refactor of the 56KB lazy core to remove fromPart10's delegation), R4 §15.4 low-alloc micro-tuning (only on a profiled need). Each entry records why a planning pass is needed and a scope sketch / trigger. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds two docs-site pages and wires them into the sidebar: - guides/event-streams.md — the practical API + usage reference: DicomEventStream sources (fromPart10/fromDicomWebJson/fromDataSet/from) and sinks (toNaturalized/toDicomWebJson/toPart10/toDataSet/process/asyncIterable), the naturalized model's behaviors (keyword keys, VM cardinality, sequences, PN, private grouping, binary, precision, meta, cardinality policy), writing, custom listeners/filters, the low-level generators, and an API summary. - architecture/event-stream.md — the conceptual model: the four layers, the contract vocabulary and invariants (loss preservation, well-formed nesting, transport-only binary, out-of-band diagnostics, optional sourceSpan), the relationship to the read/write cores, and source-agnostic equivalence. Examples and signatures verified against src/eventStream (e.g. fromPart10(buffer, listener, options); DicomEventStream factories/sinks). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Record Steve Pieper's external review of the Architecture Proposal as decision-log entries D16-D25 in CLAUDE_REFACTOR_ANALYSIS.md: - D16 byte identity (REVISED: the body-level byte-identity guarantee already exists on the lazy+passthrough path - writer.md:167, write-passthrough.test.js:275; remaining gaps are meta group, deflate wrapper, and the event/naturalized path) - D17 File System Access API browser sink - D18 naming (events -> dicomEventStream, materialize -> naturalize) - D19 oracle/corpus (pieper/dicompare + IDC + phantom generator; corrected stale fixture-gap list - big-endian/deflate/encapsulated fixtures already exist) - D20 conformance validation layer (new scope) - D21 normalization as opt-in transform, out of preserve-first core - D22 machine-readable schema as a component-1 deliverable - D23 no Part 10 ordering case forces whole-header buffering - D24 reword "progressive SEG" example - D25 dicom-curate is a dcmjs consumer working around the exact defects 1.0 fixes; integrate by adopting its rule engine and migrating it onto the event-stream contract Plan updates: add proposed slices H (conformance validation) and I (curation via dicom-curate) with shared D22 schema prerequisite; add parser import-cycle risk note to R3. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Approved design for the machine-readable naturalized schema: rule catalog as source of truth, TS + JSON-Schema projections, VR-format rule depth, dcmjs/schema subpath export - D26: slices H & I confirmed in scope (optional sinks; proceed without blocking on reviewer bandwidth) - D27: D22 design decisions with options considered - Plan: H/I flipped from proposed to in-scope Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
sedghi
requested changes
Sep 16, 2026
sedghi
left a comment
Collaborator
There was a problem hiding this comment.
I did a quick glance and had some comments. The blocker for review is the english style anthorpic models use to comment (more recently) which just gives headache to read. We need to revisit the language.
On the structure. I"m wondering if it makes sense to have @dcmjs/fixtures to have all dicom files and test images etc etc and @dcmjs/tests (not published) that we have tests. Right now fixtures and tests are all spread in many folders
Great first draft, great work
This was referenced Sep 16, 2026
awatson1978
added a commit
that referenced
this pull request
Sep 30, 2026
ReadBufferStream adopted a view's whole backing ArrayBuffer and dropped the byteOffset, so a pooled Uint8Array view either failed the DICM header check against pool junk or silently parsed a neighbouring file's bytes. The Node-only Buffer.offset property also seeded the read offset, which only cancelled out while the whole pool was adopted. The constructor now adopts exactly the viewed byte range, normalized to logical offset 0, and seeds the offset from the source only when it is a BufferStream sub-stream. Closes review finding 1 of the PR #512 review map, and flips the KNOWN GAP #311 pooled-view equivalence test to green. Co-Authored-By: Claude Fable 5 <[email protected]>
This was referenced Sep 30, 2026
awatson1978
added a commit
that referenced
this pull request
Sep 30, 2026
…erstated An overstated File Meta Information Group Length used to pull dataset elements into dicomDict.meta with no warning and drop them from dicomDict.dict. readFile now checks that the declared window holds only group-0002 elements; when it does not, it warns and re-walks the meta group structurally, framing the body at the first non-meta element. Understated lengths and the allowMissingHeader / missing group-length leniencies are unchanged. Also adds the missing TagHex.MediaStorageSOPClassUID constant, which the sampleDicomPart10 test helper referenced; without it the helper wrote that element under a garbage (0000,000F) tag inside the meta group of every synthetic sample file. Pins review finding 24 from the PR #512 review map. Co-Authored-By: Claude Fable 5 <[email protected]>
This was referenced Sep 30, 2026
Merged
wayfarer3130
added a commit
that referenced
this pull request
Oct 20, 2026
* feat(pdfs): scaffold the @dcmjs-org/pdfs workspace package The package manifest (publishable under the @dcmjs-org scope, main at src/index.js, repository directory set), a short README, and the lockfile entry linking the one dependency, @dcmjs-org/core. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(pdfs): port the encapsulated PDF builder and extractor from v2 A verbatim port of src/encapsulated/encapsulatedPdf.js from the v2 branch HEAD (including the { InlineBinary } unwrap that postdates the PR #512 review), with its core import rebased onto @dcmjs-org/core and the PDF half of the encapsulated index as the package surface. The video half stays on the v2 branch for the media wave. The eight-test v2 suite comes along, reworked for this branch's engine: the legacy datasetToBuffer / DicomMessage.readFile round-trip becomes denaturalize -> fromDataSet -> Part10Writer -> fromPart10 -> NaturalizedListener, and the last test's read of test/sample-dicom.dcm (provenance still being traced) is replaced by a synthetic MR instance round-tripped through the same pipeline, so neither the package nor its suite touches @dcmjs-org/legacy or the fixture. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(pdfs): slice extraction to EncapsulatedDocumentLength (review finding 16) The pad-trim heuristic strips a real zero byte: the Part 10 writer pads only an odd-length OB value, so a stored even length is ambiguous — the old code trimmed a trailing 0x00 anyway, corrupting an even-length original that genuinely ends in a zero byte (a 10-byte payload ending 0x00 came back as 9 bytes). encapsulatePdf now records EncapsulatedDocumentLength (0042,0015) with the exact original length, and extractEncapsulatedPdf slices to the declared length when present, keeping the trailing-NUL heuristic only as the fallback for files written before the element existed. The four new tests were written first and observed failing against the ported-unfixed code: the even-length zero-tail round-trip (9 bytes back, red), the recorded length element, and the declared-length odd slice; the heuristic-fallback test passed before and after, pinning that files without 0042,0015 still extract exactly. Co-Authored-By: Claude Fable 5 <[email protected]> * ci: ignore the unpatchable braces advisory in audit, scoped and documented 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) * docs: retire the writing style guide now that authoring is done 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) * refactor(encapsulated): rename @dcmjs-org/pdfs -> @dcmjs-org/encapsulated; add sourceInstance compose path Addresses review on PR #577: - Rename the package to @dcmjs-org/encapsulated: it is the home for DICOM's encapsulated-document IODs, with PDF the first to land (CDA/STL/OBJ/MTL to follow). Video stays in @dcmjs-org/video — it is encapsulated pixel data, not a document. Updates package name/description, headers, README, and the RELEASE_PLAN table. - Add an additive options.sourceInstance path to encapsulatePdf: copy the Patient and General Study context off a naturalized instance (or the first of an array) instead of retyping it. Precedence is defaults < sourceInstance < explicit options; the document's own identity (SOP class, Modality, SOP/Series UIDs) is never inherited, so the report lands as a new series within the source study. De-novo stays the default. - 7 new tests cover the compose path (19 in the package suite). The generic module-extraction helper this hand-rolls belongs near core and is tracked separately in #612. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(encapsulated): generic encapsulate() decorator + core hierarchy helpers Addresses the PR #577 review / follow-up conversation with Bill, and closes #612. Core (@dcmjs-org/core): - Add utilities/copyAttributesByLevel.js: patientTags / studyTags / seriesTags / patientStudyTags as Sets (names + coverage mirror cornerstone3D's copyStudyTags.ts for portability), plus copyAttributesByLevel(source, dataLevel) which copies the attributes at or above a level (patient flows down to study / series / instance). Present + non-empty only; _meta/_vrMap not copied. - Export them from the core index. Encapsulated (@dcmjs-org/encapsulated): - Add encapsulate(bytes, options): the generic Encapsulated Document builder. Layered merge defaults < baseDicom < inherited < explicit overrides, then the document payload/encoding pinned on top. Identity guard: SOPClassUID / SOPInstanceUID / SeriesInstanceUID / Modality are never inherited, so a document can't impersonate the source even at series/instance level. A fluent chaining builder is noted as a deferred follow-up. - Add defaults/pdfBase.js: the PDF-identifying base defaults (factory). - encapsulatePdf is now a thin decorator over encapsulate: magic-check, then supply the PDF base + mime type. New instance + dataLevel options; sourceInstance kept as a back-compat alias (maps to instance, dataLevel 'study'). extractEncapsulatedPdf unchanged (finding-16 behavior preserved). - README + public exports updated. Tests: 10 new core tests, 8 new encapsulate tests; the 19 existing encapsulated tests stay green. Full suite 951 passed / 12 skipped / 0 failed. Co-Authored-By: Claude Fable 5 <[email protected]> * chore: ignore local temp/ and tmp/ output Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(core): createInstance with composable base blocks; encapsulate uses it Core (@dcmjs-org/core): - createInstance({ baseDicom, instance, dataLevel, levels, predecessor, ...overrides }): merge base < inherited < overrides. Logs a warning when an inherited Modality or SOPClassUID differs from the base. - Base blocks are objects, functions of a context, arrays, or combineBases(...items); a combined block keeps its parts on .items. Core blocks: patientBase, studyBase, seriesBase, instanceBase, equipmentBase (defaultInstanceBase), plus predecessorBase and nextSeriesNumberBase(seriesList, filter). - The level blocks create new identity only below dataLevel, so dataLevel "series" now joins the source series. The "instance" level is removed; instance values are overrides. - DATA_LEVELS is a list of { name, tags }; extendDataLevels adds tags and a custom list goes in the levels option. PatientAge, PatientSize and PatientWeight are study-level. - deepCloneInstance clones naturalized data, wraps functions, clones promise values, and shares binary unless copyBinary is set. Nothing is frozen. - hierarchicalReferences builds Hierarchical SOP Instance References; predecessorBase uses it for PredecessorDocumentsSequence. Encapsulated (@dcmjs-org/encapsulated): - encapsulate calls createInstance; the bases are compositions: encapsulatedBase = defaultInstanceBase + encapsulatedDocumentBase + predecessorBase, encapsulatedPdfBase adds pdfBase. - MIME type precedence: mimeType > dataset value > base. - The sourceInstance alias and NON_INHERITABLE are removed. - The README splits user and implementation requirements. Tests: the core suites own the level rules; low-value and duplicate tests are removed; the encapsulated suites share test/part10Helpers.js. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Bill Wallace <[email protected]>
wayfarer3130
added a commit
that referenced
this pull request
Oct 21, 2026
…m media factories (#588) * feat(pdfs): scaffold the @dcmjs-org/pdfs workspace package The package manifest (publishable under the @dcmjs-org scope, main at src/index.js, repository directory set), a short README, and the lockfile entry linking the one dependency, @dcmjs-org/core. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(pdfs): port the encapsulated PDF builder and extractor from v2 A verbatim port of src/encapsulated/encapsulatedPdf.js from the v2 branch HEAD (including the { InlineBinary } unwrap that postdates the PR #512 review), with its core import rebased onto @dcmjs-org/core and the PDF half of the encapsulated index as the package surface. The video half stays on the v2 branch for the media wave. The eight-test v2 suite comes along, reworked for this branch's engine: the legacy datasetToBuffer / DicomMessage.readFile round-trip becomes denaturalize -> fromDataSet -> Part10Writer -> fromPart10 -> NaturalizedListener, and the last test's read of test/sample-dicom.dcm (provenance still being traced) is replaced by a synthetic MR instance round-tripped through the same pipeline, so neither the package nor its suite touches @dcmjs-org/legacy or the fixture. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(pdfs): slice extraction to EncapsulatedDocumentLength (review finding 16) The pad-trim heuristic strips a real zero byte: the Part 10 writer pads only an odd-length OB value, so a stored even length is ambiguous — the old code trimmed a trailing 0x00 anyway, corrupting an even-length original that genuinely ends in a zero byte (a 10-byte payload ending 0x00 came back as 9 bytes). encapsulatePdf now records EncapsulatedDocumentLength (0042,0015) with the exact original length, and extractEncapsulatedPdf slices to the declared length when present, keeping the trailing-NUL heuristic only as the fallback for files written before the element existed. The four new tests were written first and observed failing against the ported-unfixed code: the even-length zero-tail round-trip (9 bytes back, red), the recorded length element, and the declared-length odd slice; the heuristic-fallback test passed before and after, pinning that files without 0042,0015 still extract exactly. Co-Authored-By: Claude Fable 5 <[email protected]> * chore: scaffold the @dcmjs-org/dicomdir package 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]> * feat: port the DICOMDIR builder from v2.0-development (verbatim) 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]> * refactor: rewire the DICOMDIR builder onto @dcmjs-org/core 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(video): scaffold the @dcmjs-org/video package The package shell for the video wave: name, entry point, MIT license, repository directory, and the @dcmjs-org/core workspace dependency. The image-module index exports only the header parsers for now; the dataset builder joins it in the next slice. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port the JPEG and MP4 header parsers from v2 Verbatim from v2.0-development: src/image/jpegInfo.js (SOF geometry and the JPEG transfer syntax mapping), src/image/mp4Info.js (the ISO BMFF box walk over a random-access reader), the makeTinyMp4 synthesized-fixture helper, and the ported mp4Info suite. Only the test import paths moved with the files; no behavior changed in this commit — review findings 9 and 15 are fixed on top, each with its regression observed red first. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): throw on a truncated SOF segment in parseJpegInfo Review finding 9 (HIGH): the marker-walk guard only required four readable bytes, but the SOF fields span bytes[offset+4 .. offset+9]. Out-of-range reads coerce to 0 in the bitwise math, so the review map's vector — a 480x640 JPEG cut one byte into the width field — returned columns 512 instead of throwing, and a file cut right after the length field returned rows 0, columns 0. The reader now validates that the declared SOF segment fits inside the input (and is at least 8 bytes) before reading any field. The new jpegInfo suite is hand-written (v2 carried no suite for this file): the exact review vector, the cut-after-length shape, and valid SOF0/SOF1/SOF2/SOF3 paths. Both finding tests were observed red against the ported-unfixed reader before this fix. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): bound the stts entry count by its box size in parseMp4Info Review finding 15 (MED): the stts fallback loop trusted the raw uint32 entry_count. With stsz sample_count 0 and stts entry_count 0x00FFFFFF the parser spun 16.7 million iterations over zero-coerced reads past the box and fabricated numberOfFrames/frameRate from unrelated moov bytes; at 0xFFFFFFFF that is roughly 40 seconds of blocked thread. The loop now requires 16 + entryCount * 8 to fit inside the stts box and throws on the mismatch. The regression corrupts a synthesized MP4 exactly that way and asserts the parse rejects in under two seconds — observed red (the unfixed parser resolved with fabricated values) before this fix. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port buildImageDataset from v2 Verbatim from v2.0-development src/image/buildImageDataset.js and its 21-test suite, with two mechanical adjustments for the package boundary: DicomMetaDictionary and validationLog now come from @dcmjs-org/core, and the test imports the builder from the package's image index (which now exports it alongside the header parsers). No behavior changed in this commit — review finding 10 is fixed on top with its regressions observed red first. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): derive NumberOfFrames from the encapsulated fragment list Review finding 10 (HIGH): numberOfFrames came only from decodedImage.numberOfFrames || 1 and was never derived from or checked against options.encapsulated.frames.length, and the attribute was only written when above 1. Three encapsulated fragments therefore produced an instance with no NumberOfFrames — a conformant reader showed frame 1 and the rest were unreachable — while an explicit numberOfFrames 7 over 2 fragments emitted the bogus claim unchecked. In encapsulated mode the fragment list is now the ground truth: the count defaults to frames.length and an explicit mismatch throws. Both regressions were observed red against the ported-unfixed builder before this fix; two companion tests pin that a matching explicit count is accepted and that a single fragment still omits the attribute. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: let core's sequence writer run with no eager engine loaded 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]> * feat(video): port the buffered video encapsulation layer from v2 Verbatim from v2.0-development src/encapsulated/encapsulatedVideo.js and its 8-test suite, with one mechanical adjustment for the package boundary: DicomMetaDictionary and isVideoTransferSyntax now come from @dcmjs-org/core instead of relative paths. buildVideoDataset shapes the Supplement 225 Video Photographic Image shell (XC modality, cine timing, the (7FE0,0003) uint64 total length as a BigInt), encapsulateVideo splits the MP4 into fragment-sized exact ArrayBuffer slices, and extractEncapsulatedVideo concatenates fragments and truncates to the declared length so the odd-fragment pad byte drops on extraction. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): export the encapsulated module from the package index The video half of v2's encapsulated index only — the PDF half (encapsulatedPdf) belongs to the media wave. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): declare the parser and generator dependencies @dcmjs-org/parser joins the dependencies — the video event source imports fromDataSet and EVENT_STREAM_VOCABULARY — and @dcmjs-org/generator the devDependencies (StreamingPart10Writer, tests only). Deliberately NOT @dcmjs-org/legacy: this package stays off the legacy surface. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port the video event source from v2 createVideoEventSource — MP4 → contract events with the Supplement 225 dataset shell replayed first and the stream emitted as encapsulated PixelData fragments, one in memory at a time, backpressure between fragments via awaitDrain(). The run loop, exactFragment, withoutEndDataSet and sortDict are verbatim from v2.0-development src/eventStream/fromVideo.js. One seam is reworked and hand-written: v2 imported datasetToDict from what is now @dcmjs-org/legacy, which this package must not depend on, so a local datasetToMetaDict helper mints the same file meta group (element list and implementation UID copied from legacy's datasetToDict) and denaturalizes both halves via core's DicomMetaDictionary — returning the plain { meta, dict } shape, which is all parser's fromDataSet reads. The suite is the v2 fromVideo suite reworked off the DicomEventStream facade (media wave): the source drives StreamingPart10Writer directly and reads back through fromPart10/fromPart10Stream + NaturalizedListener + extractEncapsulatedVideo. All load-bearing assertions carried over: byte-identical round trips (buffered and streaming reader), the (7FE0,0003) UV uint64 pinned on the wire, the Sup 225 fragment layout, single-endDataSet ordering, per-fragment backpressure, and the ffmpeg corrective error. The facade-specific toVideo/fromPdf case stays with the media wave, as does fromImage.test.js. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): export createVideoEventSource from the package index Co-Authored-By: Claude Fable 5 <[email protected]> * feat(media): the @dcmjs-org/media bundle package Co-Authored-By: Claude Fable 5 <[email protected]> * feat(media): the DicomEventStream media factories (review finding 14) Port fromImage, fromPdf, fromVideo, fromVideoStream, toPdf, and toVideo from v2's src/eventStream/api.js, importing from @dcmjs-org/pdfs and @dcmjs-org/video. The video factories create their event source lazily on first consumption (cached across re-runs) instead of eagerly at factory time, so a bad input can no longer raise an unhandled promise rejection before anyone calls .process() — review finding 14. Co-Authored-By: Claude Fable 5 <[email protected]> * ci: ignore the unpatchable braces advisory in audit, scoped and documented 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) * docs: retire the writing style guide now that authoring is done 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) --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Bill Wallace <[email protected]>
wayfarer3130
added a commit
that referenced
this pull request
Oct 21, 2026
…584) * feat(pdfs): scaffold the @dcmjs-org/pdfs workspace package The package manifest (publishable under the @dcmjs-org scope, main at src/index.js, repository directory set), a short README, and the lockfile entry linking the one dependency, @dcmjs-org/core. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(pdfs): port the encapsulated PDF builder and extractor from v2 A verbatim port of src/encapsulated/encapsulatedPdf.js from the v2 branch HEAD (including the { InlineBinary } unwrap that postdates the PR #512 review), with its core import rebased onto @dcmjs-org/core and the PDF half of the encapsulated index as the package surface. The video half stays on the v2 branch for the media wave. The eight-test v2 suite comes along, reworked for this branch's engine: the legacy datasetToBuffer / DicomMessage.readFile round-trip becomes denaturalize -> fromDataSet -> Part10Writer -> fromPart10 -> NaturalizedListener, and the last test's read of test/sample-dicom.dcm (provenance still being traced) is replaced by a synthetic MR instance round-tripped through the same pipeline, so neither the package nor its suite touches @dcmjs-org/legacy or the fixture. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(pdfs): slice extraction to EncapsulatedDocumentLength (review finding 16) The pad-trim heuristic strips a real zero byte: the Part 10 writer pads only an odd-length OB value, so a stored even length is ambiguous — the old code trimmed a trailing 0x00 anyway, corrupting an even-length original that genuinely ends in a zero byte (a 10-byte payload ending 0x00 came back as 9 bytes). encapsulatePdf now records EncapsulatedDocumentLength (0042,0015) with the exact original length, and extractEncapsulatedPdf slices to the declared length when present, keeping the trailing-NUL heuristic only as the fallback for files written before the element existed. The four new tests were written first and observed failing against the ported-unfixed code: the even-length zero-tail round-trip (9 bytes back, red), the recorded length element, and the declared-length odd slice; the heuristic-fallback test passed before and after, pinning that files without 0042,0015 still extract exactly. Co-Authored-By: Claude Fable 5 <[email protected]> * chore: scaffold the @dcmjs-org/dicomdir package 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]> * feat: port the DICOMDIR builder from v2.0-development (verbatim) 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]> * chore(fhir): scaffold the @dcmjs-org/fhir workspace package Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the Patient mappers and shared helpers from v2.0-development helpers.js, patient.js and patientToDataset.js come over verbatim from the v2 packages/fhir sources (prettier-normalized to this repo's config). The test imports are rewired to the concrete modules because the package index lands in a later slice. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(fhir): fall back to HumanName.text when no structured name parts exist A text-only HumanName used to map to null, and patientToDataset's deterministic overwrite then erased the patient's name entirely (review finding 19 on PR #512). When family/given/prefix/suffix are all absent, the free-text form now survives as a single-component PN. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor: rewire the DICOMDIR builder onto @dcmjs-org/core 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(video): scaffold the @dcmjs-org/video package The package shell for the video wave: name, entry point, MIT license, repository directory, and the @dcmjs-org/core workspace dependency. The image-module index exports only the header parsers for now; the dataset builder joins it in the next slice. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port the JPEG and MP4 header parsers from v2 Verbatim from v2.0-development: src/image/jpegInfo.js (SOF geometry and the JPEG transfer syntax mapping), src/image/mp4Info.js (the ISO BMFF box walk over a random-access reader), the makeTinyMp4 synthesized-fixture helper, and the ported mp4Info suite. Only the test import paths moved with the files; no behavior changed in this commit — review findings 9 and 15 are fixed on top, each with its regression observed red first. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): throw on a truncated SOF segment in parseJpegInfo Review finding 9 (HIGH): the marker-walk guard only required four readable bytes, but the SOF fields span bytes[offset+4 .. offset+9]. Out-of-range reads coerce to 0 in the bitwise math, so the review map's vector — a 480x640 JPEG cut one byte into the width field — returned columns 512 instead of throwing, and a file cut right after the length field returned rows 0, columns 0. The reader now validates that the declared SOF segment fits inside the input (and is at least 8 bytes) before reading any field. The new jpegInfo suite is hand-written (v2 carried no suite for this file): the exact review vector, the cut-after-length shape, and valid SOF0/SOF1/SOF2/SOF3 paths. Both finding tests were observed red against the ported-unfixed reader before this fix. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): bound the stts entry count by its box size in parseMp4Info Review finding 15 (MED): the stts fallback loop trusted the raw uint32 entry_count. With stsz sample_count 0 and stts entry_count 0x00FFFFFF the parser spun 16.7 million iterations over zero-coerced reads past the box and fabricated numberOfFrames/frameRate from unrelated moov bytes; at 0xFFFFFFFF that is roughly 40 seconds of blocked thread. The loop now requires 16 + entryCount * 8 to fit inside the stts box and throws on the mismatch. The regression corrupts a synthesized MP4 exactly that way and asserts the parse rejects in under two seconds — observed red (the unfixed parser resolved with fabricated values) before this fix. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port buildImageDataset from v2 Verbatim from v2.0-development src/image/buildImageDataset.js and its 21-test suite, with two mechanical adjustments for the package boundary: DicomMetaDictionary and validationLog now come from @dcmjs-org/core, and the test imports the builder from the package's image index (which now exports it alongside the header parsers). No behavior changed in this commit — review finding 10 is fixed on top with its regressions observed red first. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the ImagingStudy mapper and the package index from v2.0-development imagingStudy.js comes over verbatim. The index keeps toFhir/toBundle unchanged but swaps the documentReference import for a null-returning placeholder until the DocumentReference mapper lands in the next slice (v2's index has no fromFhir re-export; the event-stream integration is a deferred slice of its own). The ported toFhir suite reads the sample-dicom.dcm fixture from packages/fixtures/dicom and naturalizes it through @dcmjs-org/parser instead of the umbrella, and the two umbrella-namespace tests are deferred with the facade slice. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(fhir): skip instances without SOPClassUID and datasets without SeriesInstanceUID Review findings 17 and 18 on PR #512. A missing (0008,0016) used to fabricate the CT Image Storage UID, asserting an unknown instance was a CT image; a missing (0020,000E) produced series.uid: null — invalid against R4B's 1..1 cardinality — and merged every such dataset under one "unknown" key. Both inputs are now skipped with a validationLog warning rather than emitted invalid, since instance.sopClass and series.uid are required elements a server would reject anyway. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): derive NumberOfFrames from the encapsulated fragment list Review finding 10 (HIGH): numberOfFrames came only from decodedImage.numberOfFrames || 1 and was never derived from or checked against options.encapsulated.frames.length, and the attribute was only written when above 1. Three encapsulated fragments therefore produced an instance with no NumberOfFrames — a conformant reader showed frame 1 and the rest were unreachable — while an explicit numberOfFrames 7 over 2 fragments emitted the bogus claim unchecked. In encapsulated mode the fragment list is now the ground truth: the count defaults to frames.length and an explicit mismatch throws. Both regressions were observed red against the ported-unfixed builder before this fix; two companion tests pin that a matching explicit count is accepted and that a single fragment still omits the attribute. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: let core's sequence writer run with no eager engine loaded 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]> * feat(video): port the buffered video encapsulation layer from v2 Verbatim from v2.0-development src/encapsulated/encapsulatedVideo.js and its 8-test suite, with one mechanical adjustment for the package boundary: DicomMetaDictionary and isVideoTransferSyntax now come from @dcmjs-org/core instead of relative paths. buildVideoDataset shapes the Supplement 225 Video Photographic Image shell (XC modality, cine timing, the (7FE0,0003) uint64 total length as a BigInt), encapsulateVideo splits the MP4 into fragment-sized exact ArrayBuffer slices, and extractEncapsulatedVideo concatenates fragments and truncates to the declared length so the odd-fragment pad byte drops on extraction. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): export the encapsulated module from the package index The video half of v2's encapsulated index only — the PDF half (encapsulatedPdf) belongs to the media wave. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the DocumentReference mapper from v2.0-development documentReference.js comes over verbatim, and the package index swaps the slice-two placeholder for the real import and re-export, completing the toFhir three-key surface. The ported test builds its Encapsulated PDF datasets synthetically (v2 built them with dcmjs.encapsulated, which belongs to the pdfs wave and is not on this branch yet), keeps the Part 10 round trip through @dcmjs-org/legacy as a test-only devDependency, and naturalizes the image fixture through @dcmjs-org/parser like the toFhir suite. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(fhir): unwrap InlineBinary payloads and honor EncapsulatedDocumentLength Review findings 8 and 16 on PR #512. The event-stream naturalizer wraps binary elements as { InlineBinary } (base64 string, ArrayBuffer, or view); payloadBytes never unwrapped that shape, and new Uint8Array of a plain object is empty, so every naturalized encapsulated document silently mapped to { size: 0, data: "" }. The unwrap block mirrors the one in v2's extractEncapsulatedPdf, kept as a local copy because this package must not depend on the pdfs package. The even-length pad-trim heuristic also stripped real trailing zero bytes, since an even stored length never carries a writer pad. When EncapsulatedDocumentLength (0042,0015) is present it now wins over the heuristic; the write side that emits it lands with the pdfs wave. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): declare the parser and generator dependencies @dcmjs-org/parser joins the dependencies — the video event source imports fromDataSet and EVENT_STREAM_VOCABULARY — and @dcmjs-org/generator the devDependencies (StreamingPart10Writer, tests only). Deliberately NOT @dcmjs-org/legacy: this package stays off the legacy surface. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port the video event source from v2 createVideoEventSource — MP4 → contract events with the Supplement 225 dataset shell replayed first and the stream emitted as encapsulated PixelData fragments, one in memory at a time, backpressure between fragments via awaitDrain(). The run loop, exactFragment, withoutEndDataSet and sortDict are verbatim from v2.0-development src/eventStream/fromVideo.js. One seam is reworked and hand-written: v2 imported datasetToDict from what is now @dcmjs-org/legacy, which this package must not depend on, so a local datasetToMetaDict helper mints the same file meta group (element list and implementation UID copied from legacy's datasetToDict) and denaturalizes both halves via core's DicomMetaDictionary — returning the plain { meta, dict } shape, which is all parser's fromDataSet reads. The suite is the v2 fromVideo suite reworked off the DicomEventStream facade (media wave): the source drives StreamingPart10Writer directly and reads back through fromPart10/fromPart10Stream + NaturalizedListener + extractEncapsulatedVideo. All load-bearing assertions carried over: byte-identical round trips (buffered and streaming reader), the (7FE0,0003) UV uint64 pinned on the wire, the Sup 225 fragment layout, single-endDataSet ordering, per-fragment backpressure, and the ffmpeg corrective error. The facade-specific toVideo/fromPdf case stays with the media wave, as does fromImage.test.js. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): export createVideoEventSource from the package index Co-Authored-By: Claude Fable 5 <[email protected]> * feat(media): the @dcmjs-org/media bundle package Co-Authored-By: Claude Fable 5 <[email protected]> * feat(media): the DicomEventStream media factories (review finding 14) Port fromImage, fromPdf, fromVideo, fromVideoStream, toPdf, and toVideo from v2's src/eventStream/api.js, importing from @dcmjs-org/pdfs and @dcmjs-org/video. The video factories create their event source lazily on first consumption (cached across re-runs) instead of eagerly at factory time, so a bad input can no longer raise an unhandled promise rejection before anyone calls .process() — review finding 14. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the fromFhir event source from v2.0-development FHIR resources as an event-stream SOURCE, for the resources that carry content rather than context: a DocumentReference with an inline PDF becomes an Encapsulated PDF instance, and a Media with an inline JPEG (the key-image case) becomes an image instance with the JPEG bytes carried verbatim as encapsulated PixelData. Bundles are unwrapped (one content resource + an optional Patient for demographics), and context-only resources are rejected with corrective errors. The module stays at root src/eventStream/ — the same wrapper-level home as api.js — because it composes five packages (pdfs, video, fhir, parser, core) and belongs inside none of them; it moves into the step-7 wrapper package with the facade. Imports are rewired to the scoped packages, and the legacy datasetToDict call is replaced with a local copy of the video wave's datasetToMetaDict (not exported from @dcmjs-org/video), producing the plain { meta, dict } shape fromDataSet consumes. @dcmjs-org/core, fhir, and parser join the root workspace dependencies. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): add fromFhir and toFhir to the DicomEventStream facade fromFhir follows the media factories' lazy-source pattern (finding 14): the v2 original built the dataset eagerly at factory time, so garbage input threw from the factory before anyone called .process(). Here the dataset is built on first consumption and cached — the corrective error surfaces from the sink, and minted UIDs stay stable across re-runs. The regression test was red against the verbatim v2 port (5 failures: the finding-14 test plus the four corrective-error tests, all throwing at factory time) and is green with the lazy form. toFhir maps one instance to { patient, imagingStudy, documentReference } via @dcmjs-org/fhir over the naturalized dataset, ported verbatim from v2's api.js. The test suite is the v2 fhirPdfEventStream suite with import and fixture-path rework, minus the parseJpegInfo block (now owned by packages/video/test/jpegInfo.test.js, a superset), plus the facade form of the deferred 'dcmjs.fhir umbrella namespace' bytes-to-FHIR test: DicomEventStream.fromPart10(bytes).toFhir() over the committed sample-dicom.dcm fixture. The namespace tests themselves still wait for the step-7 wrapper package; the deferral comments in packages/fhir/test/toFhir.test.js now say exactly that. Co-Authored-By: Claude Fable 5 <[email protected]> * chore(audit): ignore GHSA-vfj7-8cjw-p6xm (braces) — no patched release exists The advisory (braces <=3.0.3, high, stack exhaustion) was published mid-flight on this PR: the identical lockfile passed audit on the staging branch twenty minutes before the PR run failed. Its stated patched range is >=3.0.4, but the registry has no such release (latest braces is 3.0.3, from 2024), so an override pin cannot resolve — verified: ERR_PNPM_NO_MATCHING_VERSION. Every path to braces is dev tooling (cpy-cli, lint-staged, jest); it never reaches the published package. The ignore is scoped to this one GHSA and commented for removal the moment a patched braces ships. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: retire the writing style guide now that authoring is done 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) * refactor(fhir): use the createInstance options of 1.0-beta in fromFhir fromFhir takes `patient` plus the createInstance options (instance, dataLevel, levels, predecessor, postProcess, baseDicom, overrides) and gives them to encapsulatePdf or buildImageDataset. The FHIR values (the patient demographics and the DocumentTitle) go in front of the caller overrides. The local datasetToMetaDict copy is replaced by datasetToDict. Add extractEncapsulated to @dcmjs-org/encapsulated. extractEncapsulatedPdf and the fhir documentReference mapper use it, in place of the local payloadBytes copy. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(fhir): address the review findings; mark the fhir API preliminary - parseJpegInfo gives DICOM bit depths (BitsAllocated 8 or 16, BitsStored) and the photometric interpretation from the SOF type, the sampling factors, the component IDs, and the Adobe APP14 transform. fromFhir writes BitsStored, PixelRepresentation, and PlanarConfiguration. - fromFhir selects the Bundle Patient from the subject reference, and throws when the Patient is not clear. - imagingStudyFromDatasets skips a dataset of another study. - A FHIR dateTime has a time only with TimezoneOffsetFromUTC; DocumentReference.date is written only as a full instant. - extractEncapsulated removes a pad byte without a declared length only for PDF, text, and XML types. - @dcmjs-org/core gets encodeBase64, base64ToArrayBuffer, toStringFirst, toFloatFirst, and MODALITY_DISPLAY; parser, generator, encapsulated, and fhir use them. - packages/fhir/README.md marks the API preliminary and gives the FHIR-USR and FHIR-IMP requirements. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(fhir): address the clean review (B2-B4, S1-S8); native base64 - base64: use Uint8Array.prototype.toBase64 / Uint8Array.fromBase64 when present, then Buffer, then chunked btoa/atob. - B2: without options.subject, toFhir references ./patient and toBundle gives each entry fullUrl ./entry/<n> and references the Patient entry. - B3: no US Core birth-sex or clinical-sex extensions; gender only. - B4: a FHIR Patient replaces the whole patient module, and an instance of another PatientID throws. - S1: a Bundle reference matches fullUrl exactly; only a relative reference matches by id; more than one match throws. - S2: a { BulkDataURI } payload gives attachment.url, not empty data. - S3: strict DA/TM formats, with the legacy dot and colon forms. - S4: skip a dataset with no Modality; numbers only as unsignedInt. - S5: bodySite has no code system; laterality L/R/B are SNOMED codes. - S6: a lossy JPEG gets LossyImageCompression 01 and the method. - S7: toBundle skips a dataset of another patient or study. - S8: requirements for the changed behaviour in the core, imaging, encapsulated, and fhir READMEs. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Bill Wallace <[email protected]>
wayfarer3130
added a commit
that referenced
this pull request
Oct 23, 2026
* feat(pdfs): scaffold the @dcmjs-org/pdfs workspace package The package manifest (publishable under the @dcmjs-org scope, main at src/index.js, repository directory set), a short README, and the lockfile entry linking the one dependency, @dcmjs-org/core. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(pdfs): port the encapsulated PDF builder and extractor from v2 A verbatim port of src/encapsulated/encapsulatedPdf.js from the v2 branch HEAD (including the { InlineBinary } unwrap that postdates the PR #512 review), with its core import rebased onto @dcmjs-org/core and the PDF half of the encapsulated index as the package surface. The video half stays on the v2 branch for the media wave. The eight-test v2 suite comes along, reworked for this branch's engine: the legacy datasetToBuffer / DicomMessage.readFile round-trip becomes denaturalize -> fromDataSet -> Part10Writer -> fromPart10 -> NaturalizedListener, and the last test's read of test/sample-dicom.dcm (provenance still being traced) is replaced by a synthetic MR instance round-tripped through the same pipeline, so neither the package nor its suite touches @dcmjs-org/legacy or the fixture. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(pdfs): slice extraction to EncapsulatedDocumentLength (review finding 16) The pad-trim heuristic strips a real zero byte: the Part 10 writer pads only an odd-length OB value, so a stored even length is ambiguous — the old code trimmed a trailing 0x00 anyway, corrupting an even-length original that genuinely ends in a zero byte (a 10-byte payload ending 0x00 came back as 9 bytes). encapsulatePdf now records EncapsulatedDocumentLength (0042,0015) with the exact original length, and extractEncapsulatedPdf slices to the declared length when present, keeping the trailing-NUL heuristic only as the fallback for files written before the element existed. The four new tests were written first and observed failing against the ported-unfixed code: the even-length zero-tail round-trip (9 bytes back, red), the recorded length element, and the declared-length odd slice; the heuristic-fallback test passed before and after, pinning that files without 0042,0015 still extract exactly. Co-Authored-By: Claude Fable 5 <[email protected]> * chore: scaffold the @dcmjs-org/dicomdir package 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]> * feat: port the DICOMDIR builder from v2.0-development (verbatim) 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]> * chore(fhir): scaffold the @dcmjs-org/fhir workspace package Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the Patient mappers and shared helpers from v2.0-development helpers.js, patient.js and patientToDataset.js come over verbatim from the v2 packages/fhir sources (prettier-normalized to this repo's config). The test imports are rewired to the concrete modules because the package index lands in a later slice. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(fhir): fall back to HumanName.text when no structured name parts exist A text-only HumanName used to map to null, and patientToDataset's deterministic overwrite then erased the patient's name entirely (review finding 19 on PR #512). When family/given/prefix/suffix are all absent, the free-text form now survives as a single-component PN. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor: rewire the DICOMDIR builder onto @dcmjs-org/core 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(video): scaffold the @dcmjs-org/video package The package shell for the video wave: name, entry point, MIT license, repository directory, and the @dcmjs-org/core workspace dependency. The image-module index exports only the header parsers for now; the dataset builder joins it in the next slice. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port the JPEG and MP4 header parsers from v2 Verbatim from v2.0-development: src/image/jpegInfo.js (SOF geometry and the JPEG transfer syntax mapping), src/image/mp4Info.js (the ISO BMFF box walk over a random-access reader), the makeTinyMp4 synthesized-fixture helper, and the ported mp4Info suite. Only the test import paths moved with the files; no behavior changed in this commit — review findings 9 and 15 are fixed on top, each with its regression observed red first. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): throw on a truncated SOF segment in parseJpegInfo Review finding 9 (HIGH): the marker-walk guard only required four readable bytes, but the SOF fields span bytes[offset+4 .. offset+9]. Out-of-range reads coerce to 0 in the bitwise math, so the review map's vector — a 480x640 JPEG cut one byte into the width field — returned columns 512 instead of throwing, and a file cut right after the length field returned rows 0, columns 0. The reader now validates that the declared SOF segment fits inside the input (and is at least 8 bytes) before reading any field. The new jpegInfo suite is hand-written (v2 carried no suite for this file): the exact review vector, the cut-after-length shape, and valid SOF0/SOF1/SOF2/SOF3 paths. Both finding tests were observed red against the ported-unfixed reader before this fix. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): bound the stts entry count by its box size in parseMp4Info Review finding 15 (MED): the stts fallback loop trusted the raw uint32 entry_count. With stsz sample_count 0 and stts entry_count 0x00FFFFFF the parser spun 16.7 million iterations over zero-coerced reads past the box and fabricated numberOfFrames/frameRate from unrelated moov bytes; at 0xFFFFFFFF that is roughly 40 seconds of blocked thread. The loop now requires 16 + entryCount * 8 to fit inside the stts box and throws on the mismatch. The regression corrupts a synthesized MP4 exactly that way and asserts the parse rejects in under two seconds — observed red (the unfixed parser resolved with fabricated values) before this fix. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port buildImageDataset from v2 Verbatim from v2.0-development src/image/buildImageDataset.js and its 21-test suite, with two mechanical adjustments for the package boundary: DicomMetaDictionary and validationLog now come from @dcmjs-org/core, and the test imports the builder from the package's image index (which now exports it alongside the header parsers). No behavior changed in this commit — review finding 10 is fixed on top with its regressions observed red first. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the ImagingStudy mapper and the package index from v2.0-development imagingStudy.js comes over verbatim. The index keeps toFhir/toBundle unchanged but swaps the documentReference import for a null-returning placeholder until the DocumentReference mapper lands in the next slice (v2's index has no fromFhir re-export; the event-stream integration is a deferred slice of its own). The ported toFhir suite reads the sample-dicom.dcm fixture from packages/fixtures/dicom and naturalizes it through @dcmjs-org/parser instead of the umbrella, and the two umbrella-namespace tests are deferred with the facade slice. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(fhir): skip instances without SOPClassUID and datasets without SeriesInstanceUID Review findings 17 and 18 on PR #512. A missing (0008,0016) used to fabricate the CT Image Storage UID, asserting an unknown instance was a CT image; a missing (0020,000E) produced series.uid: null — invalid against R4B's 1..1 cardinality — and merged every such dataset under one "unknown" key. Both inputs are now skipped with a validationLog warning rather than emitted invalid, since instance.sopClass and series.uid are required elements a server would reject anyway. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(video): derive NumberOfFrames from the encapsulated fragment list Review finding 10 (HIGH): numberOfFrames came only from decodedImage.numberOfFrames || 1 and was never derived from or checked against options.encapsulated.frames.length, and the attribute was only written when above 1. Three encapsulated fragments therefore produced an instance with no NumberOfFrames — a conformant reader showed frame 1 and the rest were unreachable — while an explicit numberOfFrames 7 over 2 fragments emitted the bogus claim unchecked. In encapsulated mode the fragment list is now the ground truth: the count defaults to frames.length and an explicit mismatch throws. Both regressions were observed red against the ported-unfixed builder before this fix; two companion tests pin that a matching explicit count is accepted and that a single fragment still omits the attribute. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: let core's sequence writer run with no eager engine loaded 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]> * feat(video): port the buffered video encapsulation layer from v2 Verbatim from v2.0-development src/encapsulated/encapsulatedVideo.js and its 8-test suite, with one mechanical adjustment for the package boundary: DicomMetaDictionary and isVideoTransferSyntax now come from @dcmjs-org/core instead of relative paths. buildVideoDataset shapes the Supplement 225 Video Photographic Image shell (XC modality, cine timing, the (7FE0,0003) uint64 total length as a BigInt), encapsulateVideo splits the MP4 into fragment-sized exact ArrayBuffer slices, and extractEncapsulatedVideo concatenates fragments and truncates to the declared length so the odd-fragment pad byte drops on extraction. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): export the encapsulated module from the package index The video half of v2's encapsulated index only — the PDF half (encapsulatedPdf) belongs to the media wave. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the DocumentReference mapper from v2.0-development documentReference.js comes over verbatim, and the package index swaps the slice-two placeholder for the real import and re-export, completing the toFhir three-key surface. The ported test builds its Encapsulated PDF datasets synthetically (v2 built them with dcmjs.encapsulated, which belongs to the pdfs wave and is not on this branch yet), keeps the Part 10 round trip through @dcmjs-org/legacy as a test-only devDependency, and naturalizes the image fixture through @dcmjs-org/parser like the toFhir suite. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(fhir): unwrap InlineBinary payloads and honor EncapsulatedDocumentLength Review findings 8 and 16 on PR #512. The event-stream naturalizer wraps binary elements as { InlineBinary } (base64 string, ArrayBuffer, or view); payloadBytes never unwrapped that shape, and new Uint8Array of a plain object is empty, so every naturalized encapsulated document silently mapped to { size: 0, data: "" }. The unwrap block mirrors the one in v2's extractEncapsulatedPdf, kept as a local copy because this package must not depend on the pdfs package. The even-length pad-trim heuristic also stripped real trailing zero bytes, since an even stored length never carries a writer pad. When EncapsulatedDocumentLength (0042,0015) is present it now wins over the heuristic; the write side that emits it lands with the pdfs wave. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): declare the parser and generator dependencies @dcmjs-org/parser joins the dependencies — the video event source imports fromDataSet and EVENT_STREAM_VOCABULARY — and @dcmjs-org/generator the devDependencies (StreamingPart10Writer, tests only). Deliberately NOT @dcmjs-org/legacy: this package stays off the legacy surface. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): port the video event source from v2 createVideoEventSource — MP4 → contract events with the Supplement 225 dataset shell replayed first and the stream emitted as encapsulated PixelData fragments, one in memory at a time, backpressure between fragments via awaitDrain(). The run loop, exactFragment, withoutEndDataSet and sortDict are verbatim from v2.0-development src/eventStream/fromVideo.js. One seam is reworked and hand-written: v2 imported datasetToDict from what is now @dcmjs-org/legacy, which this package must not depend on, so a local datasetToMetaDict helper mints the same file meta group (element list and implementation UID copied from legacy's datasetToDict) and denaturalizes both halves via core's DicomMetaDictionary — returning the plain { meta, dict } shape, which is all parser's fromDataSet reads. The suite is the v2 fromVideo suite reworked off the DicomEventStream facade (media wave): the source drives StreamingPart10Writer directly and reads back through fromPart10/fromPart10Stream + NaturalizedListener + extractEncapsulatedVideo. All load-bearing assertions carried over: byte-identical round trips (buffered and streaming reader), the (7FE0,0003) UV uint64 pinned on the wire, the Sup 225 fragment layout, single-endDataSet ordering, per-fragment backpressure, and the ffmpeg corrective error. The facade-specific toVideo/fromPdf case stays with the media wave, as does fromImage.test.js. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(video): export createVideoEventSource from the package index Co-Authored-By: Claude Fable 5 <[email protected]> * feat(media): the @dcmjs-org/media bundle package Co-Authored-By: Claude Fable 5 <[email protected]> * feat(media): the DicomEventStream media factories (review finding 14) Port fromImage, fromPdf, fromVideo, fromVideoStream, toPdf, and toVideo from v2's src/eventStream/api.js, importing from @dcmjs-org/pdfs and @dcmjs-org/video. The video factories create their event source lazily on first consumption (cached across re-runs) instead of eagerly at factory time, so a bad input can no longer raise an unhandled promise rejection before anyone calls .process() — review finding 14. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): port the fromFhir event source from v2.0-development FHIR resources as an event-stream SOURCE, for the resources that carry content rather than context: a DocumentReference with an inline PDF becomes an Encapsulated PDF instance, and a Media with an inline JPEG (the key-image case) becomes an image instance with the JPEG bytes carried verbatim as encapsulated PixelData. Bundles are unwrapped (one content resource + an optional Patient for demographics), and context-only resources are rejected with corrective errors. The module stays at root src/eventStream/ — the same wrapper-level home as api.js — because it composes five packages (pdfs, video, fhir, parser, core) and belongs inside none of them; it moves into the step-7 wrapper package with the facade. Imports are rewired to the scoped packages, and the legacy datasetToDict call is replaced with a local copy of the video wave's datasetToMetaDict (not exported from @dcmjs-org/video), producing the plain { meta, dict } shape fromDataSet consumes. @dcmjs-org/core, fhir, and parser join the root workspace dependencies. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(fhir): add fromFhir and toFhir to the DicomEventStream facade fromFhir follows the media factories' lazy-source pattern (finding 14): the v2 original built the dataset eagerly at factory time, so garbage input threw from the factory before anyone called .process(). Here the dataset is built on first consumption and cached — the corrective error surfaces from the sink, and minted UIDs stay stable across re-runs. The regression test was red against the verbatim v2 port (5 failures: the finding-14 test plus the four corrective-error tests, all throwing at factory time) and is green with the lazy form. toFhir maps one instance to { patient, imagingStudy, documentReference } via @dcmjs-org/fhir over the naturalized dataset, ported verbatim from v2's api.js. The test suite is the v2 fhirPdfEventStream suite with import and fixture-path rework, minus the parseJpegInfo block (now owned by packages/video/test/jpegInfo.test.js, a superset), plus the facade form of the deferred 'dcmjs.fhir umbrella namespace' bytes-to-FHIR test: DicomEventStream.fromPart10(bytes).toFhir() over the committed sample-dicom.dcm fixture. The namespace tests themselves still wait for the step-7 wrapper package; the deferral comments in packages/fhir/test/toFhir.test.js now say exactly that. Co-Authored-By: Claude Fable 5 <[email protected]> * chore(audit): ignore GHSA-vfj7-8cjw-p6xm (braces) — no patched release exists The advisory (braces <=3.0.3, high, stack exhaustion) was published mid-flight on this PR: the identical lockfile passed audit on the staging branch twenty minutes before the PR run failed. Its stated patched range is >=3.0.4, but the registry has no such release (latest braces is 3.0.3, from 2024), so an override pin cannot resolve — verified: ERR_PNPM_NO_MATCHING_VERSION. Every path to braces is dev tooling (cpy-cli, lint-staged, jest); it never reaches the published package. The ignore is scoped to this one GHSA and commented for removal the moment a patched braces ships. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(dcmjs): the @dcmjs-org/dcmjs wrapper — the 0.52 surface plus the new engines The step-7 wrapper from the release plan. The root package renames from "dcmjs" to "@dcmjs-org/dcmjs" and drops "private": true in the same commit, as section 9 of RELEASE_PLAN.md specifies — the flag existed only to keep the unscoped name from publishing by accident before the wrapper existed. The unscoped dcmjs npm name stays untouched until GA. src/index.js keeps the entire 0.52 surface (the shims and the full suite prove it) and gains the new namespaces additively, following the v2 naming precedent but importing from the workspace packages: media, encapsulated (including DEFAULT_FRAGMENT_BYTES), and image come from @dcmjs-org/media; fhir spreads @dcmjs-org/fhir plus the fromPart10 convenience; eventStream was already here. The root package.json gains the workspace deps it now wraps (dicomdir, media, generator). The umbrella-namespace tests deferred by PR #579 return in packages/fhir/test/toFhir.test.js, red-green against the real wiring. test/bundle-size.test.js is the plan's bundle-size check against 0.52, with the honest numbers: the bundles are 27-30% over the 0.52 baseline because the new engines are in them; the 1.05 aspiration is logged as informational and a documented provisional ceiling of 1.35 is enforced, with the final threshold flagged as a maintainer decision. The same suite requires the built UMD bundle and touches every new namespace to prove rollup inlines the @dcmjs-org/* workspace packages. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: retire the writing style guide now that authoring is done 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) * chore: update pnpm to 12.9.1 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: @dcmjs-org/dcmjs — the 0.52 default export and the subpath entries The default export of @dcmjs-org/dcmjs now has exactly the dcmjs 0.52 names. The new engines move to subpath entries, so the default bundles stay within x1.05 of 0.52: - @dcmjs-org/dcmjs/eventStream (moved from the default export) - @dcmjs-org/dcmjs/media, /encapsulated, /image (the v2 namespaces) - @dcmjs-org/dcmjs/fhir (the FHIR sink plus fromPart10) Build: one ESM build with six entries keeps the @dcmjs-org/* imports external (they stay in dependencies); the shared code goes in one dcmjs.shared-<hash>.js chunk, so each entry exports only its public names. The UMD builds inline everything and have the default entry only. Tests: the bundle-size suite builds only the bundles it measures, rebuilds a stale build/, spawns rollup through node (works on Windows), measures an entry with its chunks, and checks the export names. A new 0.52-compatibility test pins the 0.52 export names. Release tooling: the trusted-publishing bootstrap also prepares the root package; the publish workflow builds before it tests. RELEASE_PLAN.md gets the wrapper requirements (WRAP-USR-n, WRAP-IMP-n), the size policy and the measurements. The pnpm-workspace.yaml comments name pnpm 12. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: one naturalized form for private blocks and binary values Both naturalizers (DicomMetaDictionary.naturalizeDataset and NaturalizedListener) now give the same object, and the spec in docs/specs/naturalized-dataset.md defines it. - A private creator (gggg,00xx) and its reserved block naturalize to one `${gggg}:${creator}` key: { creator, reservedBlock, xEE... }, with the VRs in _vrMap[blockKey][xEE]. The hex tags, registerTag() keywords and private dictionary keywords stay as non-enumerable aliases. - denaturalizeDataset accepts the block form and the hex-tag form. A block keeps its reservedBlock when it is free, and moves to the first free xx when it is not. - fromNaturalized / DicomEventStream.fromNaturalized() streams a naturalized dataset to any sink, for example Part10Writer. - NaturalizedListener outputs _vrMap, and gives binary values as a list of ArrayBuffer in place of { InlineBinary }. - Both naturalizers take { binaryAs: "Uint8Array" } for no-copy views. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: decode a private creator that was read as UN bytes An implicit-VR file, or a gateway that converts unknown VRs, can give a private creator as UN bytes. The block key was then "7FDD:[object ArrayBuffer]". The creator bytes now decode as LO text without the trailing padding (NAT-I-PLACE-3). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the review findings on the private blocks - A delete of a hex alias (or a registerTag() keyword alias) removes the element from the denaturalized output again, and a delete of a creator alias removes the block. De-identification code that deletes private tags by hex key keeps working (NAT-U-HIST-7). - An alias reads the block through its key, also after the user replaces the block (NAT-U-HIST-8). - A creator for two blocks of one group gives a warning (NAT-U-PRIV-9). - A creator from DICOM JSON InlineBinary decodes like a UN creator, and a creator decodes with the chunked latin1 decoder, from at most 64 bytes. Creator padding is removed for every source (NAT-U-PRIV-10). - A flat element in the range of a block joins the block, and a flat registerTag() keyword holds its block number (NAT-U-RT-1, NAT-I-RT-1). - isPrivateTag uses the Tag methods; one recordVr and one registeredTagEntry helper serve both naturalizers. - Outdated comments about { InlineBinary } and the draft section 18. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the published subpaths, and one copy of core in the ESM bundle - The packages published as source (dicomdir, encapsulated, fhir, imaging, media, video) get a files list. Without it, pnpm applied the root .npmignore, which excludes src/, and every subpath failed after an install (WRAP-IMP-6). - The src/ shims import @dcmjs-org/core and @dcmjs-org/parser in place of files in packages/<name>/src. The ESM shared chunk held a second copy of core: the consumer bundle was x1.49 of 0.52, and it is now x1.027 (WRAP-IMP-2). - The size check bundles build/dcmjs.es.js with its packages, as an application bundler does (WRAP-USR-2, WRAP-IMP-5). - core and parser get an exports map with a "source" condition, so Node runs the ESM entries in a built checkout (EXAMPLES.md, pnpm bench), and core lists its side-effect modules (WRAP-IMP-7). - The subpaths are import-only, so require() cannot load a second copy (WRAP-USR-3). - The UMD output has a fixed indent, and pnpm run build deletes build/. - bench/worker.mjs imports the eventStream subpath. - test/package-layout.test.js checks the files lists, the import-only subpaths, the sideEffects list and the source maps of build/. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the third review round on the wrapper wave Private blocks: - fromNaturalized denaturalizes the dataset itself, not a rest-spread copy, so a delete of a private alias also reaches Part10Writer and the other sinks (NAT-U-HIST-7). - A deleted alias stays deleted: definePrivateAliases does not define it again, and a plain value set on the deleted name is a new flat element that replaces the deleted one in its block. - A write to an element alias after the block is deleted makes a flat element. - A creator that is not text or bytes ({ BulkDataURI }, an object) is no creator; a SharedArrayBuffer creator decodes as bytes. - A binary-VR element with non-buffer values (UN with a string Value) is a list in both naturalizers, and hex keys are uppercase in both. - naturalBinaryFragment copies a SharedArrayBuffer to an ArrayBuffer in the default mode. Wrapper: - core reads process.env.LOG_LEVEL only when process exists. The ESM entry now imports core's dist/, where nothing replaced the expression, so a browser bundle threw "process is not defined" (WRAP-USR-6). The bundle-size suite runs the consumer bundle in a vm with no process. - The ESM build removes the shared chunks of earlier builds. - RELEASE_PLAN: WRAP-USR-3 records the CommonJS and jest limits and the two-copy case of require() plus import; the four test-only shims, the source-based size check and the jest resolution are stated exactly. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the fourth review round on the wrapper wave - A binary element with no value is null in both naturalizers (it was [] from NaturalizedListener after 86f998c), and NAT-U-BIN-1 records the binary list rule as a user requirement, without the conflict with NAT-U-VAL-4. - An alias delete removes the element while the block still holds the value that the alias last saw. The source value never survives a delete, also in a copied block object, and a different value written into the block after the delete is kept (it was lost). - A write to an element alias after the block key is deleted makes a flat element with the VR of the block element (it was skipped with no VR). - A number in a creator slot is no creator. - core reads process.env.LOG_LEVEL in a try block, so the UMD build applies the build-time level in a browser again. - One isBinaryData helper in core replaces four local byte checks. - The doc comment of creatorText, and the WRAP-USR-6 test reference (moved to WRAP-IMP-8). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: one value rule for unknown VMs, PN setters and the upsert utilities Naturalized values: - An attribute with no dictionary VM (a private or unknown element) is a list, also for one value, as for VM > 1 (NAT-U-VAL-4). A private or unknown sequence with one item is the array-like item object, as for a standard sequence (NAT-U-SQ-1). - A PN attribute of a dataset or item has a converting setter: an assigned PN string, object or list is stored in the component form, one object for VM 1 and a list otherwise (NAT-U-VAL-5). - A binary value whose fragments all have zero bytes (a Part 10 reader gives one empty fragment for an empty element) is null (NAT-U-BIN-1). Utilities in @dcmjs-org/core (NAT-U-UPS): - upsertAttribute(dataset, key, value, { vr, length }), upsertPersonName(dataset, key, value, length), and setVr(dataset, key, vr[, elementKey]), which creates _vrMap when it is missing. A private alias key stores into its block. Private aliases: - A delete of an alias always wins at the write, with no value check (the review's value-tracking rule had a new edge case in each round). - A write to an element alias after its creator alias is deleted makes a flat element, as after a delete of the block key. - A flat element that joins a block takes the VR of the block element when _vrMap has none for it. Also: DicomWebJsonWriter accepts a SharedArrayBuffer fragment, and the log.js comment no longer holds the text that the replace plugin rewrites. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: the naturalized-dataset utilities on dcmjs.data, size ceiling x1.06 dcmjs.data now also gives setVr, upsertAttribute, upsertPersonName and definePrivateAliases. With them the UMD bundle is x1.051 of 0.52, so the ceiling of WRAP-USR-2 rises from x1.05 to x1.06 (a maintainer decision). The ESM consumer bundle is x1.036. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: setAttribute and setPersonName, and the sixth review round - upsertAttribute and upsertPersonName are now setAttribute and setPersonName (NAT-U-SET); setVr keeps its name. - Without a length, the set utilities take the value count from the dictionary VM (setAttribute(ds, "PatientID", "X") stores "X"), and a hex key is uppercase, or the keyword for a standard tag. A VR other than PN replaces an earlier PN setter with plain data. - A private PN element converts a later string through its alias, when _vrMap gives PN for it. - Both producers store a PN value through setPersonName, so a value is converted once. - A present element with no Value is [] for a list VM and null for a scalar VM in naturalizeDataset too, as in the listener. - NaturalizedListener looks up a tag with the dictionary proxy, so the repeating groups (60xx OverlayRows ...) and registerTag() entries get their keywords, as in naturalizeDataset. - valueLength(entry) is the one value-count rule for both producers and the set utilities; a registerTag() entry with no VM is a list. - The isMultiVM and privateBlocks doc comments, a nested PN list, and the tests of the round-5 items that had none. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the final review findings on the wrapper wave Should fix: - An invalid LOG_LEVEL (another library's level, such as "verbose" or "fatal") no longer stops the import: core uses the variable only when loglevel knows the level, else "warn". The proper fix is proposed upstream in pimterry/loglevel#210 (log.parseLevel and a tolerant setDefaultLevel). - setAttribute stores a sequence by NAT-U-SQ: [] with no item, the array-like item object for one item. - A hex key of a flat registerTag() private element sets its keyword, so the value is no longer lost on write. - A private PN element with no creator gets the converting setter. - The source-map guard in test/package-layout.test.js builds build/ when it is absent or stale, so it runs in PR CI. The build helper is shared with test/bundle-size.test.js and takes a lock for parallel workers. Reuse: naturalValues.js holds the sequence, binary and simple value rules for both producers and setAttribute; isHexTag is the one hex-key test. Nits: setVr ignores a creator alias, setAttribute on a creator alias throws a clear TypeError, the PN setter rules are in NAT-U-VAL-5, MIGRATION (PN, the wrapper, ESM-only subpaths, LOG_LEVEL) and RELEASE_PLAN (legacy and generator inlined, LOG_LEVEL, the size table, test references out of the user requirements) are current, the README gives the @beta install, and stale test names and comments are fixed. Tests: LOG_LEVEL values, the sequence, registerTag and flat PN cases, naturalizeDataset(readFile) in the cross-source matrix, and a private round trip on a real fixture. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the round-8 review findings, and an empty DS value Should fix: - After a delete of a private hex alias, setAttribute on that hex name makes a new flat element, also when a registerTag() keyword names the same block element (the ceaf1b3 key mapping lost the value). - setAttribute treats the dictionary code "ox" (PixelData) as binary: a list of ArrayBuffer, and no "ox" in _vrMap. A binary value set through setAttribute is a list of ArrayBuffer, or Uint8Array with binaryAs. - The jest advice is a moduleNameMapper to build/<name>.es.js; jest resolves with the CommonJS conditions, so a transform alone does not find the import-only subpaths (WRAP-USR-3, MIGRATION, README). Also: - denaturalizeDataset keeps a null value entry, as a reader gives for an empty DS of VM 1-n (Value: [null]); it threw before (sample-op.dcm). - LOG_LEVEL accepts 0 to 5 as a string; WRAP-USR-7 records the run-time read of the ESM entries. - setPersonName on a creator alias throws the clear TypeError. - The listener converts binary fragments in one binaryValue call. - The PN delimiter text, MIGRATION intro, spec line wrap, a misleading comment, the source-map regex, and the real-file test parse once. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the round-9 review findings - A null entry of a text VR (LO, LT, SH, ST, UC, UT) denaturalizes to an empty value. Since 7b8c26e accepted null entries, the writers wrote it as the text "null" (NAT-U-RT-7, recorded in MIGRATION). - The jest config maps the default entry to build/dcmjs.es.js too, so the default entry and the subpaths share one reader state in jest (WRAP-USR-3, MIGRATION, README). - setAttribute checks binaryAs (NAT-I-BIN-2), and isVrCode is the one VR-code test. - MIGRATION gives the 0 to 5 LOG_LEVEL values; the null-entry comment sits at the code it describes. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: null entries in the writer layer, for every write path - BufferStream.writeUTF8String writes null as empty text, as writeAsciiString does, so LO, SH, ST, LT, UC and UT no longer write the text "null" on any write path (DICOM JSON dicts and fromDicomWebJson included). The TEXT_VRS step in denaturalizeDataset is gone. - PN: a null name is an empty name that keeps its position (pnObjectToString, toPersonNameValue): [null, "C^D"] writes "\C^D". - A binary number VR (US, SS, UL, SL, FL, FD, UV, SV) writes null as 0 with a warning, because it has no empty value. - NAT-U-RT-7 and MIGRATION state these rules; NAT-I-NULL-1 places them. - isVrCode is no longer a public @dcmjs-org/core export; the jest docs name the babel.config.js that the ESM build files need; the size table is current. - test/core/nullEntries.test.js writes the bytes on three paths. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: the round-11 review findings on the null warning - The warning for a null binary number is in one method, ValueRepresentation.warnNullEntries, which uses isBinary() in place of a separate VR list (so AT is covered too). - It warns only for a null entry of a list. A null value that is not a list is an element with no value, which is written with zero length; the false "written as 0" warning for it is gone. - The UV writer calls warnNullEntries before it turns null into 0n, so a UV null now warns. - NAT-U-RT-7, NAT-I-NULL-1 and MIGRATION give the right VR list (SV is not a core VR; AT is in) and the no-value rule. - Tests: an element with no value is written with zero length and no warning, on the dict and naturalized paths; a UV null warns. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: no /fhir subpath, FHIR marked preliminary, no plan IDs in code - @dcmjs-org/dcmjs no longer has the /fhir subpath (src/fhir.js and its test file are gone). FHIR is preliminary: a user imports the separate @dcmjs-org/fhir package. It stays a runtime dependency, because the preliminary DicomEventStream.fromFhir() and toFhir() use it. README, MIGRATION and WRAP-USR-3 say so (a maintainer decision). - The code and test comments of this wave no longer point to RELEASE_PLAN requirement IDs (WRAP-*); they keep the plain explanation. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat: no FHIR methods on DicomEventStream The wrapper no longer depends on @dcmjs-org/fhir. DicomEventStream drops fromFhir() and toFhir(); toFhir(await events.toNaturalized()) of @dcmjs-org/fhir replaces events.toFhir(). The fhir README withdraws the fromFhir requirements, and the PDF facade tests move to pdfEventStream.test.js. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Bill Wallace <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
dcmjs 1.0 — a substantial rewrite
This proposes the
awatson1978/dcmjs@developmentline as dcmjs 1.0,made possible by the generous support of the National Institutes of
Health and Massachusetts General Hospital. It is large by design — 137
commits, 302 files, roughly +143,700 / −4,400 — so the intended
entry points for review are the two prose documents, not the raw
diff:
— the authoritative summary of the new capabilities and the
API-breaking changes, with a runnable example for each.
— reproducible performance numbers (read / write / roundtrip on the
committed fixtures, plus warm-vs-cold large-file streaming), each with
the exact command to regenerate it.
Everything below is a pointer into those two documents.
What changed (headlines)
dcmjs.eventStream) — a source-agnostic,SAX-style push parser. A file can be read as a stream of events
(
startElement,value,startSequence, …) flowing source →filters → sink, producing the same naturalized metadata without
materializing the whole dataset. (README → Event Stream.)
streaming writer keeps peak memory bounded by the largest single
pixel-data fragment rather than the file size; exercised against a
21.8 GB video instance while holding ~2 GB. (BENCHMARKS → Large
files.)
write, and the deflated transfer syntax is now actually written
compressed, fixing a long-standing 0.x bug where such files claimed a
compression they did not have.
dcmjs.media), video encapsulation(Supplement 225 — byte-identical MP4 in and out, no transcoding;
dcmjs.encapsulated), and instances from decoded pixels(
dcmjs.image). (README → Images and Directories.)@dcmjs/fhir) — bidirectional DICOM ↔ FHIRmapping (Patient / ImagingStudy / DocumentReference), also available
on the event stream. (README → Fast Healthcare Interoperability.)
record; the lazy core is behind
DCMJS_CORE=lazyand scheduled forremoval.
dcmjsat the root, the vendoredtokenizer in
packages/parser(private), the FHIR mappers inpackages/fhir, and the docs site inpackages/docs.Breaking changes
DicomMessage.read/readTagstatics and thelegacy
DICOMWEBclass (usedicomweb-client).
yarn.lock); Node.js≥ 22.13. See README → For Developers.
How to review something this large
The useful review here is at the level of public API and
capabilities (the README examples) and performance claims
(BENCHMARKS, all reproducible locally). We are happy to split this into
smaller topic PRs, walk through any individual subsystem, or provide
additional context — whatever the maintainers prefer.
Build & test
CI targets Node 22 and 24; the parser package carries its own jest suite
and a non-regression gate (
pnpm run bench:parser).