- Rust 77.2%
- TypeScript 16.6%
- JavaScript 6.1%
- Vue 0.1%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
|
||
| .cargo | ||
| .forgejo/workflows | ||
| .idea | ||
| crates | ||
| docs | ||
| examples | ||
| notes | ||
| packages | ||
| scripts | ||
| skills/safe-ts-migrate | ||
| .gitattributes | ||
| .gitignore | ||
| .oxlintrc.json | ||
| Cargo.lock | ||
| Cargo.toml | ||
| CHANGELOG.md | ||
| LICENSE-APACHE | ||
| LICENSE-MIT | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| rust-toolchain.toml | ||
SAFE-TS (prototype)
A strict, Rust-flavoured subset of TypeScript for code that AI agents write, enforced by a
Rust checker built on oxc. Failures must be visible: returned as Result, or thrown as a
tracked PropagateError; never an unchecked exception, null, or shared mutable state.
An agent writes code faster than anyone can review it, and it makes the same mistakes people make. SAFE-TS turns those mistakes into checker errors, in milliseconds over the whole program, with a message that says what to write instead, so the agent fixes them before a human reads the diff.
The checker only reads source and reports diagnostics, so it has no runtime cost. A separate
build-time transform rewrites q(...), match(...), parseJson<T>(...) and array-callback
chains into plain code, on the lines they came from; what ships is ordinary JavaScript plus
the small std helpers you import.
Website: safe-ts.evobug-pages.com, with a playground that runs the checker in your browser.
Install (packages on npm under @evobug_com):
npm install -D @evobug_com/safe-ts-transform @evobug_com/oxlint-plugin-safe-ts oxlint
npm install @evobug_com/safe-ts-std # plus @evobug_com/safe-ts-vue or @evobug_com/safe-ts-react
Then Adopting SAFE-TS for the tsconfig, oxlint and Vite setup.
Learning to write SAFE-TS code: the documentation
(source): guides (errors, state without globals, absence, async, enums, JSON,
libraries, adoption) and a page per rule. Frameworks have their own section:
Vue, React.
Every example in it is tested. Locally:
npm run docs (VitePress, with search); npm run docs:build builds it to
docs/.vitepress/dist. Every push to main publishes it (.forgejo/workflows/pages.yml).
Why
I'm a lead engineer, and over ten years I've seen a lot of people, a lot of code, and lately a lot of AI slop. The same mistakes come up again and again, and AI makes them too. I'm a big fan of Rust, so I borrowed some of its concepts for this experimental library.
I'm very tired of seeing the same mistakes over and over. It's annoying and it's not effective: every fix needs its own custom checks, and people keep reinventing the wheel (as I probably am with this library, since I did zero research). I want to develop fast, satisfy what clients need, and not deal with shitty stuff anymore. It's 2026.
The idea is to set boundaries for the code, so that you can't write it in a way that breaks it. Most developers will hate this, which is why I call it my idea and an experiment. You won't be able to write code the way you're used to; it won't get past the checker. It's not that I enjoy writing code this way. It's about finding a way to be very, very safe in a language like TypeScript, where so much is only decided at runtime.
Building it meant making a lot of assumptions about how code should be written. All of it is vibe coded. If you open a pull request, there's a good chance I won't accept it, because it may not fit this experiment and what I believe is the right way.
So let's say I'm your dictator, telling you how to write your code. Everyone hates that idea, I know. But once you get deeper into it, you'll understand what's going on: why these limitations exist, why some features are forbidden, and why something simple that takes three lines elsewhere takes twenty here.
Who it's for: agents
Using it on real work projects showed me what this library is for. It isn't for people writing code by hand. It's for agents writing code, and it makes their code much better. On each of the work projects I tried it on, it found around 25 real bugs.
What makes SAFE-TS tiring for a person costs an agent nothing:
- Ceremony is free. Twenty lines instead of three, a
Resulton every failing call, a reason comment on every escape hatch. A person gets tired of that and an agent doesn't. - The rules are precise. An agent follows a rule it is told exactly. Every finding says what is wrong, why, and what to write instead, often naming the std helper, so the fix comes from the message and not from a guess.
- The loop is fast. The whole program is checked in well under a second, so an agent can run it after every edit, like a compiler.
- Review doesn't scale. An agent produces more code than anyone reads closely.
Swallowed errors,
nullmixed withundefined, unchecked casts, unvalidated JSON, shared state and async races all look fine in a diff. A checker reads every line.
There's a catch: an agent aims at "the checker passes". Whatever the checker doesn't see, an
agent will ship: a cast in disguise, a failure turned into undefined, a hand-rolled loading
flag. So the work from here goes into static analysis: catch more kinds of bugs, follow them
across files, frameworks and libraries, close the ways around the rules, and count every
escape hatch. A false negative is a bug an agent ships.
Layout
crates/safe_ts_core/ rules, per-file summaries, whole-program pass
crates/safe_ts_core/tests/ fixture tests (see below)
crates/safe_ts_cli/ `safe-ts check` / `emit` / `explain` / `coverage` / `infer` / `migrate` / `fix` / `api-diff` / `lsp` (language server)
crates/safe_ts_napi/ Node binding (napi-rs)
packages/std/ @evobug_com/safe-ts-std: result, enum, json, mut, async, random, ... (optional helpers)
packages/prelude/ @evobug_com/safe-ts-prelude: use std helpers without importing them
packages/feature-node/ feature pack: Node built-ins that throw/reject, and safe versions returning a Result or an Option (safe/)
packages/feature-browser/ feature pack: browser APIs (lib.dom.d.ts) that throw/reject, with exact errors, and safe versions (safe/, by area; `null` as Option)
packages/feature-zod/ feature pack for zod: parse() failures, safe parse(schema, x) / parseAsync, fromZod
packages/feature-vue-router/ feature pack: vue-router methods that reject or throw, and safe versions (safe/)
packages/feature-ws/ feature pack: ws 8 (WebSocket, WebSocketServer) members that throw, and safe versions (safe/)
packages/pack-kit/ for the packs (not published): the error notation, the safe-version generator
packages/safe-ts-vue/ @evobug_com/safe-ts-vue: Vue helpers (<Match>, useTask, AsyncState, useElement, useListener, safeHref, ...)
packages/safe-ts-react/ @evobug_com/safe-ts-react: React helpers (useTask, <Match>, AsyncState)
packages/safe-ts-native/ the compiled binding, shared by the packages below; the `safe-ts` command (`cli.cjs`), `bin/safe-ts` (the CLI) after `npm run build`
packages/oxlint-plugin-safe-ts/ oxlint JS plugin -> native checker
packages/safe-ts-transform/ build-time transform (q, match, parseJson, loops, ...): bundler plugin + Node loader + Bun plugin
packages/vscode-safe-ts/ VS Code extension: starts `safe-ts lsp` (not published)
packages/safe-ts-skill/ @evobug_com/safe-ts-skill: ships skills/safe-ts-migrate, with an installer (`npx @evobug_com/safe-ts-skill`)
skills/safe-ts-migrate/ agent skill for migrating a project: SKILL.md, references/ (catalogue, gates, ...), scripts/census.mjs
examples/demo/ demo app with deliberate problems
examples/vue/ small Vue app, checked by the Vite plugin (`check: "error"`): `npm run dev -w examples/vue`
examples/react/ the same app in React: `npm run dev -w examples/react`
Run it
npm install # if your ~/.npmrc sets os=linux: npm install --os=win32 --cpu=x64
npm run build # cargo build + copy the native addon next to the plugin (SAFE_TS_PROFILE=fast: see below)
npm run check # CLI, whole program: every file of examples/demo/src
npm run lint # same checks through oxlint
npm run typecheck # tsc on std + demo sources, and on the transformed output
npm run demo # run q / parseJson / enum examples in Node through the transform
npm run bench # match(...) vs a hand-written switch, through the transform
npm run bench:loops # array callbacks vs loops: which rewrites pay off
npm run bench:fusion # array method chains as written vs the loops the build makes of them
npm run bench:tags # string enum tags vs number tags, by where the tags come from
npm run bench:check # all benchmarks (also the docs' bench blocks) against a baseline
npm test # cargo test, std runtime tests, a Vite build of the demo, docs examples + site build
The Rust toolchain is a pinned nightly (rust-toolchain.toml; rustup installs it on the
first cargo call). The code may rely on what that nightly turns on: the next-generation
trait solver, the Polonius alpha borrow checker, the parallel frontend (.cargo/config.toml
runs it on 8 threads), and everything stable in Rust 1.100. crates/safe_ts_core/tests/toolchain.rs
stops compiling when one of them is off. To raise the date, change it in rust-toolchain.toml
only: CI and the release read it from there.
Build profiles. npm run build builds what ships ([profile.release]: thin LTO, one
codegen unit), which takes minutes after a one-line change to the checker. For the edit loop,
export SAFE_TS_PROFILE=fast first: npm run build, npm run check, npm run typecheck and
the soundness corpus then build and use [profile.fast] (target/fast/), which rebuilds in
under a minute and runs about 7% slower. CI's test, benchmark and docs jobs set it; the
release does not.
npm run bench:check runs npm run bench, npm run bench:loops, npm run bench:tags and
every bench block in docs/, and compares the ratios the docs claim (match through the
transform against a hand-written switch, callbacks against loops, string tags against number
tags, as written against compiled) to
scripts/bench-baseline.json. It fails when one moves past its baseline by more than the
tolerance (2x; a regression must show up in two measurements). Like production, it runs
without the dev checks (SAFE_TS_DEV_CHECKS=0),
which would otherwise add a check to every match. Ratios, not times, because
they hold across machines and noisy runners; the cost is that small changes (10-20%) go
unnoticed. Pull requests run it in CI (.forgejo/workflows/bench.yml); the test suite runs on
pull requests and pushes to main (.forgejo/workflows/test.yml). After an intended
change, or when a new Node moves the numbers, refresh it with
npm run bench:check -- --update and commit the baseline.
The checker's own speed has a guard of the same kind: counts, not times.
crates/safe_ts_core/tests/work.rs (part of cargo test) checks a project it generates, from
its entry and as a directory, and counts the work done from scratch (safe_ts_core::work):
files analyzed and parsed again, calls, names, receivers and type names resolved, type
declarations shared, types evaluated, package calls judged, failure chains and propagations
worked out, the files sentinel-error reads, feature packs loaded and alias bodies copied. Two
counts see work that grows without anything being worked out anew: the questions asked of the
pass's shared memos, answered from them or not (a rule asking again about every call), and the
allocations of the whole check, run on one thread so that they come out the same each time (a
new walk over every function, a copy made to read one field). It fails when a count grows past
its ceiling in crates/safe_ts_core/tests/work-ceilings.json (allocations: by more than 1%)
and when one falls more than 10% under it, so a speed-up is kept. After an intended change,
write the new counts with SAFE_TS_WORK_UPDATE=1 cargo nextest run -p safe_ts_core --test work
and commit them: the diff of the ceilings is where review sees what a change costs.
safe-ts check <entry.ts or dir>... checks the program reachable from one or more entries as one
program (in a monorepo, every app's entry in one run, so shared packages are reported once;
a directory is an entry for each .ts/.tsx/.mts/.cts/.vue file under it),
including workers started with new Worker(new URL("./worker.ts", import.meta.url)) and
modules loaded with import("./page.ts") (also import(`./locales/${lang}.ts`) and
import.meta.glob(...), by the files they can match). Imports resolve as a bundler resolves
them, through tsconfig.json paths and baseUrl (also inherited through extends and
references), the same way in the editor, the oxlint plugin, the Vite plugin and the Node
loader; an import that resolves to nothing is named in a could not resolve warning
(How imports are followed). Source files
under a file entry's directory that the run doesn't reach are named as not checked (pass the
directory, or add them as entries). It ends
with the root causes when several unhandled-failure findings start in the same place, and
warns about package.json scripts that run .ts files with plain node, without the loader,
and about a Vite config that imports code needing the transform (Vite loads its config
without plugins: The Vite config). Its last line
counts the escape hatches: unsafe() blocks, panic() and trust() calls, LegacyNull uses,
/** @cache */ marks, // safe-ts-ignore comments, legacy files and // @safe-ts std files,
by name, and @ts-ignore, @ts-expect-error and @ts-nocheck comments; the line after it
names each rule package.json turns off or lowers below the preset.
--json prints the problems as a JSON array, with each one's severity and each failure's
path and origin (JSON output). --summary counts the
problems by rule and by directory instead of listing them (with --json: one object, with the
version, the escape hatches, what package.json weakens, the unresolved imports and the files not
checked). It exits with 1 when there is an error; warnings fail the run only with
--deny-warnings or --max-warnings <n>, and each warning: line about the setup (a
tsconfig without strict-lib or one of the flags a guarantee depends on: strict and its members,
noUncheckedIndexedAccess, exactOptionalPropertyTypes
(why each); a feature pack not installed, a
script or Vite config that skips the transform), unresolved imports and files not checked count
as warnings (the run never says ✓ no problems with any of them). --write-baseline <file>
records the escape hatches, what package.json weakens, files not checked, unresolved imports,
setup warnings, warnings per rule and the settings that only weaken against an earlier state ("idiomatic",
"features", ...), and --baseline <file> fails the run when any of them rose or got weaker,
naming each
(A ratchet).
Each rule's level ("off", "warn", "error") comes from the oxlint preset, and package.json
changes it per rule and per directory ("safe-ts": { "rules": {...}, "overrides": [...] },
Rule levels); one line takes
// safe-ts-ignore <rule>: <reason> (Ignoring one finding).
--idiomatic also reports the opt-in idiomatic rules
(prefer-option, no-swallowed-error, ...) for one run; "safe-ts": { "idiomatic": true }
turns them on.
safe-ts --version prints the version, --help the usage. Installed projects get the command
from @evobug_com/safe-ts-native (npx safe-ts, bunx safe-ts, package.json scripts).
Codemods for existing code: safe-ts migrate <throw-to-result|null-to-undefined|ts-enum|undefined-to-option> <files or dirs...>
and safe-ts migrate union-to-enum <Type> <files or dirs...> (a type-discriminated union
into an Enum, with the values of that type) print a diff and a report of what they left alone
and why; --write changes the files. safe-ts migrate module-state <files or dirs...> changes
nothing: it lists the module state each function uses, directly or through calls, to plan a
context parameter (Migrating with codemods).
They read .ts files and Vue components (scripts and templates) as one program.
safe-ts fix <rule> <files or dirs...> applies one rule's quick fixes, the ones the editor
offers, and checks again until none is left: it prints a diff, and --write changes the files.
A site with several fixes gets the one --fix "<start of its title>" picks, else the only one
that keeps the result ((the same as now)), else it is left alone and listed with them and
why; legacy files are left out, and --json prints every site and diff
(docs).
safe-ts api-diff <git-ref> [entry.ts...] compares a package's public API at a git ref with
the working tree and exits with 1 when a change breaks callers: a removed export, a new
required parameter or key, a new error kind in a Result, a new PropagateError that can
escape, a new Enum variant in a type callers match on. It reads syntax only, so changes
it can't relate are reported as "can't classify" (docs).
In the editor, safe-ts lsp is a language server: problems as you type in .ts, .tsx,
.mts and .vue files, with failures followed into other files (unsaved buffers included),
quick fixes as code actions, and a hover listing what a call can fail with. The VS Code
extension in packages/vscode-safe-ts starts it; it was tried in VS Code 1.144.1 (Linux,
under WSL), and in no other editor yet (docs):
code --extensionDevelopmentPath="$PWD/packages/vscode-safe-ts" path/to/project
Editors running the oxlint language server (oxc extension for VS Code, RustRover/WebStorm)
also show safe-ts/* diagnostics, in .ts and .vue files (a component's template problems at
the top of its <script setup>). After npm run build, restart the
language server (SAFE-TS: Restart language server, or oxlint's) to load the new build.
Migrating a project with an agent
skills/safe-ts-migrate is an agent skill (Claude Code / Agent Skills format) for moving an
existing project to SAFE-TS: a target architecture document first, a census of findings (with
the idiomatic rules) and of the hand-rolled patterns no rule reports (scripts/census.mjs,
which doubles as a ratchet gate in CI), a catalogue of before/after examples for TypeScript, Vue
and React, the order of work, gates (safe-ts check --deny-warnings: a run with only warnings
exits 0), behaviour checks, known gaps, an escape-hatch policy and a review checklist. Its examples are tested with the docs' (docs.rs, docs-typecheck.mjs). In a
project: npx @evobug_com/safe-ts-skill copies it into .claude/skills/
(docs).
Rules
Every rule reads a member and a call one way however they are spelled: o["m"] is o.m,
Promise?.all(x) is Promise.all(x) (where the object can't be absent by how it is written),
(o).m() is o.m(), f.call(undefined, x) and f.apply(null, [x]) are f(x) (also with
this, or any this for a function the file declares), and o.m.call(o, x) is o.m(x).
A name reached through import * as ns (ns.mut(x), the type ns.Mut<T>) is the name
imported from that module, and a const that copies a name or this (const lend = mut,
const self = this) is what it copies. A type alias of the file whose body only names types
(type Lent<T> = Mut<T>) is read as its body where it is written for a value, and a name
imported from a module of the project that only re-exports it is the name it re-exports.
tests/rewrites.rs measures what else a rule's finding depends on (see Tests).
| Rule | Catches |
|---|---|
no-throw |
throw, unless it throws a PropagateError subclass (new X(...), or a factory of yours declared to return one); and the rejections that are a throw by another name: Promise.reject(x), a promise executor's reject(x) (also Promise.withResolvers()'s), or that reject handed on by name |
no-null |
null literals and null in types; absence is undefined (Option<T>). Not the null outside code needs: Object.create(null), an argument of a global or package call, el.onclick = null, x === null, a value written where a package's or the platform's type is expected |
no-undefined-check-for-null |
a value from an API that returns null (localStorage.getItem, querySelector, parentElement, RegExp#exec, ...) compared with undefined: always true or always false |
no-null-check-for-undefined |
a value whose type has no null (an Option, a field declared ?:, a pack's safe version) compared with null, or expected to be null by an assertion (assert.equal(x, null), toBeNull()): always false, or an assertion that checks nothing |
no-any |
any |
no-hidden-any |
an any nobody wrote, from lib's and Node's types: MessageEvent / CustomEvent without a type argument, MessageEvent<Job> (a claim about another context's data), Function, history.state, event.data in a "message" listener on a DOM target whose parameter isn't annotated, workerData and a worker_threads "message" value, an untyped EventEmitter's listener arguments. Also window.opener, a property descriptor's value, AbortSignal's reason (controller.signal.reason), AggregateError's errors, of a value of the type however it is reached: a field, an element, a const, a function's declared return type. What a method returns (JSON.parse, response.json(), Array.isArray, new Map(), new Array(n), Object.create, Object.values, Object.getPrototypeOf, ...) std's strict-lib retypes unknown |
no-unchecked-cast |
as (except as const), <T>x, non-null ! (except a[i]! where the checked bound proves the read in bounds: loops, while, if, tuples), definite assignment let x!: T |
brand-constructor |
a proof type (Html, SafeUrl, RegexSource, Ascii, SafePath, and the project's own Brand<"Name">) made without its constructor: raw as Html, as unknown as SafeUrl, a type argument that only says what a call returns (inject<SafeUrl>(key)), or a type predicate that claims one ((s: string): s is SafeUrl => ...) |
markup-sink |
markup written into the page (innerHTML, outerHTML, insertAdjacentHTML, setHTMLUnsafe, document.write, createContextualFragment, srcdoc, setAttribute("srcdoc", ...)) from a value that isn't a constant the source shows or an Html (escapeHtml(text), a declared or known sanitizer): the same values vue-v-html and react-dangerous-html accept (page) |
url-sink |
a URL the browser may follow (a.href, iframe.src, form.action, location.href / assign / replace, window.open, setAttribute("href", ...)) that isn't a SafeUrl (safeHref(url)) or written with a safe start (/users/${id}), a blob: URL or the page's own address |
code-sink |
code run from text the source doesn't show (eval and new Function are oxlint's no-eval and no-new-func in the preset): setTimeout(text), an on* attribute, a <script>'s text or src, a worker's script, import(specifier), Node's vm, fork, worker_threads |
command-sink |
a shell command built from text: exec, execSync, spawn / execFile with shell set; run the program without a shell, the data as arguments |
path-sink (idiomatic, warning; safe-ts check only) |
in code a handler the runtime calls with outside data reaches (a request, a socket's data, a message, and what they call), a file path given to node:fs (every function with a path parameter) that isn't a constant the source shows, what whoever runs the program gives it where the code shows it (process.argv, process.env, import.meta.dirname, a name readdir returned), a SafePath (pathUnder(root, name)) or a FromOperator |
pattern-sink |
a regular expression compiled from text: new RegExp(text) (where unhandled-failure doesn't already report it), str.search(text), str.match(text), str.matchAll(text); escapeRegExp(text) makes a RegexSource |
sql-sink |
an SQL statement given to node:sqlite (exec, prepare) that isn't a constant: bind the data as parameters |
brand-sink |
a member the project declared with brandSinks("Sql", ["pg Pool#query"]) (or a pack in its sinks) given anything but that brand, which only its brandConstructors make |
no-type-predicate |
a hand-written type predicate or assertion signature (value is User, asserts value is User, asserts value): TypeScript doesn't check the body against it, so it is a cast with a name. A body that is one test TypeScript narrows by drops the claim (TypeScript infers it; quick fix); allowed: asserts ok whose body is exactly if (!ok) throw ... / panic(...). Not in .d.ts files, declare blocks or // @safe-ts std files |
no-overload |
overload signatures on the project's functions and methods: TypeScript checks the body only against the implementation's signature. Write one function per signature, or one signature with unions (an Enum result); a result the body can't type is trust<T>(value). Allowed: overloads with the implementation's own type parameters and result, each parameter one of its union's members. Not in .d.ts files or declare blocks |
no-mutable-global |
module-level let/var, mutating module-level objects inside functions (also through aliases, destructuring, a loop or a callback over them, a list or an object holding them, a shallow copy's shared parts, and what a function, a namespace's function or a method hands back of them, across files), setting globalThis.x inside functions, subscribing from a function to a module-level event emitter (or handing it to new X(...) there; a package's emitter classes go in "safe-ts": { "emitters": [...] }), changing a package's registry from a function, a module-level latest(...) (one run in progress for every caller); /** @cache */ memos are exempt (a package's prototypes are no-foreign-prototype-patch's) |
no-param-mutation |
changing a parameter (or data reached through it) that isn't declared Mut<T>, like Rust's &T vs &mut T, also by lending it (mut(x)) or passing it to a Mut<T> parameter, calling a method of your own class that changes its object (&mut self), changing an object it holds (a loop's variable, what find / at / get give back, an element of a filtered or spread copy, as ecmascript-api.json's returns says), changing a part a function or method hands out on every path (peek(o).value = 1, return a ? o.x : o.y), or keeping it in an object whose class changes it later; one finding per parameter; a callback's parameter gets Mut from its expected type, a field can be declared Mut<T>, a canvas 2D context is owned, a platform object's on... handler slots aren't the caller's data; also Vue and React props |
missing-mut |
a value passed to a parameter (or a component's prop) declared Mut<T> without mut(value) at the call, which TypeScript refuses since Mut is nominal; also a Mut value passed on, which TypeScript accepts, so every call that lends says so. Followed into functions, methods, callback types, JSX and Vue template props, across files |
aliased-mut |
one call that lends x with mut(x) and also gets x, a part of it or what holds it, another way (transfer(mut(a), mut(a)), addAll(mut(cart), cart.items)), Rust's E0499 / E0502; a part declared a primitive (also an enum, a getter's value, a lib constant like gl.LEQUAL) is a copy and isn't reported; also two loans alive at once, or the owner writing the object while it is lent, on some path, while an async call holds a loan until its promise settles (Promise.all([f(mut(x)), g(mut(x))]), const p = f(mut(x)); if (c) await p; g(mut(x)), a loop that pushes f(mut(x)) into a list awaited after it, xs.map(async () => f(mut(x)))), runs that overlap (a listener or an interval that lends state it doesn't own, a method that keeps the promise in a field and returns), and a function that returns, or leaves by an exception (a throw, a call that throws, an await that rejects, another member of the Promise.all rejecting first), while its own parameter's loan is still held; only where the callee writes the loan after an await (its own answer too), or lends it on to one that does, or can't be named. Quick fix: Await p first |
mutating-getter |
a getter that changes its object (assigns a field, calls a method that does, lends this): a property read must not write; make it a method; a /** @cache */ field is a memo |
covariant-alias |
a Sub[], Box<Sub>, Map<K, Sub>, Vue Ref<Sub> or React RefObject<Sub> bound to a writable local, field, return or property written with a wider type argument (const bases: Base[] = subs): a Base written through it lands in subs; readonly on the wider side, or a copy; returning what the function made isn't an alias. Also a value lent (mut(x), a Mut value passed on) as a type whose writable function property takes a narrower parameter or returns a wider result than the value's own ({ onEvent: (a: Animal) => string } lent as Mut<{ onEvent: (d: Dog) => string }>), read across files |
union-tag-write |
a write through a value written as a union of object types to a property the members type differently (slot.unit.kind = "archer" on a Mason | Archer): TypeScript accepts it, and the object then says it is a member it isn't; put a new object of that member, or narrow first |
readonly-dropped |
a value whose written type has a readonly property (Readonly<T>, a readonly field, Object.freeze(...)) given a local, return, field, property, list element or collection written with that property writable (const rw: Loose = frozen): TypeScript allows it both ways, and a write through it throws on a frozen object or changes a shared one; types opened across files; quick fix Keep it read-only: Readonly<…> |
no-mutation-while-iterating |
push/splice/sort/... on a collection a for...of or forEach/map/... is going over |
stale-read |
a local holding an object read from a parameter (const room = client.state.room), used after a call that puts a new object there (client.state.room = ..., also in the functions it calls, across files): it still points at the old one |
inline |
/** @inline */ on a statement that can't be rewritten into a loop (also a chain on std's InlineArray), or on a function that can't be inlined (its body must be one expression using only its parameters and globals) |
no-redos |
regular expressions that can take exponential time ((a+)+, (\w+\s?)+) |
sort-comparator |
comparators returning booleans, .sort() without a comparator on numbers |
no-literal-collection-key |
map.get([x, y]), set.has({ id }): keys compare by identity |
no-object-dictionary |
plain objects keyed by data (counts[word]): inherited keys, __proto__, slow dictionaries; keys typed as string literals that Object.prototype doesn't have are fine |
no-for-in |
for...in, which also walks inherited keys (accepted over Object.create(null) and with an Object.hasOwn guard) |
number-parse-nan |
Number(x), parseInt, parseFloat, +x, Date.parse(text) and a number read from new Date(text) (getTime(), getFullYear(), date - other) used (arithmetic, comparison, stored, returned) before a Number.isNaN/isFinite/isInteger check (for a date: Number.isNaN(date.getTime())). A date from the clock, a number of milliseconds or its parts isn't reported |
not-found-index |
indexOf, lastIndexOf, findIndex, findLastIndex, search (-1 when nothing matches) used as a position before a comparison with -1 or < 0: an argument of splice, slice, substring, at, with, ..., an index written to, an index read past it (a[at + 1]). Not path.slice(path.lastIndexOf("/") + 1) and the other + 1 idioms, nor an element known to be there (a for...of over the list, includes first, a literal of a const list); nor an element the function shows is there (pushed, find, a for...of over the list or a filter of it, a literal built from it). Not in test files |
regex-last-index |
test / exec on a regex with the g or y flag (a literal or new RegExp(x, "g") in a const, a parameter's default or a class field) run again with the lastIndex the last call left: in a loop over other strings, a callback, a method, a second call on another string. Not the idiom (a loop walking one string's matches), matchAll / replace / split / match, or a module-level regex (no-mutable-global) |
divide-by-length |
a division or remainder by the length or size of a collection the function made by selecting (rows.filter(...), flatMap, [] / new Set() filled only under a condition), before a check that it isn't empty: NaN when nothing was kept. Not a parameter's, a field's or a module-level list's length |
use-after-consume |
a value used again on a path where an operation used it up: an ArrayBuffer after transfer() or a transfer list (postMessage, structuredClone), also through a view made on it before; a generator or another one-shot iterator (values(), entries(), matchAll()) iterated a second time; a Response / Request body read twice (also through the packs' safe versions); a ReadableStream / WritableStream locked by getReader() / getWriter() (until releaseLock()); a WebSocket, MessagePort, Worker, Node FileHandle or readline interface used after close() / terminate(). Which operations do it is data in the API maps (consumes); a platform's apply where its pack is on |
stale-across-await (warning) |
shared state (a field of this in a method, module state, a local an async callback captures) read before an await and written after it from that read (this.total += await price(id), const before = this.total; ...; this.total = before + p), or tested by a guard clause before the await and changed after it (a cache both callers miss and both fill, a flag set only after the work), or written at a position computed before it (const at = this.items.length; await save(); this.items[at] = value): a call that runs during the await is lost, or both do the work. Not reported: a write of this call's own answer, a read again after the await, a guard tested and set before the first await, a parameter declared Mut<T> (two loans at once are aliased-mut's). Quick fix: Await first |
late-listener |
a listener for an event that happens once in an object's life (abort on an AbortSignal, close / end / finish on a Node stream or socket, exit on a child process or worker, open / close on a WebSocket, a page's load), added after the function waited while it had the object, with no test of what says the event already happened (signal.aborted, conn.closed, document.readyState) since: if it came during the await, the listener never runs; also in a callback that runs later (a timer, .then, another listener), for what it captured. The events and their tests are the packs' events.once |
superseded-task-write |
a useTask / latest callback that changes state outliving the run (a captured ref, a Mut it was lent, module state, this) after an await not handed its signal, and without testing it since; or lends such state to an async function that changes it after an await of its own, without the signal: a superseded run still writes, after the newer one |
promise-never-settles |
a new Promise whose executor has a path that neither calls resolve / reject nor hands them on (an argument, stored, returned, a callback handed to a call): an if without an else, an early return, a catch that only logs, a timer whose callback settles on one path. A path that throws rejects; a callback that runs once is asked the same question; new Promise(() => {}) is on purpose |
unreleased-resource (warning) |
a resource a function acquires and doesn't release on some way out (a return, a q(...) that returns the error, the end of the body, an await of a call that can fail, a call that can throw, also where a caller catches it): a file handle, an interval or a timeout, a listening server, a worker, an observer once it observes, an AbortController once its signal is in a listener's options, an object URL, a stream reader, a temporary directory. Handing it on (returning, storing, passing it, a callback that captures it) counts as releasing; one meant to live as long as the program is reported only where the function releases it on some path. Which operations acquire and release is data in the packs' maps (acquires). Quick fix: Release it in a finally |
unbalanced-update (warning) |
a change and the change that undoes it written as a pair in one statement list (a flag set true and back to false, x += n and x -= n, set.add(k) and set.delete(k), push and pop, a value given back what a const saved of it; also made by callees the whole program shows always make it: enter(mut(room)) and leave(mut(room))), and a way out between them that skips the undo: an await of a call that can fail, a call that can throw (whoever catches it), a q(...) that returns the error, a throw, a return, and in a loop's body a continue or break (for a flag, a written one only where the function tested it first, as a lock); a call between the two is the work they bracket and leaves the pair open; not in test files |
sparse-array-write |
a write that may land past an array's end, leaving holes that read as undefined: an index or length write not shown to be at most the length, into an array made [] and filled by position; a[a.length + 1] = v; delete a[i]. Not typed arrays. a[i]! isn't proved in bounds on an array with such a write in the file |
no-foreign-prototype-patch |
assigning to the prototype of an imported or global class (Batcher.prototype.begin = ..., Object.defineProperty(X.prototype, ...), through a binding too, or handed to a helper, of the file or imported, that patches its parameter), at module level as well: each time the module runs again the patch stacks, and keeps the old module alive. ECMAScript built-ins written out are oxlint's no-extend-native |
keep-error-cause |
a new error in a catch that drops the caught one ({ cause: e }) |
dataview-endianness |
multi-byte DataView access without the littleEndian argument |
listener-cleanup |
listeners and intervals created in functions that can never be removed (not on an object the function made and hasn't handed out yet), and { once: true } alone on a target that lives as long as the page (window, document, navigator.*, a matchMedia(...) list, a module-level value); in Vue, listeners, intervals and observers a component starts and never stops; in React, ones an effect starts without returning a cleanup |
prefer-nullish-default |
enabled || true, limit || 10 where ?? is meant |
unreachable-code |
code that can never run: statements after a call that never returns (panic, unreachable, process.exit, a function declared never, also imported), and a branch the subject's written type decides (the rest of an if run or ?: chain after every member is handled, or after typeof / instanceof / === undefined / Array.isArray / in tests took every kind). After return / throw / break / continue is oxlint's no-unreachable, an error in the preset |
unknown-event |
a listener for an event its platform class never dispatches and nothing in the program does (el.addEventListener("clik", ...) on an HTMLElement, server.on("lisening", ...) on a Node server), from the browser and Node packs' event maps; on a receiver of unknown class, a typo of a DOM event; by safe-ts check only |
unmatched-event |
a listener for a name nothing in the program emits on that emitter, and an emit nobody listens for (a module-level emitter, a class extending EventEmitter / EventTarget, a field holding one, the DOM); a near miss between the two is named at both sites; by safe-ts check only |
unused-answer |
a call whose only point is its answer, as a statement: a built-in with no effect but its answer (name.trim();, list.concat(more);, Math.max(a, b);, new Error(...) not kept; measured on Node: answers.only in the language's map), a member whose answer says how much it did (encodeInto's { read, written }, readSync's count, confirm's answer: answers.tells in the maps), a function of the program that changes nothing outside itself; not with void, not a call that can fail there (the failure rules'), not a statement whose receiver or arguments do something |
misplaced-argument |
an argument named after another parameter of the function it is passed to, not its own: a parameter inserted in front (corner(x, y) for corner(size, x, y)), two swapped (area(height, width)); the two parameters declared with the same type, the names unique in the call, shifted alike or swapped in pairs; a warning |
decided-test |
a test of a place (truthiness, or === / !== / == null with a literal) while the place holds a literal the function itself just gave it, by an assignment or a call whose callee always leaves it there (stop(mut(worker)); if (worker.task !== undefined) ...), with no write, no call that may change it (any call, for this or module state) and no await between: always false or always true, with the line that set it |
compare-misses-undefined |
id !== "", count === 0 as a test where the value may be undefined (an optional parameter or field, Option<T>, a?.b, map.get(k)) and the test doesn't say what undefined does: undefined !== "" is true |
no-math-random-for-secrets |
Math.random() for tokens, keys, salts |
stable-shape |
conditional spreads, also of values and results with different keys (one optional key, ...(c ? { k: v } : {}), is allowed, and more where the object's type declares them optional), properties added after creation, and a parameter read in a loop that gets more than four object-literal shapes from the calls in its file: several hidden classes for one kind of object |
hoist-intl |
Intl formatters created on every call |
no-accumulating-copy |
[...acc, x], { ...acc, [k]: v }, acc.concat(x) on every step of a loop or reduce: copies everything collected so far, n²/2 in all |
import-attributes |
assert { type: "json" } (removed); use with |
tail-call |
/** @loop */ on a function whose self-calls aren't all in tail position |
json-literal |
/** @json */ on a constant whose value JSON can't hold exactly (-0, NaN, __proto__, spreads) |
duplicate-code-value |
two members of a code table with one value (SCOUT: 3, SCRUB: 3 in an as const or frozen table, also built with codesOf, here or imported), a literal union naming a member twice (1 | 2 | 2), two case labels of a switch with one value (labels written the same way are left to oxlint's no-duplicate-case); a member whose comment says it is an alias is exempt |
list-invariant |
a /** @sorted */ list out of order, a /** @unique */ list naming an element twice, either tag on something other than a module-level [...] as const / Object.freeze([...]) of strings or numbers |
pinned-constant-assert |
a test asserting that a constant has its declared literal value (expect(ENCODING_VERSION).toBe(34), assert.equal(Op.Hello, 1)): it only restates the constant; an assertion with a message (a pin on purpose) is exempt |
test-without-assertion |
a test with a path to its end on which no assertion runs: none at all, assertions only in a branch it may not take or after an early return, or only in a catch (it passes when nothing throws). Helpers that assert on every path count, followed by name, through arrows and across files; a loop or a callback run where it is handed over counts; an afterEach that asserts counts; an unknown call counts only when its name says it checks. A test that only checks that code doesn't throw says so: assert.doesNotThrow(...), expect(() => f()).not.toThrow() |
assertion-cannot-fail |
an assertion whose outcome doesn't depend on the code: the same expression on both sides (expect(r).toBe(r)), only constants (expect(true).toBe(true)), expect(x) with no matcher, toBeDefined() on a value whose written type has no undefined, a call of a mock the test made (expect(spy()).toBe(3)) |
deferred-assertion |
an assertion in a timer, a listener or a .then the test neither awaits nor returns: it runs after the test has passed, or never. Awaited and returned expressions, an awaited new Promise executor and fake timers moved in the test are waited for |
swallowed-assertion |
an assertion in a try whose catch neither rethrows, fails the test nor looks at the error: its failure is caught and the test passes |
focused-test |
.only (test.only, describe.only, fit, { only: true }): the other tests of the file stop running and the run still passes |
skipped-test |
a skipped test with no reason (.skip, .todo, xit, { skip: true }, t.skip(), test.skipIf(true), no body, an empty body); a reason is a comment on the line above or node:test's { skip: "why" }. Every skipped test is counted among the escape hatches |
duplicate-test-name |
two tests (or two describes) of the same name in one describe: reports, filters and snapshots can't tell them apart |
empty-test-suite |
a describe with no test, a test file that imports a runner's test and registers none (node:test passes both) |
enum-constructors |
Shape.Circle(...) where Shape is only an Enum type; the quick fix declares const Shape = constructors<Shape>() |
enum-method-name |
an enum method (Enum<V, M>) named like a method of a built-in type or a library API the feature packs describe (get, next, map, update), or like Object.prototype's (toString, valueOf), toJSON, then: a call of it the checker can't follow couldn't be told apart from the enum's |
enum-method-receiver |
a call of an enum method (error.describe()) that the build can't turn into a call of the enum's table: the receiver's type isn't declared anywhere the checker follows, the call is written in a form the rewrite doesn't take (describe?.(), a longer optional chain), it is in a Vue template, or the method is taken off its value (const f = error.describe) |
enum-method-escape |
a value of an enum with methods given where a type naming one of its methods is declared (an object type, an interface): the code there calls the method on a value that has none of its own |
enum-as-text |
an enum value turned into text: ${error}, String(error), error + "...", errors.join(", "), error.toString(); a plain object gives "[object Object]" (values whose type isn't declared aren't checked) |
unhandled-failure |
calls that can throw (builtins like JSON.parse, new URL, JSON.stringify of a value that may hold a cycle or a BigInt, new RegExp of text that isn't a RegexSource, btoa of text that isn't ASCII, reduce without an initial value on a list that may be empty, toISOString of a date parsed from text, toFixed/repeat/fromCodePoint/new Array/Intl given an argument from data, bigint / by a divisor that may be 0n: every built-in from a map of the language's built-ins, or functions in other modules that do), unless wrapped in unsafe(() => ...) or a try block; however the call is spelled (JSON["parse"](t), a copy, also one another file exports or a readonly field holds, .call/.apply, Reflect.apply, globalThis.), and a failing function used by name (texts.map(decodeURIComponent)) |
uncaught-propagation |
a PropagateError reaching module top level, or escaping from a callback (timer, event handler, forEach(async ...), a function of yours that keeps it for later) or from a function the runtime calls (setTimeout(tick), http.createServer(handle), worker.onmessage = f); a function passed by name counts as the arrow that calls it (apply(find) is apply((id) => find(id))) |
implicit-propagation |
a method the language calls for you that can propagate a PropagateError: toString, valueOf, [Symbol.toPrimitive], toJSON, toLocaleString, [Symbol.iterator] / [Symbol.asyncIterator] and an iterator's next / return / throw, [Symbol.dispose] / [Symbol.asyncDispose], then, [Symbol.hasInstance] and the other well-known symbols, a Proxy handler's traps, an object literal's getters and setters, handleEvent, [inspect.custom]; in classes and object literals at any depth. No call names them (`${x}`, JSON.stringify, a < b, for...of, using, await), so no caller is told: keep it total and put what can fail in a named method that returns a Result |
failure-contract |
a function that can propagate a PropagateError put into a slot that doesn't declare it with Throws<R, E>: a class's method against the interface member it implements, an object literal or a new C() where an interface is expected, an override against the method it overrides, an abstract method's implementation, a function's body against its own Throws, a callback kept for later against its declared type (a parameter, a field, a collection's items). A slot that declares nothing can't fail; a call through a slot propagates what it declares |
floating-rejection |
an async call that can reject with a PropagateError but is not awaited, returned or .catch()ed, including inside a try that therefore won't catch it; the same for a function that returns Promise.reject(new X()) or calls a new Promise executor's reject(new X()), and for a Promise.reject(...) nobody awaits, returns or handles |
floating-promise (warning) |
an async call that can't reject, dropped as a statement: not awaited, returned, chained or started with void, so the caller goes on before it is done. Wherever the statement is; not an arrow's value (() => save()), a function passed by name, or a Vue template's handler |
promise-as-value |
a promise read as the value it resolves to where TypeScript lets it through: a template, "..." + p, !p, p || x, p ?? x, p === undefined, String(p), { ...p }, an assertion on it (expect(p).toBeTruthy() without .resolves, assert.ok(p)), std's isErr / q / unwrapOr / isSome (whose types refuse it too), and an async callback handed to what reads its answer right away (filter, some, find, a reduce step that doesn't await its accumulator, forEach, new Promise, map read as values, a function of yours declared (x: T) => unknown) |
fetch-signal |
fetch(...) without a signal (AbortSignal.timeout(ms), the caller's): a server that never answers keeps it waiting |
bounded-concurrency |
Promise.all(items.map(...)) / Promise.allSettled over a list of any length: every task starts at once; mapLimit runs a few at a time |
pending-without-close |
a class or closure that keeps pending promises' resolvers in a collection and settles them from message events, but handles no close, error, exit or abort: when the other side dies, every pending call waits forever |
unbounded-poll |
a loop that awaits a delay (sleep, tick, a setTimeout promise) and ends only when polled state changes, with no deadline, attempt limit or AbortSignal |
unbound-method |
a method that uses this, taken off its object without being called or bound: handed on (queueMicrotask(this.tick), items.forEach(this.tick), onClick={this.save}), returned, stored, copied (const f = ticker.tick) or destructured (const { tick } = ticker); this is undefined when it runs. Not an arrow-function field, a static method, one whose body doesn't use this, one the constructor binds, this.tick.bind(this), () => this.tick() or items.forEach(this.tick, this) |
cycle-init-read |
code that runs at load (a top-level const initializer or call, extends, a static field, and the module's functions it calls) reading a binding imported through an import cycle: a TDZ ReferenceError when the other module of the cycle is imported first; names the cycle |
must-use-result |
a call whose declared return type is Result (or Promise<Result>), or that returns err(...), used as a statement, so its error is dropped; followed through objects a function returns, Pinia stores, factories and copies (const f = check); also a Result a callback returns to a caller that drops it (list.forEach(check), a timer, a listener, a list.map(check); or await Promise.all(list.map(save)); whose array nobody keeps), written as an arrow or by name; and a Result kept in a local that, on some path to the end of the function, nothing looks at (logging it or turning it into text isn't looking) or a new value replaces first; void f() discards explicitly |
no-unknown-in-result |
Result<unknown, E>, Option<any>, ...: unknown | Err is just unknown, so the check disappears; also a type parameter only the returned Result names (<T>(path) => Promise<Result<T, E>>, T is unknown at a call without <T>) |
q-position |
q(...) anywhere but const x = q(..), x = q(..), q(..);, return q(..) |
q-needs-result-return |
q(...) in a function that doesn't declare a Result return type, or get one from where it is written (a typed const, a project function's parameter) |
q-undeclared-error |
q(...) that returns early an error the function's declared error type doesn't list: the error of the call it takes (its function's declared return type, across files and through aliases, or the err("...") literals it returns when it declares none), or with q(r, mapError) the mapper's declared return type, against the function's declared error; literals, primitives, named types, Enums and classes are compared, anything else is left alone |
prelude-shadow |
with the prelude on: a local named unsafe, or q, match, is, err or Result in a file that also uses the prelude's, which hides it in its scope (q(x) is then a plain call) |
prelude-in-page |
with the prelude on: a prelude value in a function Playwright or Puppeteer runs in the page (page.evaluate(fn), addInitScript(fn), $eval(sel, fn)), where the module's imports don't exist |
needs-transform |
q(...), parseJson<T> or a prelude name without its import in a file that vite.config.* / vitest.config.* imports (or the config): Vite loads them before any plugin, without the transform |
no-method-signature |
a method signature with parameters in an interface or type literal (handle(animal: Animal): string): TypeScript checks a method's parameters in both directions, so an implementation that takes less is accepted; the quick fix writes readonly handle: (animal: Animal) => string. Not a method without parameters (destroy(): void): nothing to check there |
override-parameter |
a class member overriding a base class's method (also abstract or static; a method or an arrow function property) with a parameter that asks for more: a narrower type (after opening aliases; a union holding the base's type, an object asking for a subset, unknown and a class the base's extends are fine, the platform's and the language's classes too), required where the base's is optional or where its rest parameter may be given nothing, or T[] where it takes readonly T[]. TypeScript compares methods both ways; take the base's type and check inside, or declare the member as a function-typed property |
constructor-calls-override |
a constructor or instance field initializer that calls (directly or through the class's methods) a method a subclass in the program overrides, or an abstract one: the override runs before the subclass's fields are set; by safe-ts check only |
unbounded-spread |
a list of unknown length spread into Math.max/Math.min, push/unshift/splice/concat, String.fromCharCode/fromCodePoint, Array.of, Object.assign, append: RangeError past ~100,000 elements (and -Infinity for an empty Math.max); use maxOf/minOf or a loop. Not a method the receiver's declared type, one of the project's, declares (router.push(...names) with router: Router) |
no-nested-option |
Option<Option<T>> / Option<T | undefined>: collapses, "absent" and "present but empty" become the same |
test-only-helper |
fixture, testDouble, unchecked, expectPresent (from @evobug_com/safe-ts-std/testing) outside test files: casts there |
exhaustive-switch |
a switch on a closed set (an enum's .tag, a union of literals, a code object's constants) without default: unreachable(value); not a .tag typed string |
exhaustive-dispatch |
an if / else if, if (...) return or ?: chain that tests two or more members of a closed set and leaves some to its last branch (u.phase === Phase.WALK ? … : u.phase === Phase.RUN ? … : 0), without unreachable(x) |
negative-member-guard |
x !== E.A guarding work on a closed set, next to another member test or with a second exclusion (u.phase === Phase.INSIDE && u.job !== Job.FLEE): every other member takes the branch, those added later too |
code-range-compare |
<, <=, >, >= with a constant of a code table of whole numbers (afterJob >= Job.MOVE && afterJob <= Job.IGNITE): new names are appended, so the range quietly takes them in or leaves them out; not on a table marked /** @ordered */, nor one with a fraction among its values (tuning numbers) |
inline-member-set |
the same value tested inline against overlapping member sets in several functions (afterJob === Job.DEPOSIT || afterJob === Job.MINE here, a range there): copies of one set that drift; by safe-ts check only |
no-ts-enum |
TypeScript enum: use Enum<{...}> + match(...), or a union of string literals for plain constants |
json-type |
parseJson<T> / validate<T> / fromFields<T> / arbitrary<T> with a T that isn't JSON-shaped (Date, any, methods, ...), that the build can't evaluate or resolve, or options that aren't an object literal |
vue-sfc |
a <script> without lang="ts"; a component without <script setup> (Options API), which can't be checked; a @safe-ts legacy marker where it marks nothing |
vue-ref-value |
a ref used as a condition, with !/&&/||/??, or in a template string, without .value |
vue-lost-reactivity |
destructuring reactive() objects, props or Pinia store state; watch(props.x); passing props.x to a composable (a function using Vue's reactivity) during setup instead of a getter |
vue-setup-after-await |
lifecycle hooks, watchers, computed, provide/inject after an await (top-level await in <script setup> is fine) |
vue-async-race |
an async watcher that writes state after await without cancelling the previous run or checking it is still the latest |
vue-side-effect-in-render |
changing state in a computed getter or while the template renders; async computed |
vue-render-cost |
sorting/filtering lists in the template, lookups in lists inside v-for, new Intl.* in the template |
vue-deep-watch |
watching a whole reactive object, props or a store, or { deep: true } (or a depth over 1), unless the callback takes the whole value |
vue-prefer-shallow-ref |
ref<readonly T[]>() and other readonly types, where shallowRef is enough |
vue-inject-key |
provide/inject with a string key instead of an InjectionKey<T> |
vue-async-component |
defineAsyncComponent without errorComponent/onError |
vue-v-for-key |
v-for without :key, keyed by index in rows with state, or keyed by a new object |
vue-v-if-with-v-for |
v-if on the same element as v-for |
vue-match |
<Match :value="x"> without a slot for every variant of x's enum (or #_), a slot that isn't a variant, or a Ref instead of its value |
vue-exhaustive-v-if |
a v-if chain on x.tag without v-else that misses a variant of x's enum |
vue-maybe-undefined |
the template reads x.y where x may be undefined (ref() without a value, an optional prop, defineModel()) and no v-if/&&/?. checks it |
vue-template-ref |
useElement for an element under v-if/v-for/a slot, or read during setup, in a computed or after await (also by a function started during setup or passed as a prop); a ref name no element has |
vue-split-state |
loading = true before await, false after it (alone or next to other refs set after it), or an error = ref("") set after await: one AsyncState split in refs |
vue-ref-without-value |
a ref() without a value (ref<T>()), set after await (directly or by a helper) and shown in the template: use useTask |
vue-v-html |
v-html with anything but a constant, sanitized HTML (DOMPurify, sanitize-html, xss, a function or computed returning their result) or a value typed Html |
vue-unsafe-url |
bound :href/:action/:formaction/:src (iframe) URLs that aren't checked (javascript:): not a known start, safeHref(...), or a value typed SafeUrl |
vue-ssr-browser-global |
SSR only: window, document, localStorage, ... during setup or render |
vue-hydration-mismatch |
SSR only: Date.now(), new Date(), Math.random(), ... during setup or render |
react-async-race |
an effect that sets state after await (or in .then) without aborting or returning a cleanup |
react-split-state |
setLoading(true) before await, false after it, next to other setters after it: one AsyncState split in useStates |
react-uncached-promise |
use(fetch(...)), use(load(id)) with an async load: a new promise on every render |
react-dangerous-html |
dangerouslySetInnerHTML with anything but a constant, a sanitizer call or a value typed Html |
safe-ts-ignore |
a // safe-ts-ignore <rule>: <reason> comment without a rule or a reason, naming a rule that doesn't exist, or silencing nothing on the next line |
no-ts-suppression |
// @ts-nocheck, // @ts-ignore (@ts-expect-error fails once the error is gone) and a @ts-expect-error without a reason, and in a Vue template <!-- @vue-ignore -->, <!-- @vue-skip --> and a reasonless <!-- @vue-expect-error -->: they switch off the type checks Result, Option and Enum rely on |
no-lint-suppression |
an eslint-disable / oxlint-disable comment that names no rule or names a safe-ts/ rule, or names a rule the SAFE-TS preset makes an error (no-eval, no-proto) without -- reason: a project gated by oxlint never sees what it silences (every one is counted) |
unlisted-marker |
// @safe-ts std or // @safe-ts legacy in a file package.json doesn't list under "trustedFiles" / "legacyFiles": the marker is ignored, the file checked |
no-unchecked-declare |
an ambient declaration that asserts a value with a type nothing checks (declare const x: Config, declare function, a required member added to Window, declare module "x";): a cast with no as (every one is counted) |
Each rule is an error or a warning, as in the oxlint preset; "safe-ts": { "rules": {...}, "overrides": [...] } in package.json makes one an error, a warning or off, for the package or
some files (Rule levels).
Idiomatic rules, off unless package.json says "safe-ts": { "idiomatic": true } (or for one
run, safe-ts check --idiomatic). They hold code to one way of writing an idea rather than
catch defects (Idiomatic rules):
| Rule | Catches |
|---|---|
prefer-option (idiomatic) |
T | undefined instead of Option<T> |
no-optional-field (idiomatic) |
key?: T in a type the project declares (not JSON types, props, a library's options or declarations): a value without the key, holding anything, is accepted; write key: Option<T>; by safe-ts check only |
no-swallowed-error (idiomatic) |
if (isErr(r)) return undefined, .catch(() => undefined): a failure that becomes "missing" |
sentinel-error (idiomatic) |
return '' for "no error" and a message otherwise, tested with if (error) |
wide-param (idiomatic) |
shop: Shop used only as shop.state.cart: a context passed where two fields would do |
unneeded-mut (idiomatic) |
a Mut<T> parameter the function never changes, or mut(x) at a parameter that isn't Mut |
strict-truthiness (idiomatic) |
if (count), !name, v-if="name": a test of a number, string or bigint that hides 0 / "" / 0n |
no-positional-children (idiomatic) |
actor.children[2], el.childNodes[0], getChildAt(1): a child picked by position, which a sort (zIndex) or an insert moves |
prefer-constructor-tag (idiomatic) |
is(x, "Published"), variant(x, "Published") where Status has constructors in scope: Status.Published is the one spelling |
undeclared-return-type (idiomatic) |
a function without a declared return type whose result the checker can't read off its returns (await, a package's call, a method it doesn't know, a generic or recursive function): the rules that judge values by type say nothing about it. Not a function typed by where it is written, one returning nothing, a single test (TypeScript infers its predicate), a component, test and JavaScript files |
unused-code (idiomatic) |
a function, class, type or constant nothing used refers to: an export no file of the program imports that isn't offered outside (an entry, a package's exports, a file loaded by import() or a worker, a config file, a file nothing imports), or a declaration only such code uses; by safe-ts check only |
unused-private (idiomatic) |
a private or # member (static ones too) nothing in its class uses, a private field written and never read, a private member used only by unused private members |
string-dispatch (idiomatic) |
one plain string compared with three or more words in a function (if (word === "open") … if (word === "urls") …): a set that exists only as tests; parse it into a closed type |
Quick fixes
Diagnostics come with alternative fixes, offered as quick fixes in the editor (code actions
from safe-ts lsp, or the oxlint plugin's suggestions), listed by the CLI (= fix: ...) and
applied one rule at a time by safe-ts fix <rule>. Fixes that use a std name add its import,
in the file's quotes and semicolons (those of its imports, or of its code when it has none),
unless the prelude is on or the name is already available. In a file a
Vite or Vitest config imports, which runs without the transform, fixes don't write q(...)
and import what they use even with the prelude on.
| Diagnostic | Fixes offered |
|---|---|
unhandled-failure |
wrap in unsafe(() => …) (unsafeAsync when awaited) · propagate with q(unsafe(…)) (in functions returning Result<T, unknown>) · wrap the statement in try/catch |
must-use-result |
propagate with q(…) (in functions returning Result; if (isErr(result)) return result where the file runs untransformed) · discard with void |
no-throw |
return err(…) instead · throw a PropagateError instead |
floating-rejection |
add await (in async functions) · add .catch(…) |
floating-promise |
add await (in async functions) · start it on purpose with void |
stale-across-await |
await first: const awaited = await f(); x += awaited; for x += await f(); |
aliased-mut |
await p first: await p; before lending the object again, where const p = f(mut(x)) is in the same block of an async function |
unreleased-resource |
release it in a finally, when the release is a statement of the same block |
unbalanced-update |
undo it in a finally, when the undo is a statement of the same block as the change |
regex-last-index |
drop the g flag, where test is every use of a literal without y |
promise-as-value |
add await (in async functions) |
fetch-signal |
pass the signal in scope · time out after 10 s (AbortSignal.timeout(10_000)) |
uncaught-propagation |
wrap the statement in try/catch |
unbound-method |
bind it to its object (this.tick.bind(this)), where the object is this, super or a plain name |
readonly-dropped |
keep it read-only: Readonly<T> around the annotation, where the value is Object.freeze(...) |
number-parse-nan |
use parseNumber(…) / parseInteger(…) from @evobug_com/safe-ts-std/number (a Result) |
exhaustive-switch |
add default: unreachable(value) |
no-ts-enum |
convert to a const object + union type, keeping Color.Red and the values (literal members only) |
no-null / no-any |
replace with undefined / unknown |
strict-truthiness (idiomatic) |
compare with 0 / "" / 0n · test for a positive number · test for undefined (and ""), where the value may be undefined, also when its type is declared in another file · spread the items a [a && "x"].filter(Boolean) keeps |
needs-transform |
write q(...) out (const x = make(); if (isErr(x)) return x;) · import the prelude name |
compare-misses-undefined |
make undefined fail too (x !== undefined && x !== "") · keep what it does, written out (x === undefined || x !== "") |
missing-mut |
lend it: x → mut(x) (a fresh literal: mut<T>({ ... }) with the place's type), with the import of mut (safe-ts migrate mut applies it to a whole program) · lend each element: units → mutEach(units) where readonly Mut<T>[] (or a map's or set's Mut values) is asked |
unneeded-mut |
take it borrowed: Mut<T> → T (and the import) · at a call, remove mut(…) |
no-ts-suppression |
@ts-ignore that says why becomes @ts-expect-error, the reason kept |
no-method-signature |
write the method as a readonly property with a function type (overloads become one property with call signatures) |
no-type-predicate |
remove : x is T where the body is one test TypeScript narrows by (typeof, instanceof, Array.isArray, x !== undefined, a discriminant, std's guards): TypeScript infers the predicate and checks it (types only) |
no-hidden-any |
MessageEvent (or MessageEvent<Job>) → MessageEvent<unknown> · Function → (...args: never[]) => unknown · annotate a "message" listener's parameter MessageEvent<unknown>, a worker_threads or untyped EventEmitter listener's unknown |
undeclared-return-type (idiomatic) |
declare the return type, where every return names a type the file can write (a primitive, a declared type, new C(...), x as T), in Promise<...> for an async function |
unused-code (idiomatic) |
delete a declaration nothing refers to (with the comment above it); safe-ts fix unused-code <dirs> applies it to the whole program |
unused-private (idiomatic) |
delete a private member nothing uses |
prefer-constructor-tag (idiomatic) |
Status.Published for each string tag (importing Status as a value when the file imports only its type) |
Fixes are only offered when they are valid where the code sits: no try/catch around a
declaration (it would hide the variable), no q outside functions returning Result, no
enum conversion for computed member values. Tests apply every fix and check the diagnostic
goes away and the code still parses.
Libraries: automatic analysis and feature packs
Library calls can throw too. Every package your program imports is analyzed from its
JavaScript in node_modules, once per installed version, and what its functions throw or reject
is reported, with no configuration:
error[unhandled-failure]: `User.parse()` (zod, found in its code: contract) can throw `$ZodAsyncError | ZodError`, but the failure is not handled
error[unhandled-failure]: `new WebSocket(url).send()` (ws, found in its code: builtin) can throw `Error`, but the failure is not handled
error[unhandled-failure]: `z.string()` (zod, found in its code: argument check) can throw `Error`, but the failure is not handled
- It follows public exports (also
export *,export * as ns, re-exports from other packages, CommonJS), classes and prototype methods, and functions a factory returns, across the package's files and into its dependencies. Your own workspace packages are project code, not libraries. - Each finding names its kind:
contract(the package's own exported error class, or documented with@throws),internal,builtin(Error,TypeError, ...),dynamic(class unknown), orargument check(the guard only tests the function's parameters). "safe-ts": { "infer": "real" }reports everything except argument checks,"documented"only what the types also document with@throws,falsenothing;{ "level": "real", "exclude": ["some-lib"] }combines a level with packages to skip. The default is"all".- Cached in
node_modules/.cache/safe-ts(orSAFE_TS_CACHE_DIR), one file per package, version and level; a SAFE-TS upgrade or a changed dependency analyzes again. The first analysis of pixi.js (737 files) takes about 140 ms with the release build; after that it is a file read. - What it can't follow (API made at runtime, like axios's
axios.get) isn't reported, not guessed;safe-ts infer <package>lists it.
Feature packs are the way to be more precise: they say which failures are part of the API,
name the error details, and bring fixes. Node's built-ins have no JavaScript to read, so the
Node pack covers them. Enable packs in the nearest package.json that has a "safe-ts" field:
"safe-ts": { "features": ["@evobug_com/safe-ts-feature-node", "@evobug_com/safe-ts-feature-zod"] }
Then library calls are checked like everything else: unhandled-failure with the error type,
failures followed into callers in other files, and the pack's own fixes first:
error[unhandled-failure]: `Local.parse()` (zod) can throw `ZodError`, but the failure is not handled
= fix: Use safeParse: returns a Result (fromZod)
= fix: Wrap in unsafe(() => …): returns a Result you must check
Values are followed to where they come from: const User = z.object(...), User.extend(...),
inline chains (z.string().parse(x)), and schemas imported from other project files. A member a
pack lists wins over automatic mode; a pack entry with "complete": true (the zod pack's) covers
all of its specifiers. A call neither knows about is not judged at all (no guessing). Test
runners and assertion libraries (Vitest and vite-plus/test, @jest/globals, Mocha, Chai,
expect) are known without a pack: their hooks throw only when misused and their assertions
throw to fail the test, so neither is reported, also through a package re-exporting them.
A pack is a package with a safe-ts.json manifest:
{
"library": "zod", // optional: version-checked
"versions": { "min": "3.0.0", "below": "5.0.0" },
"modules": [{
"specifiers": ["zod"],
"functions": { "fn": { "fails": "throws", "error": "E" } }, // fn() / ns.fn()
"methods": { // on values from the module, by name
"parse": {
"fails": "throws", "error": "ZodError",
"fixes": [{ "title": "Use safeParse", "replace": "fromZod(${receiver}.safeParse(${args}))",
"imports": [{ "name": "fromZod", "from": "@evobug_com/safe-ts-feature-zod" }] }]
}
}
}]
}
classes(statics, methods,extends),creates(which class a callable returns) andinstanceskey methods by the class of the value where SAFE-TS can see it; a value of a known class is never matched by name (docs)."default": "WebSocket"names the export a default import is, for a CommonJS module that isexport =a class (import WebSocket from "ws").globals(a module's shape withoutspecifiers) describes what has no import:fetch,new URL,localStorage, aResponse's methods. It applies to names nothing in the file declares or imports (also aswindow.x) and to values declared with a global type (res: Response,el as HTMLCanvasElement). Where it lists a built-in SAFE-TS knows itself (structuredClone,new URL), the pack's entry is reported instead (docs).failsisthrowsorrejects(reported), or one of the API maps' categories thatcheckdoesn't report:args(fails only on wrong arguments),never,callback,event, ... Coverage shows those as covered, and automatic mode leaves them alone.erroris shown in the message. The official packs write it the way Node prints an error:Error [E*] {errno, syscall: 'open', path}(a system error fromopen),Error [ERR_SQLITE_ERROR] {errcode, errstr?},TypeError [ERR_INVALID_URL] {input},Error: WebSocket is not open: readyState 0 (CONNECTING)(notation). Their tests make each failure happen on the running Node (or the installedws) and check the class, code and properties.- Manifests are only read by the checker; nothing ships to the bundle. Runtime helpers like
fromZodand the packs' safe versions are tree-shakable ("sideEffects": false); importing one safe version bundles that function alone (plus two small promise handlers for one that rejects). The safe versions are generated (npm run generate:safe,packages/pack-kit/generate.ts) and written out in full, so a hot one costs about what the call it wraps does. safeon an entry names its safe version ("@evobug_com/safe-ts-feature-node/fs readFileSync"):unhandled-failureoffers Use the safe version, which rewritesstmt.run(x)torun(stmt, x)and adds the import; calls of a safe version are Results (must-use-result) (docs). The top-leveloptionlists the safe versions that return anOptionwhere the original returnsnull(get(params, k)):no-undefined-check-for-nullsuggests them, andno-null-check-for-undefinedreports comparing their value withnull(docs).- Enabling a pack is explicit: nothing changes just because a pack is installed.
- An installed library outside the pack's
versionsrange is a warning (safe-ts check), and so is a pack in"features"without asafe-ts.json(it has no rules yet).
safe-ts coverage <entry> lists the library calls a program makes and what the packs say
about each: fails (and is checked), doesn't fail, fails only on wrong arguments, or fails in a
way check doesn't report (a callback, an 'error' event, the return value), and what
automatic mode finds for the rest, with each finding's kind. Workspace packages are left out,
as project code. safe-ts infer <package> prints what the analysis finds in a package (what
each public function throws or rejects, its kind, the path and the line) and a draft pack
(docs).
| Pack | Knows | Runtime |
|---|---|---|
@evobug_com/safe-ts-feature-node |
every Node callable (2,004 in Node 26.13) mapped by how it fails; reports the ones that throw or reject on runtime conditions (187 functions, 249 methods, matched by the class of the value, and 34 globals: fetch, structuredClone, a Response's methods, crypto.subtle, ...), with the exact error (class, code, properties; 413 of 448 checked against Node by a test) |
safe versions of 434 of them that return a Result with the error typed, one module per Node module (@evobug_com/safe-ts-feature-node/fs: readFileSync, ...; /sqlite: run(statement, ...), ...), and the error types and guards (/errors: SystemError, isSystemError(e, "ENOENT"), ...); and of the 26 that return or take null, in Option (urlParse(text), get(params, key), address(server), setAuthorizer(db, undefined); Result<Option<T>, E> when it also fails) |
@evobug_com/safe-ts-feature-browser |
every browser callable in lib.dom.d.ts (2,406) mapped by how it fails, with the exact error of each failing one (class, DOMException name, the event that carries it, engine differences; checked in Chromium, Firefox and WebKit by a test); reports the 184 that throw or reject (localStorage.setItem, fetch, response.json, crypto.subtle.*, canvas.toDataURL, ...), on globals and on values declared with a DOM type |
safe versions of all 184, one module per area (/storage: setItem(localStorage, k, v); /fetch: fetch, json(response); /crypto: importKey(crypto.subtle, ...); /canvas, /clipboard, /url, /encoding, ...), with the error the union over the engines, IndexedDB's requests settled as Promise<Result> (/indexeddb: open, get(store, key, validator), put, commit, ...), and the error types and guards (/errors: isQuotaExceededError(e), isDOMException(e, "NotAllowedError"), ...); and of the 243 that return or take null, in Option (getItem(localStorage, k), querySelector(document, sel) (or querySelector(form, sel, HTMLInputElement), checked with instanceof), closest(el, sel), getAttribute, urlParse, insertBefore(list, item, undefined), WebGL's bindBuffer(gl, target, undefined), ...) |
@evobug_com/safe-ts-feature-zod |
.parse() throws / .parseAsync() rejects ZodError (zod 3–4) |
parse(schema, x) / parseAsync(schema, x) return a Result with the ZodError (zod 3, 4 and zod/mini); fromZod(schema.safeParse(x)) |
@evobug_com/safe-ts-feature-ws |
ws 8: new WebSocket() throws for a bad URL or subprotocol, send() / ping() / pong() throw before the connection is open, handleUpgrade() throws when called twice for a socket; every documented member mapped, with its 'error' events (ws-api.json) |
safe versions of all 5 in the main module, which passes ws's exports on: send(socket, data), newWebSocket(url), handleUpgrade(server, ...), ...; address(server) returns an Option |
@evobug_com/safe-ts-feature-vue-router |
router.push() / replace() / isReady() reject, router.resolve() throws (vue-router 4 and 5), with the exact errors (checked against 4.0–4.6 and 5.5) |
safe versions of all 4 in the main module, which passes vue-router's exports on: push(router, to), replace, isReady(router), resolve(router, to), with vue-router's NavigationFailure kept as the value, and isMatcherError(e) |
@evobug_com/safe-ts-std
Optional helpers; the rules don't require them, but they are what the rules point you to. The std helpers guide covers the ones beyond the first four.
| Import | Contents |
|---|---|
@evobug_com/safe-ts-std/result |
Result, Option, Err, err, isErr, isSome, unwrapOr, q, unsafe, unsafeAsync (a function returning any gives unknown: unsafe(() => JSON.parse(text)) is a Result<unknown, unknown>), PropagateError, Throws<R, E> and Throwing<Args, R, E> (a function type that says which PropagateErrors it may throw: R to TypeScript, the contract failure-contract checks; Promise<Throws<T, E>> for what an async one rejects with), panic (stop the program: a crash, counted as an escape hatch), describeError, trust<T>(value) (a named, counted cast), LegacyNull (a counted bridge for null from legacy callers). The functions that read a value (isErr, isSome, isPanic, q, unwrapOr, mapErr, describeError) refuse a promise in their types (AwaitFirst: "await it, then pass the value") |
@evobug_com/safe-ts-std/enum |
Enum, constructors, variants (the tags, generated from the type), match, is, variant, Variant, unreachable |
@evobug_com/safe-ts-std/json |
parseJson<T>, validate<T>, fromFields<T>, JsonError (with kind, expected and problems), JsonOptions, SafeInt, Int<Min, Max>, JsonValue, JsonNull / jsonNull / RawJson (a JSON null kept) |
@evobug_com/safe-ts-std/mut |
Mut<T>: a value the function may change, nominal, each property it may write checked both ways, and what a readonly one holds lent with it (a value with more properties, or a union narrowed to one member, passes on), like Rust's &mut T; a member lent where a union is asked (Mut<number[]> as Mut<number[] | Int32Array>); mut(value): lend a value at the call (addItem(mut(cart), item)), the identity, erased by the transform; mutEach(items): lend each element of a list, a map's values or a set's members (readonly Mut<T>[]), the list itself as a read-only view, erased the same way (no copy) |
@evobug_com/safe-ts-std/async |
settleAll, firstOk, withTimeout (Timed<T>), mapLimit |
@evobug_com/safe-ts-std/async-state |
AsyncState<T, E>: Idle, Loading, Ready { value }, Failed { error }, with constructors (what useTask keeps, in Vue and React) |
@evobug_com/safe-ts-std/url |
safeUrl(url) (Result), safeHref(url, fallback): only relative, http(s):, mailto:, tel: URLs, and schemes you list ({ schemes: ["blob"] }), typed SafeUrl (proof types) |
@evobug_com/safe-ts-std/base64 |
toBase64(text) (UTF-8, can't fail), fromBase64(text) (Result), fromBase64Bytes; { alphabet: "base64url" } |
@evobug_com/safe-ts-std/html |
Html, escapeHtml(text), defineSanitizer(fn): markup that can't run script, for v-html |
@evobug_com/safe-ts-std/ascii |
Ascii, isAscii(text) (narrows), asciiOf(n): text btoa can encode |
@evobug_com/safe-ts-std/open |
Open<K> (a server value from a list that can grow, with an Unknown case), lookup(table, value, fallback), toOpen, Known |
@evobug_com/safe-ts-std/patch |
Patch<T>, keep, clear: a request body that leaves, clears or sets each field |
@evobug_com/safe-ts-std/random |
randomToken, randomInt, Rng |
@evobug_com/safe-ts-std/dict |
getOwn (with a fallback typed like the table's values), KeyedMap, recordOf, keysOf, omit |
@evobug_com/safe-ts-std/events |
listen (a Disposable subscription) |
@evobug_com/safe-ts-std/regexp |
escapeRegExp, returning a RegexSource: new RegExp can't throw for one, and pattern-sink accepts it |
@evobug_com/safe-ts-std/path |
SafePath, pathUnder(root, ...parts) (Result<SafePath, PathEscape>): a path that stays under root, for node:fs (path-sink) |
@evobug_com/safe-ts-std/operator |
FromOperator, fromOperator(text) (counted as an escape hatch): text whoever runs the program gave it, past where the checker sees it come from (path-sink, code-sink, command-sink) |
@evobug_com/safe-ts-std/brand |
Brand<"Name">, brandConstructor("Name", make) (counted as an escape hatch), brandSinks("Name", members): brands of the project's own, and the library members that take only them (proof types) |
@evobug_com/safe-ts-std/number |
parseNumber, parseInteger (Result<number, NumberError>) |
@evobug_com/safe-ts-std/array |
updateEach, indexIn, maxOf, minOf, inlineArray / InlineArray (chains that always become loops), Truthy (filter(Boolean) narrows with the prelude) |
@evobug_com/safe-ts-std/testing |
fixture, testDouble, unchecked, expectPresent: test files only (test-only-helper) |
@evobug_com/safe-ts-std/arbitrary |
arbitrary<T> (test data generated from a type), check (property tests, shrinking, seeds) |
@evobug_com/safe-ts-std/strict-lib |
declarations only, for tsconfig.json "types": TypeScript's lib with unknown where it hands out any (JSON.parse, response.json(), Array.isArray, new Map() / new Set() without type arguments, new Array(n), Object.create, Object.fromEntries, Object.values / Object.entries of an interface, Object.getPrototypeOf, Object.assign of four sources, a property descriptor's value, Reflect.get / apply / construct, the callbacks of JSON.stringify and replace, a promise's rejection reason), so tsc refuses an unchecked flow. A test lists every member of lib and Node's types that hands out any and fails on one nothing answers (tests/lib-any/allowed.txt says why each other one is left). safe-ts check warns when the tsconfig doesn't load it (no-hidden-any) |
Vue
.vue components are checked whole: <script> (module level, shared by every instance),
<script setup> (per instance, so let and ref there aren't global state) and the template,
read as the code Vue runs. So every rule applies in templates too: {{ JSON.parse(x) }} is
unhandled-failure, @click="save" dropping a Result is must-use-result, a handler that
can propagate a PropagateError is uncaught-propagation (Vue only passes it to
app.config.errorHandler), v-model="props.user.name" is no-param-mutation (props are
borrowed from the parent). On top come the vue-* rules above; they also run in .ts files
that import from vue (composables). Diagnostics point at the lines of the .vue file.
// vite.config.ts: safeTs() before vue(), so script blocks are checked and rewritten first
export default defineConfig({ plugins: [safeTs({ check: "error" }), vue()] });
safe-ts check src/main.tsfollows.vueimports.- SSR rules are on with
"safe-ts": { "vue": { "ssr": true } }, or when the project depends onnuxt. - In the editor,
safe-ts lspchecks components (the VS Code extension handles.vuefiles with or without the Vue extension). oxlint hands the plugin one script block at a time; the plugin checks the whole component from disk and reports template problems at the top of<script setup>(oxlint and.vuefiles). - Not yet:
safe-ts emitdoesn't write.vuefiles; type-check components withvue-tsc.
Docs: the Vue section (source), with its own
guide, rules and a demo that runs one component written with and without safe-ts side by side.
Example app: examples/vue/.
@evobug_com/safe-ts-vue
Optional helpers for Vue 3.5+, the ones the Vue rules point to.
| Import | Contents |
|---|---|
@evobug_com/safe-ts-vue/match |
<Match :value="value">: a slot per variant of an enum value (#Ready="{ value }", #_ for the rest); checked for every variant, compiled into a v-if chain by the build |
@evobug_com/safe-ts-vue/element |
useElement(name): a template ref typed without null, for an element the checker proves is always rendered; useOptionalElement, useElements for the others |
@evobug_com/safe-ts-vue/task |
useTask(run): async work with at most one run at a time (a new run aborts the old one), outcome in state, a throw in panic, reset() back to Idle, aborted on unmount |
@evobug_com/safe-ts-vue/state |
AsyncState<T, E>: Idle, Loading, Ready { value }, Failed { error }, with constructors (from @evobug_com/safe-ts-std/async-state) |
@evobug_com/safe-ts-vue/listen |
useListener(target, type, fn), useInterval(fn, ms): stopped when the component unmounts |
@evobug_com/safe-ts-vue/inject |
injectRequired(key): Result<T, MissingInjection> that says why, instead of a bare undefined; withInjection(key, (value) => render): setup for a component that needs the value, which reports a missing provider and renders nothing |
@evobug_com/safe-ts-vue/prop |
prop<T>(String, { default }), oneOf(["left", "right"]): typed defineComponent props without as PropType<T>, keeping Vue's defaults, Boolean casting and development checks |
@evobug_com/safe-ts-vue/url |
safeUrl(url) (Result), safeHref(url, fallback): only relative, http(s):, mailto:, tel: URLs, and schemes you list, typed SafeUrl (from @evobug_com/safe-ts-std/url) |
@evobug_com/safe-ts-vue/html |
Html, escapeHtml(text), defineSanitizer(fn): what v-html accepts wherever it comes from (from @evobug_com/safe-ts-std/html) |
@evobug_com/safe-ts-vue/jsx-runtime |
a typed JSX runtime for Vue TSX ("jsxImportSource": "@evobug_com/safe-ts-vue"): jsx, jsxs, Fragment; a component's children become its default slot, as Vue's Babel plugin does |
React
.tsx and .jsx files are checked with their JSX, and every rule applies in it:
{JSON.parse(x)} is unhandled-failure. Event props (onClick, any on and a capital) are
handlers React calls later: onClick={save} or onClick={() => save()} dropping a Result is
must-use-result (on DOM elements; a component may use what its prop returns), a handler that
can propagate a PropagateError is uncaught-propagation, an async one that can reject
floating-rejection. That holds for functions declared in the component and passed by name
too. Props are a parameter, so changing them is no-param-mutation. On top come the react-*
rules above, and listener-cleanup for effects; they also run in .ts files that import
from react (custom hooks).
// vite.config.ts: safeTs() before react()
export default defineConfig({ plugins: [safeTs({ check: "error" }), react()] });
safe-ts check src/main.tsxand the oxlint plugin work on.tsxas on.ts.- Left to eslint-plugin-react-hooks and your linter's JSX rules: the rules of hooks, effect
dependencies, state set or changed during render,
keys. - Not yet: rendering a component (
<Profile />) isn't a call the checker follows, so a failure thrown while rendering isn't traced to an error boundary.
Docs: the React section (source).
Example app: examples/react/.
@evobug_com/safe-ts-react
Optional helpers for React 18+, the ones the React rules point to.
| Import | Contents |
|---|---|
@evobug_com/safe-ts-react/task |
useTask(run): async work with at most one run at a time (a new run aborts the old one), outcome in state, aborted on unmount; run and abort are stable |
@evobug_com/safe-ts-react/match |
<Match on={value} Ready={({ value }) => ...} _={...} />: a function per variant of an enum value; TypeScript checks that every variant (or _) is there |
@evobug_com/safe-ts-react/state |
AsyncState<T, E> (from @evobug_com/safe-ts-std/async-state) |
@evobug_com/safe-ts-prelude: no imports needed
Like Rust's prelude: enable it once and use match, q, Result, parseJson, ... in every
file without importing them.
// tsconfig.json
{ "compilerOptions": { "types": ["@evobug_com/safe-ts-prelude"] } }
If the tsconfig sets typeRoots, add "node_modules" to it: TypeScript looks up types
entries only there, and fails with TS2688 otherwise.
- Types:
globals.d.tsdeclares the names globally, so tsc and the editor accept them. - Runtime: the transform adds real imports for the names a file uses and doesn't declare
itself, at the start of line 1 (no line moves). Nothing goes on
globalThis; unused names cost nothing. - Analysis: SAFE-TS reads the same tsconfig switch, so
q,match,parseJson,PropagateErrorbehave exactly as if imported. - A local declaration with the same name wins, in its scope only: a local
qin one function and the prelude'sqin another both work.prelude-shadowreports a local namedunsafe, and one namedq,match,is,errorResultin a file that uses the prelude's too. Explicit imports keep working. - A function that Playwright runs in the page (
page.evaluate(fn)) has no imports there:prelude-in-pagereports prelude values in it. - Vite loads its config and the files the config imports without the transform:
needs-transformreports prelude values used there, andq(...). - A file outside any tsconfig that turns the prelude on (a script copied out of the project) gets no imports: the Node loader and the Vite plugin warn when it uses prelude names.
- If you enable a
no-undeflint rule, declare the prelude names as globals in its config.
Names: Result, Option, Err, err, isErr, isSome, unwrapOr, q, unsafe, unsafeAsync,
PropagateError, Throws, Throwing, Enum, Variant, constructors, match, is, variant, unreachable,
parseJson, validate, JsonError, JsonValue, Mut, mut, mutEach.
Result and Option (zero overhead)
Result uses the value itself for success and allocates only on the error path:
type Result<T, E> = T | Err<E>; // Err is a small nominal class
type Option<T> = T | undefined;
type PortError = Enum<{ NotANumber: { text: string }; OutOfRange: { port: number } }>;
const PortError = constructors<PortError>();
function parsePort(s: string): Result<number, PortError> {
const n = Number(s);
if (!Number.isInteger(n)) return err(PortError.NotANumber({ text: s }));
if (n < 1 || n > 65535) return err(PortError.OutOfRange({ port: n }));
return n; // no wrapper
}
const port = parsePort(input);
if (isErr(port)) return explain(port.error); // handled here; to pass it up, q(...) below
port + 1; // narrowed to number
TypeScript itself refuses to use a Result<number, E> as a number before isErr narrows it.
A promise of a Result is refused too: isErr(load()), q(load()) and std's other functions
that read a value don't compile without the await ("this is a promise: await it, then pass
the value"); see promise-as-value.
q(...): Rust's ?
function applyFontSize(raw: string): Result<Settings, SettingsError> {
const size = q(parseFontSize(raw)); // the number, or return the Err
q(saveSettings({ theme: "dark", fontSize: size }));
return { theme: "dark", fontSize: size };
}
A build-time transform rewrites each use in place, on the same line, so line numbers and stack traces stay correct (the source map maps each line to itself):
const __q1 = parseFontSize(raw); if (__q1 instanceof __qErr) return __q1; const size = __q1;
- Node:
node --import @evobug_com/safe-ts-transform/register src/main.ts(in this repository,./packages/safe-ts-transform/register.mjs), on every Node process that runs the code: servers, workers, scripts,node --test(Running TypeScript in Node). It caches rewritten files innode_modules/.cache/safe-ts, checked against each file and the files its rewrite read, keeping a few entries per file;SAFE_TS_CACHE=0turns that off, andrm -rf node_modules/.cache/safe-tsis always safe. Code Node loads before the loader can hook in (a Vite config) loads modules withawait loadTransformed(url)instead. - Bun:
preload = ["@evobug_com/safe-ts-transform/bun"]inbunfig.toml(and again under[test]) forbun runandbun test;Bun.build({ plugins: [safeTsBun()] })for bundles, since thebun buildcommand takes no plugins (Bun). The Node loader doesn't run in Bun (nomodule.registerHooks) and says so. Tested with Bun 1.4.3, 1.4.4 and 1.4.5 (packages/safe-ts-transform/test/bun.test.ts, skipped withoutbun). - Vite / Rolldown / Rollup:
import { safeTs } from "@evobug_com/safe-ts-transform"; plugins: [safeTs()](safeTs({ check: "warn" | "error" | false })also runs the rules in the dev server: terminal warnings, or Vite's error overlay;excludeleaves files out of both, andvite buildends withsafe-ts: N files checked, N legacy, N problems). Tested with Vite (npm run test:vite, and the docs site andexamples/vuebuild with it); Rolldown and Rollup share the hook shape but aren't tested directly. - Without the transform,
q()throws immediately, so a misconfigured build fails loudly. - Dev checks, like Rust's debug assertions: in the Vite dev server and the Node loader
(unless
NODE_ENV=production), the transform also checks at runtime what the rules can't see statically:q(...)given a Promise (a missingawait) or anErrfrom a second copy of std,matchgiven a variant it has no handler for, and sort comparators returningNaNor a non-number. Each failure names the file, line and column and the docs page.vite buildleaves them out completely (npm run test:vitechecks the demo bundle);safeTs({ devChecks })andSAFE_TS_DEV_CHECKS=1|0override the default. Cost and details: Dev checks.
Type safety: tsc on the source infers q(r) as the success type, but cannot check that the
error type fits the enclosing function's declared one. safe-ts emit <out> <entries...>
writes the transformed program so tsc can check the early returns, which it does
(npm run typecheck). It writes what check follows (imports, workers, import()), and
points imports of workspace packages at their emitted copies, so the output also runs with
plain node:
settings.ts(18,64): error TS2322: Type 'Err<number>' is not assignable to type 'Result<Settings, SettingsError>'.
Enums
type Shape = Enum<{
Circle: { radius: number };
Rect: { w: number; h: number };
}>; // { readonly tag: "Circle"; readonly radius: number } | { readonly tag: "Rect"; ... }
const Shape = constructors<Shape>(); // Shape.Circle({ radius: 2 }), Shape.Rect({ w, h })
const area = match(shape, {
Circle: ({ radius }) => Math.PI * radius ** 2, // payload typed per variant
Rect: ({ w, h }) => w * h,
}); // a missing variant is a compile error
For one variant, like Rust's _ =>, matches! and if let:
const round = match(shape, { Circle: () => true, _: () => false });
if (is(shape, Shape.Circle, Shape.Rect)) { ... } // narrows shape
const radius = variant(shape, Shape.Circle)?.radius; // the variant, or undefined
On an Option of an enum, like Rust's match opt { Some(..) => .., None => .. }:
const address = match(order.delivery, { pickup: (d) => d.at, ship: (d) => d.to, undefined: () => undefined });
const unset = match(order.delivery, { undefined: () => true, _: () => false }); // `_` covers undefined too
is(order.delivery, Delivery.pickup); // false for a missing value; variant(...) gives undefined
Values are plain objects: Shape.Circle({ radius: 2 }) is { tag: "Circle", radius: 2 }, and
the transform writes it that way, so constructors cost nothing. Recursive and generic enums work.
For switch, end with default: return unreachable(shape), and tsc proves every variant is handled.
match costs nothing at runtime: when it is a whole statement (const x = match(..),
return match(..), x = match(..), match(..);) with arrow handlers, the transform rewrites
it line for line into a switch on .tag (?.tag with case undefined: when the value may
be missing), with default: unreachable(...) so the emitted type-check still proves
exhaustiveness. Other uses stay a normal call (correct, slower).
| (3M calls, Node 26) | without the transform | with it (npm run bench) |
|---|---|---|
match(...) |
22–33 ns/call | 5 ns/call |
hand-written switch |
6 ns/call | 5–6 ns/call |
Without the transform match is a real call with an object of handlers, about 4–6x a
switch; rewritten, the two are the same code.
JSON from types
export type SafeUser = { readonly id: string; readonly name: string; readonly email: Option<string> };
const user = parseJson<SafeUser>(raw); // Result<SafeUser, JsonError>
const user = q(parseJson<SafeUser>(raw)); // or propagate
The transform generates a validator from the type and appends it to the end of the file (no existing line moves). Behaviour:
- errors carry a path:
$.items[3].price: expected number, got "12" - unknown fields are dropped; a fresh object is built
- options, as an object literal:
unknownKeys: "error"reports unknown fields instead,allErrors: truelists every problem inerror.problemsinstead of stopping at the first,compact: truechecks big types with a table of their fields (about 4× smaller code, up to 9× slower; opt-in) - each problem has a
kind(missing,wrongType,unknownKey, ...) and what wasexpected, for messages of your own - JSON
nullbecomesundefinedforOption<T>andfield?: - invalid JSON text is an
Err, not an exception - the call keeps its type argument (
__jsonParse<SafeUser>(raw, __v0)), so the emitted type-check verifies that the generated validator really produces aSafeUser
Supported: string, number, boolean, bigint, SafeInt, Int<Min, Max>, literal types, object types,
interfaces (with extends), arrays, tuples, unions, Option, Enum, Readonly, Record
(over string literal keys, or over string, like an index signature [key: string]: V),
typeof of a literal const, of members of an as const table, of Object.freeze(…) and of
a call of a function with a declared return type, keyof, T[K], the utility
types (Partial, Required, Pick, Omit, Exclude, Extract, NonNullable), mapped and
conditional types (with infer, T extends object and template literal patterns), tuple
spreads and lengths, JsonValue and unknown (any JSON), JsonNull and RawJson (a JSON
null kept), and type aliases, also imported (through
re-exports and from workspace packages too), declared in a function, generic and recursive.
Anything else (Date, any, methods, number keys) is a live json-type
error with the reason
(full list).
The same machinery runs the other way for tests: arbitrary<User>() becomes a generator of
User values (edge values such as "", -0, empty arrays and missing optional fields come
up often), and check(arb, property, { runs, seed }) returns the first failing value, shrunk,
with the seed that reproduces it (guide).
Propagating errors with throw
If you prefer throwing over returning Result, throw a subclass of PropagateError:
export class NotFound extends PropagateError {}
export function findUser(id: string): User {
const user = users.get(id);
if (user === undefined) throw new NotFound(id); // allowed
return user;
}
The checker tracks which error kinds every function, method and nested helper can propagate,
through sync calls and through awaited/returned async calls, across modules (also through
default and namespace imports and re-exports), until a try/catch catches them. A catch
that rethrows some kinds (if (e instanceof NotFound) return fallback; throw e;) only
handles the others. A callback handed to one of your own functions that calls it right away
(also through a const copy, or handed on to another function that does) runs inside that
call (try { apply(() => find(id)) } catch ... catches it), and a call that
passes a literal for a flag (encode(packet, false)) skips the branches that flag turns off.
Anything that reaches top level or leaves a detached callback is an error.
A call is a call however it is spelled, and a function used by name is the arrow that calls
it. apply(find) gets what apply((id) => find(id)) gets, list.map(find) what
list.map((id) => find(id)) gets, setTimeout(find) and .then(find) what a timer or a
.then callback gets. A copy is the function it copies (const load = find,
const { find: load } = api, handler = find in a class, also imported from another file), and
so are find.call(...), find.apply(...), find.bind(...)(...) and Reflect.apply(find, ...).
A method is followed wherever the source writes its class down one hop away from the call:
this.repo.load(id) with a field private readonly repo: Repo (or = new Repo(), a
constructor parameter property, this.repo = new Repo() in the constructor),
deps.repo.load(id) with deps: Deps and type Deps = { readonly repo: Repo },
makeRepo().load(id) with function makeRepo(): Repo (also (await openRepo()).load(id)),
api.users.load(id) into a module-level object or a readonly field holding one
(private readonly api = { load(id) { ... } }), and chains of these, in this file or another. Reading repo.value runs
get value() and repo.value = v runs set value(v), and each propagates what the accessor
does. A value declared with an interface or a union isn't followed: its methods are contracts,
not bodies.
A rejection is a throw by another name: return Promise.reject(new NotFound(id)) and
reject(new NotFound(id)) in a new Promise executor propagate NotFound like throw in an
async function, and Promise.reject(new Error()) is no-throw like throw new Error().
The CLI prints a map of what propagates where and where it is caught:
PropagateError map
↑ findUserName propagates InvalidInput, NotFound examples/demo/src/repo.ts:5:8
↑ fetchUserName (async) propagates InvalidInput, NotFound examples/demo/src/repo.ts:12:8
✓ caught in handleRequest (call to fetchUserName at examples/demo/src/app.ts:11:18): InvalidInput, NotFound
Escape hatches and trusted code
unsafe(() => ...)/unsafeAsync(...)turn a throw into anErr.// @safe-ts legacyin a file's first lines: the file is not checked itself, but strict code calling into it is; failure paths are traced through it, also when it is imported through a tsconfig.jsonpathsalias. It gets only the rewrites it needs to run (prelude imports,q,match,parseJson), no loops,@inlineor dev checks. In a.vuefile: the first lines of either<script>block, or<!-- @safe-ts legacy -->at the top.// @safe-ts std: trusted library code (like Rust'score), exempt from the rules. Both markers count only in files package.json lists:"safe-ts": { "trustedFiles": [...], "legacyFiles": [...] }; elsewhere the marker is reported and ignored (unlisted-marker).// eslint-disable.../// oxlint-disable...: counted; one that names no rule or asafe-ts/rule is reported (no-lint-suppression).declare ...and the project's.d.tsfiles: counted; one that asserts a type nothing checks is reported (no-unchecked-declare).test.skip,.todo,xit,{ skip: ... },t.skip(), a test with an empty body: counted as skipped tests, with a reason or without; one without a reason is reported (skipped-test).defineSanitizer(fn): counted liketrust(). Every hatch is counted however it is spelled (a copy, a namespace member,.call,(0, f)(...), a dynamic import), and a use that isn't a call (handed on, exported under another name) counts too..oxlintrc.json: a config that doesn't extend the SAFE-TS preset, or turns its rules off or down, ignores files or overrides them, is named under the escape-hatch line like a weakened package.json setting.// safe-ts-ignore <rule>: <reason>: one rule off for the next line (<!-- ... -->in a Vue template,safe-ts-ignore-filefor the file). The reason is required, and an ignore that silences nothing is reported (Ignoring one finding).// @ts-expect-error <reason>: TypeScript's check off for the next line.@ts-ignore,@ts-nocheckand a@ts-expect-errorwithout a reason are reported (no-ts-suppression); every one is counted, a test file's@ts-expect-error <reason>(a compile-time test) apart."off"or"warn"in package.json's"rules"/"overrides": a rule quieter than the preset, named under the escape-hatch line, with"infer"below"all", its"exclude","testRunners"and"vue": { "sanitizers" }.
safe-ts check --write-baseline <file> records every count, and --baseline <file> fails the
run when one rose, something was newly weakened, or a setting got weaker than it was (the
idiomatic rules off, a feature pack gone)
(A ratchet).
Tests
Each directory in crates/safe_ts_core/tests/fixtures is a small program (entry main.ts)
with expectations written as trailing comments on the lines they describe:
throw new Error("x"); // expect: no-throw
export function find(id: string): string { // propagates: NotFound
run(); // caught: NotFound
Lines without annotations must produce nothing, so false positives fail too. Fixtures import
the real @evobug_com/safe-ts-std (run npm install first); a fixture with its own tsconfig.json covers
the prelude. A second test
checks that the editor path (check_file, one file with unsaved text) agrees with the
whole-program CLI path. tests/transform.rs pins the exact q rewrite.
crates/safe_ts_cli/tests/lsp.rs drives safe-ts lsp over stdio: diagnostics on open and
change, a quick fix, a .vue file, and a failure followed into an unsaved imported file.
crates/safe_ts_core/tests/meaning.rs checks that a quick fix changes what code does only
where its title says so: it applies each fix to small functions whose value is typed every way
(T, x?: T, Option<T>, T | null, a field, a type from another file, a call), runs the code
before and after in Node over every value the type allows, and compares the results. A new
rule with fixes needs one entry in its FIXES table (what each fix does to the result), and one
program in GENERATED or WRITTEN to run it; a fix missing from the table fails the test. The
codemod cases in tests/migrate/ that can run have a probe.mjs: calls compared before and
after the codemod. What quick fixes keep lists them all.
packages/std/test/ holds compile-time tests (enum.check.ts, every @ts-expect-error
must be needed) and runtime tests that run generated JSON validators on real input.
npm run test:browsers (not part of npm run test:std: it starts browsers) makes the browser
pack's failing members fail in Chromium, Firefox and WebKit and checks each error against
browser-api.json (how,
running it).
npm run test:soundness (after npm run build; about a second) counts what gets past the
checker. The soundness corpus is a set of known bug classes,
each a hand-written program generator with small random variations: not a fuzzer, it can't find
new classes. Every program is checked as the adoption guide sets a
project up (tsc strict with strict-lib, safe-ts check --deny-warnings with the idiomatic rules
and the feature packs, oxlint with the preset); the ones that pass every gate run in Node with the
loader, and an oracle per class says whether they went wrong (threw, changed data they only
borrowed, returned a wrong result or a value of another type, or passed their own test under
node --test while the function the test is about returns a wrong result: a test that can't
fail). The classes that escape are listed
in scripts/soundness/escaping.txt, one per line, and the test fails when that list is wrong
either way. A class that escapes and isn't listed is a regression (or a class you just added:
list it); a listed class that no longer escapes must come off the list, like an unused
@ts-expect-error. The message names the class and the finding;
node scripts/soundness/corpus.mjs --class <id> --keep keeps its programs to look at.
crates/safe_ts_core/tests/rewrites.rs asks whether a finding depends on how the code is
spelled. It rewrites every fixture one meaning-preserving way at one site at a time (40
transformations: a const copy of a callee or a receiver, a namespace import, a SAFE-TS export
imported under another name, x?.m(),
x["m"](), .call and .apply, a re-export, an arrow for a declaration and back, a callback
by name, a value through a const, destructuring, a type alias, Readonly<T>, a for...of for
a forEach, if/else for ?:, a compound assignment, and more), keeps the variants tsc
accepts, and compares each variant's findings with the fixture's, line by line through the edits.
A finding the variant loses is a miss, one it gains a new report; in the full run, a quick fix
that breaks the variant's code is a fix, and a finding that says or offers something else than on
the tree as parsed (Project::analyze_as_parsed) a text. Messages and fixes must come from the
code as written: the normal run also compares every fixture finding both ways. So must what is
used: unused-code and unused-private read the references of the tree as parsed, and the
normal run checks that every fixture's findings of the two are the same both ways and that no
escape hatch is counted fewer times on the normalised tree (a used line in the full run, for
every variant). The count of sites per
(rule, transformation) is a ratchet in tests/rewrites/misses.txt: the test fails when it
differs either way. The normal run (about 20 seconds on 32 threads) checks the sites near a
finding and compares the misses; npm run test:rewrites checks every site and compiles every
variant, for the new reports and the counts tsc discards (about a minute).
SAFE_TS_REWRITES_REPORT=<dir> writes the table and every case.
One normalisation of the parsed tree (spelling::normalize) gives every rule one spelling of a
member, a call, an import (a SAFE-TS package's export imported under another name, q as ask, is
read by the name it is exported as, where nothing else in the file has either name; fixes and
messages keep the name written), a copy of a name and a type alias; on the checker's tree it also opens
Readonly<T> as a parameter's type to T (override-parameter still reads the view) and takes
?. off a name the file shows is there (a parameter or const whose written type can't be
absent, a const bound to new C(), a literal or a function). A value read once through a
const, and a function passed once by name, are a question rules ask of the tree rather than a
rewrite of it (analyze/values.rs, Values::value_of, function_of, slot_callee): the analyzer's
walk (and any visitor that judges a value by where it goes: Values::defers / read) visits such
a value where it is read, the readers of arguments follow it (follow), a visitor that reads a
callback in its call's context visits it at the call (defers_function), so rules about the binding
still see it and every span stays the code as written. The transform
reads neither (Tree::Spelled): safe-ts emit gives what it gave.
Known gaps
-
Code nothing reaches (
unused-code) is judged by what the run sees: code outside the program and its packages, a name looked up at run time (window[name]), templates other than Vue's and framework conventions it doesn't know keep nothing alive. Event names (unmatched-event,unknown-event) are matched on emitters the source writes down (a module-level or local instance, a class extendingEventEmitter/EventTarget, a field holding one, the DOM, a Node object the source names); an emitter passed around untyped has no identity, and other libraries' emitters have no event list. std'slisten(target, type, ...)doesn't checktypeagainst the target either: type the handler's event ((event: MouseEvent) => ...onaddEventListener), which TypeScript does check. -
The sink rules (
markup-sinkand the rest) judge the value at the sink by its type and how it is written, not where it came from: a value from a request and one from the project's own configuration are refused alike when neither is a constant the source shows nor the sink's brand (that is the design;path-sinkis idiomatic for that reason, and reports only in code a handler of outside data reaches: a framework whose handlers no pack describes, a call through a value whose type isn't written, a port typed with a type of the project's own leave what they run silent). A sink is seen where the receiver's class is written down (a declared type,document,location,document.createElement("a"), a package's class);innerHTML,outerHTML,insertAdjacentHTML,setHTMLUnsafe,srcdocandcreateContextualFragmentare matched by name on any receiver. Not followed: nodes moved from a parsed document into the page, ashelloption built elsewhere. Header and log injection, prototype pollution and where a request may go (SSRF) have no rule. -
A test that cannot fail (
test-without-assertionand the rules next to it) is judged as written: a loop over a table, or aforEach, counts as running its body, so a table that is empty passes; a helper in a source file without assertions that only calls another helper is taken not to assert; an unknown call counts as an assertion only by its name. Whether the assertion is about the code under test is out of scope; coverage and mutation testing are too. -
A promise read as its value (
promise-as-value) or dropped (floating-promise) is seen where the call is known to return one (a project function that isasyncor declaredPromise<...>, aconstholding its call, a pack's function that rejects), not once it is stored in alet, a field or an array. A built-in that reads its callback's answer is told by the receiver's written type (an array, aMap, an iterator; not a class of yours or a package'sReadable); a receiver with no type written is taken for the built-in. std's types can't tell a type parameter from a promise, so in generic code they let it through (the checker still sees the call), and explicit type arguments that are type parameters (isErr<T, E>(r)) don't compile, with a message aboutNotAPromisethat doesn't say why: let them be inferred. -
The language's built-ins (map): a method is reported only on a receiver whose type the code says; a typed array's or buffer's length,
target.set(source, offset), a date made from a number or out of sight, aDataViewkept in a field and an argument the function computes itself (not one it receives) aren't reported: on an adopter's code they were all in range for reasons the checker can't see. -
Calls are followed into functions, nested helpers, methods (static, instance, private, inherited, and those of module-level object literals, nested ones too), getters and setters, constructors and field initializers, also through default and namespace imports and re-exports. A method call (or an accessor's read or write) is followed when the receiver's class is written down one hop away:
this,super,new C(), a module-level instance, a variable or parameter declared asC(alsoMut<C>,Option<C>,C | undefined, or an object type, type alias or interface whose member is declaredC:deps.repo.load()), aconstcopy of one (const repo = this.repo,const self = this), a field declared with the class (an annotation,= new C(), a constructor parameter property, orthis.x = new C()in the constructor; inherited too), a value returned by a function or method declared to returnC(makeRepo().load(),Tof anasyncone'sPromise<T>once awaited, also(await openRepo()).load()), a member chain into a module-level object literal (api.users.load()) or into one areadonlyfield holds (this.api.load()), and chains of these, across files. A call through an interface, an object type, an abstract method or a callback's declared type has no body to follow: it propagates what the type declares withThrows<R, E>(nothing when it declares nothing), andfailure-contractchecks what is put there: implementations, overrides, object literals,new C(), stored callbacks. It can't check a value of an inferred type or from a package, or a class put where an unrelated class is expected, and a genericEnames nothing. A slot reached through aMaplookup, a computed key or an item (handlers[name]?.(),byName.get(name)?.(),jobs[0]?.()) is read by the function type written for it, like any other. Not followed, so not reported: a receiver whose declared type is a union of several types, a generic type parameter, an element of aMap(this.repos.get(k).load(); afor...oforforEachover a value declared as an array orSetofC, or of a function type, is), classes and objects declared inside functions, an object literal's getters, and namespace member chains (ns.sub.f()). A function used by name is treated as the arrow that calls it, written where the name is, and a copy (const f = api.load) as what it copies. A function used by name in a call that only looks it up, compares it, takes it out or prints it (handlers.includes(f),seen.has(f),seen.delete(f),indexOf,removeEventListener("x", f),emitter.off("x", f),Object.is(f, g),String(f),console.log(f)) is never called there: by the method's name on a built-in receiver (an array,Set,Map,console,Object, a DOM target); on one of unknown type only for taking a listener out, and forincludes,indexOf,lastIndexOf,hasanddeletewith the function as the only argument (app.delete("/a", remove)is a route); and by what a function of yours does with its parameter. A function written in place is always followed as called. Kept in a collection (push,add,set) it is called later by whoever reads it, and is reported like a timer's callback; where the collection (or the parameter of yours that keeps it) is declared with a function type, it is checked against that type instead (failure-contract). Where the arrow standing for a name isn't followed, neither is the name, and nothing is reported for a project function that can propagate: stored in an object or array literal written inside a function and called through it (const h = { load: find }; h.load(id)), picked in an argument (apply(strict ? find : lookup),apply(...handlers)), a default parameter value (function run(load = find)), a JSX prop that isn't an event handler (render={find}), and a promise'srejectcalled through what it is stored in (pending.get(id)?.reject(e); it is reported where it is handed on by name). A built-in that throws is reported wherever it is used by name, as it is in an arrow wherever that is written. A copy of a built-in or a global object that another file exports (export const parseText = JSON.parse,export const storage = localStorage, also renamed or re-exported) is followed to the calls made through it, and so is areadonlyfield holding one (private readonly parse = JSON.parse). A copy that can't be followed from where it is called counts where it is made: exported destructured (export const { parse } = JSON), aletset again, a field that isn'treadonly, and areadonlyone other files can reach (public orprotected, orstatic), which also counts at the calls in its class. A callback written as an argument is followed into the function it is handed to, when that function can be followed and calls it right away (also through aconstcopy of the parameter, handed on up to three functions deep, or in anasyncfunction before its firstawait, where it rejects that function's promise); anasynccallback counts as detached. A generator's body counts where it is stepped (for...of,.next(), spread) when every use of the generator steps it, else where it is made. -
Methods the language calls for you (
toString,valueOf,toJSON,[Symbol.iterator],then,[Symbol.dispose], aProxy's traps, ...) aren't followed where they run (a template,JSON.stringify,for...of,await,using):implicit-propagationrefuses one that can propagate, where it is defined in a class or an object literal. One added another way (assigned later, put on a prototype,Object.defineProperty, inherited from a package's class, aProxyhandler not written atnew Proxy(...)) isn't seen. A tagged template's tag, a decorator and a getter destructured off a value of a written-down class (const { total } = order) are followed like calls. -
override-parametercompares an override's parameters with the overridden method's as written, after opening aliases, and reports only what it can show narrower: a parameter class is compared through what extends what (the program's, lib.dom's in the browser pack, the language's map, Node's API map), and a package's class no pack describes, a function type or a type the opener stops at is left alone. A base class of a package or the platform isn't read. -
Literal arguments narrow one level: in the function called directly, code under a test of a parameter it never assigns (
if (strict),strict && ...,strict ? ... : ..., afterif (!strict) return) doesn't count when the literal rules it out. -
Promises are followed through
await,return,.then/.catch/.finally,new Promiseexecutors (a call of theirreject, also from a callback inside, rejects the promise),Promise.withResolvers(),Promise.reject(...)andPromise.all(and siblings), with or without theasynckeyword. A promise kept in a local variable is followed to where every path awaits, returns or handles it, or hands it to a function whose parameter is awaited on every path; kept in a field or an array, or passed anywhere else, it is reported as floating; a.thencallback counts as detached. -
A
catchhandles the kinds it doesn't rethrow, read fromif/else,returnandthrow ewithe instanceof Xtests (also negated, combined with&&/||, orns.X). A branch also ends at a call that never returns:assert.fail,process.exit, std'sunreachable, and the file's own: neverfunctions.assert.throws(fn)andassert.rejects(fn)catch whatfnthrows or rejects with (alsodoesNotThrow, Chai'sassert.throwsandexpect(fn).to.throw(), Vitest'sexpect(fn).toThrow()andexpect(promise).rejects.toThrow()), and so do tests, suites and hooks ofnode:testand Vitest (imported, also from a package re-exporting them likevite-plus/testor one listed in"safe-ts": { "testRunners": [...] }, or as globals), mock implementations (vi.fn(impl),mockImplementation(impl),mock.fn(impl),mock.method(o, name, impl)), and std'scheck,withTimeout,mapLimit,settleAllandfirstOk. Loops,switchand other tests in acatchare not read in detail: if they can reachthrow e, every kind counts as rethrown. Other failures (built-ins, libraries, unchecked code) count as handled only when thecatchkeeps them whatever they are, or keepsinstanceof Error. -
In the editor, an error type that doesn't fit the function's declared one (through
q) is only reported by the emitted type-check, not live. -
must-use-resultand the rules that judge a value by its type go by declared types (through type aliases), and read a function's result off itsreturns only where each is plain (what is read off); the rest needs type information.undeclared-return-type(idiomatic) asks for those return types. -
Workers are followed only when started as
new Worker(new URL("./x.ts", import.meta.url))(orSharedWorker, orWorkerfromnode:worker_threads) with the path written out, andimport(...)only with a path written out (relative, or through a tsconfig.jsonpathsalias:import("@/views/Home.vue")) or a relative pattern Vite also accepts (`./dir/${name}.ts`,import.meta.glob("./dir/*.ts"); a pattern through an alias,import.meta.glob("@/views/*.vue"), isn't expanded). Give other files nothing imports tosafe-ts checkas more entries. A failedimport()itself (a chunk that doesn't load after a deploy) isn't reported: routers have their own hook for it. -
Calls into
node_modulesare judged from a summary of each package (automatic mode) or a feature pack, not followed call by call (workspace packages are, through their symlinks). Automatic mode can't see API made at runtime (methods installed under computed names). Packs and automatic mode only see values created directly from a library (or from such values, also across files), not values passed in as parameters. -
matchoutside a whole statement (e.g.f(match(...))), or withfunction/async handlers, is not rewritten and keeps the per-call cost. -
JSON: when a union of object types fails, the error names the union, not the deepest mismatch inside it.
-
Type predicates and overloads are reported, not verified: no claim is checked against its body. The quick fix hands an inferable predicate to TypeScript, and a claim wider than its test then fails to compile where it was used.
no-overloadcompares overloads with the implementation as written (a union behind an alias isn't split into its members). Adeclare functionin a.tsfile implemented elsewhere,trust<T>(value)and// @safe-ts stdmodules are counted or trusted, not checked. -
Mut<T>closes the loans written at a call: TypeScript refuses aDog[]lent asMut<Animal[]>, aMutfunction in a callback slot that only lends to read, and a value passed withoutmut(...);aliased-mutrefuses two ways into one object in one call, and two loans alive at once on the function's paths (a branch, a loop, a list, a field, a dropped promise), runs that overlap (listeners, intervals, methods that keep the promise) and a loan of a parameter that outlives the call, where the callee holds the loan across anawait. It doesn't see who calls a function, callbacks it doesn't know run again, a promise kept where it loses it, which parts two loans of one object touch, the owner's reads, elements reached by index, or loans of two parameters that are the same object by value.no-param-mutationfollows methods of your own classes that change their object, a part handed out by a function or method whose everyreturngives back the same path, and a borrowed value a class keeps and changes later;mutating-getterrefuses a getter that changes its object, andcovariant-aliasaSub[]bound to a writableBase[]local, field,returnor property.union-tag-writerefuses a write through a union to a property its members type differently, andreadonly-droppeda value with areadonlyproperty given a place where that property is writable. Still open: a method declared in an interface (no body to read) or a subclass's override that changes the object where its base doesn't, a part handed out by a project method of the receiver through more than one call (peek(peek2(o))) or by amapwhose callback returns its argument, a borrowed value kept somewhere other than the object's own fields (a collection of aMutparameter, a closure kept for later), loans alive at once where the code doesn't show the overlap (above), a covariant alias or a union write where a side has no written type (also for a function in a writable property replaced by one that needs more, whichcovariant-aliasreports at the lend where both types are written). A key chosen at run time is written through the plain view (const target: T = obj; target[key] = value): TypeScript readsMut<T>[K]from the intersectionMutis.Mutchecks each property: a value with more properties than the parameter names is lent, one whose writable property is narrower (x: 0 | 1forx: number) is refused, and what areadonlyproperty holds is checked the same way, as deep as it goes ({ readonly dogs: Dog[] }lent as{ readonly dogs: Animal[] }is refused). Not refused, because a plain assignment reaches them anyway: a value lent asMut<Record<string, V>>(the callee maydeletea required key), asMut<object>(Object.assignwrites anything), or as a type with an optional property the value lacks. Not refused by the type either: a function in a writable property replaced by one that needs a narrower argument (types can't tell it from a method, which is compared one way so subclasses lend);covariant-aliasreports that lend, reading the syntax, where both types are written. A write through a member shared by areadonlyproperty's union (unit.kind = "soldier"in areadonly unit: Builder | Soldierlent aBuilder) passes the type, andunion-tag-writerefuses it. -
Sentinel values:
not-found-indextakes uses and checks in the order they are written, not along paths (number-parse-nanfollows paths, docs/guide/flow.md).not-found-indexdoesn't see an element known to be in a list for a reason outside the function (a caller or a helper found it there), and doesn't check test files.divide-by-lengthlooks only at collections a function makes by selecting (filter, a conditionalpush): a parameter's length, a field, a number parameter or an imported constant as a divisor isn't checked (on an adopter's project, every divisor that isn't a literal or checked was ~1,700 places, none of those read could be 0; every list's length was 29, 2 of them real).sparse-array-writereports writes past the end into arrays filled by position; an index write into a list that is pushed to, made with its elements or of a kind it can't see is only taken into account (noa[i]!is proved on it), and a hole made in another file isn't seen. -
use-after-consumefollows a value in the function that uses it up: an operation inside a function it is handed to, or inside a callback, isn't seen, and a value of no known kind (an imported generator function's result, a field, a property, a destructuring, a reassignedlet) isn't followed. A secondconstname for the value and the views on a buffer are. -
stale-across-awaitdoesn't know who calls a function: a method only ever awaited in sequence by one caller is reported like one run twice at once. State reached through a local alias, an element or a method that writes for you isn't followed, and a guard held on one place counts for every place the function reads. -
late-listenerknows the events that happen once from the packs, for the classes the source writes down (a parameter or local declared with the class,window,document,new WebSocket(...), whatspawn()orcreateReadStream()returns, and every written form calls are resolved through: a loop variable, an element, a destructured parameter, a field, a member; a member of a platform object by the packs'creates): the program's own emitters have no data, and what a library or a platform method returns (store.put(...)'s request), or a library callback's parameters, isn't known. A listener added synchronously to an object that arrives already done (a function called with an aborted signal) andevents.once(emitter, name)aren't followed. -
unused-answerknows the language's built-ins with no effect but their answer by measuring them on Node, and of the platform's only the few whose answer tells what they did (encodeInto,readSync,confirm): a lookup of the browser's or Node's (params.get(k);) isn't known. A dropped answer that isn't a statement of its own (an arrow whose body is the call, a branch of?:), a receiver the shapes don't follow (a union, an inferred type), andSet#add(whose answer is the set, not whether the value was new) aren't seen. A function of the program counts only when every function it calls is followed, and one passed by name isn't. -
misplaced-argumentreads the parameters of the program's own functions: a built-in's, the platform's and a package's (Math.atan2(x, y)) aren't compared, and arguments with no name (a literal, an expression), one argument out of place alone, and names that don't match (pxforx) aren't seen. -
superseded-task-writefollows a task callback written in place, and one call down: a function the callback lends state to is read, a function that function hands it to isn't. A change made through a method of an object (store.setOpen(text)) isn't seen, only the known changing methods on the state itself. -
promise-never-settlestrusts whoever is handedresolve(a function of the project, a listener for an event that never comes), and follows only an executor written in place. -
unreleased-resourcetakes a resource returned, stored, passed on or captured by a callback as released by whoever holds it, and follows only aconst/letof the function bound from an operation the maps name. Anawaitoutside atryis a way out when the awaited call can fail, and a call when it can throw (the whole program decides); anawaitof a promise held in a property or a parameter is taken to reject, a call the checker can't resolve not to throw. -
unbalanced-updatesees a pair written in one function (or made by callees that always make the change, as a statement of their own):begin()/end()called by someone else, a pair with nothing in common the code shows (lock(name)/unlock(name)on a table elsewhere), a change made below the callee (a callee's summary describes its own changes) and a call between that the checker can't resolve (taken not to throw) are out of its sight. A flag left set on a writtenreturn,continueorbreakis reported only where the function tested the flag first. -
decided-testknows only literals in places, given in the function itself or by a callee that always leaves them (itself, or by a call it makes; a literal set further down isn't known): a test in a callee that reads state the caller already cleared (the function that ends a mode, called after the mode was already switched off) isn't reported, because the reads of that state that are meant to see it cleared are far more common. -
must-use-resultfollows a keptResultin its local: a copy is handing it on, and an earlyreturnbefore the code that looks at it isn't counted as dropping it. -
anythat nobody writes: the checker reads lib's from a curated list (no-hidden-any), and std's strict-lib retypes what lib's methods return, in the projects whose tsconfig loads it. A listener counts only on a receiver visibly of a known kind (a DOM target, aworker_threadsport, an untypedEventEmitter). A library's ownany(an untyped package, a.d.tsthat saysany), Node's other ones (process.on("message"),require,events.once) and ananyonly the type checker sees (event.dataafterinstanceof MessageEvent, a receiver of unknown type) aren't seen:unsafe(...)around such a call givesunknown. -
Escaping the checker: a
declareis reported only where it asserts a value TypeScript can't check (no-unchecked-declare): members a library's namespace gets indeclare global, what an interface'sextendsadds, a bare read of a global declaredOption<T>(aReferenceErrorwhen never set) isn't. Lint suppressions are those of eslint and oxlint (no-lint-suppression);.oxlintrc.jsonis read next to the package.json (not the files itsextendsnames, nested configs,oxlint -c, or a config in JavaScript), and other linters' comments aren't. A"trustedFiles"/"legacyFiles"pattern broader than the files that use it allows the marker in files written later; the legacy and std file counts still rise.
Releasing
The packages are published on npm as @evobug_com/*,
all with one version:
node scripts/build-packages.mjswrites one publishable directory per package to.release/. std, safe-ts-vue, safe-ts-react and feature-zod go through the safe-ts transform and tsc and are published as.js+.d.ts(Node won't strip types insidenode_modules); the rest are copied as they are.@evobug_com/safe-ts-skillgetsskills/safe-ts-migratecopied in, and itsSKILL.mdmust name the version ("Written for SAFE-TS ."), whichbuild-packageschecks.- The native addon is published per platform (
@evobug_com/safe-ts-native-linux-x64-gnu,-linux-arm64-gnu,-darwin-x64,-darwin-arm64,-win32-x64-msvc), as optional dependencies of@evobug_com/safe-ts-native, so npm installs only the one for the machine. Each platform package also carries the CLI asbin/safe-ts(the language server; the VS Code extension finds it there).node scripts/build-native.mjs --allcross-compiles them all on Linux (cargo-zigbuild, cargo-xwin). node scripts/verify-packages.mjspacks everything, installs the tarballs into a new project under the system temp directory, and checks std, Vue and React helper imports, a Vite build usingq/match/parseJson, the Node loader, the prelude, tsc on the declarations, the oxlint preset, the CLI from the platform package (check,lsp, and that the VS Code extension finds it), and the migration skill (its installer, and its census running that CLI).
Changes to the packages go in CHANGELOG.md, under Unreleased, in the pull request that makes them. One file for every package, since they share a version.
To release: set the version in every packages/*/package.json and in
skills/safe-ts-migrate/SKILL.md (build-packages refuses mismatches), rename the changelog's
Unreleased heading to ## [<version>] - <date> (a tag whose version has no section there is
refused), merge, and push a tag v<version>
(git tag v0.1.0 && git push origin v0.1.0).
.forgejo/workflows/release.yml builds the addons, runs the checks and publishes with the
NPM_TOKEN secret. Started by hand, the workflow is a dry run: everything except the upload.
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option. Unless you explicitly state otherwise, any contribution you submit for inclusion in this project, as defined in the Apache-2.0 license, is dual licensed as above, without any additional terms or conditions.