Skip to content

feat(wasm)!: Phase 2 — replace inline DTOs with include_str! (closes #1224) - #1225

Merged
robcohen merged 1 commit into
mainfrom
feat/ts-rs-phase-2-1224
May 28, 2026
Merged

robcohen merged 1 commit into
mainfrom
feat/ts-rs-phase-2-1224

Conversation

@robcohen

Copy link
Copy Markdown
Member

ADR-0004 Phase 2. The inline typescript_custom_section DTO block in crates/rustledger-wasm/src/lib.rs (~300 lines of hand-maintained types) is replaced with include_str!("../bindings/index.d.ts"). wasm-bindgen now embeds the ts-rs-generated bundle into the auto-generated pkg/*.d.ts, so the two TS surfaces (the hand-importable bundle and the wasm-bindgen npm-package types) are now the same types — no duplication, no drift.

Breaking for consumers using only the wasm-bindgen-generated pkg/*.d.ts — same rename set Phase 1 (#1223) brought to direct-bundle consumers, plus one new rename: Ledger (the wire-format DTO) now emits as LedgerJson on the TS side to avoid colliding with the Ledger runtime class.

What's in the PR

  • TS_TYPES_DTOS = include_str!("../bindings/index.d.ts"); new wasm-bindgen typescript_custom_section block. wasm-bindgen embeds include_str! contents identically to a raw-string literal.
  • Inline TS_TYPES block now contains ONLY the wasm-bindgen-managed surface:
    • ParsedLedger and Ledger runtime classes (with updated getDirectives() return type)
    • FileMap utility type
    • Standalone function signatures (parseMultiFile, validateMultiFile, queryMultiFile, hashSources)
  • ~300 lines deleted from src/lib.rs.
  • #[ts(rename = "LedgerJson")] on the Rust Ledger struct; bundle regenerated.
  • getDirectives() returns DirectiveJson[] in both classes (was Directive[]).
  • CHANGELOG entry under `[Unreleased] / ⚠ BREAKING CHANGES`.
  • ADR-0004 status: Phase 1 → Phase 1 + Phase 2.

Why LedgerJson?

Ledger in TS_TYPES was both an interface (the wire shape) AND a class (the runtime wrapper). TS handled this via declaration merging. After Phase 2, the bundle's Ledger would be a type alias — which can't merge with a class, causing TS errors. Renaming the wire-shape type to LedgerJson keeps both surfaces clean:

  • LedgerJson — wire shape returned by parse(...), stored on ParseResult.ledger
  • Ledger — runtime class instantiated via Ledger.fromFiles(...)

Migration

// Old
import { Posting, Directive, Amount, Error } from "@rustledger/wasm";

// New
import {
  PostingJson, DirectiveJson, AmountValue, BeancountError
} from "@rustledger/wasm";

For ledger data vs the runtime class:

// Class (unchanged)
const ledger: Ledger = Ledger.fromFiles(files, "main.beancount");

// Wire shape from parse() (renamed)
const result: ParseResult = parse(source);
const data: LedgerJson | null = result.ledger;

Test plan

  • cargo test -p rustledger-wasm (default): 80/80 pass
  • cargo test -p rustledger-wasm --features ts-export --lib: 114/114 pass
  • cargo clippy -p rustledger-wasm --all-targets -- -D warnings: clean
  • cargo fmt --all -- --check: clean
  • RUSTLEDGER_TS_CHECK=1 scripts/regen-ts-bindings.sh: OK

Closes #1224.

🤖 Generated with Claude Code

…1224)

ADR-0004 Phase 2: the inline `typescript_custom_section` DTO block in
`crates/rustledger-wasm/src/lib.rs` (~300 lines of hand-maintained
types) is replaced with `include_str!("../bindings/index.d.ts")`.
wasm-bindgen now embeds the ts-rs-generated bundle into the
auto-generated `pkg/*.d.ts`, so the two TS surfaces (the
hand-importable bundle and the wasm-bindgen npm-package types) are
the SAME types -- no duplication, no drift.

BREAKING CHANGE: this is the second wave of TS renames hitting
consumers who only use the wasm-bindgen-generated `pkg/*.d.ts` (the
first wave, in #1223, hit direct-bundle consumers). The full set of
renames:

- `Directive` -> `DirectiveJson` (discriminated union, no longer
  separate `TransactionDirective` / `BalanceDirective` / etc.
  interfaces)
- `Posting` -> `PostingJson`
- `Amount` -> `AmountValue`
- `CostNumber` -> `CostNumberJson`
- `PostingCost` -> `PostingCostJson`
- `TypedValue` -> `TypedValueJson`
- `Completion` -> `CompletionJson` (BQL completion)
- `CompletionResult` -> `CompletionResultJson`
- `EditorCompletionKind` -> `CompletionKind`
- `Error` -> `BeancountError` (avoiding JS-builtin Error shadow)

Plus one new rename specifically for Phase 2:

- `Ledger` (the wire-format DTO returned by `parse(...)`) now emits
  as `LedgerJson` on the TS side, to avoid colliding with the
  wasm-bindgen-exported `Ledger` CLASS (the runtime wrapper
  consumers instantiate via `Ledger.fromFiles(...)`). `LedgerJson`
  is the wire shape; `Ledger` is the class.

Class method signatures updated: `ParsedLedger.getDirectives()` and
`Ledger.getDirectives()` now return `DirectiveJson[]` (was
`Directive[]`).

## Implementation

- New `#[wasm_bindgen(typescript_custom_section)] const TS_TYPES_DTOS:
  &'static str = include_str!("../bindings/index.d.ts");` block in
  `src/lib.rs`. wasm-bindgen embeds the include_str! contents into
  the generated `pkg/*.d.ts` identically to a raw-string literal.
- Inline `TS_TYPES` block now contains ONLY:
  - The `ParsedLedger` and `Ledger` runtime classes (with updated
    `getDirectives()` return types)
  - The `FileMap` utility type
  - The standalone `parseMultiFile` / `validateMultiFile` /
    `queryMultiFile` / `hashSources` function signatures
- ~300 lines of duplicate DTO declarations deleted from `src/lib.rs`.
- `#[ts(rename = "LedgerJson")]` added to the Rust `Ledger` struct
  in `src/types.rs`.
- Bundle regenerated to use the new `LedgerJson` name.

## Migration

Consumers using the wasm-bindgen-generated `pkg/*.d.ts` (i.e. anyone
doing `import { Posting, Directive } from "@rustledger/wasm"`) must
update imports:

```ts
// Old
import { Posting, Directive, Amount, Error } from "@rustledger/wasm";

// New
import {
  PostingJson, DirectiveJson, AmountValue, BeancountError
} from "@rustledger/wasm";
```

For ledger data vs the runtime class:

```ts
// Class (unchanged)
const ledger: Ledger = Ledger.fromFiles(files, "main.beancount");

// Wire shape from parse() (renamed)
const result: ParseResult = parse(source);
const data: LedgerJson | null = result.ledger;
```

## Verification

- `cargo test -p rustledger-wasm` (default features): 80/80 pass.
- `cargo test -p rustledger-wasm --features ts-export --lib`: 114/114
  pass.
- `cargo clippy -p rustledger-wasm --all-targets -- -D warnings`:
  clean.
- `cargo fmt --all -- --check`: clean.
- `RUSTLEDGER_TS_CHECK=1 scripts/regen-ts-bindings.sh`: OK.

Closes #1224.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner May 28, 2026 15:51
Copilot AI review requested due to automatic review settings May 28, 2026 15:51
@codecov

codecov Bot commented May 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR completes ADR-0004 Phase 2 by making the wasm-bindgen-emitted TypeScript surface reuse the generated DTO bundle, reducing duplicated hand-maintained TypeScript definitions and aligning package consumers with the generated bindings.

Changes:

  • Embeds bindings/index.d.ts into wasm-bindgen TypeScript output via include_str!.
  • Renames the TypeScript wire DTO Ledger to LedgerJson to avoid colliding with the runtime Ledger class.
  • Updates ADR and changelog documentation to reflect Phase 2 completion and the converged TypeScript surface.

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
docs/reference/adr/index.md Updates ADR-0004 status to Phase 1 + 2.
docs/reference/adr/0004-ts-types-from-rust-dtos.md Documents Phase 2 completion and the new embedded generated DTO bundle.
crates/rustledger-wasm/src/types.rs Adds the LedgerJson TypeScript rename for the Rust Ledger DTO.
crates/rustledger-wasm/src/lib.rs Replaces inline DTO definitions with the generated bundle and updates runtime class method return types.
crates/rustledger-wasm/CHANGELOG.md Records the Phase 2 breaking TypeScript surface convergence.
crates/rustledger-wasm/bindings/index.d.ts Regenerates bindings with LedgerJson and updates ParseResult.ledger.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@robcohen
robcohen merged commit 9ecef97 into main May 28, 2026
36 of 37 checks passed
@robcohen
robcohen deleted the feat/ts-rs-phase-2-1224 branch May 28, 2026 15:57
@github-actions

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.2ms ± 0.5ms 25.1 MB
beancount 886.2ms ± 12.5ms 50.4 MB
Comparison 25.9x faster 2.0x less

vs main branch (2026-05-28)

Metric main this PR Change
Time 29.7ms 34.2ms +15.2% 🔴
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 791
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen added a commit that referenced this pull request May 29, 2026
) (#1241)

* feat(wasm): ADR-0004 Phase 3 -- JSON Schema + Python types (closes #1232)

Adds JSON Schema and Pydantic v2 outputs alongside the existing ts-rs
TypeScript generation, completing ADR-0004's single-source-of-truth
arc for wire-format DTOs.

## What

- New `json-schema` feature on `rustledger-wasm` -- mirrors `ts-export`.
  Pulls in `schemars` 1.x as a host-only optional dep behind the same
  `cfg(not(target_arch = "wasm32"))` guard.
- Every DTO that has `#[derive(ts_rs::TS)]` now also has
  `#[derive(schemars::JsonSchema)]` (35 new derives, mechanical).
  schemars respects the existing serde attributes natively
  (`tag = "type"`, `rename`, `rename_all`, `skip_serializing_if`,
  untagged enums) so no per-field annotation was needed.
- New `export_index_schema` test (`#[ignore]` by default) walks the
  DTO graph from `ParseResult` and writes a single draft-2020-12
  schema. All other types appear under `$defs`.
- `scripts/regen-ts-bindings.sh` renamed to `scripts/regen-bindings.sh`
  and extended with two new phases:
  - Phase 2: run the schema export test, prettier the output to
    `bindings/index.schema.json`.
  - Phase 3: pipe the schema through `datamodel-code-generator`
    (Pydantic v2 BaseModel, target Python 3.12) into
    `bindings/types.py`. Three invocation paths tried in order:
    `datamodel-codegen`, `pipx run`, `uvx`.
- CI's `ts-bindings-fresh` job renamed to `bindings-fresh` and now
  diffs all three artifacts (`index.d.ts`, `index.schema.json`,
  `types.py`). Adds `actions/[email protected]` with Python 3.12;
  `pipx` is preinstalled on ubuntu-latest.
- `should_build` path filter now includes `scripts/regen-bindings.sh`
  and `crates/rustledger-wasm/bindings/**` -- closes the gap that
  PR #1228 review flagged (script-only changes used to skip the
  freshness job).

## Why

Phase 1 + 2 (#1218 -> #1223 -> #1225) closed TypeScript drift but two
surfaces stayed hand-maintained:

1. `crates/rustledger-ffi-wasi/python/compat.py` -- same drift class
   ADR-0004 closed for TS was still live for Python.
2. No machine-readable schema for external integrators (LLM tool
   builders, third-party SDKs, MCP server).

This PR closes both.

## Alternatives ruled out (documented in ADR-0004 Phase 3 section)

- **specta wholesale migration** -- still `2.0.0-rc.25` after 14
  months, sister crates at `0.0.x`. `specta-jsonschema` planned but
  unpublished. Python listed as "planned" with no crate.
- **`serde-generate` (Diem/Aptos)** -- single tool with Python output
  but doesn't support `serde(tag = ...)` tagged enums (our entire
  `DirectiveJson` is one).
- **`pyo3-stub-gen` / `rustantic`** -- both require DTOs as PyClasses,
  not plain serde-deriving structs.
- **`quicktype` TS->Python** -- no Pydantic v2 output path
  (glideapps/quicktype#1474).

There is no ts-rs analogue for Python in May 2026. The hybrid
(`schemars` + `datamodel-code-generator`) is what the ecosystem
actually supports.

## Trade-offs

- `TypedValueJson` narrowing is applied only on the TS side
  (hand-tuned override in the regen script). JSON Schema and Python
  see the wide `{type, value}` form. Pydantic v2's discriminated-union
  ergonomics don't map cleanly from a TS literal-union override;
  maintaining two narrowings wasn't worth it for one type.
- One additional `cargo deny check` review: `schemars` 1.x has a clean
  license + advisory profile; small dep graph.

## Verified locally

- `cargo check -p rustledger-wasm --features json-schema --lib` --
  all 35 DTOs compile with the new derive.
- `cargo test -p rustledger-wasm --features json-schema --lib --
  --include-ignored export_index_schema` -- writes
  `bindings/index.schema.json` (669 lines, draft-2020-12, with
  doc-comments propagated as `description` fields, `LedgerJson` /
  `BeancountError` renames picked up, `anyOf+null` for
  `Option<Ledger>`, `required` excludes `skip_serializing_if` fields).
- `uvx datamodel-code-generator ...` -- emits 451-line `types.py`
  with `DirectiveJson` as `RootModel[Union[DirectiveJson1..12]]` and
  per-variant `type: Literal["transaction"|...]` discriminators.
  Pydantic v2 narrowing works.
- `RUSTLEDGER_TS_CHECK=1 ./scripts/regen-bindings.sh` -- passes after
  initial bootstrap.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* chore: regenerate cargo-vet exemptions

* fix(wasm): address PR #1241 deep review findings

Fixes all 15 correctness/quality findings from the high-effort review of
PR #1241 (ADR-0004 Phase 3). Schema-level changes regenerate the three
artifacts; the regen script itself gets tightened up.

## Critical

1. **CI: bindings-fresh now blocks merge.** The aggregate `build` gate
   omitted `bindings-fresh` from its `needs:` list, so wire-format
   drift could land on main even with a red bindings-fresh check. Add
   it to needs + the result-check.

2. **Schema `required` arrays match the documented wire contract.**
   `ParseResult.ledger`, `LedgerOptions.title`, `BeancountError.line`,
   `BeancountError.column` are `Option<T>` without
   `skip_serializing_if` -- always present on the wire as null. The
   Rust DTO docstrings have always said so; schemars 1.x defaulted
   Option<T> to non-required, contradicting that. Use
   `schemars(extend("required" = [...]))` (which preserves the
   nullable type, unlike per-field `schemars(required)` which drops
   the null arm).

3. **Schema root broadened from `ParseResult` to a new
   `RustledgerBindings` wrapper** so the schema $defs covers every
   public DTO, not just the parse subgraph. Was 11 of 34 TS types
   covered; now 33 of 34 with 53 Pydantic classes generated.
   `RustledgerBindings` is a codegen-only struct (no Serialize, no
   wasm_bindgen export) -- its sole purpose is to give
   `schema_for!` a single root that reaches the full surface.

4. **Removed `sed '/^WARNING/d'` filter on datamodel-code-generator
   output** -- this was exactly the pattern `feedback_no_error_swallowing.md`
   warns about. Warnings now flow to stderr where they belong.
   Replaced with a final `[ ! -s "$PY_OUTPUT" ]` sanity check so a
   0-exit + empty output still fails the regen.

5. **`cargo test` schema invocation uses `--exact` plus an mtime
   guard.** Was a substring filter that exits 0 on zero matches --
   silently leaving the committed schema stale if `fn
   export_index_schema` is ever renamed. The mtime guard catches
   any non-write.

## Medium

6. **`rm -rf "$RAW_DIR"`** before Phase 1's `cargo test --features
   ts-export` so stale per-type `.ts` files from removed/renamed
   DTOs don't leak into the concatenated bundle.

7. **`export_index_schema` test requires `RUSTLEDGER_REGEN_SCHEMA=1`**
   in addition to `#[ignore]`. A developer running `cargo test
   --include-ignored` no longer silently mutates the checked-in
   schema; the test no-ops with an explanatory message.

8. **EXIT trap covers all sidecar files** (`.new`, `.fmt`, `.err` for
   both TS and schema outputs), not just `$TMP_OUT`. SIGINT or
   mid-script failure no longer leaks files into `bindings/` that
   could be accidentally committed.

9. **Freshness check fixes:**
   - Drop `2>&1` swallow on `git diff` so genuine git errors (not a
     repo, ambiguous ref, etc.) surface instead of being misdiagnosed
     as drift.
   - Add `git ls-files --error-unmatch` per path so a future binding
     added by the regen but not `git add`-ed gets caught instead of
     silently escaping (git diff only reports tracked-file changes).
   - `cd "$REPO_ROOT"` before the loop so absolute paths resolve
     regardless of CWD.

10. **Pinned versions** for both schemars (`Cargo.toml`:
    `schemars = "=1.2.1"`) and datamodel-code-generator (script:
    `DATAMODEL_CODEGEN_VERSION="0.32.0"` propagated to `pipx run
    --spec` and `uvx --from`). The TS phase already pinned
    `prettier@3`; the new tools now match.

## Minor

11. **CHANGELOG.md**: `regen-ts-bindings.sh` -> `regen-bindings.sh`
    reference at line 37.

12. **`BeancountError.line`/`column`**: schema now emits `minimum: 1`
    via `schemars(range(min = 1))`, matching the doc-comment "1-based"
    instead of the u32-default `minimum: 0`.

13. **Dropped `--no-semi=false` from prettier invocation** -- prettier
    3 silently ignored it (warning in every CI log: "Did you mean
    --semi?"). Prettier's default is semis-on; the flag was both
    wrong syntactically and unnecessary.

14. **Import-strip rewritten as awk block-mode** so multi-line `import
    type { ... }` blocks (which ts-rs can emit for long import lists)
    don't leak continuation lines into the bundle as orphan TS syntax.
    The old `sed '/^import type/d'` only handled single-line imports.

## Verified

- `nix develop -- ./scripts/regen-bindings.sh` regenerates all three
  artifacts cleanly.
- `RUSTLEDGER_TS_CHECK=1 ./scripts/regen-bindings.sh` reports "OK: TS
  / JSON Schema / Python bindings match the committed state" --
  regen is idempotent on the committed output.
- Schema $defs count: 11 -> 33 (32% -> ~97% coverage).
- Pydantic class count in types.py: 28 -> 53.
- `ParseResult.required = ["ledger", "errors"]`, ledger property still
  `anyOf: [LedgerJson, null]`. Same shape for LedgerOptions.title and
  BeancountError.line/column.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(wasm): address PR #1241 round-2 review findings

Addresses the 5 critical findings from the second deep review pass:

1. **FormatResult.formatted required.** The first round's `schemars(extend)`
   sweep caught ParseResult/LedgerOptions/Error but missed FormatResult,
   which has the same documented-always-present-Option pattern
   (Option<String> without skip_serializing_if). Schema now correctly
   reports `required: [formatted, errors]`.

2. **EditorLocation now in $defs + types.py.** RustledgerBindings missed
   it (no other DTO transitively references it), so ts-rs was emitting
   `export type EditorLocation` while the schema and Python had no
   counterpart. Added `editor_location: EditorLocation` to the wrapper.

3. **RustledgerBindings no longer leaks as a public Pydantic class.**
   The wrapper struct exists only to seed `$defs` with every public
   DTO; its own `type: object, properties, required` shape was not
   intended as wire format. The export test now strips the wrapper's
   own root-level keys (`type`, `title`, `properties`, `required`,
   `additionalProperties`, `description`) before writing the schema.
   datamodel-code-generator's residual `class Model(RootModel[Any])`
   placeholder is awk-stripped in the regen script, with an assertion
   to fail loudly if the placeholder shape ever drifts. Net result:
   types.py contains exactly the 53 real public DTO classes, no
   wrapper artifacts.

4. **export_index_schema now panics when RUSTLEDGER_REGEN_SCHEMA is
   unset.** Was previously a silent `return;` that made cargo report
   the test as PASS even though no schema was written -- the eprintln
   advisory was invisible without `--nocapture`. Verified locally:
   `cargo test --include-ignored ... export_index_schema` now reports
   FAILED with a clear panic message.

5. **mtime guard replaced with a stdout sentinel.** The previous
   `[ $mtime_after -le $mtime_before ]` comparison used `stat -c %Y`'s
   whole-second resolution; a warm-cache regen completing in <1s
   could trigger a false-positive failure. The schema export test
   now `println!`s a sentinel (`EXPORT_INDEX_SCHEMA_RAN_OK`) on
   success, and the regen script pipes cargo output through `tee`
   and greps for it. No timing dependency; works on any filesystem.

The latent maintenance hazards from the same review (extend overrides
auto-detect, schemars exact-pin, etc.) are documented but not
addressed here -- they're trade-offs rather than bugs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(wasm): guard extend(required) lists + principled unused-import prune

Three follow-ups to the PR #1241 review work:

1. extend("required") sync guard. schemars(extend("required" = [...]))
   REPLACES the auto-detected required array rather than merging, so a
   field added to a struct without updating its extend list would
   silently drop out of the schema's required set. Added a test module
   (schema_required_invariants) asserting required == all properties for
   each of the four structs using the pattern (ParseResult,
   LedgerOptions, BeancountError, FormatResult). The tripwire fires if
   any extend list drifts out of sync.

2. clippy::doc_markdown fix on the RustledgerBindings doc comment
   (backticked the type name). Was never linted before because CI
   doesn't build with --features json-schema.

3. Replaced the hardcoded sed Any-strip with a pinned autoflake pass.
   The Model(RootModel[Any]) placeholder strip leaves an orphaned Any
   import (the CodeQL finding); autoflake==2.3.1
   --remove-all-unused-imports is a Python-aware prune rather than a
   line-delete band-aid. autoflake (pure Python) chosen over ruff
   because ruff's prebuilt dynamically-linked binary can't run on NixOS
   via uvx/pipx. Regenerated types.py drops the unused Any import.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Phase 2: replace typescript_custom_section with include_str!(bindings/index.d.ts) (ADR-0004)

2 participants