Repository navigation
feat: dcmjs core — the event-stream reading engine and the green regression tests - #542
Merged
Merged
Conversation
Supersedes the 2026-08-07 plan. Describes the package split, the 1.0-beta release branch, per-package staging branches, the test-first sequence for core, routing of the 33 review findings, and lockstep publishing with semantic-release. Co-Authored-By: Claude Fable 5 <[email protected]>
Two trivial assertions on the committed sample-sr.dcm fixture. The purpose is to exercise the CI checks on the 1.0-beta branch and prove they run and report on pull requests. See RELEASE_PLAN.md section 6, step 0. Co-Authored-By: Claude Fable 5 <[email protected]>
…e 24 fs.readFileSync can return a small file inside a larger shared memory pool. Taking .buffer on that result hands the parser the whole pool, with the file sitting at a nonzero offset, and the DICM marker check then fails. Node 24 pools more aggressively, which is why anonymizer.test.js and data.test.js fail there today (7 tests) while Node 22 passes by luck of alignment. This adds readFileAsArrayBuffer() to testUtils and routes all 22 file-read sites through it. Typed-array .buffer uses are untouched. Same class of problem as issue #311. Co-Authored-By: Claude Fable 5 <[email protected]>
…ware helper The first pass converted single-line fs.readFileSync(...).buffer sites. CI on Node 24 then failed in a second population: reads assigned to a variable first, with .buffer taken on a later line. This converts those sites in data.test.js, data-options.test.js, lossless-read-write.test.js and normalizers.test.js, and drops the imports that became unused. Sites that already handle byteOffset correctly are untouched. Co-Authored-By: Claude Fable 5 <[email protected]>
ensureTestDataDir checked for the directory and then created it. Two parallel jest workers can both pass the check, and the slower mkdir then fails with EEXIST, which failed test_multiframe_1 on one CI leg. mkdirSync with recursive:true succeeds whether or not the directory exists, so the check goes away. Co-Authored-By: Claude Fable 5 <[email protected]>
Three process documents the release plan calls for. The style guide defines the audience (healthcare-literate, no assumed programming or imaging jargon) and bans machine-flavored prose. The PR template requires plain-language descriptions, runnable examples, test evidence, and fixture citations. DATACITATION.md records the origin and license of every committed DICOM test file, with the legacy files honestly marked as provenance-pending. Co-Authored-By: Claude Fable 5 <[email protected]>
semantic-release computes one version from conventional commits; stamp-workspace-versions.mjs writes it into every publishable workspace package.json, and pnpm -r publish releases them together under the npm beta tag. The publish workflow now also fires on 1.0-beta and release/0.5x, and passes NODE_AUTH_TOKEN for pnpm publish. Nothing publishes until the repository owner adds 1.0-beta to the publish environment allowlist. See RELEASE_PLAN.md sections 9 and 12. Co-Authored-By: Claude Fable 5 <[email protected]>
Adapts the rules from Cursor's unslop skill: the fuller AI-vocabulary list, filler phrases, fancy synonyms for is, vague attributions, synonym cycling, false ranges, punctuation and formatting rules (em dashes, colons, bold, sentence-case headings, straight quotes), abstract metaphor nouns, and a plain-speech section that includes the rule against over-compressed arrow-speak. Also states the boundary this guide draws that unslop does not: metaphors that teach a concept to a non-technical reader stay, metaphors that decorate go. The guide's own prose now follows its own em-dash rule. Source: https://github.com/cursor/plugins/blob/main/pstack/skills/unslop/SKILL.md Co-Authored-By: Claude Fable 5 <[email protected]>
Adopts wayfarer3130's review comments: the engines split from the data types (core = building blocks only; legacy = today's readers and writers; parser = the new streaming reader; generator = the new writers). The vendored dicom-parser tokenizer is dropped from the 1.0 stream entirely, and about 300 tests retire with it. @dcmjs/media is added as a bundle over dicomdir, pdfs, and video, which all remain individually installable. The wrapper publishes as @dcmjs/dcmjs during the beta so the real dcmjs name stays untouched until the team is ready. FHIR stays in the plan with its landing order marked as an open question. Section 7 is rewritten to the simpler tests-travel-with-code approach discussed since the first draft. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…s sequencing Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…e git mv) Co-Authored-By: Claude Fable 5 <[email protected]>
…hrough fixturePath() Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
refactor: move committed test DICOM fixtures into packages/fixtures
…regression bank Co-Authored-By: Claude Fable 5 <[email protected]>
test: add the issue triage catalog and part10 walker for the regression bank
…avior Co-Authored-By: Claude Fable 5 <[email protected]>
…gth behavior Co-Authored-By: Claude Fable 5 <[email protected]>
…rdering Co-Authored-By: Claude Fable 5 <[email protected]>
…d strict-write Co-Authored-By: Claude Fable 5 <[email protected]>
… value-handling behaviors Co-Authored-By: Claude Fable 5 <[email protected]>
test: pin round-trip integrity, UUID-derived UIDs, and UN padding behavior
test: pin encapsulated write, latin1 fallback, and CS multi-value length behavior
test: pin private tag handling, undefined value writes, and element ordering
wayfarer3130
added a commit
that referenced
this pull request
Oct 7, 2026
…519) * docs: release plan for landing 1.0 as staged package PRs Supersedes the 2026-08-07 plan. Describes the package split, the 1.0-beta release branch, per-package staging branches, the test-first sequence for core, routing of the 33 review findings, and lockstep publishing with semantic-release. Co-Authored-By: Claude Fable 5 <[email protected]> * test: add pipeline smoke test Two trivial assertions on the committed sample-sr.dcm fixture. The purpose is to exercise the CI checks on the 1.0-beta branch and prove they run and report on pull requests. See RELEASE_PLAN.md section 6, step 0. Co-Authored-By: Claude Fable 5 <[email protected]> * test: read fixtures with an offset-aware helper so suites pass on Node 24 fs.readFileSync can return a small file inside a larger shared memory pool. Taking .buffer on that result hands the parser the whole pool, with the file sitting at a nonzero offset, and the DICM marker check then fails. Node 24 pools more aggressively, which is why anonymizer.test.js and data.test.js fail there today (7 tests) while Node 22 passes by luck of alignment. This adds readFileAsArrayBuffer() to testUtils and routes all 22 file-read sites through it. Typed-array .buffer uses are untouched. Same class of problem as issue #311. Co-Authored-By: Claude Fable 5 <[email protected]> * test: route the remaining indirect fixture reads through the offset-aware helper The first pass converted single-line fs.readFileSync(...).buffer sites. CI on Node 24 then failed in a second population: reads assigned to a variable first, with .buffer taken on a later line. This converts those sites in data.test.js, data-options.test.js, lossless-read-write.test.js and normalizers.test.js, and drops the imports that became unused. Sites that already handle byteOffset correctly are untouched. Co-Authored-By: Claude Fable 5 <[email protected]> * test: make the shared temp directory creation race-free ensureTestDataDir checked for the directory and then created it. Two parallel jest workers can both pass the check, and the slower mkdir then fails with EEXIST, which failed test_multiframe_1 on one CI leg. mkdirSync with recursive:true succeeds whether or not the directory exists, so the check goes away. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: writing style guide, PR template, and data citation file Three process documents the release plan calls for. The style guide defines the audience (healthcare-literate, no assumed programming or imaging jargon) and bans machine-flavored prose. The PR template requires plain-language descriptions, runnable examples, test evidence, and fixture citations. DATACITATION.md records the origin and license of every committed DICOM test file, with the legacy files honestly marked as provenance-pending. Co-Authored-By: Claude Fable 5 <[email protected]> * ci: configure lockstep prerelease publishing from the 1.0-beta branch semantic-release computes one version from conventional commits; stamp-workspace-versions.mjs writes it into every publishable workspace package.json, and pnpm -r publish releases them together under the npm beta tag. The publish workflow now also fires on 1.0-beta and release/0.5x, and passes NODE_AUTH_TOKEN for pnpm publish. Nothing publishes until the repository owner adds 1.0-beta to the publish environment allowlist. See RELEASE_PLAN.md sections 9 and 12. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: fold the unslop pattern catalog into the writing style guide Adapts the rules from Cursor's unslop skill: the fuller AI-vocabulary list, filler phrases, fancy synonyms for is, vague attributions, synonym cycling, false ranges, punctuation and formatting rules (em dashes, colons, bold, sentence-case headings, straight quotes), abstract metaphor nouns, and a plain-speech section that includes the rule against over-compressed arrow-speak. Also states the boundary this guide draws that unslop does not: metaphors that teach a concept to a non-technical reader stay, metaphors that decorate go. The guide's own prose now follows its own em-dash rule. Source: https://github.com/cursor/plugins/blob/main/pstack/skills/unslop/SKILL.md Co-Authored-By: Claude Fable 5 <[email protected]> * docs: restructure the package map per first review round Adopts wayfarer3130's review comments: the engines split from the data types (core = building blocks only; legacy = today's readers and writers; parser = the new streaming reader; generator = the new writers). The vendored dicom-parser tokenizer is dropped from the 1.0 stream entirely, and about 300 tests retire with it. @dcmjs/media is added as a bundle over dicomdir, pdfs, and video, which all remain individually installable. The wrapper publishes as @dcmjs/dcmjs during the beta so the real dcmjs name stays untouched until the team is ready. FHIR stays in the plan with its landing order marked as an open question. Section 7 is rewritten to the simpler tests-travel-with-code approach discussed since the first draft. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: drop the FHIR sequencing aside from the package table Co-Authored-By: Claude Fable 5 <[email protected]> * docs: describe FHIR's role in the landing order instead of hedging its sequencing Co-Authored-By: Claude Fable 5 <[email protected]> * docs: add @dcmjs/mcp and @dcmjs/web to the package map as stretch goals Co-Authored-By: Claude Fable 5 <[email protected]> * Update RELEASE_PLAN.md * docs: plain-language pass on the plan intro, plus three publishing clarifications from review Rewrites the section-1 metaphor in direct terms and retitles section 6. Adds the breaking-change-commit requirement for the first 1.0.0-beta.1 version calculation, documents the private root package during the beta, records dist-tag promotion as a deliberate manual step, and fixes the appendix publishCmd to tag by channel instead of hardcoding beta. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: tag publishes by channel and keep the unscoped root private during the beta Review found the publish command hardcoded --tag beta, which would have followed 1.0-beta into master at GA, and that a recursive publish would ship the unscoped dcmjs name during the beta against the plan's intent. The tag now derives from the release channel, and the root package is private until the @dcmjs/dcmjs wrapper PR renames it. Dist-tag promotion stays deliberately manual, now documented in RELEASE_PLAN section 10. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: publish under the @dcmjs-org scope The @dcmjs npm organization is not ours; per review discussion the packages publish under @dcmjs-org (matching the GitHub organization), and the team can reconsider the shorter scope if its owner responds. Every package name in the plan now reads @dcmjs-org/. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: follow the @dcmjs-org scope in the data citation file 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]> * docs: name the @dcmjs-org scope in the owner actions of the release plan Co-Authored-By: Claude Opus 5.5 <[email protected]> * build(release): OIDC trusted publishing and a hardened, fully pinned publish job Review feedback from #519 (trusted publishing becomes required in 2027, so adopt it now): - minimumReleaseAge 1440 -> 2880 (two days) - semantic-release and its five plugins are exact-pinned devDependencies installed from the lockfile; the publish step runs pnpm exec semantic-release instead of cycjimmy/semantic-release-action with runtime-fetched extra_plugins - every action in the publish workflow is pinned by commit SHA - npm auth is OIDC trusted publishing: no NPM_TOKEN/NODE_AUTH_TOKEN, no registry-url .npmrc; RELEASE_PLAN documents the per-package trusted publisher setup and the first-publish bootstrap - cache: pnpm removed from the publish job Co-Authored-By: Claude Fable 5 <[email protected]> * build: move override pins to pnpm-workspace.yaml where pnpm 11 reads them pnpm 11 stopped reading package.json pnpm.overrides (it warned on every install), so the security pins silently stopped applying and the audit gate failed once the lockfile was regenerated: form-data@3 and ws@7 resolved to advisory-vulnerable versions through jest 27's jsdom chain, with more paths added by the new semantic-release devDependencies. Ports the fix already on release/1.0-beta-core: the overrides block (old pins plus audit minimums for adm-zip, js-yaml, brace-expansion, browserslist, ws@7, form-data@3) and the braces GHSA ignore (advisory names a patched >=3.0.4 that still does not exist on the registry; all paths are dev tooling) live in pnpm-workspace.yaml, and the dead package.json pnpm field is removed. pnpm audit --audit-level=high exits 0; full suite 320/320. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Bill Wallace <[email protected]>
Some older modalities illegally pad odd-length SpecificCharacterSet values to even length with a NUL byte instead of the space required by the standard (e.g. "ISO 2022 IR 6\0", seen in real 2007-era CR files). The NUL survived charset normalization, so the encodingMapping lookup missed and parsing threw "Unsupported character set: iso-2022-ir-6" — confusing, since the NUL is invisible in the message and that charset is supported. Strip NUL padding (and trim) before the lookup in all three readers: the core iso2022 resolver, the legacy synchronous DicomMessage, and the legacy AsyncDicomReader. Co-Authored-By: Claude Fable 5 <[email protected]>
Resolves the conflicts GitHub reported on PR #542. All fourteen came from PRs #518/#519 squash-merging onto 1.0-beta content that was co-developed with this branch, which hid the shared history. Resolution, per file: - DATACITATION.md and the nine conflicted test files: kept this branch's versions — 1.0-beta's copies are exact older snapshots of this branch's own history. - RELEASE_PLAN.md and .github/workflows/publish-package.yml: took 1.0-beta's versions — PR #519 deliberately superseded ours with the OIDC trusted-publishing rewrite and SHA-pinned actions. - pnpm-workspace.yaml: 1.0-beta's newer security config plus this branch's "packages/*" workspace entry (needed for packages/fixtures). - pnpm-lock.yaml: regenerated via pnpm install against the merged package.json. Verified with the full suite: 855 passed, 11 skipped. Co-Authored-By: Claude Fable 5 <[email protected]>
Commit cb65227 added graphify-out/ (local output of a code-graph tool) and an npm package-lock.json from 0.49.2 by mistake. This is a pnpm workspace, so pnpm-lock.yaml is the only lockfile. Ignore both paths from now on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The lint, format and format:check globs covered packages/*/src only, so the tests under packages/*/test were never checked in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CodeString.applyFormatting used trim(), which keeps a trailing NUL. Some modalities pad CS values to even length with NUL instead of a space, so values such as "CT\0" kept the NUL. The new trim0 helper also removes trailing NUL bytes. Also move the UV writeBytes explanation into its doc comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
DicomMessage and AsyncDicomReader each had their own copy of the SpecificCharacterSet normalization. Both now call resolveCharsetDecoder from @dcmjs-org/core, so a multi-valued ISO 2022 value now decodes in legacy too. Also move the long readFile and readSequence comments into doc comments, and add _readMetaGroupStructurally for the two duplicated structural File Meta reads. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The engine packages pointed main at ESM sources with imports that have no file extension, so a published package did not load in plain Node. rollup.packages.config.mjs now builds dist/index.mjs and dist/index.cjs for core, legacy, parser and generator, with every bare import external. publishConfig points main, module and exports at dist/, and main stays on src/ inside the workspace so that the tests run on the sources. The root build script also builds the packages. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The parser passes two input shapes to the eager reader of legacy: an undefined-length element that is not SQ, and a bare dataset. It did not declare or load legacy, so a standalone parser threw on valid input. The parser now depends on @dcmjs-org/legacy and imports it to wire the eager reader. Notes in index.js, decodeCore.js and the README mark the dependency as temporary, until both fallbacks move to the standard async handling. The generator standalone test now checks that the generator's own manifest and sources do not reference legacy, because the module graph reaches legacy through the parser. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Long inline comment blocks now live in the doc comments of their methods. Where a block explained a distinct step, the step became a named function (readFileMetaInformation, decodeFmiValue, detectPreamble, replayBareDataset, runFeed, runInflateRelay, emitInlineBinary, writeDeflatedDataSet and others). The behaviour does not change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
beta-1-release-notes.md lists the user-facing changes of beta 1, and the open items to do after the staged package PRs merge. User-facing items and implementation items are in separate sections. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The parser decodes undefined-length elements that are not SQ with core only (decodeCore.decodeUndefinedLengthValues), and streams a bare dataset through the normal body loop of fromPart10Stream. The parser no longer imports @dcmjs-org/legacy, and the generator standalone test again has the jest.mock tripwire on legacy. Core no longer calls the eager reader. The SQ reader gets the item parser from readOptions.readItem, which DicomMessage._readTag gives. ValueRepresentation.setDicomMessageClass, getDicomMessageClass and Tag.setDicomMessageClass are removed. The release notes record the user-visible changes, and add the open item to replace AsyncDicomReader in a later 1.0 beta. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Naturalization no longer uses a Proxy. There is one naturalizer, core's DicomMetaDictionary.naturalizeDataset, which the 0.x surface also uses: - A dictionary VM of "1" or "0-1" gives a single value, or null when the value is empty. Any other VM keeps the list, also for one value. A binary VR keeps the list, because its Value lists frames. - A single-item sequence is the item object itself, with a hidden [0] (the item), a length of 1 and an iterator (core addAccessors). It is not an array. NaturalizedListener uses the same shape. - The readers and naturalize add the PN value accessors when they store a value (ValueRepresentation.addValueAccessorsFor). The tag Proxy (tagProxyHandler) is gone from core. Legacy keeps addTagAccessors and ValueRepresentation.addTagAccessors as no-ops for 0.x callers. Also fix the JSON of a PN list that holds a PN object with its own toJSON, and accept Value: null in naturalizeDataset. BREAKING CHANGE: a value with a VM above 1 stays a list when it has one value (for example ImageType, OperatorsName, SpecificCharacterSet). An empty VM-1 value is null instead of []. A single-item sequence is not an array, so forEach, map and push do not work on it; [0], length and for...of work. A PN value that a caller assigns gets its accessors when the dataset is denaturalized, not on assignment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
docs/MIGRATION.md and beta-1-release-notes.md now describe the 1.0 VM rule and the single-item sequence shape without a Proxy. The migration guide no longer says that the proxy arrays and the single-value collapse stay as in 0.x. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
beta-1-release-notes.md gets an open implementation item: code comments and test titles still carry slice, stage, review and TDD labels, and some comments describe old behaviour. The item lists the labels, the files, the names to keep, and the comments to correct. Co-Authored-By: Claude Opus 5.5 <[email protected]>
wayfarer3130
approved these changes
Oct 14, 2026
… test The 1.0 VM rule keeps SpecificCharacterSet as a list, as the charset tests already expect. This test needs the downloaded dclunie-charsets fixture, so the update landed separately. Co-Authored-By: Claude Fable 5 <[email protected]>
awatson1978
added a commit
that referenced
this pull request
Oct 14, 2026
Resolve the conflicts from the core merge (#542): - DATACITATION.md: take the 1.0-beta table, which has the same packages/fixtures paths plus the testImages rows - babel.config.js: take the 1.0-beta root config with the workspace-wide preset; remove packages/schemas/.babelrc, which a root babel.config.js no longer honors - pnpm-lock.yaml: take 1.0-beta and re-resolve with pnpm install Co-Authored-By: Claude Fable 5 <[email protected]>
wayfarer3130
added a commit
that referenced
this pull request
Oct 17, 2026
* feat: add the @dcmjs/schemas package with the naturalized-rules catalog generator Co-Authored-By: Claude Fable 5 <[email protected]> * refactor: drop the stale spec-file reference from the generated catalog header Co-Authored-By: Claude Fable 5 <[email protected]> * feat: commit the generated naturalized catalog, JSON-Schema, and type projections Co-Authored-By: Claude Fable 5 <[email protected]> * test: gate the schema artifacts with freshness, projection, and tsc consumer checks Co-Authored-By: Claude Fable 5 <[email protected]> * refactor: publish the workspace packages under the @dcmjs-org scope Co-Authored-By: Claude Fable 5 <[email protected]> * feat: mark @dcmjs-org/schemas publishable Drops the scaffold-era private flag and fills in the publish metadata the other packages already carry: the entry point (the naturalized rules module), the type declarations, license, and repository directory. Publishing stays gated behind the publish GitHub environment — merging this changes nothing on npm. 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) * fix(schemas): type AT as a number The readers store Tag.readTag(stream).value for AT, so a naturalized AT value is a number, not the "ggggeeee" string of the DICOM JSON model. FrameIncrementPointer read from a file now validates. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): parenthesize union element types in list attributes A one-string union like "number | string" with VM 1-n produced "number | string[]". SelectorSVValue and SelectorUVValue are now "(number | string)[]". Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): type binary VRs as frame arrays regardless of VM A binary Value lists frames, so PixelData and the other binary VRs naturalize as an array even with VM 1. The consumer check now asserts BinaryValue[] and indexes a frame. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): emit maxItems for fixed-VM attributes A fixed VM ("2", "3", "6") has vm.max equal to vm.min, and the old condition skipped maxItems in exactly that case, so the schema accepted PixelSpacing: [a, b, c]. 206 fixed-VM properties now carry the bound. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): require unique keywords, exclude the keywordless retired tags The dictionary gives the placeholder keyword RETIRED_undefined to three unrelated tags (00180061, 04000315, 300A0782), and the projections kept only the first. The generator now throws on a missing or duplicated keyword, the three keywordless retired tags are excluded explicitly, and the silent dedup paths in the d.ts and JSON Schema projections are gone. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(schemas)!: a sequence value is a dataset array or the single item The 1.0 VM rule naturalizes a single-item sequence as the item object itself (with a hidden [0], a length, and an iterator), not an array. The d.ts now types SQ as NaturalizedDataset | NaturalizedDataset[], the JSON Schema uses oneOf, and the envelope token is datasetArrayOrItem. BREAKING CHANGE: envelope.sequences changes from datasetArray to datasetArrayOrItem, and the generated SQ property types widen. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): declare the package as ESM with an exports map main points at a file that uses export, but the package had no type field, so Node before 22.7 fails with a SyntaxError and newer Node warns MODULE_TYPELESS_PACKAGE_JSON. The package now declares type module, an exports map with the types entry and the JSON Schema path, and a files list that ships only the generated artifacts. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): share the sequence shape through one $defs entry Inlining the two-branch sequence shape into every SQ property made the compiled ajv validator exceed the call stack, at compile time without allErrors and at validation time with it. Every SQ property now refs #/$defs/sequenceValue, which ajv compiles once. Co-Authored-By: Claude Fable 5 <[email protected]> * test(schemas): validate naturalized fixtures against the published schema Naturalize the three committed DICOM files and validate the result with ajv against schema/naturalized.schema.json. The structural contract holds with no exceptions; the three known value-space divergences (zero-length DA as "", a noncompliant AS value passed through, a zero-length DS list element as null) are pinned in the test until the value-format contract is decided. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(schemas)!: derive the attribute rules from the dictionary on demand The committed 642 KB catalog repeated the packed dictionary that dcmjs already ships. src/schema/naturalizedRules.js is now a hand-written module: the hand-decided data stays (envelope, vrFormats, MULTI_VR, the exclusion lists), and the per-attribute rules derive lazily from getAllStandardTagEntries through the same isMultiVM rule the runtime uses, so the two cannot drift. Each rule carries multi, and BINARY_VRS moves to a shared core utility that DicomMetaDictionary and the schemas package both import. parseVm loses its competing multi field and keeps only the VM bounds for the JSON Schema. The generator consumes the src module and writes only the two artifacts that must be static for ajv and tsc: the JSON Schema and the .d.ts. The jest determinism gate now compares those two projections to the committed files. The envelope gains values: "asReturned" — the schema describes what dcmjs returns, and vrFormats documents the Part 5 value formats separately (DS and IS are absent there, because they naturalize as numbers). The vrFormats stop being applied with the nullability fix, which lands next. BREAKING CHANGE: naturalizedRules.attributes is a derived, cached getter instead of committed data; entries carry a multi flag; dictionaryHash lives only on the generated artifacts. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas)!: encode the as-returned value space The schema now describes what naturalizeDataset returns (envelope.values "asReturned"): - A present-but-empty element is null, so every property type carries null, and list entries can be null (a DS list holds null for an empty entry). - A binary value is a frame list OR one bulk reference object ({BulkDataURI} | {InlineBinary}), through a shared $defs/binaryValue. - A PN value is the component object, enforced through $defs/personName. - UV and SV are bigint — the readers store readBigUint64/readBigInt64 values. JSON.stringify throws on them; the type now says so. - The Part 5 value formats move from validation keywords to the x-dicom-format annotation; vrFormats documents them separately. The fixture validation test now expects zero divergences for all three files and adds the two shapes from the review: a present-but-empty PatientID and PixelData as a bulk reference, plus a null DS list entry. BREAKING CHANGE: generated property types are nullable; binary and PN properties validate through $defs; the JSON Schema no longer enforces Part 5 patterns or lengths. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(schemas): close the consumer-facing gaps from the review - The generated .d.ts declares the module exports (naturalizedRules, getAttributeRule, envelope, vrFormats, the rule and format interfaces), so a TypeScript import of the package resolves without TS2305, and the tsc gate now imports them. - The exports map gains a default condition for require() users. - schema-freshness.yml watches the dictionary sources where they live now (packages/core/src), plus the isMultiVM and binaryVRs rules the derivation depends on. - A consumer-walk test reads each fixture file and checks every naturalized attribute against its derived rule: list vs scalar and the VR's JavaScript type, recursing through sequences. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(schemas): explain the package, pin the tool versions The README now answers what the package is for and who uses it, how the rules differ from the raw dictionary (semantics derived on demand, not a copy), why the package lives in this repository, which artifact serves which task, and the as-returned value contract — with an ajv usage example matching the validation test. ajv and typescript move to exact pins like the other devDependencies, so a minor tsc release cannot change an @ts-expect-error outcome. Co-Authored-By: Claude Fable 5 <[email protected]> * style: run prettier on the projection test Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Bill Wallace <[email protected]>
wayfarer3130
pushed a commit
that referenced
this pull request
Oct 19, 2026
* 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]> * 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]> * 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) * test(dicomdir): add opt-in large-media round-trip; clarify multi-study support Addresses review on PR #575: - README: add a two-patient/two-study example and state that grouping by patient/study/series is automatic. The single-entry example read as single-series only. - standalone.test.js: reword the header so the no-legacy framing belongs to the test (which pins it), not to the package (whose purpose is building and writing DICOMDIRs). - Add mediaRoundTrip.long.test.js, gated on DCMJS_LONG_TESTS: stream a multi-GiB video to disk, index it in a DICOMDIR, then read the media back via fromPart10Stream with a zero-retention listener. Verified at 3 GiB under a 512 MB heap cap. Pulls in @dcmjs-org/parser as a devDependency. - README: link #611 for the follow-up read/index/QIDO API. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
|
🎉 This PR is included in version 1.0.0-beta.1 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
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
* 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]> * 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]> * 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) * feat(imaging): extract @dcmjs-org/imaging from @dcmjs-org/video PR #588 review (conversation with Bill): split the lightweight, codec-free image building out of video so a consumer that only needs to build image instances doesn't pull the heavy MP4/video machinery, and SOP-specific image info stays out of core. New @dcmjs-org/imaging (depends on core only): - buildImageDataset + SECONDARY_CAPTURE_SOP_CLASS_UID (moved from video/src/image) - parseJpegInfo (moved) - h264TransferSyntaxUID (extracted from video/src/image/mp4Info.js into src/h264.js) @dcmjs-org/video now depends on @dcmjs-org/imaging: - parseMp4Info stays (MP4 container parsing is video-domain) and imports h264TransferSyntaxUID from imaging - src/image/ and the public surface trimmed to parseMp4Info + the video encapsulation/streaming; descriptions/comments updated Tests moved with their code (buildImageDataset, jpegInfo); the h264TransferSyntaxUID describe block moved to packages/imaging/test/h264.test.js. RELEASE_PLAN gains an imaging row and notes the landing order (imaging with/before video). Full suite 954 passed / 11 skipped / 0 failed. Follow-ons (separate branches): media exports an imaging namespace and sources the image builders from imaging; fhir->imaging deferred until fhir builds images. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(imaging,video): build image and video instances with createInstance buildImageDataset and buildVideoDataset now use createInstance from @dcmjs-org/core, the same creator pattern as @dcmjs-org/encapsulated: - New base blocks: imageBase / secondaryCaptureImageBase and videoBase / videoPhotographicBase, each with predecessorBase. - The instance, dataLevel, levels, predecessor and baseDicom options pass through to createInstance. Payload attributes (geometry, stream values, transfer syntax) are set after it. - createInstance writes only DICOM attributes (keywords, tags, _meta/_vrMap) from the overrides; other keys are dropped with a warning. Each builder removes its own control keys first. - The video base no longer sets StudyID 1; a new study gets the Type 2 empty StudyID from studyBase. - buildImageDataset reuses the core EXPLICIT_LITTLE_ENDIAN and merges _vrMap. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(core): createInstance keeps keywords added with registerTag The attribute filter now accepts a keyword that lookupRegisteredTagByName finds, as denaturalizeDataset does. Before this fix, such an override was dropped with a warning. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(core,imaging,video): one instance-creation model for all builders All builders (encapsulate, buildVideoDataset, buildImageDataset) take the same options: createInstance options, attribute overrides, and their own payload control keys. packages/core/README.md documents the shared model (CORE-USR/CORE-IMP); the package READMEs refer to it. core createInstance: - never copies the identity of `instance` (SOPInstanceUID, SOPClassUID, InstanceNumber, media storage UIDs), also with a custom `levels` - InstanceNumber at series level is the largest prior number + 1 - Type 2 empty StudyDate/StudyTime/SeriesNumber for an inherited level - skips undefined overrides; rejects a DICOM JSON `instance` - nextSeriesNumberBase counts only IS integers imaging: - remove the `metadata` option and the old `derivedFrom` shapes - new derivedImageAttributes / derivedImageBase: derivation from one or more naturalized instances, as a base block; lossy history is kept - ImageType ORIGINAL\PRIMARY is a base value video: README with VID requirements; control keys removed before the call. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(core,encapsulated,imaging,video): overrides provider and postProcess All builders take one option shape: the createInstance controls (baseDicom, instance, dataLevel, levels, predecessor, postProcess), their own control keys, and `overrides`. `overrides` is a naturalized DICOM provider with the same forms as baseDicom; its attributes go only into the result. An extra option key has no effect. core createInstance: - baseDicom resolves, then overrides; merge base < inherited < overrides, with a key merge of _meta; then postProcess (default removeUndefinedAttributes, top level only), so an undefined override removes the attribute - `instance` gives the attributes that `levels` lists; at dataLevel series the new InstanceNumber is the sample (first) instance's + 1 - Modality warning uses a presence check of the override - validation is part of the usage flow (CORE-IMP-11); pure type checks removed encapsulated: export PDF_MIME_TYPE; a builder sets only _meta.TransferSyntaxUID on a copy of _meta. imaging: geometry, HighBit and PixelRepresentation are written only when the decoded image gives them; ConversionType is a base value; a float pixel array throws. video: no attribute for a missing mp4Info field; createVideoEventSource keeps the returned _meta and the caller's file meta keys; normalizeFragmentBytes is no longer exported. eslint: no-unused-vars ignoreRestSiblings. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(imaging,video): predecessorBase only in the encapsulated bases predecessorBase is an optional base block in core, one more way to add default attributes. The encapsulated document bases include it. imageBase and videoBase no longer include it, so `predecessor: true` has no effect with those default bases. A caller can add the block, for example combineBases(imageBase, predecessorBase). 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.
This is the assembly PR for the core package: it brings
release/1.0-beta-coreinto1.0-beta, carrying everything that landed on the staging branch as PRs #521 through #596, each of which was individually reviewed and has its own plain-English description with code samples. This PR is ready for a review for the merge. The review fixes of 2026-10-13 are in the section Review fixes below.What this is in plain terms. The 1.0 rewrite replaces dcmjs's read path with an event-stream engine. Instead of one function that buffers a whole DICOM file and returns a finished object, the new engine parses bytes as they arrive and emits small events — "element started," "value decoded," "sequence item ended" — that any consumer can listen to. A buffered read is now just the degenerate case: feed the stream one big chunk. That's what makes bounded-memory reading of large files possible, and it's the foundation the FHIR mapping and the rest of the rewrite will build on in later PRs. This assembly delivers both halves of that engine — the complete reading stack and the writer sinks including the streaming Part 10 writer — plus the
DicomEventStreamfacade over them, the fixes for all sixteen core-scope findings from the #512 review, a regression bank of tests pinning today's behavior, the fixtures package they run against, and the process documents that govern how all of this lands.A worked example. Streaming a file from disk into a naturalized dataset — the memory high-water mark stays bounded no matter how large the file is:
The buffered entry points still work exactly as before —
DicomMessage.readFile(buffer)— and gained one explicit opt-in from issue #93, for data that has no file header at all (bare DIMSE-style datasets):What's in it, wave by wave. Six groups of changes, in the order they landed:
Process and tooling (from the docs PRs this branch was built on): RELEASE_PLAN.md, the writing style guide, the PR template, DATACITATION.md, lockstep prerelease publishing config (
.releaserc.json) so merges into1.0-betacan publish1.0.0-beta.Nunder the npmbetatag, a pipeline smoke test, and a fixture-reading helper that keeps the suites green on Node 24.The fixtures package (#521, #534): the six committed test DICOM files moved by pure
git mvintopackages/fixtures/dicom, every test routed through afixturePath()helper, and a vendored corpus of 20 test images inpackages/fixtures/testImagescovering all three endianness/explicitness permutations, deflate, and single- and multi-frame encapsulated pixel data. Every image's origin and license is recorded in DATACITATION.md (the dicomParser MIT set and David Clunie's deflate set). This PR also carries the fix that moved dependency pins intopnpm-workspace.yamloverrides, resolving 15 pre-existing high-severity audit advisories in dev tooling.The green regression bank (#524–#529): twenty-plus suites under
test/issues/, each named for the GitHub issue it pins, covering round-trip integrity, UUID-derived UIDs, UN padding, encapsulated write, latin1 fallback, CS multi-value lengths, private tags, undefined-value writes, element ordering, async reader behavior, pooled buffer reads, lenient-read/strict-write, anonymizer behavior, and prototype safety. The idea: everything today's code gets right is pinned green before the engine changes anything, and everything still broken is checked in as anit.skipnaming the issue it waits on — 20 of them, which is exactly the skip count in the test summary. The later fix PRs flip skips to green; nothing can regress silently.The event-stream engine (#530, #532, #533, #535–#540): the contract and its reference
CollectorListener; thefromDicomWebJsonandfromDataSetsources for input that's already parsed;createEventAsyncIterablefor pull-style consumption with cancellation on early exit (review finding 13); the element-decode primitives and ISO 2022 character-set decoders; theallowMissingHeaderfix for issue #93; the xs meta-VR fix (signed-vs-unsigned now resolved via PixelRepresentation) plus a much quieter unknown-VR fallback; the streaming Part 10 reader itself (#538, under the granted budget waiver — a single 1,468-line state machine handling incremental File Meta decode, deflate via incremental pako inflation, encapsulated fragments with Basic Offset Table windowing, and a backpressure relay for review finding 12); theNaturalizedListenerthat turns any event stream into the familiar naturalized model; and the dual-path suites proving the buffered and streaming paths agree.One structural decision deserves its own sentence: the vendored dicom-parser tokenizer is gone. The buffered
fromPart10is now a thin wrapper feeding the streaming reader one chunk, so the library carries exactly one tokenizer — the inversion the #512 review recommended.The engine-fix wave (#544–#551): the eight core-scope code findings from the #512 review map, each fixed in its own small PR with the regression test that pins it — Buffer views parsed by their exact byte range (finding 1), UV null writes (3), private elements preserved through denaturalize in a writable shape (4), a structural fallback when the meta group length is overstated (24), the async reader brought into the xs contract (25), honest memory accounting in SplitDataView (27), the concat write-position fix (28), and registerTag symmetry without mutating the shared nameMap (32). Each PR body records whether the defect also exists on 0.x master; FINDINGS-CHECKLIST.md on this PR's base branch tracks all 33 findings with their fixing PRs.
The writers wave (#552–#557): the writer sinks ported from the rewrite with their review findings fixed in the port —
Part10WriterandDicomWebJsonWriter(#553); the streamingStreamingPart10Writerwith body-syntax-aware endianness, fragment-span slicing, and the test-helper fix (findings 5, 11, 22 — #555); the deflate-relay deadlock and dropped-source-error fixes infromPart10Stream(findings 6, 7 — #554); the 1,400-line stream-equivalence corpus bank with its chunk-gate fix (finding 23 — #556); and theDicomEventStreamfacade wiring the whole engine into adcmjs.eventStreamnamespace (#557, retiring finding 14 by trimming the video factories to their media-wave home). Plus a small test-infrastructure fix making fixture downloads fail fast instead of poisoning later runs (#552).The package split and review response (#563–#567): the engine now lives in its package folders —
@dcmjs-org/core(the shared building blocks: value representations, tags, buffer machinery, character sets, constants, the runtime dictionary, andDicomMetaDictionary),@dcmjs-org/legacy(the eager and async engines users run today, re-exporting the shared pieces so its surface is unchanged),@dcmjs-org/parser(the event-stream reading side), and@dcmjs-org/generator(the writer sinks). Every move is a puregit mvin its own commit with shims left at the old paths, so nothing outside the packages changed behavior — the full suite and the bundle surface are identical before and after. Two placement decisions are declared in the split PRs for reviewer eyes:DicomMetaDictionarywent to core (its imports are all core, its consumers span every package, and it andValueRepresentationreference each other — anywhere else creates a package cycle), andBufferStream/SplitDataViewwent to core rather than the plan table's legacy (the streaming reader and writers use them; legacy placement would force the new engines to depend on legacy, which we want to stay deprecable). One known residue, declared in #567:Part10Writerkeeps a temporary dependency on legacy'sDicomDict.write. #563 also renamed the intentional-changes document todocs/BREAKING_CHANGES.mdper review.The finish-out wave (#570, #590–#593): the engine packages dropped their scaffold-era private flags so the gated publish can ship them, with the
BREAKING CHANGE:footer §9 requires (#570); the anonymizer's defaulttagNamesToEmptylist had 103 entries that matched no dictionary keyword and were silently skipped — they now resolve andcleanTagsactually empties them, completing review finding 2 (#590, contract documented indocs/BREAKING_CHANGES.md); a corrected migration guide landed asdocs/MIGRATION.md, fixing the three documentation findings 29–31 (#592) — which closes out all 33 findings from the #512 review: fixed, retired with the lazy core, documented as intentional, or routed to their package waves and fixed there; the step-8@dcmjs-org/testsand@dcmjs-org/validatorscaffolds (#591); a scoped, documented audit ignore for the unpatchable braces advisory published 2026-10-02 (#593); and the removal of the generator package's last declared legacy edge — the Part 10 envelope relocated fromDicomDict.writeinto core'swriteCore, byte-exactness pinned on plain and deflated fixtures, so all three new-engine packages are now fully independent of legacy (#596).Test evidence. 863 tests across 73 suites: 852 passing, 11 skipped, 0 failing. The skip count has fallen from twenty to eleven as fixes landed. CI is green at the branch tip
a954dda— tests, lint/format, and audit — and I reproduced the same 847/11/858 locally. The corpus gate runs every vendored image through raw-bytes-to-events and compares element-for-element against the eager reader (it's the test that caught the xs defect fixed in #537), and the stream-equivalence bank additionally drives the corpus through the streaming path at multiple chunk sizes, down to one byte at a time.The GitHub issues this addresses. Between the regression bank and the engine-fix wave, this branch touches 53 GitHub issues, in four distinct ways — fixed outright, verified already-correct and pinned against regression, documented as a known gap with a skipped failing test, or blocked on a fixture nobody can obtain:
Fixed by this PR (9):
allowMissingHeader)(One mapping caveat for reviewers: #338's fixing PR #549 cites review finding 24 from the #512 review map rather than the issue number, and its regression test lives in
test/data.test.jsrather than an issue-named suite.)Behavior pinned green (30) — verified correct today and locked by regression tests; no code fix was needed:
cleanTagsfunction from anonymizer #172 (closed) — expose cleanTags from the anonymizer — pinned by issue345-anonymizer-names.test.jsCodeString.writeBytes()throws on valid multivalued CS tag when individual value exceeds maxLength of 16 #487 (open) — CodeString.writeBytes throws on valid multivalued CS — pinned by issue487-cs-multivalue-length.test.jsKnown gaps documented as skipped tests (10) — still failing, each tracked by an
it.skipKNOWN GAP entry naming the issue it waits on:Blocked awaiting fixtures (4) —
it.skipBLOCKED inventory markers in issue78-unobtainable-fixtures.test.js; these cannot be verified pass or fail until someone produces a file:Test usage and examples. The branch now carries an
EXAMPLES.mdat the repo root (#558) — a library-oriented worked tour of every API surface in this PR, adapted from the CLI examples document in awatson1978/dcmjs-commands. Every snippet in it was run against real files from the dcmjs-org/data releases before being written down, and the test-drive section at the bottom fetches everything it needs into/tmpin about two minutes. Three of its recipes, re-run for this description from a fresh checkout (pnpm install && pnpm run build, snippets saved as.mjsfiles in the repo root):Bounded memory, concretely. Take the 4 MB ultrasound cine from the fixtures release, inflate it to 211 MB by replaying its event stream through a filter that re-emits every pixel-data fragment 48 times, then read it back sampling live
ArrayBuffermemory as it streams:4.3 MB of peak live buffer memory against a 211 MB file, on this run — the eager
readFileSync+DicomMessage.readFilepath sits near 379 MB on the same file, and the streaming number is bounded by the chunk size and largest element, never the file. (Exact peaks vary a few MB run to run with GC timing; EXAMPLES.md records 15.6 MB for the same recipe.)Whole-slide imaging over live DICOMweb.
fromDicomWebJsonpointed at a real digital-pathology study on the public OHIF demo server — the base pyramid level is 21,710 frames tiling a 40,001 × 31,019 matrix, and the metadata naturalizes in under a second because pixel data stays behindBulkDataURIreferences:Pull events and stop early.
asyncIterable()givesfor await-able events with real backpressure, and breaking out of the loop cancels the parse — "what modality is this file?" costs a few kilobytes of reading, not a full pass:Benchmarks. The branch now also carries a
BENCHMARKS.mdat the repo root, with thebench/harness that produced it (#561), measured on both CI-tested Node versions — v22.20.0 and v24.9.0, which agree within run-to-run noise (Apple M4, 16 GB RAM, macOS). The headline comparison on the 211 MB stress file from the recipe above — median wall time plus peak liveArrayBuffermemory sampled after forced GC:On the write side that's the one-line summary:
StreamingPart10Writeris ~10–13× faster than the buffered writer at roughly 1/90th of the memory. On small committed fixtures the eager path remains the fastest way to a dataset (sub-millisecond; streaming adds ~1–2 ms of per-chunk overhead there). Full tables for both Node versions, the chunk-size/throughput trade-off, the method, and exact reproduction commands are in BENCHMARKS.md (#561).The numbers. 217 files changed, +28,470 / −6,687 lines against the base. Almost all of the deletions come from the package-split moves (git records them as renames; the PR view shows R100 for the pure moves). The branch has 100 conventional commits: the commits of 38 reviewed PRs, and the review fixes below. The PRs merged without a squash, so the release tooling sees each commit.
Review fixes (2026-10-13 and 2026-10-14). A review of this PR found ten items. The commits below fix six items, and they also remove the proxies from naturalization. Normal pushes added the commits, without a change to the history, so open PRs against
release/1.0-beta-coremerge cleanly.8f66e0cremovesgraphify-out/(output of a code-graph tool) and a stale npmpackage-lock.json. Commitcb65227added these files by mistake..gitignorenow excludes both paths.1fc7686addspackages/*/testto thelint,formatandformat:checkglobs.6baba9daddstrim0toCodeString.applyFormatting. A CS value now loses trailing NUL padding.6b268e7makesDicomMessageandAsyncDicomReaderuseresolveCharsetDecoderfrom@dcmjs-org/core. Before, legacy had two more copies of the charset normalization.3a8b290buildsdist/index.mjsanddist/index.cjsfor core, legacy, parser and generator.publishConfigpoints the published package atdist/, so the package loads in plain Node. A test packed the four packages withpnpm packand loaded them as ESM and as CJS.fe432f4declared a temporary dependency of@dcmjs-org/parseron@dcmjs-org/legacy.ae5348ethen removed the dependency: the parser reads undefined-length elements that are not SQ, and bare datasets, without the eager reader. Core no longer calls the eager reader either.c0a7c7fmoves long inline comments into doc comments, and splits some steps offromPart10Stream.jsinto named functions. The behaviour does not change.81912e0addsbeta-1-release-notes.md. This file lists the user-facing changes and the open items.795a69cand4544628add more open items.11dd755removes the proxies from naturalization (see User-facing changes).b8ba8b5updatesdocs/MIGRATION.mdfor this change.After the fixes, the full suite has 861 tests that pass, 11 skipped tests and no failures. Lint, format, the root build and the package builds pass.
User-facing changes. This PR changes behaviour that a user can see.
docs/BREAKING_CHANGES.md,docs/MIGRATION.mdandbeta-1-release-notes.mdgive the details. The naturalization change and the removed methods break the API. Most other changes correct a defect or an edge case:Naturalization has no Proxy, and the dictionary VM decides the shape. A VM of "1" or "0-1" gives a single value, or
nullwhen the value is empty. Any other VM keeps the list, also for one value, for exampleImageType,OperatorsNameandSpecificCharacterSet. A binary VR keeps the list, sodataset.PixelData[0]works as before.A single-item sequence is the item object, with a hidden
[0], alengthof 1 and an iterator. Bothseq.Fieldandseq[0].Fieldwork. The value is not an array, soforEach,mapandpushdo not work on it.A PN value that a caller assigns gets its accessors when the dataset is denaturalized, not on assignment.
ValueRepresentation.addTagAccessorsis a no-op.ValueRepresentation.setDicomMessageClass,ValueRepresentation.getDicomMessageClassandTag.setDicomMessageClassare removed. A direct call of the SQreadmust givereadOptions.readItem.fromPart10Streamstreams a bare dataset through its normal body loop. WithignoreErrors: true, a malformed bare dataset now throws.cleanTagsempties about 103 more attributes, which include sequences that can hold diagnostic content (PS3.15). The old default list had names that did not match a dictionary keyword, and the anonymizer skipped them.docs/BREAKING_CHANGES.mdgives the opt-out recipe.Input that is not DICOM fails with the error message of the streaming reader. The error text of the old vendored tokenizer is gone.
A non-conformant undefined-length UT element throws on both entry points. Before, the buffered path returned wrong data and gave no error.
The
xsmeta-VR resolves correctly for signed pixel data, on the sync reader and on the async reader.The fallback for an unknown VR logs one time, not one time for each element.
A UV element with null values writes. Before, the write threw.
A private element survives denaturalize and write. Before, the writer dropped the element or wrote it in a shape that it could not read back.
An overstated File Meta group length recovers with a warning. Before, the reader put the start of the body at the wrong offset.
2.25 UIDs come from RFC 4122 UUIDs.
The legacy readers decode a multi-valued ISO 2022 SpecificCharacterSet. Before, they threw, or used only the first value.
A CS value loses trailing NUL padding.
The tests that pinned the 0.x naturalized shapes now pin the 1.0 shapes. All other existing tests pass without a change.
Open items after the merge. No structural work remains on this branch.
beta-1-release-notes.mdtracks the open items: the routing of stream input inDicomEventStream.from(), the fullcleanTagslist indocs/BREAKING_CHANGES.md, the Basic Offset Table inStreamingPart10Writer, the original SpecificCharacterSet value, the replacement ofAsyncDicomReader, the npm name of the beta, a trim of the large streaming test suites, the removal of work-breakdown labels from comments, the move of the rootsrc/intopackages/dcmjs/, and the removal oftest/issues/catalog.json. Earlier cleanup items all landed — #559 restored the PS3.5 7.8.1 private-creator range (finding 26), #560 added deflate-on-write so the corpus gate now covers the deflate trio, and #562 ported the RFC 4122 uid() and starteddocs/BREAKING_CHANGES.md. Separately queued but not blockers for this branch: the master hotfix PRs for the master-applicable findings (1, 3 partial, 24, 25, 28 latent — verdicts in FINDINGS-CHECKLIST.md on the base branch; deferred for now), and the schemas assembly in #543. Merging this PR will also auto-resolve #518 and shrink #519, since this branch's history contains their commits.🤖 Generated with Claude Code