Skip to content

feat(wasm)!: generate TypeScript bindings from Rust DTOs (#1218 Phase 1) - #1223

Merged
robcohen merged 6 commits into
mainfrom
feat/ts-rs-phase-1-1218
May 28, 2026
Merged

robcohen merged 6 commits into
mainfrom
feat/ts-rs-phase-1-1218

Conversation

@robcohen

Copy link
Copy Markdown
Member

ADR-0004 Phase 1 implementation. The hand-maintained beancount.d.ts (494 lines) and beancount_wasm.d.ts (398 lines) are deleted and replaced by a single generated bindings/index.d.ts derived from the Rust DTOs in src/types.rs via ts-rs. CI fails the PR if a DTO changes without regenerating the bundle.

BREAKING to the TypeScript API surface: file layout + some type names. Type shapes are equivalent or narrower; the migration is mostly renames + import path updates.

What's in this PR

  • ts-export cargo feature (replaces the prior ts-rs-spike from the spike). Host-only optional dep; default builds + wasm32 unaffected.
  • Per-DTO derives on MetaValueJson, TypedValueJson, DirectiveJson, PostingJson, PostingCostJson, CostNumberJson, AmountValue. #[ts(optional)] on every Option field with skip_serializing_if = "Option::is_none".
  • Post-process script scripts/regen-ts-bindings.sh — runs cargo test --features ts-export, collates per-type files into bindings/index.d.ts, applies the hand-tuned TypedValueJson narrowing override (ADR-0004 refactor: extract validate_transaction into focused helper functions #4).
  • CI freshness gate — new ts-bindings-fresh job in .github/workflows/ci.yml runs the script with RUSTLEDGER_TS_CHECK=1 and fails if the bundle drifts.
  • CHANGELOG entry under Unreleased / Breaking Changes documenting the migration.
  • ADR-0004 status moves from Proposed → Accepted (Phase 1). Phase 2 (replacing typescript_custom_section with include_str!) is deferred.

Migration

  • Import from crates/rustledger-wasm/bindings/index.d.ts (the single bundle) instead of the two old files.
  • Per-variant directive interfaces are gone; use Extract<DirectiveJson, { type: "transaction" }> for the per-variant type.
  • Amount → AmountValue; Posting → PostingJson; Directive → DirectiveJson.

Test plan

  • cargo test -p rustledger-wasm (default): 80/80 pass.
  • cargo test -p rustledger-wasm --features ts-export --lib: 87/87 pass.
  • cargo clippy -p rustledger-wasm --all-targets -- -D warnings: clean.
  • cargo fmt --all -- --check: clean.
  • cargo deny check: clean (ts-rs 12.0.1 no advisories).
  • scripts/regen-ts-bindings.sh: produces a clean 200-line bundle.

Closes #1218.

🤖 Generated with Claude Code

ADR-0004 Phase 1 implementation. The hand-maintained
`crates/rustledger-wasm/beancount.d.ts` (494 lines) and
`beancount_wasm.d.ts` (398 lines) are deleted and replaced by a
single generated `crates/rustledger-wasm/bindings/index.d.ts` that
derives from the Rust DTOs in `src/types.rs` via `ts-rs`. CI fails
the PR if a DTO changes without regenerating the bundle.

BREAKING CHANGE: the TypeScript API surface changes file layout
and some type names. Type *shapes* are equivalent or narrower than
what we shipped; the migration is mostly renames + import path
updates. See `CHANGELOG.md` for the full list.

## Implementation

### `ts-export` cargo feature

Replaces the prior `ts-rs-spike` feature. `ts-rs` is now a host-only
optional dep gated behind `ts-export`. With the feature off, the
crate compiles without ts-rs in the dep graph (the `#[cfg_attr]`
derives compile out). Default builds and wasm32 are unaffected.

### Per-DTO derives

`#[cfg_attr(feature = "ts-export", derive(ts_rs::TS))]` plus
`#[cfg_attr(feature = "ts-export", ts(export, export_to = "bindings/"))]`
on every wire-format DTO in `src/types.rs`:

- `MetaValueJson`, `TypedValueJson`
- `DirectiveJson` (discriminated union, narrows on `type`)
- `PostingJson`, `PostingCostJson`, `CostNumberJson`, `AmountValue`

`#[cfg_attr(feature = "ts-export", ts(optional))]` on every
`Option<T> + skip_serializing_if = "Option::is_none"` field so the
emitted TS uses `field?: T` (matching the actual wire absence) rather
than the default `field: T | null` (present-but-null). This was the
single largest finding from the spike (#1220).

### Post-process script

`scripts/regen-ts-bindings.sh` runs `cargo test --features ts-export`
(which triggers ts-rs's auto-generated export tests), then collates
the per-type files into `bindings/index.d.ts` by:

1. Stripping per-file `// generated by ts-rs` headers and `import
   type` statements (everything resolves within the bundle).
2. Sorting files deterministically so regen produces stable diffs.
3. Replacing the wide `TypedValueJson` shape with a narrowed
   discriminated union (per ADR-0004 #4 -- the Rust struct can't
   express the narrowing structurally without a custom Deserialize
   for the `null` variant, so the override lives in the script).

### CI freshness gate

`.github/workflows/ci.yml` gains a `ts-bindings-fresh` job that runs
the script with `RUSTLEDGER_TS_CHECK=1`. Set, the script ends with
`git diff --exit-code bindings/index.d.ts` so a contributor who
changes a DTO without regenerating the bundle fails CI loudly.

## Migration notes

- File layout: import from `crates/rustledger-wasm/bindings/index.d.ts`
  instead of the two old files. wasm-pack consumers get the bundle
  automatically.
- The per-variant directive interfaces (`TransactionDirective`,
  `BalanceDirective`, ...) are gone; the discriminated union is
  inlined on `DirectiveJson`. Use
  `Extract<DirectiveJson, { type: "transaction" }>` for the
  per-variant type.
- `Amount` is now `AmountValue` (the Rust DTO name).
- `Posting` is now `PostingJson`; `Directive` is now `DirectiveJson`.

## Phase 2 (deferred to a follow-up)

The `typescript_custom_section` block in `src/lib.rs` stays
hand-maintained in Phase 1. Phase 2 replaces it with an `include_str!`
of `bindings/index.d.ts` so it stays in sync automatically. Filed as
a follow-up issue.

## Verification

- `cargo test -p rustledger-wasm` (default features): 80/80 pass.
- `cargo test -p rustledger-wasm --features ts-export --lib`: 87/87
  pass (the additional tests are ts-rs's auto-export hooks).
- `cargo clippy -p rustledger-wasm --all-targets -- -D warnings`:
  clean.
- `cargo fmt --all -- --check`: clean.
- `cargo deny check`: clean (ts-rs 12.0.1 has no advisories).
- `scripts/regen-ts-bindings.sh`: produces a 200-line bundle with
  proper discriminated-union narrowing on `DirectiveJson` and a
  hand-tuned narrowed `TypedValueJson`.

Closes #1218.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 28, 2026 13:45
@robcohen
robcohen requested a review from a team as a code owner May 28, 2026 13:45
@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 implements ADR-0004 Phase 1 for rustledger-wasm by making the Rust wire-format DTOs the source of truth for TypeScript declarations, replacing the hand-maintained .d.ts files with a generated bundle and adding CI enforcement to keep it up to date.

Changes:

  • Add a host-only ts-export cargo feature and annotate selected DTOs in crates/rustledger-wasm/src/types.rs for ts-rs export (including #[ts(optional)] where needed).
  • Add scripts/regen-ts-bindings.sh to generate per-type ts-rs output, collate into bindings/index.d.ts, and apply a hand-tuned TypedValueJson narrowing override.
  • Add a CI freshness gate (ts-bindings-fresh) and update docs/ADR/changelog to document the breaking TS surface change.

Reviewed changes

Copilot reviewed 8 out of 12 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
scripts/regen-ts-bindings.sh New generator + post-processing script for producing bindings/index.d.ts and enforcing drift checks.
docs/reference/adr/index.md Marks ADR-0004 as accepted (Phase 1).
docs/reference/adr/0004-ts-types-from-rust-dtos.md Updates ADR-0004 status text to reflect Phase 1 acceptance/implementation details.
crates/rustledger-wasm/src/types.rs Adds ts-rs export derives/attributes on DTOs and #[ts(optional)] for optionals.
crates/rustledger-wasm/Cargo.toml Replaces spike feature with ts-export feature and host-only optional ts-rs dependency.
crates/rustledger-wasm/bindings/index.d.ts New checked-in generated TypeScript declaration bundle.
crates/rustledger-wasm/CHANGELOG.md Documents breaking change and migration notes for the TS declaration consolidation.
.github/workflows/ci.yml Adds ts-bindings-fresh job to regenerate + fail on drift in CI.
.gitignore Ignores only the ts-rs intermediate per-type output directory (keeps bundled output tracked).
crates/rustledger-wasm/examples/tsrs_spike.rs Removes the now-obsolete spike example.
crates/rustledger-wasm/beancount.d.ts Deletes legacy hand-maintained TS declarations.
crates/rustledger-wasm/beancount_wasm.d.ts Deletes legacy hand-maintained TS declarations.

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

Comment thread scripts/regen-ts-bindings.sh Resolved
@github-actions

github-actions Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.6ms ± 0.6ms 25.3 MB
beancount 857.3ms ± 6.2ms 50.6 MB
Comparison 26.3x faster 2.0x less

vs main branch (2026-05-28)

Metric main this PR Change
Time 29.7ms 32.6ms +9.8% 🟡
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

github-actions Bot commented May 28, 2026 •

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 and others added 5 commits May 28, 2026 16:41
#1223)

Two valid Copilot findings:

1. ADR-0004 Spike section referenced PR #1218 (the tracking issue)
   instead of #1220 (the actual spike PR). It also documented the
   spike invocation with --features ts-rs-spike, but the example and
   feature are deleted in this PR (Phase 1). Rewrite the section to
   reference #1220 for the spike and #1223 (this PR) for the Phase 1
   landing, and drop the dead invocation.

2. regen-ts-bindings.sh comment claimed cargo test output was piped
   to /dev/null, but the command actually uses --quiet without
   redirection. Update the comment to match the implementation.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The new ts-bindings-fresh job uses cargo test under the hood (via
`scripts/regen-ts-bindings.sh`). The workflow sets `RUSTC_WRAPPER:
sccache` at the workflow level, so every job that compiles Rust must
install `mozilla-actions/sccache-action` to provide the wrapper
binary. Without it, cargo's `rustc -vV` probe fails immediately
with `No such file or directory (os error 2)` and exits 101.

Confirmed locally that `RUSTLEDGER_TS_CHECK=1 scripts/regen-ts-bindings.sh`
passes -- this is purely a missing-action issue in the workflow
definition.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Addresses the deep-review findings on #1223:

1. **Wrapper types now in the generated bundle**: ParseResult,
   Ledger, LedgerOptions, ValidationResult, QueryResult, CellValue,
   PositionValue, CostValue, FormatResult, PadResult, Severity, plus
   Error (renamed to BeancountError on the TS side to avoid
   shadowing the JS-builtin Error). 12 more types added. Consumers
   reading the bundle directly now see the full public TS surface,
   not just the wire-format DTOs.

2. **i64 -> number override on CellValue::Integer**: ts-rs defaults
   i64 to bigint, but the JSON wire emits a plain Number. Override
   via `#[ts(type = "number")]` so the TS shape matches what JS
   consumers actually receive at runtime.

3. **CHANGELOG note on Phase 2 caveat**: the inline
   typescript_custom_section in src/lib.rs still ships the old
   hand-maintained shape via wasm-bindgen's generated .d.ts; only
   consumers importing `crates/rustledger-wasm/bindings/index.d.ts`
   directly see the new names. Phase 2 replaces it with an
   include_str! of the bundle so both surfaces converge -- tracked
   separately.

Also handles fields like ParseResult.ledger and LedgerOptions.title
correctly: they're Option<T> WITHOUT skip_serializing_if, so they
emit as JSON null on the wire. Leave them as `T | null` in TS
(not `field?: T`) to match the actual wire shape -- same lesson as
#1221's Transaction.payee fix.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Closes the remaining gap from the last review: the bundle was at
19 types, missing the plugin types (PluginResult, PluginInfo), BQL
completion types (CompletionJson, CompletionResultJson), and the
LSP-like editor types (EditorCompletion, CompletionKind,
EditorCompletionResult, EditorHoverInfo, EditorRange, EditorLocation,
EditorDocumentSymbol, SymbolKind, ReferenceKind, EditorReference,
EditorReferencesResult).

These types are public on the Rust side and reachable via wasm-bindgen
when the relevant feature is on (`plugins` and `completions` are both
default features). For the "no legacy" / structural-completeness
principle, every public DTO that JS consumers can see goes in the
bundle, regardless of which feature gates the function that returns
it. The bundle becomes a faithful, complete reflection of the public
TS API surface.

Bundle grows from 397 to 631 lines, 19 to 34 types. Every
`Option<T> + skip_serializing_if = "Option::is_none"` field also
gets `#[ts(optional)]` so the TS shape matches the actual wire
(absent rather than null) -- consistent with the existing pattern.

CHANGELOG migration note lists the full set of types now in the
bundle so consumers know what's available without spelunking
through the file.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The new TypeScript bindings freshness CI job (added in this PR) was
failing because `find ... | sort` produces a different order on
the GitHub Actions Ubuntu runner than my local nix-shell. Specifically
locale-dependent collation of `.` (0x2E) vs uppercase letters made
`EditorCompletion.ts` sort either before or after
`EditorCompletionResult.ts` depending on the active locale -- same
issue for `Ledger` / `LedgerOptions`.

Pin `LC_ALL=C` on the sort so the order is deterministic across
every machine (C locale uses pure byte comparison, no collation
rules). Regenerate the bundle to match.

This was the bug that broke the gate check on PR #1223 itself --
without the fix, every machine would see freshness drift purely from
locale differences, which is exactly what the gate is supposed to
prevent.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@robcohen
robcohen merged commit 5c609fd into main May 28, 2026
39 checks passed
@robcohen
robcohen deleted the feat/ts-rs-phase-1-1218 branch May 28, 2026 15:24
robcohen added a commit that referenced this pull request May 28, 2026
…1224) (#1225)

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 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.

Design spike: generate TypeScript types from Rust DTOs (item 2 of #1200)

2 participants