Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 344 lines · 33.4 KiB · at 503e839

# TypeScript-Ultra-StrictThis is my proposal for TypeScript-Ultra-Strict: a stricter TypeScript for a world where AI writes most of the code.> **This repo is a thought experiment, not a production tool.** The compiler works, type-checks, and every example passes, but the macro syntax is lowered by a preprocessor with known edge cases, the bundler plugins skip semantic checking, there are no published packages, and there is no stability promise. It exists to make the proposal concrete enough to argue with. Do not build anything you care about on it yet.**Status:** working prototype. This branch adds [v2](#v2-plain-ts-a-checker-and-security-types), which replaces the macros and the new extension with plain `.ts`, a checker and a small type library, and adds security types. The v1 description follows it.v1 status: `packages/cli` implements `tsus check` and `tsus build`: a tokenizer built on `ts.createScanner`, a preprocessor that lowers `match` and the `?` operator with a source map back to the `.tsus` file, and a full `ts.createProgram` type-check over the project. `match` is exhaustiveness-checked at compile time, `tsus build` emits `.js.map` files that point at the `.tsus` source, `packages/runtime` implements `Option`/`Result`, the typed match helpers and the boundary layer, `packages/plugin` provides webpack/Vite/esbuild/Bun adapters, the checker enforces 18 strictness rules with machine-applicable fixes (`tsus fix`, `tsus explain`, `tsus migrate`, `tsus init`; see [For agents](#for-agents)), and all 57 projects under `examples/` pass, 53 for v1 and 4 for v2 (`npm install && npm test`). `LEARNINGS.md` documents what broke along the way, how that shaped the design, and the known limitations.TypeScript's early design decisions assumed humans would write and maintain it, so a lot of features exist to make a human's life easier. We valued speed over quality. With AI writing most of our code, we can flip that tradeoff and force the language to be declarative and verifiable, like Rust.## v2: plain `.ts`, a checker, and security typesv2 lives on the `v2` branch. It keeps what v1 proved and drops what it cost. Everything is ordinary, erasable TypeScript: no macros, no `.tsus` extension, no compile step. A file that uses v2 is a `.ts` file that tsc, esbuild, wrangler and node's own type stripping handle unchanged (example 61 runs the same file through an esbuild bundle and through `node main.ts`; the root `tsconfig.json` checks the v2 files with `erasableSyntaxOnly`). v2 is three pieces:- **`@tsus/v2`** (`packages/v2`), a type library with a small runtime: `Option`, `Result`, `match`, `Sql`, `Permit`, `Secret`, `Untrusted`.- **`tsus check --v2 [dir]`**, a checker over the project's own TypeScript program (its tsconfig, plus `strict` and `noUncheckedIndexedAccess`). Codes TSUS500 to TSUS607, documented with the reason each one exists in [docs/v2/rules.md](docs/v2/rules.md) and by `tsus explain`.- **`tsus audit <file.ts...>`**, a report-only pass over existing plain TypeScript.### What the experiment taught, and what v2 does about itOn a new feature built from a detailed spec (the search query language, judged on 118 hidden tests and 20,400 fuzz pairs), v1 tied plain strict TypeScript on correctness and cost 28% more tool calls, 65% more code, a 51-line adapter and workarounds such as `parts.slice(0, 1).join("")` for `parts[0]`. Its checker reported nothing in 8 runs. In the on-call pilot, the Option and Result wrapper objects cost 2 to 6 times on the hot path, while rewriting existing logic exposed real bugs. And the risks that reviews of AI-written web code kept finding were SQL injection, permission scoping, secrets and untrusted input, for which v1 had nothing.| Lesson | v2 ||---|---|| Wrappers cost 2 to 6x | `Option<T>` is `T \| undefined`; `Result<T, E>` is `{ ok: true, value } \| { ok: false, error }`; `match` is one lookup and a call || The adapter was mostly null conversion | Comparing with `null` is allowed, producing it is not (TSUS502); `safeDb` turns D1's SQL NULL into `undefined` || Banning `undefined` and `!` banned indexing | `noUncheckedIndexedAccess` and an `=== undefined` check || Friction rules caught nothing | Dropped: no class, var, throw, enum, `==`, default export, parameter reassignment, unused `let`, tagged-errors-only. Each kept or dropped rule is listed with its evidence in docs/v2/rules.md || Exhaustive matching was the one prevention reviewers credited | Kept: `match()` and `matchLiteral()` are typed so a missing arm is a type error, and TSUS501 checks switches || No security model | `Sql`, `Permit`, `Secret`, `Untrusted`, with checker rules for what the types cannot express || Rewriting found bugs | `tsus audit` lists where the bugs hide in code nobody is rewriting |### The library```tsimport { match, matchLiteral, matchResult, Ok, Err, sql, safeDb, html, fence, secret, reveal, untrusted, validate } from "@tsus/v2";import type { Option, Result, Sql, Permit, Secret, Untrusted } from "@tsus/v2";const area = (s: Shape): number =>  match(s, "kind", { circle: (c) => Math.PI * c.r ** 2, square: (q) => q.side ** 2 }); // a missing arm is a type errorconst rows = await safeDb(env.DB).all<IssueRow>(  sql`SELECT number, title FROM issues WHERE repo_id = ${permit.resource} AND title LIKE ${pattern}`); // values are bound paramsconst page = html`<li>${issue.title}</li>`;                     // Untrusted text is escapedconst prompt = `Summarize:\n${fence(issue.body, "issue body")}`; // marked as data for the modelconst headers = { authorization: `Bearer ${reveal(apiKey)}` };   // the one explicit way out of a Secret```- **Sql** is a branded type that only the `sql` tag makes; every interpolation becomes a `?` and a bound parameter, nested `Sql` splices in, `sql.ident` takes only a string literal type. `SafeDb` accepts only `Sql`, so a query built with `+` or an untagged template is a compile error (TS2345, reported as TSUS601). For raw D1 calls the checker flags `prepare(text)` whenever the text is not a compile-time constant.- **Permit<"repo.read", RepoId>** is an opaque capability. Only `issuePermit` from `@tsus/v2/authority` makes one, and only files named `*.access.ts` may import it (TSUS602). A data-access function that reads private data takes a Permit, so calling it without the check is a missing argument and a hand-made object is a missing brand (TSUS600). It should read the id from `permit.resource`; a separate id of the same type is flagged (TSUS603), since that is how a check on repo A guards a read of repo B.- **Secret<T>** is not a string. `reveal()` is the explicit way out. The checker rejects a Secret, or an object containing one, in templates, `+`, `String()`, `JSON.stringify`, `console.*` and other log calls, URLs, `fetch` and `Response` (TSUS604). At runtime it prints as `[secret]` as a backstop.- **Untrusted** is the raw string at runtime (marking costs nothing) with a type that is not a string. It reaches HTML through `html`/`escapeHtml`, SQL through `sql`, a prompt through `fence`, and code that needs a plain string through `validate(text, /pattern/)`. Untagged templates and concatenation are rejected by context: HTML (TSUS605), SQL (TSUS601), an LLM prompt (TSUS606, a template assigned to a name like `prompt`, `system` or `messages`, or passed to a model call), anything else (TSUS607). `fence` wraps the text as `<untrusted source="...">` and neutralizes the closing tag and role markers inside it, the markers Rebasely's injection screen looks for.- Files named `*.boundary.ts` may cast, use `!`, `any` and `null`, and call raw drivers: they are where outside data is checked and converted. Their names make them reviewable.### Proof: the same module twice, with planted bugs`examples/60-v2-security-demo` is a Workers-style module (D1 queries, a permission check, a webhook secret, user text into HTML and into an LLM prompt) written in plain strict TypeScript (`plain/`) and with v2 (`v2/`), with the same six bugs planted in both, and a fixed v2 version (`fixed/`). The runner asserts all of it: plain passes `tsc --strict --noUncheckedIndexedAccess`; v2 reports every planted bug with the expected code and nothing on any other line; the fixed version passes, bundles with esbuild, and a harness runs the attacks against both versions on the same in-memory SQLite.| Planted bug | plain strict TS | `tsus audit` on the plain file | v2 (`tsus check --v2`) | At runtime, plain / fixed v2 ||---|---|---|---|---|| 1. Search text pasted into the query | nothing | string-built SQL | TSUS601 | `' OR 1=1 --` returns the private repo's rows / no rows || 2. Sort column pasted into the query | nothing | string-built SQL | TSUS601 | a `CASE WHEN` sort leaks who owns a private repo / ignored || 3. List handler skips the permission check | nothing | unchecked permission | TSUS600 (TS2345) | private rows listed signed out / 404 || 4. Webhook key in a log line | nothing | nothing | TSUS604 | key in the logs / not || 5. Issue titles into HTML unescaped | nothing | nothing | TSUS605 | `<script>` served / escaped || 6. Issue body into an LLM prompt unmarked | nothing | nothing | TSUS606 | `<system>` reaches the model / fenced and neutralized |The audit finds the two classes it can see without types; the other four need to know which values are secrets and which are user text, which is what the v2 types add.### Runtime`npm run bench` rebuilds the on-call micro benchmark from the pilot (`bench/oncall`; the pilot's own scripts were not committed, so the event generator is new and absolute numbers differ from the pilot's). The v1 rules are the pilot's compiled `rules.js` and runtime, unchanged. A differential check first confirms all versions agree on 20,000 events. Node 24.17, darwin arm64, median of 7 runs (raw output in `bench/oncall/RESULTS.txt`):| Path | before (plain .ts) | v1 | v2 ||---|---|---|---|| `jobFor`, per event (page of 1,000) | 310 ns | 523 ns (1.69x) | 348 ns (1.12x); 339 ns (1.09x) with the rank as a switch || dedupe test, per job | 8.3 ns | 56.9 ns (6.88x) | 7.6 ns (0.92x) || absent-or-value, 1,000 reads | 775 ns (`x ?? 0`) | 14,368 ns (`fromNullable(x).unwrapOr(0)`) | 1,115 ns (`fromNullable(x) ?? 0`) || 4-way literal match, 1,000 calls | 934 ns (switch) | 47,445 ns (match macro) | 13,813 ns (`matchLiteral`, arms inline); 6,016 ns (arms hoisted) |Option is free. `match()` is not: its arms are closures, so a hot loop should use a switch, which TSUS501 checks for exhaustiveness all the same. About half of what is left on `jobFor` is `tryCatch` (a closure and an `Ok` object per event) around `JSON.parse`: with a plain try/catch there, v2's `jobFor` measured 326 ns (1.05x) in the same run.### `tsus audit``tsus audit <file.ts...> [--json] [--scope dir] [--permission-fn name,...]` reads plain TypeScript with the project's own tsconfig and writes nothing. It ranks: string-built SQL (a query whose text is not a compile-time constant, or a template that assembles SQL text from non-constant parts), unchecked permission paths (a database read reachable from an entry point, through the call graph of the package, with no call to something named like a check before it), ignored promises, swallowed errors, non-exhaustive switches over unions, implicit null paths (index reads that `noUncheckedIndexedAccess` would reject, truthiness tests on optional strings and numbers, `!`) and casts. Every finding is a lead with the reason it was flagged; `--json` also lists each database read it considered checked and the check it found. Example 63 pins the findings on a legacy file and asserts the file is unchanged.Run read-only against Rebasely (origin/main 438e678a, apps/web/src/search/*.ts and apps/web/src/triage/*.ts), it reported 17 and 65 findings. Of the 82, 7 were true positives, all in triage: per-repository Actions failures in the Inbox are dropped without marking the result partial (`inbox.ts:184`), and six failures are swallowed without a log while the calls next to them log theirs (`inbox.ts:222-224`, `handlers.ts:54-55`, `handlers.ts:101`). The other 75 were false positives: 3 wrong (two SQL fragments whose column names are literals at every call site, and one data read reached through a dispatch table) and 72 correct about the pattern but harmless on inspection (bounds-checked index reads, documented fallbacks, safe casts). The search module, which the experiment's judge had already fuzzed, had none. LEARNINGS.md has the breakdown.### Limits- The security rules are as good as the marking: text is Untrusted because a boundary said so, and a value that never got marked is a plain string. The prompt rule recognizes prompts by name and by call; a prompt built under another name falls to TSUS607.- The permission rule in v2 is a type, so it holds wherever the data-access function is the only way to the rows. Raw D1 calls in application code are still possible; TSUS601 catches their string-built queries, not their missing checks. The audit's permission analysis is a name-based heuristic with call-site ordering, and it cannot follow calls through dispatch tables.- `match()` costs closures; use a switch on hot paths.## v1: what changes1. Removes `null` and `undefined`. In their place, `Option<T>` and `Result<T, E>` become first-class types. This is the centerpiece: the removals below only work because these replacements exist.2. Removes classes. Data is plain objects; behavior lives in functions.3. Removes `var`.4. Introduces an SDK for macros, used for pattern matching and variable destructuring over `Option`, `Result`, and tagged unions. (TC39 already has a pattern-matching proposal in the pipeline; this accelerates where the language is heading.)## The interop boundaryEvery existing DOM and npm API returns `undefined`, throws, and hands you classes. Ultra-Strict code never sees those directly. At the boundary, a checked bindings layer converts `T | undefined` and `T | null` into `Option<T>`, and throwing calls into `Result<T, E>`. Inside the boundary, the strict rules hold everywhere. In source, the boundary is the `@tsus/runtime/boundary` helpers (`fromNullable`, `wrapSync`, `wrapAsync`) plus any file named `*.boundary.tsus`, the only place casts and default exports are allowed.## Why not just an eslint preset?Banning classes, nulls, and `var` can be approximated with tsconfig and lint rules today. Two things need a real compiler:1. The macro SDK. This is the honest cost of the proposal: TypeScript's types are fully erasable, which is why esbuild and swc can strip them in a single fast pass. Macros break that property. The bet is that with AI writing the code, we should spend build-time budget on expressiveness and checkability rather than on keeping type-stripping trivial.2. The boundary layer, which needs type information to generate the `Option`/`Result` wrappers.## Why TypeScript?Back in 2008, Google shipped Chrome and V8, and the industry built its edge compute on top of that runtime. Cloudflare Workers runs V8 isolates directly. Node, Deno, and Bun's ecosystem all trace back to it. JavaScript and ESM are the substrate that's already deployed everywhere.TypeScript is the typed layer the ecosystem already adopted. Rather than asking everyone to move to a new language, Ultra-Strict is a subset-plus-macros of a language AI models already know deeply, targeting a runtime that's already everywhere.## Ideal UXAny file with a `.tsus` extension (TypeScript Ultra Strict) is processed under the strict rules and compiled to plain JavaScript. `.ts` and `.tsus` files coexist in one project, so adoption is per-file: an AI agent can write new modules in `.tsus` while the legacy `.ts` code keeps working untouched. Importing a `.tsus` module from `.ts` just works; importing `.ts` (or any npm package) into `.tsus` goes through the boundary layer, which rewrites the types so nullable returns arrive as `Option<T>` and throwing functions arrive as `Result<T, E>`.What a `.tsus` file looks like:```tsimport { readFile } from "node:fs/promises"; // boundary-wrapped: returns Resulttype User = { name: string; email: Option<string> };const loadUser = async (path: string): Promise<Result<User, IoError>> => {  const raw = await readFile(path, "utf8")?; // ? returns the Err early  return parseUser(raw);};// macro from the SDK; leaving out an arm is a compile errorconst greeting = match (user.email) {  Some(email) => `Reach me at ${email}`,  None => "No email on file",};```### How the macros compile`match` lowers to a call whose arms are an object keyed by variant tag:```tsmatch (opt) { Some(x) => a, None => b }   // -> __tsus_match(opt)({ Some: (x) => (a), None: () => (b) })match (opt) { Some(x) => a, _ => b }      // -> __tsus_match_or(opt)({ Some: (x) => (a) }, () => (b))match (path) { "/" => a, _ => b }         // -> __tsus_match_lit(path)([["/", () => (a)]], () => (b))````@tsus/runtime` types that object with a mapped type over the subject union's `tag` field, so TypeScript itself requires every variant (unless there is a `_` arm), rejects arms the union cannot hold, and narrows each arm's binding to its variant's payload. This works for `Option`, `Result`, and any user union with a string `tag`. Literal patterns lower to a list of `[literal, handler]` pairs; each literal must be a value of the subject's type, and `_` is required unless the literals cover a finite union like `"GET" | "POST"`. When the match has a contextual type (a declared return type, an annotated `const`, a typed parameter), every arm is checked against it, so `Err({ kind: "missing" })` infers the declared error union and a wrong arm is reported on that arm; with no context, the match's type is the union of its arms. If any arm awaits, every arm becomes async and the match is a Promise; `await` inside a string or comment does not count.`expr?` works like Rust's: on an `Err` or `None` it returns that value from the enclosing function, otherwise it unwraps.```tsconst port = parsePort(raw)?;// -> const __tsus_t0 = __tsus_try(parsePort(raw)); if (__tsus_isBail(__tsus_t0)) return __tsus_bail(__tsus_t0); const port = __tsus_t0.value;```The enclosing function must declare a `Result`, `Option`, or `Promise` of one as its return type, and the propagated error must fit it. In async code `?` applies to the awaited value (`await load()?`). `?` binds like the conditional operator, so it covers everything to its left: write `(a()?) + (b()?)`, not `a()? + b()?`. Optional chaining (`?.`), `??`, ternaries, and optional properties are untouched.### Diagnostics| Code | Meaning ||---|---|| `TSUS000` | Syntax error after macro expansion || `TSUS001`-`TSUS005` | Banned `class`, `null`, `undefined`, `var`, `throw` || `TSUS006` | Malformed `match` (bad pattern, mixed variant and literal patterns, duplicate arm) || `TSUS100` | Runtime only: a match with no arm for its value (only reachable if the checker was bypassed) || `TSUS200` | Any TypeScript error, mapped to the `.tsus` position; `tsCode` holds the TS code || `TSUS201` | Non-exhaustive match: missing variants, or literal arms with no `_` || `TSUS202` | A match arm for a variant or literal the subject cannot hold || `TSUS203` | A match subject that is not a tagged union or a literal type || `TSUS300` | `?` outside a function declaring a `Result`/`Option` return type (or at top level, or in a match arm) || `TSUS301` | `?` applied to something that is not a `Result` or `Option` || `TSUS302` | `?` propagating an `Err`/`None` the function's return type cannot hold || `TSUS303` | `?` in a position that may not run (`?:` branch, right of `&&`/`\|\|`/`??`, loop condition) |Every TypeScript-derived code (`TSUS2xx`, `TSUS301`, `TSUS302`) carries the original TS code as `tsCode` in `tsus check --json`.### Framework integrations`packages/plugin` (@tsus/plugin) is one transform core with a thin adapter per host, all sharing the CLI's preprocessor and checker:- `@tsus/plugin/webpack`: a loader. In Next.js, one rule in `next.config.mjs` makes `.tsus` importable from any page or component (`examples/27-nextjs`, verified by `next build` emitting the rendered string into static HTML).- `@tsus/plugin/vite`: a Vite plugin, which also covers Astro, SvelteKit, and Nuxt through their `vite.plugins` config (`examples/28-astro`).- `@tsus/plugin/esbuild`: an esbuild plugin. Bun's plugin API is esbuild-shaped, so the same object registers with `Bun.plugin`; with a one-line `bunfig.toml` preload, `bun run` executes `.tsus` imports natively with no build step (`examples/29-bun`).The adapters deliberately leave import specifiers untouched: the host bundler resolves `.tsus` to `.tsus` chains through its own pipeline and each hop hits the transform again. The `tsus` CLI stays the standalone path (and the CI path, via `tsus check --json`).Tooling:- `tsus build` compiles to JS with source maps, `tsus check` type-checks without emitting. Both run as an esbuild/swc plugin so existing bundler setups pick up `.tsus` files without config changes. (Today the plugins run the syntactic rules only; the semantic type-check lives in `tsus check`.)- Editor support ships as a TypeScript language service plugin, so VS Code and every TS-aware editor get diagnostics, go-to-definition, and macro expansion previews for free.- Diagnostics are machine-first: every error has a stable code, a JSON output mode, and a suggested fix, so an agent can consume `tsus check --json` in a loop without parsing prose. Human-readable output is a rendering of the same data.- No new package manager and no new registry. npm packages work through the boundary layer, and published `.tsus` packages ship compiled JS plus `.d.ts` files, so consumers don't need to know the source language existed.## Evidence`evals/` holds a harness that tests the thesis directly: a model writes the same 30 small programs (config parsing, an LRU cache, retries with typed errors, a state machine, date ranges, an inventory ledger, and so on) in `.ts` and in `.tsus`, the compiler's errors go back to it for up to three repair rounds, and hidden tests the model never sees decide which version is correct. The tasks were chosen because null, undefined, exceptions and unhandled cases cause real bugs in them. Every task ships a reference solution in both languages and a plausible buggy solution that the hidden tests must catch (`node evals/validate.mjs`).Results are in [evals/RESULTS.md](evals/RESULTS.md). So far that file holds only the harness self-test, which runs the reference solutions through the pipeline and says nothing about the thesis. No model run has been recorded yet; `node evals/run.mjs --pilot` runs the 10-task pilot once the Claude Code CLI is logged in or `ANTHROPIC_API_KEY` is set. Even then, one model, one sample per task and 10 to 30 tasks is a pilot, not proof. [evals/README.md](evals/README.md) lists the caveats, starting with this one: results recorded before the compiler foundation landed came from a tsus checker that did not type-check, so `.ts` got more compile-time help than `.tsus`; `tsus check` now runs a full TypeScript type-check too.## Known limitationsThe four limitations the MVP shipped with are closed: `tsus check` type-checks the whole project with `ts.createProgram`, a non-exhaustive match is a compile-time `TSUS201`, `await` in arms is detected on the parsed AST, and the tokenizer is TypeScript's own scanner with regex and template rescanning. What is still rough, roughly in order of how likely it is to bite:1. The bundler plugins (`@tsus/plugin/*`) transform one file at a time and only run the syntactic rules. Type errors surface in `tsus check`, not in `next build` or `vite build`.2. `tsus check` uses fixed compiler options (strict, ES2022, bundler resolution, DOM and Node types) and ignores any `tsconfig.json`.3. `?` binds like the conditional operator, so `a()? + 1` is a syntax error; write `(a()?) + 1`. It cannot appear in a match arm (arms are closures), a `?:` branch, the right side of `&&`/`||`/`??`, or a loop condition. Its return-type check is syntactic: the declared type must be spelled `Result<...>`, `Option<...>`, or `Promise<...>` of one, not an alias.4. Regex detection is a one-token lookbehind: after `)` or `}` a `/` is read as division, so `if (x) /re/.test(s)` misparses. Commas in an arm body's type arguments are handled by a heuristic, and an arm body cannot be a statement block.## For agentsThe language is designed to be written by models, so the toolchain treats an agent as its primary user.**Drop-in primer.** [`AGENTS.md`](AGENTS.md) is a one-page description of the whole language (types, `match`, `?`, the boundary, every diagnostic code) meant to be copied into any project that uses tsus. `tsus init` does that for you.**Commands.**| Command | What it does ||---|---|| `tsus check [dir] --json` | Every diagnostic has a stable `code`, `start`/`end` offsets and line/col ranges in the original `.tsus` file, a `hint`, an `explain` pointer, and a `fix` (or `null`) || `tsus fix [dir]` | Applies every safe fix, re-checking between passes. `--unsafe` adds fixes that can change behavior, `--code TSUS405` limits it to one rule, `--dry-run` reports without writing || `tsus explain <CODE>` | The rule, why it exists, a rejected and an accepted example, for every code: the strictness rules, the macro and type-check codes (TSUS000, TSUS006, TSUS200 to TSUS203) and the `?` codes (TSUS300 to TSUS303). `--list` prints every code, `--json` the raw entry || `tsus init [dir]` | Scaffolds `AGENTS.md` (plus a `CLAUDE.md` that imports it), a strict `tsconfig.json`, `package.json` and a starter `src/main.tsus`. Never overwrites; `--force` refreshes only `AGENTS.md` || `tsus migrate <file.ts>` | Codemod: `T \| null` and `T \| undefined` returns become `Option<T>`, throwing functions return `Result<T, E>` with a literal or tagged `E`, simple classes become a data type plus functions, `var` becomes `const` or `let`. Writes `<file>.tsus` next to the input and reports, with line numbers, everything it did not convert (including whatever the checker still rejects in the output) |A fix is `{ description, safe, edits: [{ start, end, line, col, endLine, endCol, newText }] }`, where offsets index the original file as UTF-16 code units. "Safe" means runtime behavior is unchanged: `==` to `===`, `let` to `const`, `var` to `const`/`let` when nothing depends on hoisting, `any` to `unknown`, deleting a suppression comment. Unsafe fixes (`"safe": false`) are offered where a mechanical rewrite exists but intent matters: an `enum` becomes a union of literals with its members inlined, a default export becomes a named one, a floating promise gets `await`, `param.sort()` becomes `param.toSorted()`.**Rules beyond the original five.** Each has a stable code, a rejection example, and `tsus explain` text, all generated from one registry (`packages/cli/src/rules/registry.js`). `npm run docs` regenerates [`docs/rules.md`](docs/rules.md) and the code table in `AGENTS.md`; `npm run docs:check` (part of `npm test`) fails if they drift or if a rule has no example.| Code | Rule | Fix ||---|---|---|| TSUS401 | no `any` | safe: `unknown` || TSUS402 | no `as` casts, except `as const` and in boundary files | none || TSUS403 | no non-null `!` | none || TSUS404 | no `enum` | unsafe: union of literals || TSUS405 | no `==` / `!=` | safe: `===` / `!==` || TSUS406 | no default exports, except in boundary files | unsafe: named export || TSUS407 | no reassigning parameters | none || TSUS408 | `let` that is never reassigned | safe: `const` || TSUS409 | no mutating parameters (property writes, array mutators, `Map`/`Set` mutators, `Object.assign`) | unsafe for `sort`/`reverse`/`splice` || TSUS410 | `Result` error types must be string literal unions or tagged unions | none || TSUS411 | no floating promises (including `void p` and `forEach(async ...)`) | unsafe: `await` || TSUS412 | no unused `Result` | none || TSUS413 | no `@ts-ignore`, `@ts-expect-error`, `@ts-nocheck` | safe: delete |The rules run on the macro-expanded source with the TypeScript parser and a per-file binder, so names resolve through real scopes (a shadowed parameter is not a parameter). TSUS410 to TSUS412 follow relative `.tsus` and `.ts` imports to see what an imported function returns or what an imported error type is; when a full `ts.Program` is handed to the checker, they use its types instead.**Boundary files.** A file named `*.boundary.tsus` is where the outside world is let in: `as` casts (after a runtime check) and default exports are allowed there, and nothing else is relaxed. Cloudflare Workers' `export default { fetch }` lives in one (`examples/23-cloudflare-worker`), as does a checked JSON config loader (`examples/53-boundary-file`).## The examples`examples/` is the test suite: 53 small projects, each with an `example.json` declaring what must happen. `npm run examples` builds and executes all of them and fails on any drift (`npm test` also checks that generated docs are current).**Core language and runtime**| Example | Shows ||---|---|| `01-hello` | Smallest possible `.tsus` file compiling to plain ESM || `02-option-basics` | `Option<T>` with `map`/`andThen`/`unwrapOr` || `03-result-basics` | `Result<T, E>` with `map`/`mapErr` || `04-match-option`, `05-match-result` | The `match` macro over Some/None and Ok/Err || `06-tagged-union` | User-defined tagged unions with a `_` wildcard arm || `32-regex-literals` | Regex literals containing braces, quotes, a backtick, and a fake match block || `33-await-in-string` | `await` inside a string in an arm stays synchronous; a real `await` makes the match async || `34-try-operator` | `?` on Result and Option, several per expression, in async functions, next to `?.`, `??`, and ternaries || `36-literal-patterns` | Literal arms over string, number, and boolean subjects; finite unions need no `_`; arms typed by the declared return type |**Rejected on purpose** (these pass by failing the checker with the right code)| Example | Code ||---|---|| `07-banned-null` | TSUS002 || `08-banned-class` | TSUS001 || `09-banned-var` | TSUS004 || `10-banned-undefined` | TSUS003 || `11-banned-throw` | TSUS005 || `30-non-exhaustive-match` | TSUS201, for a missing tagged-union variant, a missing `Err`, and literal arms that miss a union member || `31-wrong-arm-type` | TSUS200 (an arm of the wrong type, a payload used as the wrong type) and TSUS202 (a misspelled variant) || `35-try-misuse` | TSUS300, TSUS301, TSUS302, TSUS303 || `40-banned-any` | TSUS401 || `41-banned-as-cast` | TSUS402 || `42-banned-non-null` | TSUS403 || `43-banned-enum` | TSUS404 || `44-banned-loose-equality` | TSUS405 || `45-banned-default-export` | TSUS406 || `46-banned-param-reassign` | TSUS407 || `47-banned-let-never-reassigned` | TSUS408 || `48-banned-param-mutation` | TSUS409 || `49-banned-untagged-error` | TSUS410 || `50-banned-floating-promise` | TSUS411 || `51-banned-unused-result` | TSUS412 || `52-banned-ts-suppression` | TSUS413 |Rejection examples can also pin exact positions (`"diagnostics": [{ "code", "file", "line", "col", "tsCode" }]` in `example.json`), which tests the source map back to the `.tsus` file.Examples that list `fixable` codes in `example.json` also assert that those diagnostics carry a machine-applicable fix.**Interop and stress**| Example | Shows ||---|---|| `12-tsus-imports-tsus`, `20-deep-chain` | `.tsus` import chains, four levels deep || `13-tsus-imports-ts`, `14-ts-imports-tsus` | Mixed projects in both directions; `.ts` keeps its classes and nulls || `15-npm-dependency` | zod feeding `Result` || `16-boundary-fs`, `26-json-boundary` | `wrapAsync`/`wrapSync` turning throws into `Result` || `17-nested-match`, `18-generics`, `19-async-result` | Nested matches, generic signatures, `await` inside match arms || `21-circular-imports` | Function-level `.tsus` cycles (fine, because ESM) || `22-mixed-project` | ts + tsus + zod + boundary in one project || `24-hostile-syntax` | Decoy `match` blocks in strings, comments, and template literals || `25-shadowed-match` | A user function named `match` staying a plain call |**Runtimes and frameworks**| Example | Shows ||---|---|| `23-cloudflare-worker` | Cloudflare `{ fetch }` module shape, tested against real `Request`/`Response` || `27-nextjs` | Next.js 14 via the webpack loader; `next build` renders `.tsus` output into static HTML || `28-astro` | Astro 4 via the Vite plugin, verified in built HTML || `29-bun` | Bun runs `.tsus` imports natively via a `bunfig.toml` preload, no build step |**v2** (plain `.ts`; see [v2](#v2-plain-ts-a-checker-and-security-types))| Example | Shows ||---|---|| `60-v2-security-demo` | The same Workers module in plain strict TS and in v2 with six planted bugs: plain passes tsc, v2 flags all six (and nothing else), the fixed version bundles with esbuild, and a harness runs the attacks against both || `61-v2-basics` | `match`, `matchLiteral`, `matchResult`, Option as `T \| undefined`, `sql`, `html`, `validate`; checked, bundled with esbuild and run with node's type stripping, same output || `62-v2-rejected` | Every v2 code from TSUS500 to TSUS607, each pinned to the line it must land on, with nothing reported anywhere else || `63-v2-audit` | `tsus audit` on a legacy file: the findings pinned to their lines, and the file unchanged |**Agent tooling**| Example | Shows ||---|---|| `53-boundary-file` | A `*.boundary.tsus` file using a checked cast; the rest of the program sees only a tagged `Result` || `54-fix-roundtrip` | `tsus fix` on a copy (including edits inside match arms), compared byte for byte with `expected/`, then built and run || `55-migrate` | `tsus migrate` on a legacy `.ts` module (class, var, nullable returns, throws) against golden output, then run; a second file shows the not-converted report || `56-init` | `tsus init` into an empty directory, then the starter project builds and runs |