Skip to content

chore(wasm): spike ts-rs TypeScript generation + ADR-0004 (#1218) - #1220

Merged
robcohen merged 4 commits into
mainfrom
chore/ts-rs-spike-1218
May 28, 2026
Merged

robcohen merged 4 commits into
mainfrom
chore/ts-rs-spike-1218

Conversation

@robcohen

Copy link
Copy Markdown
Member

Re-opening of #1219 after a branch rename (spike/... failed the workspace's allowed-types regex). Same content, plus the deep-review fixes applied as a follow-up commit:

  • bindings/ path docstring corrected to bindings/bindings/ in both the spike file and ADR.
  • Cargo.toml feature comment now spells out why ts-rs-spike and the target-gated ts-rs dep are deliberately split.
  • ADR explicitly notes the spike is a snapshot of the production DTOs and won't track future changes.

Summary

Spike + design doc for #1218. Item 2 of the closed #1200 tracking issue, deferred for design because it had substantial open questions.

This PR lands:

  • crates/rustledger-wasm/examples/tsrs_spike.rs — prototype that mirrors the four key wire-format DTOs (MetaValueJson, TypedValueJson, PostingJson, DirectiveJson + supporting types) with #[derive(TS)]. Run with cargo test --example tsrs_spike -p rustledger-wasm --features ts-rs-spike.
  • docs/reference/adr/0004-ts-types-from-rust-dtos.md — proposed ADR with concrete recommendations.

bindings/ output is gitignored; regenerable from the spike.

Spike findings

ts-rs got these right:

  • DirectiveJson discriminated union — narrows correctly on switch (d.type).
  • CostNumberJson with tag = "kind" — same, narrowing-friendly.
  • MetaValueJson untagged union — bit-identical to hand-written.
  • Doc comments → JSDoc.
  • Cross-file imports compose.

One solvable friction:

  • Option<T> + skip_serializing_if = "Option::is_none" emits field: T | null by default. The #[ts(optional)] attribute fixes this to field?: T. Verified in the spike.

One structural limitation:

  • TypedValueJson's TS-side narrowing is lost. The Rust DTO is struct { value_type: String, value: MetaValueJson }; ts-rs faithfully emits the wide TS. The hand-written narrowed type TypedValue = { type: "string"; value: string } | { type: "amount"; value: AmountValue } | ... is more precise than the Rust struct can express. ADR proposes hand-tuning this one type via a post-process step.

ADR-0004 recommendation

Adopt ts-rs with these constraints:

  1. #[ts(optional)] on skip-if-none fields.
  2. Replace beancount.d.ts + beancount_wasm.d.ts with a generated bindings/index.d.ts (post-process concat).
  3. Keep typescript_custom_section hand-maintained in Phase 1; replace with include_str! of the bundle in a follow-up.
  4. Hand-tune TypedValueJson narrowing in the post-process step.
  5. Python .pyi stubs explicitly out of scope.

Verification

  • cargo check --workspace --all-targets — clean
  • cargo clippy --workspace --all-targets -- -D warnings — clean
  • cargo fmt --all -- --check — clean
  • cargo deny check — clean (ts-rs 12.0.1 has no advisories)
  • ts-rs-spike feature gates the optional dep; default build unaffected

Relates to #1218. Supersedes #1219.

🤖 Generated with Claude Code

robcohen and others added 2 commits May 28, 2026 14:33
Item 2 of the closed #1200 tracking issue was deferred for design
spiking because it had substantial open questions: which generator,
how to collate multiple .d.ts files, what to do with hand-tuned
discriminated-union narrowing, whether Python compat follows the
same pattern.

This commit lands the spike + a proposed ADR with concrete findings.

## Spike

`crates/rustledger-wasm/examples/tsrs_spike.rs` mirrors the four
key wire-format DTOs (MetaValueJson, TypedValueJson, PostingJson,
DirectiveJson + supporting AmountValue, CostNumberJson,
PostingCostJson) verbatim from `src/types.rs`, with `#[derive(TS)]`
added. Run with:

    cargo test --example tsrs_spike \
      -p rustledger-wasm --features ts-rs-spike

Per-type .d.ts files land under `crates/rustledger-wasm/bindings/`
(gitignored — regenerable from the spike).

The mirror approach (rather than feature-gating the derive on the
production DTOs) keeps the spike self-contained until the design
decision lands.

## Findings (full write-up in ADR-0004)

**ts-rs handled cleanly:**
- DirectiveJson discriminated union with `tag = "type"` -> narrows on
  `switch (d.type)` exactly like the hand-written shape.
- CostNumberJson with `tag = "kind", rename_all = "snake_case"` ->
  same.
- MetaValueJson untagged union -> bit-identical to hand-written.
- Doc comments on fields -> JSDoc above the TS field.
- Cross-file imports compose cleanly.

**ts-rs had one solvable friction:**
- `Option<T> + skip_serializing_if = "Option::is_none"` emits
  `field: T | null` (present-but-null) by default, not `field?: T`
  (optional). The `#[ts(optional)]` attribute fixes this -- one
  extra attribute per skip-if-none field. Verified in the spike.

**One structural limitation:**
- TypedValueJson's TS-side narrowing is lost. The Rust DTO is
  `struct { value_type: String, value: MetaValueJson }`; ts-rs
  faithfully emits `{ type: string, value: MetaValueJson }`. The
  hand-written `type TypedValue = { type: "string"; value: string }
  | { type: "amount"; value: AmountValue } | ...` is narrower than
  the Rust struct can express. Restructuring as a tagged Rust enum
  is awkward because of the `null` variant's payload. ADR proposes
  hand-tuning this one type via a post-process step.

## ADR-0004

`docs/reference/adr/0004-ts-types-from-rust-dtos.md` proposes:

1. Adopt ts-rs with `#[ts(optional)]` on skip-if-none fields.
2. Replace `beancount.d.ts` + `beancount_wasm.d.ts` with a generated
   `bindings/index.d.ts` (post-process concatenation step).
3. Keep `typescript_custom_section` in src/lib.rs hand-maintained
   in Phase 1; replace with `include_str!` of the generated bundle
   in a follow-up.
4. Hand-tune TypedValueJson narrowing in the post-process step
   (documented override).
5. Python .pyi stubs explicitly out of scope.

Status: Proposed. Awaiting decision before Phase 1 implementation.

## Verification

- cargo check --workspace --all-targets -- clean
- cargo clippy --workspace --all-targets -- -D warnings -- clean
- cargo fmt --all -- --check -- clean
- cargo deny check -- clean (ts-rs 12.0.1 has no advisories)
- ts-rs-spike feature gates the optional dep; default build
  unaffected

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Three findings from the self-review on #1219:

1. **`bindings/` path nesting** -- the spike file's docstring and
   the ADR both said output lands in `bindings/`, but the actual
   path is `bindings/bindings/` (ts-rs's `export_to = "bindings/"`
   appends the subdirectory under the crate's per-output root).
   Correct both spots and explain the nesting so the next person
   running the spike doesn't search the wrong directory.

2. **Cargo.toml feature/target mismatch clarification** -- the
   `ts-rs-spike = ["dep:ts-rs"]` feature lives in the top-level
   `[features]` table, but `ts-rs` itself is declared in
   `[target.'cfg(not(target_arch = "wasm32"))'.dependencies]`. The
   net behavior is correct (wasm32 builds with the feature hard-fail
   on the missing `ts-rs` crate, which is intentional for a host-only
   spike), but the inline comment didn't say so. Spell it out so the
   feature/dep split is obviously deliberate rather than incidental.

3. **Spike-vs-production drift note in ADR** -- the spike file in
   `examples/tsrs_spike.rs` is a snapshot of the production DTOs at
   the moment of writing; it intentionally won't track future changes
   to `src/types.rs`. The ADR now states this explicitly so a reader
   coming back in six months doesn't get confused by drift between
   the spike and the live types.

Branch will be renamed to `chore/ts-rs-spike-1218` in a follow-up
push (the original `spike/...` name failed the workspace's allowed-
types regex for branch validation).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 28, 2026 12:38
@robcohen
robcohen requested a review from a team as a code owner May 28, 2026 12:38
@robcohen
robcohen enabled auto-merge (squash) May 28, 2026 12:41
@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 adds a ts-rs design spike for generating TypeScript declarations from Rust WASM DTOs and documents the proposed adoption path in ADR-0004.

Changes:

  • Adds a host-only ts-rs-spike feature, example, dependency lockfile entries, and ignored generated bindings output.
  • Adds ADR-0004 and indexes it under the ADR reference docs.
  • Adds cargo-vet exemptions for the newly introduced ts-rs crates.

Reviewed changes

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

Show a summary per file
File Description
.gitignore Ignores generated spike TypeScript bindings.
Cargo.lock Locks ts-rs and ts-rs-macros dependencies.
crates/rustledger-wasm/Cargo.toml Adds spike feature, example gating, and optional host-only ts-rs dependency.
crates/rustledger-wasm/examples/tsrs_spike.rs Adds the DTO-copy spike used to inspect generated TypeScript output.
docs/reference/adr/0004-ts-types-from-rust-dtos.md Documents the proposed TypeScript generation design.
docs/reference/adr/index.md Adds ADR-0004 to the ADR index.
supply-chain/config.toml Adds vet exemptions for ts-rs and ts-rs-macros.

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

Comment thread crates/rustledger-wasm/Cargo.toml Resolved
@github-actions

github-actions Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.9ms ± 1.2ms 25.2 MB
beancount 921.3ms ± 9.7ms 50.7 MB
Comparison 25.7x faster 2.0x less

vs main branch (2026-05-28)

Metric main this PR Change
Time 29.7ms 35.9ms +20.9% 🔴
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

@robcohen
robcohen disabled auto-merge May 28, 2026 12:46
Four findings applied verbatim, one declined as a misreading of the
production wire shape:

1. **`PostingCostJson` Option fields** -- add `#[ts(optional)]` to
   `number`, `currency`, `date`, `label`. Verified: ts-rs now emits
   `{ number?: CostNumberJson, currency?: string, date?: string,
   label?: string, }` instead of the `T | null` shape. Brings the
   spike's PostingCost shape in line with the hand-written one.

2. **DECLINED for `Transaction.payee` and `Transaction.narration`**.
   The production code at `src/types.rs:159-160` has NO
   `skip_serializing_if` on these fields, so they emit as
   `"payee": null` / `"narration": null` on the wire. ts-rs's
   `payee: string | null` / `narration: string | null` faithfully
   matches the actual wire. Adding `#[ts(optional)]` would make the
   spike LIE about the wire shape -- the opposite of what we want.

   (Aside: the hand-written `beancount_wasm.d.ts` declares these as
   `payee?: string`, which IS a drift from the wire -- but that's a
   separate audit finding belonging in its own issue, not in the
   spike.)

3. **`Balance.tolerance`** -- add `#[ts(optional)]`. Verified: now
   emits `tolerance?: string` instead of `tolerance: string | null`.

4. **Cargo.toml stale `target/ts-rs-spike/` path** -- corrected to
   `crates/rustledger-wasm/bindings/bindings/` (the actual output
   location, matching the .gitignore entry).

5. **Spike file-level docstring used `cargo run`** -- corrected to
   `cargo test`, with a parenthetical explaining that ts-rs emits
   the `.d.ts` from auto-generated unit tests, not `main()`.

Re-ran the export, confirmed all four applied findings produce the
expected output, and the `payee | null` shape is preserved.

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

Copy link
Copy Markdown
Member Author

Addressed Copilot's 5 inline findings in 7723e9c:

Re-ran the spike to verify all four applied findings produce the expected output.

@robcohen
robcohen enabled auto-merge (squash) May 28, 2026 12:50
@robcohen
robcohen merged commit 99e9548 into main May 28, 2026
39 checks passed
@robcohen
robcohen deleted the chore/ts-rs-spike-1218 branch May 28, 2026 12:53
@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 28, 2026
…WASI (closes #1221)

BREAKING CHANGE: the WASM binding's wire shape for `Transaction.payee`
and `Transaction.narration` now matches FFI-WASI. Pre-fix WASM emitted
`"payee": null` when None and `"narration": ""` when empty; post-fix
both fields are absent on the wire via `skip_serializing_if`. JS
consumers using `"payee" in t` (now `false` instead of `true`) or
`t.narration === ""` (now `undefined` instead of `""`) must update.
See `crates/rustledger-wasm/CHANGELOG.md` for details.

Surfaced by the ts-rs spike in #1220. FFI-WASI already used
`skip_serializing_if = "Option::is_none"` on both fields, but the
WASM binding diverged:

- `payee`: WASM emitted `"payee": null` when None; FFI-WASI omitted.
- `narration`: WASM wrapped `txn.narration` unconditionally in
  `Some(...)`, so an empty narration always emitted as `""` on the
  wire; FFI-WASI's converter normalized empty-string to None and
  thus elided the field via `skip_serializing_if`.

This divergence was masked in the wire-format equivalence harness by
the `strip_empty_meta_and_directive_nulls` normalization helper --
the harness was documented as a known divergence (item 3 in its
module docstring) with the recommended convergence being exactly
what this PR does.

## Changes

- `src/types.rs`: add `#[serde(skip_serializing_if = "Option::is_none")]`
  to both `Transaction.payee` and `Transaction.narration`.
- `src/convert.rs`: change `narration: Some(txn.narration.to_string())`
  to elide on empty string -- matches FFI-WASI's converter pattern at
  `crates/rustledger-ffi-wasi/src/convert.rs:133-137`.
- Three TS surfaces aligned:
  - `beancount.d.ts`: `payee: string | null` → `payee?: string`;
    `narration: string` → `narration?: string`.
  - `beancount_wasm.d.ts`: `narration: string` → `narration?: string`
    (payee was already correct).
  - `typescript_custom_section` in `src/lib.rs`: already had
    `payee?: string` and `narration?: string`; no change needed.
- `CHANGELOG.md`: BREAKING CHANGES entry under [Unreleased].
- Wire-format harness docstring updated -- divergence item 3 marked
  as ~~converged~~ with a pointer to this fix.

## Tests

Two new regressions in `src/convert.rs`:

- `transaction_omits_payee_and_empty_narration_1221` -- no-payee +
  empty narration transaction must have neither field on the wire.
- `transaction_emits_payee_and_nonempty_narration_1221` -- present
  payee + non-empty narration must both appear on the wire.
  Counterpoint so a future regression that elides unconditionally
  also fails CI.

The existing wire-format-tests harness already covered Transaction
equivalence (`metadata_equivalence_on_transaction_directive`) and
continues to pass; the null-stripping in
`strip_empty_meta_and_directive_nulls` is no longer load-bearing for
the payee/narration case but stays as a defensive guard against
future regression.

## Notes

The `.d.ts` audit that fixed Posting.price and 7 missing variants
(#1210) didn't catch this because it looked for missing/extra fields,
not type-mismatches on existing fields. The ts-rs spike (#1220)
surfaced it as a side-effect of comparing generated TS against the
hand-written shape -- evidence for ADR-0004's CI gate proposal.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
robcohen added a commit that referenced this pull request May 28, 2026
…ASI (closes #1221) (#1222)

* fix(wasm)!: converge Transaction.payee/narration wire shape with FFI-WASI (closes #1221)

BREAKING CHANGE: the WASM binding's wire shape for `Transaction.payee`
and `Transaction.narration` now matches FFI-WASI. Pre-fix WASM emitted
`"payee": null` when None and `"narration": ""` when empty; post-fix
both fields are absent on the wire via `skip_serializing_if`. JS
consumers using `"payee" in t` (now `false` instead of `true`) or
`t.narration === ""` (now `undefined` instead of `""`) must update.
See `crates/rustledger-wasm/CHANGELOG.md` for details.

Surfaced by the ts-rs spike in #1220. FFI-WASI already used
`skip_serializing_if = "Option::is_none"` on both fields, but the
WASM binding diverged:

- `payee`: WASM emitted `"payee": null` when None; FFI-WASI omitted.
- `narration`: WASM wrapped `txn.narration` unconditionally in
  `Some(...)`, so an empty narration always emitted as `""` on the
  wire; FFI-WASI's converter normalized empty-string to None and
  thus elided the field via `skip_serializing_if`.

This divergence was masked in the wire-format equivalence harness by
the `strip_empty_meta_and_directive_nulls` normalization helper --
the harness was documented as a known divergence (item 3 in its
module docstring) with the recommended convergence being exactly
what this PR does.

## Changes

- `src/types.rs`: add `#[serde(skip_serializing_if = "Option::is_none")]`
  to both `Transaction.payee` and `Transaction.narration`.
- `src/convert.rs`: change `narration: Some(txn.narration.to_string())`
  to elide on empty string -- matches FFI-WASI's converter pattern at
  `crates/rustledger-ffi-wasi/src/convert.rs:133-137`.
- Three TS surfaces aligned:
  - `beancount.d.ts`: `payee: string | null` → `payee?: string`;
    `narration: string` → `narration?: string`.
  - `beancount_wasm.d.ts`: `narration: string` → `narration?: string`
    (payee was already correct).
  - `typescript_custom_section` in `src/lib.rs`: already had
    `payee?: string` and `narration?: string`; no change needed.
- `CHANGELOG.md`: BREAKING CHANGES entry under [Unreleased].
- Wire-format harness docstring updated -- divergence item 3 marked
  as ~~converged~~ with a pointer to this fix.

## Tests

Two new regressions in `src/convert.rs`:

- `transaction_omits_payee_and_empty_narration_1221` -- no-payee +
  empty narration transaction must have neither field on the wire.
- `transaction_emits_payee_and_nonempty_narration_1221` -- present
  payee + non-empty narration must both appear on the wire.
  Counterpoint so a future regression that elides unconditionally
  also fails CI.

The existing wire-format-tests harness already covered Transaction
equivalence (`metadata_equivalence_on_transaction_directive`) and
continues to pass; the null-stripping in
`strip_empty_meta_and_directive_nulls` is no longer load-bearing for
the payee/narration case but stays as a defensive guard against
future regression.

## Notes

The `.d.ts` audit that fixed Posting.price and 7 missing variants
(#1210) didn't catch this because it looked for missing/extra fields,
not type-mismatches on existing fields. The ts-rs spike (#1220)
surfaced it as a side-effect of comparing generated TS against the
hand-written shape -- evidence for ADR-0004's CI gate proposal.

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

* ci: retrigger after sccache outage

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
robcohen added a commit that referenced this pull request May 28, 2026
#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]>
robcohen added a commit that referenced this pull request May 28, 2026
… 1) (#1223)

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

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

* docs: fix stale PR refs in ADR-0004 + script comment (Copilot review on #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]>

* ci(wasm): install sccache-action in ts-bindings-fresh job

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

* feat(wasm): expand ts-rs coverage to wrapper types + i64 number fix

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

* feat(wasm): complete ts-export coverage of all 33 public types

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

* fix(wasm): pin LC_ALL=C in regen-ts-bindings sort (CI freshness gate)

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

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
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.

Prevent wire-format drift across bindings (cross-binding tests, TS generation, audit)

2 participants