Repository navigation
Conversation
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]>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
5 tasks done
Contributor
There was a problem hiding this comment.
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_spikeexample using#[derive(TS)]on mirrored DTO shapes. - Documents the proposed
ts-rsadoption 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. |
Contributor
📊 Benchmark Results
vs main branch (2026-05-28)
What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 withcargo 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:
switch (d.type).tag = "kind"— same, narrowing-friendly.One solvable friction:
Option<T> + skip_serializing_if = "Option::is_none"emitsfield: T | nullby default. The#[ts(optional)]attribute fixes this tofield?: T. Verified in the spike.One structural limitation:
struct { value_type: String, value: MetaValueJson }; ts-rs faithfully emits the wide TS. The hand-written narrowedtype 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:
#[ts(optional)]on skip-if-none fields.beancount.d.ts+beancount_wasm.d.tswith a generatedbindings/index.d.ts(post-process concat).typescript_custom_sectionhand-maintained in Phase 1; replace withinclude_str!of the bundle in a follow-up..pyistubs explicitly out of scope.Verification
cargo check --workspace --all-targets— cleancargo clippy --workspace --all-targets -- -D warnings— cleancargo fmt --all -- --check— cleancargo deny check— clean (ts-rs 12.0.1 has no advisories)ts-rs-spikefeature gates the optional dep; default build unaffectedWhat to review
typescript_custom_sectionhand-maintained initially) and the TypedValueJson hand-tune.Relates to #1218.
🤖 Generated with Claude Code