Transform: dev checks for what the rules can't see #10

Merged
sionzee merged 1 commit from dev-checks into main 2026-11-03 21:36:11 +01:00
Owner

Dev-only runtime checks, like Rust's debug assertions. In development the transform wraps a few values in a check. Production builds never contain them, and their output is the same bytes as before this change.

What is checked, and why these

I went through the "What the rule can't see" sections and README "Known gaps", looking for places where a value breaks its type at runtime and the program then carries on quietly. I kept a check only if it is cheap and has a clear message:

  • q(...) given a Promise. A missing await type-checks: Result<T, E> lets T be a Promise. No rule reports it either. I checked: q(saveUser(u)); with an async saveUser gives no problems from safe-ts check and none from tsc. Without the check, the Promise is treated as the value and the Err inside it is never returned. This was the strongest candidate.
  • q(...) given an Err it doesn't recognize. q tests instanceof against the Err the file imports. If std is loaded twice (two versions, or one module reached through two paths), the other copy's Err passes through as a success value. The check reports any object whose class is named Err, that has an error field and fails instanceof.
  • match without _, given a variant it has no handler for, or a value with no tag. This catches data that skipped validation: a cast of JSON.parse output, a type guard that lies, a server that added a variant. The message lists the tags the match handles. It covers every match whose handlers are an object literal, including the ones the switch rewrite leaves as calls.
  • .sort(f) / .toSorted(f) comparators returning NaN or a non-number. sort-comparator says it can't see these. With a.price - b.price and a missing price, the sort finishes in an order that depends on the engine. The message shows the two values compared.

