Repository navigation
fix(wasm): pipe ts-rs output through prettier (closes #1226) - #1228
Merged
Merged
Conversation
The wasm-bindgen-generated `pkg/*.d.ts` had escalating indentation on the bundle types embedded via `include_str!` -- `AmountValue` at column 0, `BeancountError` at column 4, `CellValue` at column 8, etc. wasm-bindgen's typescript_custom_section formatter miscounts brackets on ts-rs's compact one-line-per-field layout and ends up accumulating indentation across declarations. Pipe the regen script's output through `prettier --parser=typescript` so the bundle has standard layout (proper indentation, semicolons, one declaration per line block). wasm-bindgen then embeds clean output, and the checked-in `bindings/index.d.ts` is easier to read and review as a side effect. The script gains a `npx` precondition check with a helpful error message; CI adds `actions/setup-node@v4` with node 24 pinned for the `ts-bindings-fresh` job so `npx prettier` is available. ubuntu-latest preinstalls Node, but pinning the major version means runner image updates can't surprise us. Verified: `wasm-pack build --target nodejs --dev` now produces a `pkg/rustledger_wasm.d.ts` where every `export type` declaration is at column 0. `tsc --noEmit --strict` still parses cleanly. 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! |
Contributor
There was a problem hiding this comment.
Pull request overview
Pipes the ts-rs–generated bindings/index.d.ts bundle through Prettier in scripts/regen-ts-bindings.sh so that wasm-bindgen's typescript_custom_section formatter no longer produces escalating indentation in pkg/*.d.ts. The checked-in bundle is reformatted to match Prettier's output, and the ts-bindings-fresh CI job gets an explicit Node 24 setup so npx prettier is available.
Changes:
- Add a
npx --yes prettier@3 --parser=typescriptformatting pass (withnpxpresence check and error reporting) before the drift check inscripts/regen-ts-bindings.sh. - Reformat the committed
crates/rustledger-wasm/bindings/index.d.tsto Prettier's layout. - Pin Node 24 via
actions/setup-node@v4in thets-bindings-freshCI job.
Reviewed changes
Copilot reviewed 2 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| scripts/regen-ts-bindings.sh | Adds Prettier post-processing step with npx availability check and error handling. |
| crates/rustledger-wasm/bindings/index.d.ts | Regenerated bundle reflecting the new Prettier-normalized layout. |
| .github/workflows/ci.yml | Adds Node 24 setup to the ts-bindings-fresh job so npx prettier is available. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
2 of 3 tasks
robcohen
added a commit
that referenced
this pull request
May 28, 2026
Follow-up to #1228 -- Copilot's review caught that `wasm.yml:88` already uses `node-version-file: '.nvmrc'`, and `.nvmrc` pins `24`. Hardcoding `node-version: '24'` in the `ts-bindings-fresh` job was a second source of truth that could drift from `.nvmrc`. Switch to `node-version-file: '.nvmrc'` so the version lives in one place. Co-authored-by: Claude Opus 4.7 <[email protected]>
4 of 6 tasks
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>
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
The wasm-bindgen-generated
pkg/*.d.tshad escalating indentation on the bundle types embedded viainclude_str!:AmountValueat column 0BeancountErrorat column 4CellValueat column 8wasm-bindgen's typescript_custom_section formatter miscounts brackets on ts-rs's compact one-line-per-field layout. The file remained syntactically valid (
tsc --noEmit --strictpasses) but was ugly to read and diff.Fix
scripts/regen-ts-bindings.sh: pipes the regenerated bundle throughnpx prettier --parser=typescriptso the bundle has standard layout. wasm-bindgen then embeds clean output. Side effect: the checked-inbindings/index.d.tsis also prettier-formatted, which makes review easier..github/workflows/ci.yml: pins Node 24 viaactions/setup-node@v4in thets-bindings-freshjob sonpx prettieris available regardless of runner image changes.Verification
RUSTLEDGER_TS_CHECK=1 scripts/regen-ts-bindings.sh—OK: TS bindings match the committed state. EXIT=0.wasm-pack build --target nodejs --dev— everyexport typedeclaration inpkg/*.d.tsis now at column 0 (verified line 193AmountValueand line 212BeancountError).tsc --noEmit --strict pkg/rustledger_wasm.d.ts— clean parse.cargo test -p rustledger-wasm— unchanged, 80/80 pass.Closes #1226.
🤖 Generated with Claude Code