Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 250 lines · 22.0 KiB · at eb4a6ea

# 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. `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 and `.d.ts` declarations for plain TypeScript consumers, `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 55 projects under `examples/` pass (`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.## 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 and `.d.ts` declarations (relative `.tsus` imports in them point at the emitted `.js`), `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. `tsus check`, `tsus build` and `tsus fix` also hand TSUS411 and TSUS412 the project's `ts.Program`, so a call through a parameter or an object (`api.save()`, `deps.log()`) or into a package is judged by its real type; the bundler plugins, which see one file at a time, keep the per-file answer (`examples/58-typed-promise-rules`).**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 || `58-typed-promise-rules` | TSUS411 and TSUS412 on calls through a parameter, which need the project's types |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 |**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 || `57-declarations` | `tsus build` writes `.d.ts` files, including an import type that names another `.tsus` module as `./shapes.js` |