Candidates I left out (explained in the guide too):

  • Freezing non-Mut parameters. It freezes the caller's object permanently, so the caller's own later, correct changes would throw in dev and work in prod. A Proxy changes identity (===, Map keys, #private).
  • stable-shape at runtime. Hidden classes aren't visible without V8 flags.
  • Lying type guards. Checking them needs a validator, and only JSON types have one.
  • Inconsistent comparators. Checking needs twice as many comparisons.

How it works

  • New crates/safe_ts_core/src/devchecks.rs. It runs first, on the text as written, so the locations it reports are the developer's own line and column. It wraps each argument where it stands, so lines don't move: q(__safeTsDevQ(x, "src/a.ts:3:16")), match(__safeTsDevMatch(s, "…", ["Circle", "Rect"]), …), .sort(__safeTsDevSort(f, "…")). Then the existing rewrites run as before. The helper functions are plain JS added after the file's last line (the same way JSON validators are), and only the ones the file uses. std files (@safe-ts std) are skipped. Vue script blocks get their own helper names and component-relative locations.
  • Messages look like safe-ts dev check failed at <file>:<line>:<col>: …\n See https://safe-ts.evobug-pages.com/<page>. The error's name is SafeTsDevCheck. Pages: rules/floating-rejection (Promise), rules/no-unchecked-cast (match), rules/sort-comparator. The foreign Err case has no rule, so it links to guide/dev-checks#q.
  • API: Project::transform_with(path, text, TransformOptions { dev_checks }) (transform is unchanged and leaves the checks out). The napi transform(filename, source, { devChecks }) and the JS transform(file, code, { devChecks }) default to off.
  • How it decides: safeTs({ devChecks }), when set, decides. Otherwise it follows Vite's command: serve (dev server, Vitest) means on, build means off. Rollup/Rolldown without Vite means off. The Node loader is on unless NODE_ENV=production, and SAFE_TS_DEV_CHECKS=1|0 overrides that. safe-ts emit/explain, the wasm playground and the docs' compiled tabs stay off.
  • Cost (dev only): one call plus one or two typeof tests per q; one call plus an array of the handled tags per match; one extra call and a typeof per comparison; a few hundred bytes of helpers per file.

Tests

  • crates/safe_ts_core/tests/transform.rs: exact output with dev checks for q, match (also _ → not wrapped, and a non-rewritten call), sort (and .sort() / two-argument .sort left alone), nested wraps on one line, Vue locations, std files skipped. Each test also checks that the default transform contains no __safeTsDev.
  • scripts/vite-check.mjs (npm run test:vite) uses the demo's real build output. dist/run.js must contain none of __safeTsDev, safe-ts dev check or SafeTsDevCheck. The dev server, with the same config, must serve the wrapped match/q with the right location, and ssrLoadModule of shapes.ts must throw the located check for an unknown variant.
  • packages/std/test/dev-checks.test.ts (runtime, through the Node loader) shows each check firing, with exact file:line:col and page URL: q with a Promise; q with an Err from a second instance of result.ts; match with an unknown variant or no tag; NaN and boolean comparators. Correct values pass through unchanged.
  • packages/safe-ts-transform/test/dev-checks.test.ts: JS transform() default off; the loader's env logic; the plugin's defaults for serve/build/no Vite and the overrides. It also runs the same code both ways: the prod output sorts NaN silently, the dev output throws.

Results:

  • cargo nextest run --workspace: 100 passed, 1 failed. The failure is fixtures_match_annotations: the features fixture reports main.ts:55 unhandled-failure (createDecipheriv). It fails the same way on a clean checkout of main (I checked in a separate worktree), so it is not from this change.
  • npm run test:std: 129 tests, 128 passed, 1 failed. The failure is packages/feature-node/test/manifest.test.ts "every Node callable is mapped exactly once". It also fails with SAFE_TS_DEV_CHECKS=0, so it is not from the dev checks; it looks like the same Node feature-pack drift as the fixture failure. The 13 new dev-check tests pass.
  • npm run test:vite: passed.
  • npm run test:docs: passed (214 examples compile, wasm build, VitePress build without dead links).
  • npm run typecheck: passed.

Docs

  • New guide page docs/guide/dev-checks.md, in the sidebar (Going further) and in docs/README.md. It covers when the checks are on, exactly what is checked, what the transform adds, the cost, and what isn't checked and why.
  • Mentioned in the README (q(...) section), guide/adoption.md and guide/transforms.md.

Left out / uncertain

  • Only the q(...) calls the transform rewrites get the Err check. isErr(...) and hand-written instanceof Err don't, and neither does <Match> in Vue templates.
  • The foreign-Err test goes by the class name Err. A minifier that renames classes in dev would hide it (dev builds usually aren't minified).
  • The Promise check reports any thenable. A Result whose success value really is a Promise would be flagged too. I expect that to be rare enough to accept, and the docs say what is checked.
  • Rollup and Rolldown on their own (without Vite) aren't tested; there the default is off.

🤖 Generated with Claude Code

Dev-only runtime checks, like Rust's debug assertions. In development the transform wraps a few values in a check. Production builds never contain them, and their output is the same bytes as before this change. ## What is checked, and why these I went through the "What the rule can't see" sections and README "Known gaps", looking for places where a value breaks its type at runtime and the program then carries on quietly. I kept a check only if it is cheap and has a clear message: - **`q(...)` given a Promise.** A missing `await` type-checks: `Result<T, E>` lets `T` be a Promise. No rule reports it either. I checked: `q(saveUser(u));` with an `async` `saveUser` gives no problems from `safe-ts check` and none from `tsc`. Without the check, the Promise is treated as the value and the `Err` inside it is never returned. This was the strongest candidate. - **`q(...)` given an `Err` it doesn't recognize.** `q` tests `instanceof` against the `Err` the file imports. If std is loaded twice (two versions, or one module reached through two paths), the other copy's `Err` passes through as a success value. The check reports any object whose class is named `Err`, that has an `error` field and fails `instanceof`. - **`match` without `_`, given a variant it has no handler for, or a value with no `tag`.** This catches data that skipped validation: a cast of `JSON.parse` output, a type guard that lies, a server that added a variant. The message lists the tags the match handles. It covers every `match` whose handlers are an object literal, including the ones the switch rewrite leaves as calls. - **`.sort(f)` / `.toSorted(f)` comparators returning `NaN` or a non-number.** `sort-comparator` says it can't see these. With `a.price - b.price` and a missing `price`, the sort finishes in an order that depends on the engine. The message shows the two values compared. Candidates I left out (explained in the guide too): - **Freezing non-`Mut` parameters.** It freezes the caller's object permanently, so the caller's own later, correct changes would throw in dev and work in prod. A Proxy changes identity (`===`, Map keys, `#private`). - **stable-shape at runtime.** Hidden classes aren't visible without V8 flags. - **Lying type guards.** Checking them needs a validator, and only JSON types have one. - **Inconsistent comparators.** Checking needs twice as many comparisons. ## How it works - New `crates/safe_ts_core/src/devchecks.rs`. It runs first, on the text as written, so the locations it reports are the developer's own line and column. It wraps each argument where it stands, so lines don't move: `q(__safeTsDevQ(x, "src/a.ts:3:16"))`, `match(__safeTsDevMatch(s, "…", ["Circle", "Rect"]), …)`, `.sort(__safeTsDevSort(f, "…"))`. Then the existing rewrites run as before. The helper functions are plain JS added after the file's last line (the same way JSON validators are), and only the ones the file uses. std files (`@safe-ts std`) are skipped. Vue script blocks get their own helper names and component-relative locations. - Messages look like `safe-ts dev check failed at <file>:<line>:<col>: …\n See https://safe-ts.evobug-pages.com/<page>`. The error's name is `SafeTsDevCheck`. Pages: `rules/floating-rejection` (Promise), `rules/no-unchecked-cast` (match), `rules/sort-comparator`. The foreign `Err` case has no rule, so it links to `guide/dev-checks#q`. - API: `Project::transform_with(path, text, TransformOptions { dev_checks })` (`transform` is unchanged and leaves the checks out). The napi `transform(filename, source, { devChecks })` and the JS `transform(file, code, { devChecks })` default to off. - **How it decides:** `safeTs({ devChecks })`, when set, decides. Otherwise it follows Vite's `command`: `serve` (dev server, Vitest) means on, `build` means off. Rollup/Rolldown without Vite means off. The Node loader is on unless `NODE_ENV=production`, and `SAFE_TS_DEV_CHECKS=1|0` overrides that. `safe-ts emit/explain`, the wasm playground and the docs' compiled tabs stay off. - Cost (dev only): one call plus one or two `typeof` tests per `q`; one call plus an array of the handled tags per `match`; one extra call and a `typeof` per comparison; a few hundred bytes of helpers per file. ## Tests - `crates/safe_ts_core/tests/transform.rs`: exact output with dev checks for q, match (also `_` → not wrapped, and a non-rewritten call), sort (and `.sort()` / two-argument `.sort` left alone), nested wraps on one line, Vue locations, std files skipped. Each test also checks that the default `transform` contains no `__safeTsDev`. - `scripts/vite-check.mjs` (`npm run test:vite`) uses the demo's real build output. `dist/run.js` must contain none of `__safeTsDev`, `safe-ts dev check` or `SafeTsDevCheck`. The dev server, with the same config, must serve the wrapped `match`/`q` with the right location, and `ssrLoadModule` of `shapes.ts` must throw the located check for an unknown variant. - `packages/std/test/dev-checks.test.ts` (runtime, through the Node loader) shows each check firing, with exact file:line:col and page URL: q with a Promise; q with an `Err` from a second instance of `result.ts`; match with an unknown variant or no tag; NaN and boolean comparators. Correct values pass through unchanged. - `packages/safe-ts-transform/test/dev-checks.test.ts`: JS `transform()` default off; the loader's env logic; the plugin's defaults for serve/build/no Vite and the overrides. It also runs the same code both ways: the prod output sorts NaN silently, the dev output throws. Results: - `cargo nextest run --workspace`: 100 passed, 1 failed. The failure is `fixtures_match_annotations`: the `features` fixture reports `main.ts:55 unhandled-failure` (`createDecipheriv`). It **fails the same way on a clean checkout of `main`** (I checked in a separate worktree), so it is not from this change. - `npm run test:std`: 129 tests, 128 passed, 1 failed. The failure is `packages/feature-node/test/manifest.test.ts` "every Node callable is mapped exactly once". It **also fails with `SAFE_TS_DEV_CHECKS=0`**, so it is not from the dev checks; it looks like the same Node feature-pack drift as the fixture failure. The 13 new dev-check tests pass. - `npm run test:vite`: passed. - `npm run test:docs`: passed (214 examples compile, wasm build, VitePress build without dead links). - `npm run typecheck`: passed. ## Docs - New guide page `docs/guide/dev-checks.md`, in the sidebar (Going further) and in `docs/README.md`. It covers when the checks are on, exactly what is checked, what the transform adds, the cost, and what isn't checked and why. - Mentioned in the README (`q(...)` section), `guide/adoption.md` and `guide/transforms.md`. ## Left out / uncertain - Only the `q(...)` calls the transform rewrites get the `Err` check. `isErr(...)` and hand-written `instanceof Err` don't, and neither does `<Match>` in Vue templates. - The foreign-`Err` test goes by the class name `Err`. A minifier that renames classes in dev would hide it (dev builds usually aren't minified). - The Promise check reports any thenable. A `Result` whose success value really is a Promise would be flagged too. I expect that to be rare enough to accept, and the docs say what is checked. - Rollup and Rolldown on their own (without Vite) aren't tested; there the default is off. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Like Rust's debug assertions: in development the transform wraps a few values in a runtime
check, and production builds never emit them. The checks cover gaps the static rules
document, where a value breaks its type and the program carries on quietly:

- q(...) given a Promise (a missing await type-checks, since a Result may hold any value)
  or an Err from a second copy of std, which instanceof misses;
- match without `_` given a variant it has no handler for, or no tag at all (data that
  bypassed its type);
- sort/toSorted comparators returning NaN or a non-number.

Each failure names file:line:column and the docs page. On for the Vite dev server and the
Node loader (unless NODE_ENV=production), off for vite build; safeTs({ devChecks }) and
SAFE_TS_DEV_CHECKS override. The checks are inserted on the text as written, so locations
are what the developer wrote, and every wrap stays on its line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch dev-checks 2026-11-03 21:36:11 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!10
No description provided.