Skip to content

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

Closed
robcohen wants to merge 2 commits into
mainfrom
spike/ts-rs-1218
Closed

robcohen wants to merge 2 commits into
mainfrom
spike/ts-rs-1218

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Spike + design doc for #1218. Item 2 of the closed #1200 tracking issue, deferred for design because it had substantial open questions (which generator? how to collate? what about hand-tuned narrowing?).

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

What to review

  1. ADR-0004 itself — does the recommendation match what you want? Particularly the Phase 1/Phase 2 split (keep typescript_custom_section hand-maintained initially) and the TypedValueJson hand-tune.
  2. Spike code — fair representation of the production DTO shapes? Missed any load-bearing patterns?

Relates to #1218.

🤖 Generated with Claude Code

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]>
Copilot AI review requested due to automatic review settings May 28, 2026 12:34
@robcohen
robcohen requested a review from a team as a code owner May 28, 2026 12:34
@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!

@robcohen robcohen closed this May 28, 2026
@robcohen
robcohen deleted the spike/ts-rs-1218 branch May 28, 2026 12:37

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 spikes ts-rs as a path toward generating TypeScript declarations from Rust DTOs, and adds ADR-0004 to document the proposed migration away from hand-maintained .d.ts surfaces.

Changes:

  • Adds a gated tsrs_spike example using #[derive(TS)] on mirrored DTO shapes.
  • Documents the proposed ts-rs adoption strategy in ADR-0004 and links it from the ADR index.
  • Adds optional dependency metadata, lockfile updates, generated-output ignore rules, and supply-chain exemptions.

Reviewed changes

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

Show a summary per file
File Description
.gitignore Ignores generated wasm TypeScript binding output.
Cargo.lock Locks the newly introduced optional ts-rs dependencies.
crates/rustledger-wasm/Cargo.toml Adds the spike feature, example gating, and optional host-only ts-rs dependency.
crates/rustledger-wasm/examples/tsrs_spike.rs Adds the prototype DTO declarations used to inspect ts-rs output.
docs/reference/adr/0004-ts-types-from-rust-dtos.md Adds the ADR proposing generated TypeScript types from Rust DTOs.
docs/reference/adr/index.md Links ADR-0004 in the ADR index.
supply-chain/config.toml Adds cargo-vet exemptions for ts-rs and ts-rs-macros.

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


4. **Cross-file imports compose cleanly.** Per-type files reference each other via `import type { MetaValueJson } from "./MetaValueJson"`.

5. **`#[ts(optional)]` solves the `Option<T> + skip_serializing_if = "Option::is_none"` mismatch.** Without it, ts-rs emits `field: T | null` (present-but-null); with it, `field?: T` (optional, matching wire absence). One attribute per Option field.
cargo test --example tsrs_spike -p rustledger-wasm --features ts-rs-spike
```

ts-rs writes per-type `.d.ts` files under `crates/rustledger-wasm/bindings/bindings/`.
Comment on lines +86 to +92
#[serde(skip_serializing_if = "Option::is_none")]
pub number: Option<CostNumberJson>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub date: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(tag = "type")]
#[ts(export, export_to = "bindings/")]
pub enum DirectiveJson {
Comment on lines +145 to +148
#[serde(skip_serializing_if = "Option::is_none")]
tolerance: Option<String>,
#[serde(skip_serializing_if = "HashMap::is_empty", default)]
meta: HashMap<String, MetaValueJson>,
Comment on lines +155 to +168
#[serde(skip_serializing_if = "Vec::is_empty", default)]
tags: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
links: Vec<String>,
#[serde(skip_serializing_if = "HashMap::is_empty", default)]
meta: HashMap<String, MetaValueJson>,
},
#[serde(rename = "custom")]
Custom {
date: String,
custom_type: String,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
values: Vec<TypedValueJson>,
#[serde(skip_serializing_if = "HashMap::is_empty", default)]
Comment on lines +62 to +64
# `target/ts-rs-spike/` so we can eyeball what ts-rs produces for
# our existing wire-format DTO shapes. Not pulled into normal builds
# or the wasm32 target.
@github-actions

github-actions Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.1ms ± 0.9ms 25.2 MB
beancount 894.9ms ± 17.6ms 50.5 MB
Comparison 25.5x faster 2.0x less

vs main branch (2026-05-28)

Metric main this PR Change
Time 29.7ms 35.1ms +18.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 28, 2026
)

* chore(wasm): ts-rs TypeScript generation prototype + ADR-0004 (#1218)

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

* chore(wasm): address #1219 deep-review nits

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

* chore: regenerate cargo-vet exemptions

* chore(wasm): apply 4 of 5 Copilot inline findings on #1220

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

---------

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.

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

2 participants