Adopting SAFE-TS
How to add SAFE-TS to a greenfield project or roll it out incrementally across an existing codebase.
In short
- Install & wire up: add the packages, extend the oxlint preset, and enable the Vite plugin.
- Run transforms outside Vite: Node scripts, workers, and
node --testneed--import @evobug_com/safe-ts-transform/register(Running TypeScript in Node); Bun uses itsbunfig.tomlpreload (Bun). Vite loads its own config without plugins (The Vite config). - Turn on the strict tsconfig flags: enable
strict,noUncheckedIndexedAccess,exactOptionalPropertyTypes, and"types": ["@evobug_com/safe-ts-std/strict-lib"](why each matters; for legacy repos, measure then ratchet). - Run whole-program CI checks:
safe-ts check src/main.tsfollows imports acrosstsconfig.jsonpaths; pass--deny-warningsto gate warnings too, and configure overrides per directory inpackage.json(rule levels). - Migrate incrementally: keep new files strict from day one, tag legacy files with
// @safe-ts legacy, automate repetitive conversions withsafe-ts migrate, and lock escape-hatch counts with--baseline. - Migrating with an AI agent? Install the migration skill.
Setup
sh
npm install -D @evobug_com/safe-ts-transform @evobug_com/oxlint-plugin-safe-ts oxlint
npm install @evobug_com/safe-ts-stdNode needs the loader
q(...), parseJson<T>(...) and the prelude are rewritten at build time. Code that skips the rewrite fails when it gets there: q() throws "q() was not compiled". The bundler plugin rewrites an app; for code Node runs directly, start Node with --import @evobug_com/safe-ts-transform/register. See Running TypeScript in Node. For Bun, see Bun. match, is and variant imported by name need no rewrite: they run anywhere.
- tsconfig: turn on
strict,noUncheckedIndexedAccessandexactOptionalPropertyTypes. Each keeps something true that a rule counts on, andsafe-ts checkwarns when the tsconfig that applies leaves one off (the table); the rules about absence, for one, assumeitems[i]is typedT | undefined(why). And load@evobug_com/safe-ts-std/strict-libintypes: TypeScript's own declarations hand outany(JSON.parse,response.json(),Array.isArray,new Map(), a promise's rejection reason), which switches the type checks off for that value; strict-lib makes themunknown, sotscrefusesJSON.parse(text).nameuntil the value is checked (no-hidden-any).safe-ts checkwarns when the tsconfig doesn't load it. Atypeslist replaces TypeScript's default of every@typespackage: list the ones you use ("node"), and the prelude if you use it.
jsonc
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
// and the @types packages you use: "node", ...
"types": ["@evobug_com/safe-ts-std/strict-lib"]
}
}The tsconfig flags SAFE-TS relies on
safe-ts check reads the tsconfig that applies to each entry (the nearest one, through extends; for a solution file, "files": [] with references, one of its projects having the flag is enough) and warns, once per flag, when it leaves one of these off. Each program below is accepted by tsc with the flag off, safe-ts check --idiomatic reports nothing in it, and it fails at run time (or computes the wrong thing); tsc refuses it once the flag is on (crates/safe_ts_core/tests/tsconfig_flags.rs checks each, with the TypeScript the repository installs).
| Flag | Without it | tsc then accepts |
|---|---|---|
strictNullChecks | undefined and null leave every type: Option<T> is T, items[i] is always there, and no absence check is asked for | function size(o: Option<string>): number { return o.length; } |
noImplicitAny | a parameter written without a type is any, and so is everything read through it | function first(x): number { return x.a.b; } |
strictFunctionTypes | a function type's parameters are compared in both directions; no-method-signature's rewrite exists to get this check, and checks nothing without it | const h: (x: string | number) => number = (x: string) => x.length; |
strictBindCallApply | f.call(t, ...), .apply and .bind take any arguments, and the checker reads f.call(t, x) as f(x) | fixed.call(undefined, "x") for fixed(n: number) |
strictPropertyInitialization | a class field typed as always there is undefined until something assigns it | class Box { name: string; }, then new Box().name.length |
noImplicitThis | this in a function that doesn't declare it is any | function read(): number { return this.value.deep; } |
useUnknownInCatchVariables | the value a catch gets is any | catch (e) { return e.message.trim(); } |
strictBuiltinIteratorReturn | iterator.next().value is any, where a finished iterator gives undefined | new Map<string, number>().keys().next().value.toUpperCase() |
exactOptionalPropertyTypes | an optional property accepts undefined written out, so { ...defaults, ...changes } is typed with every default there while a key: undefined in changes erases it | merge({ theme: undefined }).theme.length for merge(changes: Partial<Settings>): Settings |
strict turns on every one of the first eight. A tsconfig without strict (with TypeScript 5, where it is off unless set; 6 and later turn it on) gets one warning naming the members it leaves off, and a member set to false on its own gets its own. noUncheckedIndexedAccess and strict-lib have their warnings too (above).
Not warned about, and why:
skipLibCheck: with it on, a type that a package's declarations import from a package that isn't installed isany, and nothing says so (import { load } from "lib"; load().size.deepcompiles whenlib's declarations name a type from a package missing from the install). It is a hole, but warning on it would cost more than it finds: nearly every scaffold sets it, and turning it off under the flags above reports errors in third-party declarations a project can't fix. Runtscwith"skipLibCheck": falseonce after adding a package, and look at anyCannot find moduleit reports innode_modules.noImplicitOverride: no rule finds an override by itsoverridekeyword.override-parameterandfailure-contractcompare a method with the one of the same name in the class it extends, keyword or not.noFallthroughCasesInSwitch: a case that runs into the next is the code's choice; TypeScript types it right, and no rule reads a case as ending where it doesn't.noPropertyAccessFromIndexSignature: withnoUncheckedIndexedAccess,record.keyisT | undefinedeither way; the flag only asks forrecord["key"], which the checker reads asrecord.key.alwaysStrict: every ES module is strict code already.verbatimModuleSyntax,erasableSyntaxOnly: they don't let a wrong value through; they keep a module from failing to load under Node's own type stripping, which fails loudly, at once, and never under Vite or Bun. Recommended for code Node runs itself (Running TypeScript in Node).On a new project that costs nothing. On an existing one, measure it first: each flag is a type-checker setting, so the errors come from
tsc(orvue-tsc), not from SAFE-TS. One Vue app of 113,000 lines withstrictalready on got 958 errors fromnoUncheckedIndexedAccessand 348 fromexactOptionalPropertyTypes. They cluster: most of the 958 were in three algorithmic modules (a diff walkthrough, a rebase resolver), and were fixed by hand there; no codemod does it. See the tsconfig flags for a route that doesn't stop the team.The
safe-tscommand (safe-ts check,explain,migrate,lsp): it comes with the packages above, in@evobug_com/safe-ts-native, and is on the PATH of package.json scripts,npxandbunx. pnpm links the commands of direct dependencies only: there, add it withpnpm add -D @evobug_com/safe-ts-native.safe-ts --versionprints the version, for bug reports and CI logs.
jsonc
// package.json
{ "scripts": { "check": "safe-ts check src/main.ts", "check:summary": "safe-ts check src/main.ts --summary" } }npx safe-ts check src/main.ts and bunx safe-ts check src/main.ts run the installed one. In a folder where it isn't installed they would download an unrelated npm package named safe-ts: there, name the package, npx -p @evobug_com/safe-ts-native safe-ts check ....
- Editor: the SAFE-TS language server shows problems as you type, in
.tsand.vuefiles, with quick fixes. It is thesafe-tscommand above (safe-ts lsp). For VS Code there is an extension: Editor. - CI checks: extend the recommended oxlint config. The oxlint language server can also show the problems in the editor. In
.vuefiles oxlint hands the plugin one script block at a time; the plugin checks the whole component (template included) from the file on disk (Vue setup).
jsonc
// .oxlintrc.json
{ "extends": ["./node_modules/@evobug_com/oxlint-plugin-safe-ts/recommended.json"] }It turns on every safe-ts/* rule, plus oxlint's own rules that the v8.dev review pointed at: precision loss in number literals (no-loss-of-precision), Object.hasOwn over hasOwnProperty (prefer-object-has-own), holes in array literals (no-sparse-arrays), keeping the caught error as cause (preserve-caught-error), eval and friends, and suggestions such as .at(-1), replaceAll and flatMap. Rules that would fight the build-time transforms (for example unicorn/no-array-for-each, while forEach is turned into a loop) are left out, and so is unicorn/prefer-global-this: with both @types/web and @types/node loaded, its fix turns window.setTimeout(...) (a number) into globalThis.setTimeout(...) (Node's NodeJS.Timeout), so timer: number fields stop compiling. Rules that need type information (require-array-sort-compare, prefer-nullish-coalescing) only work in oxlint's --type-aware mode.
On an existing codebase, extending the preset changes more than SAFE-TS. Its 33 oxlint rules (listed below) are ordinary lint: // @safe-ts legacy silences only the safe-ts/* rules, so they report in legacy files too. One Vue app got 7 new errors and about 140 new warnings in files that were all marked legacy. Your own rules win over the preset's, so set the ones you aren't ready for to "warn" or "off" while files are legacy, and delete those lines once the code is fixed. Running oxlint once with the extends and once without shows what it adds.
The preset's oxlint rules
Errors: no-loss-of-precision, no-prototype-builtins, prefer-object-has-own, no-sparse-arrays, no-proto, no-extend-native, no-constructor-return, no-misleading-character-class, no-useless-backreference, preserve-caught-error, no-unsafe-finally, no-empty, guard-for-in, no-sequences, no-shadow-restricted-names, no-eval, no-new-func, no-implied-eval, unicorn/no-thenable, unicorn/no-invalid-remove-event-listener, oxc/bad-replace-all-arg, typescript/no-dynamic-delete.
Warnings: prefer-rest-params, prefer-spread, prefer-object-spread, prefer-exponentiation-operator, unicorn/prefer-at, unicorn/prefer-string-replace-all, unicorn/prefer-string-trim-start-end, unicorn/prefer-includes, unicorn/prefer-array-flat-map, unicorn/prefer-array-find, unicorn/no-new-array.
unicorn/numeric-separators-style is not in it: it only changes how a number is written, and its fix breaks a program that reads the number's text, such as a server config reading a port from a .ts file with a regular expression (below). Nor are oxlint's promise/* rules: if oxlint --deny-warnings asks for a return at the end of a .then((x) => { ... }) callback (promise/always-return), that rule comes from your own config.
- Build: add the bundler plugin, which rewrites
q(...),match(...),parseJson<T>(...)and prelude names at build time:
ts
// vite.config.ts
import { safeTs } from "@evobug_com/safe-ts-transform";
import { defineConfig } from "vite";
export default defineConfig({ plugins: [safeTs()] });The plugin also runs the SAFE-TS rules on every file it transforms, so problems show up in the dev server too: safeTs({ check: "warn" }) (the default) prints them in the terminal, "error" shows Vite's error overlay in the browser and fails the build when a finding is an error (warnings are printed, rule levels), false turns it off. It resolves imports with tsconfig.json paths and the string aliases of Vite's resolve.alias, and warns once per import and file about one it can't follow (How imports are followed). vite build ends with one line saying what the plugin saw:
text
safe-ts: 1,293 files checked, 960 legacy, 0 problems(The dev server transforms files as the browser asks for them, so it has no end to report at.) Files the plugin should leave alone entirely, such as vendored or generated code, go in exclude: globs relative to Vite's root, regular expressions tested on the absolute path, or a function of the path:
ts
safeTs({ exclude: ["src/vendor/**", "**/*.generated.ts", (file) => file.includes("/third-party/")] });An excluded file is neither checked nor transformed, so it must not use q, match, parseJson or prelude names. For your own code that isn't migrated yet, use the legacy marker instead.
In the dev server (and the Node loader) the transform also adds dev checks: runtime checks for a few things the rules can't see, such as q(...) given a Promise. vite build leaves them out; safeTs({ devChecks: false }) turns them off in development too.
Each named type's JSON validator is generated once, in a module every file using it imports (One validator per type). safeTs({ sharedValidators: false }) gives every file its own copies instead.
- Faster startup in Chrome (opt-in):
safeTs({ compileHints: true })adds//# allFunctionsCalledOnLoadto entry chunks, so Chrome 136+ compiles their functions in the background while loading, instead of on first call. V8 measured 630 ms less main-thread parse and compile time on average across 20 sites (v8.dev). It also compiles functions that never run, which costs memory: use it for chunks whose code runs at startup, or pass chunk names (compileHints: ["main"]). The plugin checks the finished chunks too, so the comment survives a minifier that drops comments after the plugins ran (Rolldown's, in Vite 8). - Large data in code (opt-in):
/** @json */on a module-levelconstholding plain data (a table, translations, a config) turns its literal intoJSON.parse("..."), which loads faster: 2.6x for 180 kB, measured on Node 26 with a cold start each time. JSON is a simpler grammar to parse (v8.dev). Only data JSON keeps exactly qualifies; anything else is reported byjson-literal. - Node without a bundler (servers, workers, scripts, tests):
node --import @evobug_com/safe-ts-transform/register main.ts, on every command. See Running TypeScript in Node. - Bun (
bun run,bun test,bun build): preload@evobug_com/safe-ts-transform/buninbunfig.toml, and bundle withBun.build({ plugins: [safeTsBun()] }). See Bun. - A project inside the project (a folder with its own
package.jsonandtsconfig.json, such as a CLI next to the app) needs the setup too:@evobug_com/safe-ts-stdin its own package.json, and"@evobug_com/safe-ts-prelude"in its own tsconfig.json'stypes. The transform reads the nearest tsconfig.json, not the one it extends, so without that entry prelude names get no imports there (details). - Checking the whole program (CI):
safe-ts check src/main.tsfollows every import from the entry (relative paths, tsconfig.jsonpathsaliases and workspace packages; see How imports are followed), workers started withnew Worker(new URL("./worker.ts", import.meta.url)), and modules loaded withimport(): lazy routes (component: () => import("./views/Home.vue")),defineAsyncComponent, code loaded on demand.import(`./locales/${lang}.ts`)andimport.meta.glob("./widgets/*.ts")bring in every file they can match, by Vite's rules (each${...}stands for one path segment). Calls into a loaded module are followed:m.f()afterconst m = await import("./x"), a destructuredf(), andimport("./x").then((m) => m.f()). In a monorepo, give every app's entry in one run:safe-ts check apps/web/src/main.ts apps/server/src/main.ts. A package several apps use is then checked, and its problems reported, once. A file nothing imports or loads with its path written out (a worker or module whose path is built at runtime, a script, a file nothing uses yet) is checked only when it is an entry too, so a directory is an entry for each of its source files:safe-ts check srcchecks every.ts,.tsx,.mts,.ctsand.vuefile undersrc(not.d.tsfiles,node_modulesor hidden directories) as one program, and files and directories mix (safe-ts check src scripts/seed.ts). Symlinked directories are followed, and each file is checked once, also when a link leads back up or two paths lead to it (asfixandmigratetake directories too). With file entries,checklooks through each entry's directory for source files the run didn't reach, and names them (the first ten, then how many more):
text
warning: 1 source file under the entries' directories is not checked: nothing the entries import reaches it: src/orphan.ts. Pass the directory to check every file in it (`safe-ts check src`), or add the file as an entryBuild output (dist, build, out, coverage, target), a directory with its own package.json (another package, checked from its own entries), tool configs (vite.config.ts, vitest.config.ts: the tool loads them) and the validator modules safe-ts emit writes (*.safe-ts-json.ts) don't count. --json prints the problems as JSON (below). --summary counts them by rule and by directory instead of listing each one, which is the table to start a migration from. It exits with 1 when there are errors; warnings are printed and counted, and fail the run only with --deny-warnings or --max-warnings <n> (rule levels). An import that resolves to nothing (below) and a source file the run didn't reach count as warnings there: both are code that wasn't checked, and the status line says ⚠ 1 unresolved import or ⚠ 2 files not checked instead of ✓ no problems. --idiomatic also reports the idiomatic rules, for one run. --write-baseline <file> and --baseline <file> hold the escape hatches down (a ratchet).
- Which rewrites happened:
safe-ts explain src/orders.tslists every place a build-time rewrite could apply (q,match, loops, enum constructors,@inline,@loop), whether it did, and why not when it didn't, e.g. "a callback before the last step has side effects". Rewrites that don't apply leave correct, slower code, so nothing else would tell you. - Type-checking the rewritten code:
safe-ts emit <out-dir> <entry.ts>...writes the program the entries reach, rewritten, in the project's layout under<out-dir>: what they import, workers started withnew Worker(new URL(...))and modules loaded withimport(), ascheckfollows them. Then run tsc on it, withallowImportingTsExtensions(see the next point). This catches, for example, aq(...)that propagates an error type the function doesn't declare. - Running without the loader (a production build step): the emitted program runs with plain
node out/apps/server/src/main.ts, orbun out/apps/server/src/main.ts(Bun). An import of a package that resolves to your own source (a workspace package, linked intonode_modules) is pointed at its emitted copy:from "@acme/pricing"becomesfrom "../../../packages/pricing/src/index.ts". Otherwise the package name would load the source without the rewrites. Packages installed innode_moduleskeep their names. Relative imports stay as written, so for Node they need their extension (./config.ts); the loader adds a missing one, plain Node doesn't. Imports in.vuefiles aren't changed.
How imports are followed
safe-ts check, the editor, the oxlint plugin, the Vite plugin and the Node loader resolve an import the same way, so they agree on what it means. It is resolved as a bundler does with "moduleResolution": "Bundler":
- Relative paths, with the extension or
/index.tsleft out, and./x.jsfor./x.ts. compilerOptions.pathsandbaseUrlof the tsconfig.json that includes the importing file:"@utils/*": ["./src/utils/*"], exact keys ("config": ["./src/config.ts"]), and several targets, tried in order. Also when they come throughextends(a file or a package, such as@vue/tsconfig), and from thereferencesof a solution tsconfig.json, as in Vite's scaffold. A.vuefile gets thepathsof the tsconfig.json that includes the.tsfiles next to it.- Workspace packages linked into
node_modules, whose source is in the project.
Vite's resolve.alias is read by the Vite plugin only: it hands the aliases with a string find to its checks and to the transform. safe-ts check, the editor and the oxlint plugin don't load the Vite config, so tsconfig.json paths is the source of truth: write every alias there too (TypeScript needs it there anyway), and a regular-expression alias as the paths patterns it stands for.
An import that resolves to nothing isn't followed, so what it would bring in goes unchecked. safe-ts check names each one, once per specifier, with the files importing it:
text
warning: could not resolve "@utils/b" from src/a.ts: the checker doesn't follow it (for an alias, check tsconfig.json `paths`)Each one counts as a warning: the run ends ⚠ 1 unresolved import, not ✓ no problems, and fails with --deny-warnings (--json --summary has the count, unresolvedImports).
The editor underlines the specifier, the oxlint plugin and the Vite plugin print the same line once per import and file. Packages aren't named: an installed one (also one with only types, or with no JavaScript for this import), a Node or Bun built-in, virtual: and other scheme: imports, or any bare name before dependencies are installed. Nor are stylesheets, images and data (/vite.svg from Vite's public directory, ./logo.svg?raw), which the checker doesn't follow anyway. A bare name that no installed package provides is named: usually an alias Vite knows and tsconfig.json doesn't.
Library code is what is under a node_modules directory below the project root: the directory safe-ts check runs in, the Vite root, the directory oxlint runs in. It isn't checked, and its types can't be validated (json-type). A project that itself lives under some node_modules (a copy in node_modules/.cache) is checked as a project when you run in it.
Running TypeScript in Node
Node strips the types from a .ts file, but doesn't rewrite q(...), parseJson<T>(...), validate<T>(...), arbitrary<T>() or prelude names. The loader does:
sh
node --import @evobug_com/safe-ts-transform/register src/main.tsNode strips the types itself, so for code it runs, turn on verbatimModuleSyntax and erasableSyntaxOnly in that code's tsconfig: without them, tsc accepts a type imported without type (import { Point } from "./types.ts", which then fails to load: does not provide an export named 'Point') and syntax Node can't strip (a constructor's parameter properties, enum, a namespace holding values), which fails to load too. Loud and at once, so safe-ts check doesn't warn about them; a project Vite or Bun builds never meets it.
Every process that runs your TypeScript needs it, and a missing one shows only at runtime, where the first q(...) throws. What Node can't resolve, the loader resolves the way safe-ts check does (How imports are followed): tsconfig.json paths aliases (@utils/router), baseUrl, and an import without its extension or /index.ts. So a test imports the same files the check followed, and a validator finds a type imported through an alias. Checked on Node 26.13:
Entry points and scripts. Each
nodecommand: thescriptsin package.json, a Dockerfile'sCMD, a systemd unit.--importgoes before the file.safe-ts checkwarns about scripts in the package.json nearest each entry that run a.tsfile with plainnode, when the program uses something the loader rewrites:textwarning: package.json: script `start` runs `node src/main.ts` without the safe-ts transform, but this program uses `q(...)`, ...It looks only at commands that start with
nodeitself;tsx,nodemonand shell scripts aren't read. Nor are the commands written for people: a script's header comment (// Run: node scripts/import-products.ts), a README, a runbook. A script that uses what the loader rewrites (q(...),parseJson<T>, prelude names such asunsafe) needs--importin those too, so update them when you migrate the script.worker_threadsworkers. AWorkerinherits its parent'sexecArgv,--importincluded, so a worker started from a process that has the loader has it too. PassingexecArgvto theWorkerreplaces the inherited one: put the--importin it. The loader imported from code (import "@evobug_com/safe-ts-transform/register"in the entry file, rather than--import) applies to that thread only, and workers don't get it.Child processes.
child_process.forkinheritsexecArgvthe same way.spawn("node", ...)doesn't: give it the--importtoo.Tests.
node --import @evobug_com/safe-ts-transform/register --test "test/*.test.ts": the test runner passes--importon to the process that runs each test file. Vitest uses the Vite plugin from your config instead.Everything at once.
NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register"reaches every Node process started with that environment, workers with their ownexecArgvincluded.
The loader keeps what it rewrote in a cache on disk, so a restart, a worker or a test process doesn't rewrite the same file again. An entry is used while the file, every file the rewrite read for it (the types behind parseJson<T>, @inline functions, enum tables, the tsconfig), the options (dev checks) and the transform itself are unchanged. It lives in node_modules/.cache/safe-ts of the nearest directory above the current one that has a node_modules, or in the system's temporary directory when that isn't writable.
SAFE_TS_CACHE=0turns it off;SAFE_TS_CACHE_DIR=<dir>puts it somewhere else.- Entries are written to a temporary file and renamed into place, so threads and processes starting at once share it safely.
- Each file has one entry per set of options; a new version of the file replaces it, so the cache doesn't grow as you edit. Writing an entry keeps the file's three newest (entries made by an older transform, or with options no longer used, go), and about once a day a write also drops the entries of files that no longer exist. Deleting the directory is always safe:
rm -rf node_modules/.cache/safe-ts. - A shared validator module (
types.ts?safe-ts-json=v$User) has an entry of its own, used whiletypes.tsand the other declarations it was built from are unchanged. - The checker keeps what automatic mode found in each library in the same directory (
<package>@<version>....json, in thenode_modulesthe package is installed in), and honours the same two variables.
Resolve hooks of your own. The loader already resolves an extensionless relative import (./config) to ./config.ts, as bundlers do, so code written for Vite needs no hook for that. A hook you register yourself (module.registerHooks) also sees the shared validator modules a rewritten file imports, ./types.ts?safe-ts-json=v$User. Keep the query as it is: a hook that appends .ts to every relative specifier turns it into ...?safe-ts-json=v$User.ts, and the load fails ("no type User.ts is declared", or ENOENT). Add the extension before the ?, or pass on a specifier with a query unchanged:
js
// hooks.mjs: node --import @evobug_com/safe-ts-transform/register --import ./hooks.mjs ...
import { registerHooks } from "node:module";
registerHooks({
resolve(specifier, context, nextResolve) {
const [path, query = ""] = specifier.split(/(?=\?)/);
if (/^\.\.?\//.test(path) && !/\.[cm]?[jt]sx?$/.test(path)) {
return nextResolve(`${path}.ts${query}`, context);
}
return nextResolve(specifier, context);
},
});SAFE_TS_SHARED_VALIDATORS=0 also avoids it, at the cost of a validator copy in every file.
Generic arrows in .mts files. const first = <T>(items: T[]) => items[0] is a parse-error in a .mts or .cts file under the loader, because TypeScript reserves that syntax there. Node's own type stripping runs it, so a test file that worked before the loader was added stops at it. Write <T,>(items: T[]) => ...; the message says so.
A file that uses prelude names (q, unsafe, err, ...) where no tsconfig.json above it turns the prelude on runs without those imports, and fails with ReferenceError: q is not defined. The loader warns first, naming the file and the names: typically a script copied out of the project (to /tmp, with a node_modules link), which leaves its tsconfig.json behind. Keep it inside the project, or import the names from @evobug_com/safe-ts-std.
The loader costs memory in every thread that has it: about 10 MB for the transform and its native addon, before any file is loaded (Node 26, Linux). A server with several workers pays it once per worker. Two ways to avoid it in production: run the program safe-ts emit wrote, without the loader, or start workers that only run plain JavaScript with execArgv: [], so they don't inherit --import.
The Vite config
Vite loads vite.config.ts, and every file it imports, before any plugin runs, so safeTs() doesn't rewrite them. Code there that needs the rewrite fails as soon as it runs: a prelude name throws ReferenceError: PropagateError is not defined, and q(...) throws "q() was not compiled". Tests of the same code pass, because their process has the loader. Three setups work (checked with Vite 8.3):
Load what needs the rewrite with
loadTransformed. It registers the loader's hooks in Vite's process and imports the module through them, so it and everything it imports are rewritten. You get the module's exports, plugins and functions included, with any config loader:ts// vite.config.ts import { loadTransformed, safeTs } from "@evobug_com/safe-ts-transform"; import { defineConfig } from "vite"; const { offlinePage } = await loadTransformed<typeof import("./scripts/offline-page.ts")>( new URL("./scripts/offline-page.ts", import.meta.url), ); export default defineConfig({ plugins: [safeTs(), offlinePage()] });Only what goes through
loadTransformed(or a laterimport()) is rewritten: a module the config also imports the usual way is loaded first, without the hooks, and stays as it was.import typeof the same module is fine.Load the config through the loader. Vite's default config loader bundles the config with its imports, which bypasses Node's module hooks. With
--configLoader native, Node loads it, and the loader rewrites it:shNODE_OPTIONS="--import @evobug_com/safe-ts-transform/register" vite build --configLoader nativeKeep the config's imports free of what needs the rewrite. Import std names explicitly (
import { PropagateError } from "@evobug_com/safe-ts-std/result") instead of using the prelude, and don't useq(...),parseJson<T>orvalidate<T>in files the config imports.
import "@evobug_com/safe-ts-transform/register" as the config's first line is not enough on its own: Node loads every file the config imports before running any of them, so the loader is registered too late for them. It does apply to modules the config loads later with await import("./dev/api.ts") (with the default and the native config loader).
In such a file, needs-transform reports each q(...), parseJson<T> and prelude name used without its import, with the plain form as a quick fix (const x = make(); if (isErr(x)) return x;, or the import). It looks for vite.config.*, vitest.config.* and vitest.workspace.* in the file's folder and the folders above it, and follows what they import. There, the other rules' quick fixes don't write q(...) and import the std names they add.
safe-ts check warns about it: when the folder of an entry's nearest package.json has a vite.config.* that imports, directly or not, a file needing the rewrite (unless the package.json passes --configLoader native). safeTs() prints the same warning when Vite starts with such a config, naming the files. Only code that runs when the config loads counts: imports of types (import type, or names used only as types), prelude types such as Option<T>, and import() or loadTransformed(...) in the config are left out. When the config imports the register hooks, the warning says why they don't cover its own imports.
JSON output
safe-ts check --json prints the problems as one JSON array on stdout, and nothing else (the propagation map and the summary are left out). What the run couldn't see goes to stderr, so it stays in a CI log: the warnings (unresolved imports, config problems), the source files not checked, and what package.json weakens below the defaults. With --summary it prints one object instead: the checker's version, files, lines, problems (of them errors and warnings), legacyFiles, rules (the count of each rule), directories (for each directory: problems, and rules as before), escapeHatches (each count of the escape-hatch line), weakened (each rule or setting package.json sets below the defaults: the package.json, the setting (a rule's name, or infer, infer.exclude, testRunners, vue.sanitizers, vue.ssr), its value and, for an "overrides" entry, its files), configs (per package.json, what a baseline compares with its earlier state), setupWarnings (the warning: lines about the setup), unresolvedImports and unreachedFiles (every source file not checked).
jsonc
{ "version": "0.6.0", "files": 1293, "lines": 113000, "problems": 5484, "errors": 5400, "warnings": 84,
"legacyFiles": 0,
"rules": { "no-null": 421, "unhandled-failure": 163 },
"directories": { "src/stores": { "problems": 58, "rules": { "no-null": 40, "unhandled-failure": 18 } } },
"escapeHatches": { "unsafeBlocks": 12, "panicCalls": 0, "trustCalls": 3, "legacyNulls": 0, "cacheMarks": 1,
"safeTsIgnores": 2, "legacyFiles": 0, "stdFiles": 1, "tsIgnores": 0, "tsExpectErrors": 1,
"testExpectErrors": 14, "tsNochecks": 0, "vueSkips": 0, "lintSuppressions": 2, "skippedTests": 4,
"ambientDeclarations": 3, "sanitizers": 1 },
"weakened": [{ "config": "package.json", "setting": "no-mutable-global", "value": "off", "files": ["src/stores/**"] }],
"configs": { "package.json": { "idiomatic": true, "features": ["@evobug_com/safe-ts-feature-browser"],
"emitters": [], "requestFunctions": ["api"], "vueSsr": false } },
"setupWarnings": 0,
"unresolvedImports": 0,
"unreachedFiles": ["src/legacy/old-report.ts"] }Each problem in the array has:
| Field | |
|---|---|
file | the file, relative to the current directory |
rule | the rule, without the safe-ts/ prefix: unhandled-failure |
severity | "error" or "warning": the rule's level for this file |
message, help | the text check prints; help may be null |
line, column, endLine, endColumn | where it is: 1-based, columns counted in UTF-16 code units, as editors count them |
path | the functions the failure passes through, from the called one to the one it starts in: ["readConfig"]. [] when the call itself fails |
origin | where the failure starts: "JSON.parse() at src/config.ts:10:10". Findings with the same origin have one root cause |
paths | one { "path", "origin", "kind" } per error that can get out, kind being the PropagateError class (null for unhandled-failure). path and origin above are the first one |
unhandled-failure, uncaught-propagation and floating-rejection fill in path, origin and paths when they report a failure they traced. Other findings have null, null and [].
json
[
{
"file": "src/main.ts",
"rule": "unhandled-failure",
"severity": "error",
"message": "`readConfig` can throw, but the failure is not handled",
"help": "Failure path: readConfig → JSON.parse() at src/config.ts:10:10. Wrap it: `unsafe(() => ...)` returns a Result",
"line": 7,
"column": 42,
"endLine": 7,
"endColumn": 57,
"path": ["readConfig"],
"origin": "JSON.parse() at src/config.ts:10:10",
"paths": [{ "path": ["readConfig"], "origin": "JSON.parse() at src/config.ts:10:10", "kind": null }]
}
]Checker.checkFile in @evobug_com/safe-ts-native (one file, as the editor checks it) gives its diagnostics severity, path and origin too, but not paths.
The prelude: no imports
Install it (npm install -D @evobug_com/safe-ts-prelude), add "@evobug_com/safe-ts-prelude" to compilerOptions.types, and use Result, Option, q, match, Enum, parseJson, PropagateError, ... without importing them. The transform adds the imports a file needs at build time; nothing is put on globalThis.
jsonc
// tsconfig.json
{ "compilerOptions": { "types": ["@evobug_com/safe-ts-prelude", "@evobug_com/safe-ts-std/strict-lib"] } }The prelude doesn't load strict-lib itself: keep both in the list (Setup).
A tsconfig that sets typeRoots makes TypeScript look up types entries in those folders only, so the line above fails with TS2688: Cannot find type definition file for '@evobug_com/safe-ts-prelude'. Add "node_modules" to typeRoots:
jsonc
// tsconfig.json
{
"compilerOptions": {
"typeRoots": ["node_modules/@types", "node_modules", "src/types"],
"types": ["node", "@evobug_com/safe-ts-prelude"]
}
}A local with a prelude name wins in its own scope only, so a helper q in one function and the prelude's q in another both work; prelude-shadow reports a local named unsafe, and one named q, match, is, err or Result in a file that uses the prelude's too. In a function Playwright runs in the page (page.evaluate(fn)), the module's imports don't exist: prelude-in-page reports prelude values there.
Existing code: start strict, mark legacy
Turning the rules on for a large codebase at once produces thousands of errors. Instead:
New code is strict from day one.
Old code gets a marker in its first lines:
ts// @safe-ts legacyIn a
.vuefile, put it on the first line inside either<script>block, or as an HTML comment at the top of the file. Either marks the whole component, template included:vue<!-- @safe-ts legacy --> <script setup lang="ts"> // ...or here: // @safe-ts legacy </script>A marker anywhere else in a component marks nothing, and is reported (
vue-sfc).The file must also be listed in the package.json, under
"legacyFiles"(patterns relative to it, as in"overrides"):json{ "safe-ts": { "legacyFiles": ["src/old/**", "src/forms.vue"] } }A marker in a file the list doesn't name is reported (
unlisted-marker) and the file is checked as if it weren't there: anyone can write a comment, and the list puts the decision in package.json, where it is reviewed.safe-ts checkprints the"legacyFiles"and"trustedFiles"lines that list every marked file it found, for a project upgrading in one step.// @safe-ts stdworks the same way, with"trustedFiles".The rules are not reported inside that file, but strict code calling into it still is: if a legacy function can throw, the strict caller gets
unhandled-failurewith the full failure path through the legacy code. Legacy code is quarantined, not ignored. This holds for every import the checker follows: a relative path, a tsconfig.jsonpathsalias (import { f } from "@utils/leg"), a workspace package. An import it can't follow is named in acould not resolvewarning (How imports are followed): behind it, the quarantine doesn't reach, so fix those first.The bundler plugin and the Node loader give a legacy file only the rewrites it needs to run: prelude imports (a legacy file using
unsafeorisErrwithout importing them still works),q(...),match(...)andparseJson<T>/validate<T>. The rewrites that only make code faster (loops,@inline,@json,@loop, enum constructors) and the dev checks are left out, so adopting SAFE-TS doesn't change the code you ship until a file is migrated.safe-ts explainlists them as "not applied, the file is marked legacy".Migrate file by file. Remove the marker, apply the quick fixes, commit.
safe-ts checkprints how many legacy files and escape hatches are left: your progress report (below). For the changes that repeat across a codebase, use a codemod. One line in a migrated file that must stay as it is takes an ignore comment, not a marker.
Where to start. One throw in a small helper (a byId(id) that throws when the element is missing) is reported at every caller that doesn't handle it, and their callers. When findings share an origin, safe-ts check ends with a summary:
text
Root causes: 312 unhandled-failure findings come from 9 places
187 throw at src/dom.ts:12:5
64 JSON.parse() at src/storage.ts:30:18
...Fixing the helper (returning a Result, or handling the failure inside it) clears all of its findings at once.
Markers are a staging device, with a burn-down. Mark every file that fails on day one (a short script does it), so CI is green from the start, and from then on only remove markers. The legacy count in the escape-hatches line (below) is the burn-down: record it per week or per release, and treat a file that gains a marker as a review question, like a new unsafe(...). Don't keep legacy files away from the transform (with exclude, or a wrapper around the plugin): it gives them the prelude imports, so prelude names (unsafe, isErr) work in them. Without it, a legacy file using one fails with ReferenceError: unsafe is not defined in the browser, and neither tsc nor the checker says so.
Run the app in a browser, and compare. tsc, the checker and unit tests all passed while a migration broke two things that only a browser showed: a startup check that validated data another module decorates with functions as it loads, and a legacy file using a prelude name the build didn't rewrite. A smoke run of every page, with the browser console watched for errors and Vue warnings, is a gate no tool replaces. It is worth more as a comparison: build the baseline and the branch, run both against one database with outside services blocked, and compare what they render and the bodies of the requests they send (a null that became a missing key shows up there, on the wire). One team compared 490 formatted dates, 44 screenshots and 16 write requests that way; cheap once the harness existed, it caught more than any rule.
With an agent. The migration skill has an agent plan the target architecture first, take a census of what the checker reports (with the idiomatic rules) and of the hand-rolled patterns it doesn't (loading flags, sentinels, string if-chains, casts), and migrate area by area behind gates that let those counts only fall. An agent told to make the checker pass stops at the first run that exits 0, and a run with only warnings does: give it safe-ts check ... --deny-warnings as the gate.
Rule levels: errors, warnings, off
Each rule is an error, a warning or off. The defaults are the oxlint preset's (recommended.json): the rules that protect data and control flow are errors; the ones about cost and style (stable-shape, hoist-intl, vue-render-cost, prefer-nullish-default, ...) are warnings. safe-ts check prints error[rule] or warning[rule] and exits with 1 only when there is an error. To fail on warnings too, add --deny-warnings, or --max-warnings 20 to allow up to 20. Those count every warning the run prints: a rule's, each warning: line about the setup (the tsconfig doesn't load strict-lib or leaves off one of the flags SAFE-TS relies on, a feature pack is enabled but not installed, a package.json script or the Vite config runs code without the transform; the status line says ⚠ 1 setup warning), an unresolved import, and a file not checked.
Change a rule's level in package.json, for the whole package or for some files:
jsonc
// package.json
"safe-ts": {
"rules": { "stable-shape": "error", "no-mutable-global": "warn" },
"overrides": [
{ "files": ["src/stores/**"], "rules": { "no-mutable-global": "off" } },
{ "files": ["src/generated/**"], "rules": { "no-null": "off", "no-any": "warn" } }
]
}- A level is
"off","warn"or"error". A rule name may have thesafe-ts/prefix. filesare patterns relative to the package.json:*within one directory,**any number of them,{ts,vue}either. A pattern without a/matches the file name in any directory:"*.d.ts".- For each file the last word wins: the default, then
"rules", then each entry of"overrides"that matches, in order. - A name, a level or an entry
checkdoesn't understand is reported as awarning:line at the top of the run, and left out. - A rule set below the preset's level (
"off", or"warn"where the preset says"error") is an escape hatch too:safe-ts checknames each one under its escape-hatch line,weakened below the defaults: no-mutable-global warn, no-mutable-global off for src/stores/** (package.json),--json --summarylists them inweakened, and a baseline fails the run when one is added. Naming an idiomatic rule while the layer is off only turns it on.
The setting is read wherever the rules run: safe-ts check, the editor (warnings are shown as warnings), the Vite plugin (with check: "error", only errors stop the build), --json and the Node addon (severity on each finding). In oxlint, "off" in package.json wins: the finding isn't produced, so no oxlint setting brings it back. The level of what is produced is oxlint's: the preset's, or what your .oxlintrc.json sets ("safe-ts/stable-shape": "error", its own overrides for paths). A plugin can't pick the level of its reports, so for oxlint set "warn" and "error" in .oxlintrc.json, and "off" in either place.
Declaration files. In .d.ts files (.d.mts, .d.cts), no-null, prefer-option, no-mutable-global, no-method-signature and no-optional-field are off. A declaration describes values something else makes, such as types generated from a backend or the shape of a library: its null says what is there at run time, and the file can't change it. Where the values are made, the rules apply. The rules about types that hand callers something unchecked stay on: no-any, no-nested-option, no-unknown-in-result, no-ts-enum, and no-unchecked-declare, since nothing checks that a value a declaration file says exists (declare let current: User, export function load(): User) is there with that type (no-unchecked-declare). safe-ts check reads the project's declaration files under the entries' directories, and counts their declarations among the escape hatches. To check your own declarations for null too, turn it back on: { "files": ["src/**/*.d.ts"], "rules": { "no-null": "error" } }.
Ignoring one finding
When one line is right as it is, say so next to it:
✓ Accepted0 diagnostics
ts
// safe-ts-ignore no-null: the payment SDK tells "no locale" (null) from "the default" (undefined)
export const locale = null;- The comment silences the named rules on the next line. Name several with commas:
// safe-ts-ignore no-null, no-unchecked-cast: .... A few ignore comments in a row all cover the line after them. - The rule and the reason are required. A comment without them, with a rule that doesn't exist, or that silences nothing (the finding was fixed, or is on another line) is reported as
safe-ts-ignore, as TypeScript reports an unused@ts-expect-error. An ignore for a rule onlysafe-ts checkreports (such asno-optional-fieldorunused-code) is called unused bysafe-ts checkonly: the editor and the oxlint plugin don't see the whole program, so they can't tell. - In a Vue template, write it as an HTML comment before the element:
<!-- safe-ts-ignore vue-unsafe-url: the server checks every link it sends -->. It covers the element's start tag, attributes on later lines included. // safe-ts-ignore-file no-null: generated from the backend schemacovers the whole file. For a directory, set the rule"off"in"overrides".safe-ts checkcounts the comments in its escape-hatch line (below).
An ignore hides a finding; it doesn't change the code. A q(...) the transform can't rewrite still stops the build, ignored or not. Prefer // @safe-ts legacy for a file that isn't migrated yet, and an ignore for one line in a migrated file that the rule gets wrong or that must stay as it is. oxlint's own // oxlint-disable-next-line safe-ts/no-null works in oxlint only, says no reason and is reported (no-lint-suppression); safe-ts-ignore works everywhere and keeps a reason.
The tsconfig flags on an existing project
noUncheckedIndexedAccess, exactOptionalPropertyTypes and strict-lib are type-checker settings: the errors they bring come from tsc or vue-tsc, and can number in the hundreds (above). strict-lib's are where a value of JSON.parse, response.json() or Array.isArray was used unchecked (JSON.parse(raw).id, const user: User = JSON.parse(raw)): validate<T> or parseJson<T> fixes each in migrated code; a legacy file can keep its old behaviour by writing the any out (const data: any = JSON.parse(raw)), which no-any reports once the file is migrated. A route that keeps the build green:
- Measure. Add a
tsconfig.strict.jsonthatextendsyour tsconfig and turns the flags on (and adds strict-lib totypes), and count:npx vue-tsc -p tsconfig.strict.json --noEmit | grep -c "error TS"(ortsc). Sort the errors by folder; they tend to sit in a few modules. - Ratchet. Run the strict config in CI, and fail when its error count rises above the number committed next to it; lower the number as modules are fixed. New code then meets the flags from the first day, and old errors are fixed one module at a time.
- Move the flags into
tsconfig.jsonwhen the count is 0, and delete the second file.
Do the last step as early as you can, even before the other markers are gone, because other tools read tsconfig.json only:
exactOptionalPropertyTypeserrors come late, and in templates. In a migration wheretsconfig.jsonlacked the flag,safe-ts checkandvue-tscstayed clean for weeks, and the strict config listed 14 errors after the merge, all of one kind: an optional propx?: stringgiven astring | undefinedin a template. Builders working against the main tsconfig never saw them.- oxlint and SAFE-TS disagree about
items[i]!withoutnoUncheckedIndexedAccess. SAFE-TS treatsitems[i]as possibly missing whatever the flag says. oxlint's type-awaretypescript/no-unnecessary-type-assertionfollows the flag in the tsconfig it reads: without it,export const first = (items: string[]) => items[0]!is an error there ("unnecessary"), with it there is no finding. Until the flag is intsconfig.json, avoid!on an index: check the bound, or give a fallback with??.
Migrating with codemods
safe-ts migrate rewrites existing code for one rule at a time. It prints a diff and changes nothing until you add --write:
sh
safe-ts migrate throw-to-result src/ # show the diff and the report
safe-ts migrate throw-to-result src/ --write # change the files| Codemod | Rewrites | For the rule |
|---|---|---|
throw-to-result | functions that throw into functions returning Result | no-throw |
null-to-undefined | null and T | null into undefined and Option<T> | no-null |
ts-enum | TypeScript enum into a union of strings or a const object | no-ts-enum |
undefined-to-option | T | undefined into Option<T> | prefer-option |
union-to-enum <Type> | a union discriminated by type into an Enum, with its producers and consumers | Enums |
module-state | nothing: reports the module state each function uses, to plan a context parameter | no-mutable-global |
mut | a value passed to a Mut<T> parameter or prop into a loan, mut(value) (the upgrade to the nominal Mut<T>) | missing-mut |
- Only what it can do safely. Anything else is left as written and listed in the report, with the reason. The report goes to stderr, so
> changes.patchgives a patch forgit apply. - Edits are small. Only the rewritten code changes; comments and formatting around it stay. Legacy files are migrated too (the marker doesn't stop a codemod).
- The files you give are the whole program. Callers and uses in other files aren't seen, so give it the source folder, not one file. The report says when an exported function or enum changed. Vue components are part of the program: their scripts and templates are rewritten with the
.tsfiles they use (below). - Check afterwards. Run
tsc(vue-tscin a Vue project) andsafe-ts check, as for any change. The codemods are tested to produce code that compiles and passes the rule, but they can't see your whole build.
throw-to-result
A function whose throw the no-throw rule reports returns a Result instead. Callers that already return a Result get q(...).
❌ Before
✕ Rejectedno-throw
ts
import { type Result } from "@evobug_com/safe-ts-std/result";
export class NotFound extends Error {}
export class InvalidAge extends Error {}
const names = new Map([["1", "Ada"]]);
export function findName(id: string): string {
const name = names.get(id);
if (name === undefined) throw new NotFound(`no user ${id}`);
return name;
}
export function parseAge(input: string): number {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) throw new InvalidAge(`not an age: ${input}`);
return age;
}
export function profile(id: string, age: string): Result<string, NotFound | InvalidAge> {
const name = findName(id);
const years = parseAge(age);
return `${name}, ${years}`;
}✅ After safe-ts migrate throw-to-result --write
✓ Accepted0 diagnostics
ts
import { type Result, err, q } from "@evobug_com/safe-ts-std/result";
export class NotFound extends Error {}
export class InvalidAge extends Error {}
const names = new Map([["1", "Ada"]]);
export function findName(id: string): Result<string, NotFound> {
const name = names.get(id);
if (name === undefined) return err(new NotFound(`no user ${id}`));
return name;
}
export function parseAge(input: string): Result<number, InvalidAge> {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) return err(new InvalidAge(`not an age: ${input}`));
return age;
}
export function profile(id: string, age: string): Result<string, NotFound | InvalidAge> {
const name = q(findName(id));
const years = q(parseAge(age));
return `${name}, ${years}`;
}ts
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { type Result, err, q } from "@evobug_com/safe-ts-std/result";
export class NotFound extends Error {}
export class InvalidAge extends Error {}
const names = new Map([["1", "Ada"]]);
export function findName(id: string): Result<string, NotFound> {
const name = names.get(id);
if (name === undefined) return err(new NotFound(`no user ${id}`));
return name;
}
export function parseAge(input: string): Result<number, InvalidAge> {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) return err(new InvalidAge(`not an age: ${input}`));
return age;
}
export function profile(id: string, age: string): Result<string, NotFound | InvalidAge> {
const __q1 = findName(id); if (__q1 instanceof __qErr) return __q1; const name = __q1;
const __q2 = parseAge(age); if (__q2 instanceof __qErr) return __q2; const years = __q2;
return `${name}, ${years}`;
}The error type is the union of the thrown classes, plus what converted functions pass up through
q.throw new Error("text")andthrow "text"becomeerr("text")with astringerror, and anew Error(...)built from anything else stays anError. Give those a name afterwards, anEnumof the failures the callers handle (Give errors names). A method the class had (describe(),isRetryable()) becomes a method of the enum: declared in its type (Enum<V, { readonly describe: () => string }>), written on its table (constructors<LookupError>().impl({ describe: (error) => ... })), and still callederror.describe()(Methods on an enum). What the class kept in fields goes in the variant's data, a retry count included. A method the class namedtoStringorgettakes a name of its own (describe,valueOrDefault).Callers decide whether it happens. A function is converted only when every use of it can take a
Result: a caller that returns one (or is converted too), with the call whereq(...)fits (const x = f(),x = f(),f();,return f(), withawaitfor an async function). Any other use is listed under Needs a decision, and the function stays as it is, so the code still compiles:textNeeds a decision src/report.ts:14:10 `parsePort` would return a Result here, but `portOrDefault`, which calls it, doesn't return a Result src/ports.ts:8:20 `parsePort` would return a Result here, but it is used as a value here (passed, stored, re-exported or `typeof`), not calledMake those callers return a
Result(or handle the error), and run it again.Files a Vite config loads (what
vite.config.*orvitest.config.*imports) run without the transform (needs-transform), so the codemod doesn't writeq(...)there: a caller there getsconst x = f();andif (isErr(x)) return x;(a newresultbinding forf();), andreturn f()stays as it is. A call there in another shape (x = f(),const x: T = f(), a destructuring, an unbracedifbody) is listed under Needs a decision.Top-level functions. A
functiondeclaration, or aconstholding an arrow function or a function expression (export const load = async (id: string): Promise<User> => { ... }). Without a declared return type, a function that returns no value getsResult<void, E>(Promise<Result<void, E>>when async).Not converted: functions without a declared return type that return a value, or returning
unknown/any; throws inside the function's owntry(it catches them today), inside callbacks, methods and nested functions, or in a function held by alet(it can be given another one); throws of a value whose class it can't tell (throw wrap(error)); functions with overloads, default exports, and generators.PropagateErrorthrows are allowed and stay, and so is rethrowing the caught error unchanged (throw error).
null-to-undefined
null becomes undefined, T | null becomes Option<T>, and x === null becomes x === undefined. A parameter that defaults to null, near: T | null = null, becomes near?: Option<T> when every parameter after it may be left out too (otherwise near: Option<T> = undefined, which is the same).
❌ Before
✕ Rejectedno-null
ts
export type User = { readonly name: string; readonly email: string | null };
export function findUser(users: readonly User[], name: string): User | null {
return users.find((user) => user.name === name) ?? null;
}
export function contactLine(user: User): string {
return user.email === null ? user.name : `${user.name} <${user.email}>`;
}✅ After
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export type User = { readonly name: string; readonly email: Option<string> };
export function findUser(users: readonly User[], name: string): Option<User> {
return users.find((user) => user.name === name);
}
export function contactLine(user: User): string {
return user.email === undefined ? user.name : `${user.name} <${user.email}>`;
}null from outside is real, so it stays wherever it can appear, and the report says where:
- values from JSON (
JSON.parse,response.json()), DOM and Web APIs (querySelector,getItem,match,parentElement, ...) and packages, and the variables that hold them. A check likelocalStorage.getItem(key) !== nullstays as it is: as!== undefinedit would always be true. If a hand edit or a search-and-replace does that,no-undefined-check-for-nullreports it. The other way round, code merged later that still tests anOptionfornull(next === null,expect(x).not.toBeNull()) isno-null-check-for-undefined; - variables, parameters, properties and return types whose type mentions a type that isn't declared in your files (
HTMLElement, a package's types); - your types that describe such data (
JSON.parse(text) as UserkeepsnullinUser, and in the typesUseruses); nullpassed to code outside your files (Object.create(null)), or in a value that is (JSON.stringify(payload)would print the field differently).
text
Left as written
src/page.ts:3:20 `null` kept: compares `element`, which may be `null` from outside; `== undefined` matches bothWhat it can't see: null reaching a value through a path it doesn't follow, such as a library method with an unusual name, or a value passed through several functions first. A type-check catches most of these, since the converted types no longer accept null.
ts-enum
A string enum becomes a union of its values, and its uses become the strings:
❌ Before
✕ Rejectedno-ts-enum
ts
export enum Status {
Draft = "draft",
Published = "published",
}
export function isLive(status: Status): boolean {
return status === Status.Published;
}
export const fallback: Status = Status.Draft;✅ After
✓ Accepted0 diagnostics
ts
export type Status = "draft" | "published";
export function isLive(status: Status): boolean {
return status === "published";
}
export const fallback: Status = "draft";- A
constobject instead, with the same values, when the strings alone wouldn't do: the enum is used as an object (Object.values(Status)), a member sits where a bare string would be typedstring(an unannotated object literal), or the enum has numbers. That's the quick fix's form:Status.Draftkeeps working, andStatus.Draftas a type becomestypeof Status.Draft. - Not converted: members with computed values (
1 << 2),declare enum, an enum merged with a namespace, enums re-exported, default-exported or imported throughimport * as(their uses aren't followed), and numeric enums used as objects (Color[0]is"Red"only for a real enum). - A numeric enum's type accepts any
number; theconstobject's type doesn't. Iftsccomplains after the conversion, that code was passing numbers that aren't members.
undefined-to-option
T | undefined becomes Option<T>, in every position a type can be written, and the import is added where the file doesn't have one (none with the prelude). It applies prefer-option's quick fix everywhere at once, so run it after null-to-undefined, or on code where a bulk rewrite left T | undefined behind:
❌ Before
✕ Rejectedprefer-option
ts
export type Sale = { readonly startsAt: number; readonly coupon?: string | undefined };
export function discount(sale: Sale, t: number): { readonly percent: number } | undefined {
return t < sale.startsAt ? undefined : { percent: t - sale.startsAt };
}
export const prices: (number | undefined)[] = [];✅ After
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export type Sale = { readonly startsAt: number; readonly coupon?: Option<string> };
export function discount(sale: Sale, t: number): Option<{ readonly percent: number }> {
return t < sale.startsAt ? undefined : { percent: t - sale.startsAt };
}
export const prices: Option<number>[] = [];- The same type.
Option<T>isT | undefined, so nothing changes fortscor at runtime, and callers in other files don't need to change. - Not converted: unions with
null(that'snull-to-undefined), withvoid,any,unknownornever, and files that have their ownOptiontype (listed in the report).
union-to-enum
safe-ts migrate union-to-enum Upload src/ turns the union Upload, discriminated by a type field, into an Enum with constructors, and updates the values of that type in the given files:
❌ Before
✕ Rejected0 diagnostics
ts
export type Upload =
| { type: "queued"; file: string }
| { type: "sending" | "retrying"; file: string; sent: number }
| { type: "failed"; file: string; reason: string };
export function isFailed(upload: Upload): boolean {
return upload.type === "failed";
}
export function progress(upload: Upload): string {
switch (upload.type) {
case "queued":
return "waiting";
case "sending":
case "retrying":
return `${upload.sent} bytes sent`;
case "failed":
return upload.reason;
}
}
export const first: Upload = { type: "queued", file: "photo.jpg" };✅ After
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, is, match } from "@evobug_com/safe-ts-std/enum";
export type Upload = Enum<{
Queued: { file: string };
Sending: { file: string; sent: number };
Retrying: { file: string; sent: number };
Failed: { file: string; reason: string };
}>;
export const Upload = constructors<Upload>();
export function isFailed(upload: Upload): boolean {
return is(upload, Upload.Failed);
}
export function progress(upload: Upload): string {
return match(upload, {
Queued: () => "waiting",
Sending: (upload) => `${upload.sent} bytes sent`,
Retrying: (upload) => `${upload.sent} bytes sent`,
Failed: (upload) => upload.reason,
});
}
export const first: Upload = Upload.Queued({ file: "photo.jpg" });ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, is, match } from "@evobug_com/safe-ts-std/enum";
export type Upload = Enum<{
Queued: { file: string };
Sending: { file: string; sent: number };
Retrying: { file: string; sent: number };
Failed: { file: string; reason: string };
}>;
export const Upload = constructors<Upload>();
export function isFailed(upload: Upload): boolean {
return (upload?.tag === "Failed");
}
export function progress(upload: Upload): string {
{ const __ms1 = upload; let __mv1: string; switch (__ms1.tag) {
case "Queued": { __mv1 = "waiting"; break; }
case "Sending": { const upload = __ms1; __mv1 = `${upload.sent} bytes sent`; break; }
case "Retrying": { const upload = __ms1; __mv1 = `${upload.sent} bytes sent`; break; }
case "Failed": { const upload = __ms1; __mv1 = upload.reason; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}
export const first: Upload = ({ tag: "Queued", file: "photo.jpg" } satisfies Upload as Upload);- One variant per literal. A member whose
typeis itself a union ("sending" | "retrying") becomes one variant for each, sharing the payload. Names are the literals in PascalCase ("order-placed"isOrderPlaced). - Only values of that type. Other unions often use the same literals under
type; they are left alone. A value counts when an annotation says so, followed through variables, fields of your interfaces, array elements,for...of, array callbacks (events.filter((e) => ...)) and the signatures of functions in the given files. Producers ({ type: "queued", ... }where anUploadis expected,uploads.push({ ... })) become constructor calls. Checks becomeis:u.type === "queued"isis(u, Upload.Queued),!==is!is(...). Aswitch (u.type)whose every case returns a value becomesreturn match(u, { ... }), one handler per variant (cases that shared a body each get a copy).Extract<Upload, { type: "queued" }>becomesVariant<Upload, "Queued">. Files that need them get the imports. - Listed for a decision:
u.typeread as a value (stored, printed, compared with a variable),typedestructured,Upload["type"]. These are rewritten totag, which holds the variant name now ("Queued", not"queued"): check what they are compared with or written to. Aswitch (u.type)where a case doesn't return (abreak, a statement before thereturn), or with a comment between its cases, stays aswitch, overu.tagwithcase "Queued":; it is listed, andprefer-is-over-tagreports it with the idiomatic rules on. Producers that spread another object or computetypeare listed and left as written. - Not converted: members that aren't written out as object types (a named
Refundin the union), a member withouttypeor with atagfield, two literals giving the same name. - Run
tscafterwards. A value the codemod couldn't see the type of still has its old shape, andtscpoints at each one. - A value outside the union.
matchcallsunreachablefor a value no handler takes, where the oldswitchfell through: only data that never had the union's type (an unchecked cast, JSON read withoutparseJson<T>) behaves differently.
module-state
safe-ts migrate module-state src/ changes nothing: it prints, for each function, the module-level state it uses (what no-mutable-global calls state), directly or through the functions it calls, and for each piece of state the functions that use it. That is the list of functions a "module state → context parameter" change has to touch:
ts
let visits = 0;
const recent: string[] = [];
export function track(page: string): void {
visits += 1;
recent.push(page);
}
export function report(): string {
return `${visits} visits, last ${latest()}`;
}
function latest(): string {
return recent.at(-1) ?? "none";
}text
1:5 module state `visits`: used by `report`, `track`
2:7 module state `recent`: used by `latest`, `track`; through calls by `report`
4:8 `track` uses module state `visits` (changes it), `recent` (changes it)
9:8 `report` uses module state `visits`, `recent` (through `latest`)
13:1 `latest` uses module state `recent`The given files are the program: a module's state is followed into the functions of other given files that import it. A /** @cache */ constant isn't state, nor a const nothing changes.
mut
Mut<T> is a type of its own, and a value is lent to a Mut parameter by writing mut(value) at the call, like Rust's &mut value (State without globals). safe-ts migrate mut src/ writes the loan at every call, method call, JSX prop and Vue template binding that passes a value to a parameter or prop declared Mut<...>, across the files you give, with the import of mut where the file doesn't have the prelude. It is missing-mut's quick fix, applied in one pass over the program.
❌ Before (TypeScript refuses it with the nominal Mut<T>)
✕ Rejectedmissing-mut
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { items: string[] };
function addItem(cart: Mut<Cart>, item: string): void {
cart.items.push(item);
}
export function fill(cart: Mut<Cart>, items: readonly string[]): void {
for (const item of items) addItem(cart, item);
}✅ After safe-ts migrate mut --write
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { items: string[] };
function addItem(cart: Mut<Cart>, item: string): void {
cart.items.push(item);
}
export function fill(cart: Mut<Cart>, items: readonly string[]): void {
for (const item of items) addItem(mut(cart), item);
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { items: string[] };
function addItem(cart: Mut<Cart>, item: string): void {
cart.items.push(item);
}
export function fill(cart: Mut<Cart>, items: readonly string[]): void {
for (const item of items) addItem(cart, item);
}It also lends a value put into a place declared Mut<...> outside a call (an initializer or an assignment, a parameter's default, a field, a return, the elements of an array literal where readonly Mut<T>[] is asked), writes a fresh literal's loan with the place's type (mut<Cost>({ ... }), mut<number[]>([])), and rewrites Mut<Option<T>> and Mut<T | undefined> as Option<Mut<T>> and Mut<T> | undefined: a missing value can't be changed in place, and mut(maybe) keeps the undefined. Under "Needs a decision" it lists what it leaves to you: a call the checker can't follow whose name is a function's that takes Mut (TypeScript says whether it is), a [] or {} whose type it can't name in that file, and Mut inside another type built by a call (readonly Mut<T>[]: whoever builds the list lends each element). Lines under // @ts-expect-error are left as written. Then run tsc (or vue-tsc): what it still refuses is a hole the old Mut let through, such as a function taking Mut<T> passed as a callback that only lends to read, a Dog[] lent as Mut<Animal[]>, or a property narrower in the value where the function may write it (State without globals says what to write for each).
What remains is a short list of kinds. On one real program of about 700 files, after the migration (and the Mut declarations the new findings asked for), tsc refused 52 places:
What tsc still refuses | Places | Declarations to change | What to write |
|---|---|---|---|
A Mut<A> lent where Mut<B> lets the function write a property A has narrower or optional (an Inventory whose gold is optional, lent to addGood(target: Mut<Goods>) that may write gold) | 16 | 4 | A correct refusal, fixed where the function is declared: give the parameter the type it changes (Mut<Inventory>), or make the property the same |
A value the migration couldn't follow, without mut(...): a method of an object it can't resolve, a [] whose type it can't name, a default value | 20 | 0 | The loan, where it is lent (mut(x), mut<T>([])): the migration lists each under "Needs a decision" |
A function taking Mut<T> in a slot that only lends to read: a table of handlers, a plugin hook, an array callback | 8 | one per slot | Declare the slot's parameter Mut<T> in your own type, or take the value borrowed where the function only reads it; for a package's hook, wrap it in a function that lends |
| A fresh object lent where the parameter's type has an optional property the object doesn't have (a dependencies object) | 4 | 0 | Lend it with the type written, mut<Deps>({ ... }), or build it in a local of that type |
A subclass, a wider element type or a generic Mut<T> lent as another type's Mut (a point type for its base, a WeakSet<Texture> for WeakSet<object>) | 3 | 3 | As in the first row: the parameter's type is what the function changes |
| An overload that no longer matches | 1 | 1 | Pick the signature the call means, or lend the argument it asks for |
Two kinds that used to be on this list are gone: a member lent where its union is asked (Mut<number[]> where Mut<number[] | Int32Array> is) is accepted, and a list passed where each element is lent (readonly Mut<Unit>[]) is lent with mutEach(units), which the migration writes: the list itself, without a copy.
Vue components
Give the codemods the folder with your components: .vue files are read like the checker reads them, <script> and <script setup> (lang="ts") with the template's expressions, as one program with the .ts files they import. Each change is written back into the component, in the script, or in the attribute or {{ }} it came from; the rest of the file stays as it is. A type changed in a .ts file reaches the components that use it in the same run, so don't run a codemod on the .ts files alone: that leaves the components behind.
text
Left as written
src/components/UserBadge.vue:7:48 `null` type kept: in a prop type, which describes what parent components pass
src/App.vue:12:25 `null` kept: bound to the prop `fallback` of `<UserBadge>`, whose type keeps `null`null-to-undefined. A Pinia store's own state is the program's own: in an options store (state: () => ({ name: null as string | null })) itsnulls go, and components readinguser.name === nullbecomeuser.name === undefinedwith it. A setup store returning aref<T | null>(null)keeps it, asref(...)does everywhere, and then every read of that store keeps itsnulltoo. The same holds for any module-level value or function result in your files that holds outside data (a composable returning a template ref). Prop types (defineProps<{ user: User | null }>()), event types and slot props keep theirnull, since parent components pass them, and values a parent binds to such a prop keep theirs:<UserBadge :fallback="null" />stays.undefined-to-optionrewrites prop types too: Vue's compiler readsOption<string>likestring | undefined, so the prop works the same at runtime.ts-enumandunion-to-enumupdate uses in templates. A string written into an attribute gets the other quotes, sov-if="status === Status.Live"becomesv-if="status === 'live'".union-to-enumfollows props declared as an interface (defineProps<Props>()) intov-forand template comparisons, which becomeis(event, UploadEvent.Failed).throw-to-resultconverts functions of<script setup>like any other, but a function the template calls ({{ years(age) }},@click="save") stays: nothing there would receive the error. The report lists those calls.module-statecounts a plain<script>block as module state, shared by every instance of the component. What<script setup>declares belongs to each instance, so it isn't.- Left unchanged: a component whose change would go into code Vue generates from the template (a handler written as a name,
@click="save", or an expression with HTML entities,a && b) is left as written, and the report points at the expression. Scripts that aren't TypeScript and other template languages (Pug) aren't read.
Applying one rule's quick fixes
safe-ts fix <rule> applies the quick fixes of one rule, the ones the editor offers, to the files and folders you give. Like migrate, it prints a diff and changes nothing until you add --write:
sh
safe-ts fix prefer-is-over-tag src/ # show the diff and the report
safe-ts fix prefer-is-over-tag src/ --write # change the files
safe-ts fix unhandled-failure src/ --fix "Wrap in try/catch"- One fix per site, or none. A site with exactly one fix gets it. Among several, the one
--fix "<start of the title>"picks; else the only one whose title says (the same as now), which keeps the result for every input (What quick fixes keep):if (name)on an optional string gets Test for undefined and "" (the same as now) without--fix. Otherwise the site is left alone and listed with its fixes and why: each fix changes the result for some input (a number's Compare with 0 (NaN counts as true) and Test for a positive number), or more than one keeps it and which one is meant is a choice. The report ends with the--fixfor each kind of site left, with how many sites offer it. - Checked again until nothing changes. Each round applies the fixes whose edits don't touch each other, checks the file again, and goes on with what is left, so two fixes adding to one import both land. A round that would leave the file unparsable is undone, and its fixes are tried one by one; one that still breaks it is listed as not applied.
- Checked as
checkchecks. The program resolves the same way (tsconfig.jsonpaths, workspace packages), failures are followed into other files, and a changed file is seen by the files after it. Legacy files report nothing, so nothing in them changes. The idiomatic rules are on for the run, unless the project turns the rule off. - The report goes to stderr: sites skipped (with their fixes and why), not applied, without a fix, and fixed, then a summary (sites fixed, skipped, files changed).
--jsonprints one object instead: the counts, each site with its status and fix or options (a skipped site's"skipped"is"none-keeps-meaning"or"several-keep-meaning"), and each changed file's diff. - The whole program, for the rules only it shows (
unused-code, the event rules): onecheckof the files given, every file an entry when nothing imports it (as checking a directory does), and each site's fix once.safe-ts fix unused-code apps packagesdeletes what nothing refers to; what that leaves (the helpers only the deleted code called) is found by the next run.
Apply one rule at a time, and review the diff before --write: a quick fix is the usual answer, not always the right one (unsafe(...) around a call still leaves the Result to handle). oxlint --fix-suggestions applies the first suggestion of every rule at once: prefer safe-ts fix, one rule per run.
Upgrading and bulk fixes
- Bump every
@evobug_compackage in one step. They are released together, and each peer range is its own minor (^0.4.0), so a mix of versions doesn't install. Changing the pins and runningnpm installcan stop withERESOLVEwhile the lockfile still holds an old version: install them all in one command (npm install @evobug_com/[email protected] @evobug_com/[email protected] ...), or delete theirnode_modules/@evobug_com/...entries frompackage-lock.jsonfirst. Then apply the new rules' fixes one rule at a time and review them,strict-truthinesson values that may beundefinedmost of all. The steps: Upgrading between versions. - Scripts need the loader too. A script that uses
q(...),unsafe,parseJson<T>or any prelude name runs only through the rewrite: write its command asnode --import @evobug_com/safe-ts-transform/register scripts/report.ts, in package.json and in the comment at its top, not plainnode.safe-ts checkwarns about package.json scripts that miss it (above). unicorn/numeric-separators-stylechanges text that other programs may read. The preset no longer turns it on. If you turn it on yourself, its fix (oxlint --fix,vp lint --fix) groups decimals in thousands and hex in bytes: the values stay the same for JavaScript, but the text changes. A Rails initializer readingCONSOLE_PORT = 47474from a.tsfile with/CONSOLE_PORT = (\d+)/read47_474as47, so its content security policy allowed port 47 and the browser refused the real one; only running the app in a browser showed it. Before applying the fix, search for programs that read your source files (build scripts, configs in other languages,grepin a deploy script). To apply only that fix:oxlint --fix -A all -D unicorn/numeric-separators-style src/.- Review
unicorn/prefer-at's fix. It turnsa.length ? a[a.length - 1] : fallbackintoa.length ? a.at(-1) : fallback, which is typedT | undefined(atdoesn't know the length was checked), sotscthen reports each such place. Write it asa.at(-1) ?? fallback, which says the same thing. The preset keeps the rule: on its own,.at(-1)is the form SAFE-TS wants, sincea[a.length - 1]!is an unchecked cast. - Copies in a
for...of. Iterate a copy withArray.from(items), not[...items], when the loop changes the collection: oxlint'sunicorn/no-useless-spreadreports the spread (it can't see the change), andno-mutation-while-iteratingaccepts both. Deleting the entry the loop is on from aMaporSetneeds no copy. - Lint output. oxlint prints a summary ("Found 0 warnings and 0 errors") after the problems. In a terminal it detects as an AI agent's (
CLAUDECODE,AI_AGENT, ...), it prints only the problems, so a clean file prints nothing;--format defaultbrings the summary back. A plugin can't add to it. Each problem is printed once per rule and place.
Idiomatic rules
The rules above catch defects. A second, opt-in layer holds code to the framework's own way of writing things, so a codebase doesn't drift into two spellings of one idea:
jsonc
// package.json
"safe-ts": { "idiomatic": true }To see what they would report without turning them on, run safe-ts check src/main.ts --idiomatic once. check reminds you of the layer in its last line while it is off. Naming an idiomatic rule in "rules" turns that one on alone ("rules": { "prefer-option": "warn" }), and "off" turns one off while the others are on.
| Rule | Asks for |
|---|---|
prefer-option | Option<T>, not T | undefined |
no-optional-field | key: Option<T>, not key?: T, in the project's own types (JSON types, props, a library's options and declarations keep ?:); by safe-ts check only |
no-swallowed-error | the Result, not undefined, when something failed (if (isErr(r)) return undefined) |
sentinel-error | Result<void, E> or Option<string>, not '' for "no error" and a message otherwise |
wide-param | the fields a function reads, not the whole context (cart, not shop read as shop.state.cart) |
unneeded-mut | T, not Mut<T>, for a parameter the function never changes, and no mut(x) where the parameter isn't Mut |
prefer-is-over-tag | is, variant or match, not x.tag === "Ready" or switch (x.tag) |
prefer-constructor-tag | is(x, Status.Published), not is(x, "Published"), when the enum has constructors |
prefer-q | const x = q(...), not if (isErr(x)) return x |
prefer-map-err | mapErr(x, f), not err(f(x.error)) in an isErr branch |
json-null-in-app | an Enum or AsyncState<Option<T>, E>, not JsonNull as app state |
null-or-undefined-check | one absence per value, or a test for both |
undefined-to-null | null written where one body needs it, not for every undefined |
latest-wins-counter | useTask (or std latest outside components), not a hand-written "latest run wins" ticket |
unused-task-signal | the task's signal passed to the request |
catch-on-result | the Result checked, not a .catch that never runs |
misplaced-axios-check | the function's own error type read |
unsafe-project-call | a direct call, or unsafe(..., Panic), around the project's own code |
key-presence-union | an Enum, not variants told apart by their keys |
panic-on-loading | a state the page shows, not a crash before the first answer |
cast-in-test | fixture, testDouble or unchecked from @evobug_com/safe-ts-std/testing |
strict-truthiness | count > 0, name !== undefined, not if (count) / v-if="name" on a number or string |
no-positional-children | a reference to the child, or a lookup by name, not children[2] |
string-dispatch | a string parsed once into a closed type, not compared with three or more words |
undeclared-return-type | a declared return type where the checker can't read a function's result off its returns |
unused-code | no export nothing imports, and no code only such code uses; by safe-ts check only |
unused-private | no private member nothing in its class uses, no field written and never read |
safe-ts check, the Vite plugin, the Node loader, the editor and the oxlint plugin all follow the setting. The oxlint preset lists all of them (prefer-option an error, the others warnings), but they report nothing until the setting is on: the setting lives in package.json, where every tool reads it, so neither the preset nor a stricter preset turns them on. The layer is off by default because its findings change signatures one by one, which is the second step of an adoption, after the defects. Turning it on in an existing codebase: run undefined-to-option first, then decide the other rules' findings one by one: each changes a function's signature, and its callers with it. unneeded-mut's quick fix changes no caller; fixing one finding can reveal the next one up the call chain.
The rules from prefer-is-over-tag down catch the forms an agent-led migration falls back to: each compiles and passes the other rules, but writes a SAFE-TS idea by hand or works around it (the migration skill uses them as gates). They are warnings, so safe-ts check reports them without failing unless it runs with --deny-warnings. Most are decided from the code as written, without types; panic-on-loading goes by names and is the roughest, and its page says what it can't tell apart. prefer-q, prefer-is-over-tag and prefer-constructor-tag have quick fixes.
Dead code on day one
unused-code on an existing project finds what agents and refactors left behind: on an adopter's monorepo, 58 declarations in a run of its directories (46 from its entries alone), each dead on reading. Start with the baseline, which records each rule's warnings so the count can only fall, then delete in reviewed steps with safe-ts fix unused-code on the same directories (a diff; --write to apply), and again for what each step leaves. unreachable-code is a defect more often than not, so it is on by default as an error.
Escape hatches, and keeping them few
Every escape hatch is visible and countable:
| Escape hatch | Meaning | Use when |
|---|---|---|
unsafe(() => ...) / unsafeAsync | this call may throw; I turn it into a Result | calling code that throws (built-ins, libraries, legacy) |
panic(message) | this can't happen; stop the program | an invariant nothing can handle, never a loading state (std helpers) |
// @safe-ts legacy | this file isn't migrated yet | gradual adoption; the file is listed under "legacyFiles" in package.json (unlisted-marker) |
// @safe-ts std | trusted library code | writing low-level helpers like @evobug_com/safe-ts-std itself; the file is listed under "trustedFiles" |
// safe-ts-ignore <rule>: <reason> | this line is right as it is, for this rule | one line in a migrated file (above) |
void f() | I'm ignoring this Result on purpose | best-effort work whose failure really doesn't matter |
trust<T>(value) | I vouch for this value's type without checking it | a boundary no check fits: data another part of the program made, a result type the body can't build (std helpers). Not an overload over a looser implementation or a value is T predicate: they say the same uncounted, and no-overload and no-type-predicate report them |
LegacyNull | strict code still accepts null from callers not migrated yet | the bridge while legacy callers pass null (std helpers) |
/** @cache */ | this module-level value is a memo, not state | a cache that can be thrown away and computed again (no-mutable-global) |
// @ts-expect-error <reason> | TypeScript is wrong about this line, for this reason | one line no type fits yet; @ts-ignore, @ts-nocheck and a reasonless @ts-expect-error are reported (no-ts-suppression) |
"rules" / "overrides" in package.json | this rule is quieter here than the preset | a rule turned "off" or lowered to "warn" for the package or some files (rule levels) |
"infer" below "all", "infer": { "exclude" } | automatic mode finds fewer library failures, or none in those packages | a package whose inferred failures are wrong, while a pack is written (Libraries) |
"testRunners" | files importing this module are test files | a package re-exporting a test runner in a way the checker can't follow |
"vue": { "sanitizers" } | v-html takes this function's output unchecked | the one sanitizer the project vouches for; defineSanitizer says it in the code |
defineSanitizer(fn) | this function's output is safe HTML (Html) | the one sanitizer the project vouches for; counted however it is imported or re-exported |
// eslint-disable-next-line rule -- why | another linter's rule is off for the next line | a rule of another linter that is wrong here; a blanket one, or one naming a safe-ts/ rule, is reported (no-lint-suppression) |
declare const x: unknown, declare module "*.svg", a .d.ts of the project | this value exists, made by something the checker doesn't see | a constant a bundler injects, an asset module, a global the project sets; one that asserts a type nothing checks is reported (no-unchecked-declare) |
safe-ts check counts them after each run, however each one is spelled (a copy, a namespace member, .call, a re-export: a hatch handed on or exported under another name counts too), names the std files, since each one turns the rules off for a whole file, and names what package.json sets below the defaults: the rules above, infer, infer.exclude, testRunners, vue.sanitizers, "vue": { "ssr": false } in a project that depends on Nuxt, and a package.json inside another one's directory that leaves out what the outer one turns on (the idiomatic rules, a pack, an emitter, a request function, Vue SSR), since its files lose it (idiomatic off (on in package.json)). It also reads the .oxlintrc.json next to the package.json, since the preset is how a project gated by oxlint gets SAFE-TS's rules and some of oxlint's own (no-eval, no-proto): a config that doesn't extend the preset (oxlint not extending the SAFE-TS preset), turns one of its rules off or down (oxlint.rules no-eval off, oxlint.overrides no-new-func off for scripts/**), or leaves files out (oxlint.ignorePatterns legacy/**). It reads JSON with comments; not the files extends names, nested configs, oxlint -c, or a config in JavaScript (one next to the package.json is a setup warning):
text
escape hatches: 2 unsafe() block(s), 0 panic() call(s), 0 trust() call(s), 0 LegacyNull use(s), 0 @cache mark(s), 1 safe-ts-ignore comment(s), 0 legacy file(s), 1 std file(s) (src/protocol/trusted.ts), 0 @ts-ignore, 1 @ts-expect-error (and 14 in test files), 0 @ts-nocheck comment(s), 0 @vue-skip comment(s), 2 eslint-disable / oxlint-disable comment(s), 4 skipped test(s), 3 ambient declaration(s), 1 defineSanitizer() call(s)
weakened below the defaults: infer documented, no-mutable-global off for src/stores/** (package.json)A @ts-expect-error <reason> in a test file is a compile-time test ("this must not compile"), so it is counted apart. Treat an increase in any count as a code review question, the way Rust projects treat new unsafe blocks. Code the run didn't see is shown next to them: imports that resolve to nothing and source files no entry reaches (checking the whole program).
A ratchet: baseline
--write-baseline <file> records the counts, and --baseline <file> fails the run when any of them rose: every escape hatch above, what package.json weakens below the defaults, the source files not checked, the unresolved imports, the setup warnings (setupWarnings), and the warnings of each rule. Some settings only weaken against what they were, so the baseline records them per package.json and fails when one got weaker: the idiomatic rules turned off ("idiomatic": false, or a gate run without --idiomatic), a feature pack no longer loaded (taken out of "features", or no longer installed), a class taken out of "emitters" or a wrapper out of "requestFunctions", and the Vue SSR rules turned off. A package.json the run no longer reads counts as one with nothing set. It names each rise:
sh
safe-ts check src --write-baseline safe-ts-baseline.json # once, and after a reviewed exception
safe-ts check src --baseline safe-ts-baseline.json # in CItext
baseline gate: 3 counts rose against safe-ts-baseline.json
@ts-expect-error comments: 0 -> 1 (+1)
weakened: package.json: no-any off
weakened: the idiomatic rules are off (package.json)
Fix them, or (for a reviewed exception) write a new baseline with --write-baseline.A count missing from the file is 0; a value that isn't a count stops the run (exit 2). That holds for a baseline written by an earlier SAFE-TS, before it counted lint suppressions, ambient declarations, @vue-skip comments and defineSanitizer calls: the gate fails on those until the baseline is written again, and says why (defineSanitizer() calls (the baseline has no escapeHatches.sanitizers: written before SAFE-TS counted them?): 0 -> 2 (+2)). Failing is the choice that keeps the ratchet closed: a count it skipped would let it rise unseen. When counts fell, the run says so: write the baseline again to hold them there. The baseline doesn't excuse errors, which fail the run either way, and doesn't hold warnings at zero (--deny-warnings does). Commit the file, so a raised count shows in the diff that raises it. With --json the gate's lines go to stderr.