Stricter .tsus rules (TSUS401-413) with machine-applicable fixes, tsus fix/explain/init/migrate, AGENTS.md
New AST rules in packages/cli/src/rules/, hooked into check.js at the end of checkSource: any, as casts (outside *.boundary.tsus), non-null !, enum (with a fix to a literal union), == and !=, default exports, parameter reassignment and mutation, let that is never reassigned, untagged Result error types, floating promises and unused Results (syntactic, cross-file for relative imports, and type-aware when a ts.Program is passed in), and @ts-ignore style suppressions. Every diagnostic now carries start/end, an explain pointer and a fix with exact edits mapped back to the original .tsus text through the match expansion. One registry drives tsus explain, docs/rules.md and the code table in AGENTS.md. Examples 40-52 reject one code each; 53 shows a boundary file, 54 a tsus fix round trip, 55 tsus migrate against golden output, 56 tsus init. Existing examples moved to tagged error types, and the worker entry is now a boundary file because Workers require export default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changed files
78 files changed1,283 additions53 deletionsagainst f30ac63
- Changed.gitignore+1−0
- AddedAGENTS.md+134−0
- Addeddocs/rules.md+542−0
- Changedexamples/03-result-basics/src/main.tsus+1−1
- Changedexamples/05-match-result/src/main.tsus+13−5
- Changedexamples/14-ts-imports-tsus/src/lib.tsus+3−3
- Changedexamples/15-npm-dependency/src/main.tsus+4−4
- Changedexamples/17-nested-match/src/main.tsus+1−1
- Changedexamples/18-generics/src/main.tsus+1−1
- Changedexamples/19-async-result/src/main.tsus+5−5
- Changedexamples/22-mixed-project/src/repo.tsus+2−2
- Changedexamples/22-mixed-project/src/validate.tsus+2−1
- Changedexamples/23-cloudflare-worker/example.json+1−1
- Addedexamples/23-cloudflare-worker/src/worker.boundary.tsus+15−0
- Removedexamples/23-cloudflare-worker/src/worker.tsus+0−12
- Changedexamples/28-astro/src/lib/banner.tsus+1−1
- Addedexamples/40-banned-any/example.json+1−0
- Addedexamples/40-banned-any/src/main.tsus+4−0
- Addedexamples/41-banned-as-cast/example.json+1−0
- Addedexamples/41-banned-as-cast/src/main.tsus+8−0
- Addedexamples/42-banned-non-null/example.json+1−0
- Addedexamples/42-banned-non-null/src/main.tsus+4−0
- Addedexamples/43-banned-enum/example.json+1−0
- Addedexamples/43-banned-enum/src/main.tsus+10−0
- Addedexamples/44-banned-loose-equality/example.json+1−0
- Addedexamples/44-banned-loose-equality/src/main.tsus+5−0
- Addedexamples/45-banned-default-export/example.json+1−0
- Addedexamples/45-banned-default-export/src/main.tsus+5−0
- Addedexamples/46-banned-param-reassign/example.json+1−0
- Addedexamples/46-banned-param-reassign/src/main.tsus+9−0
- Addedexamples/47-banned-let-never-reassigned/example.json+1−0
- Addedexamples/47-banned-let-never-reassigned/src/main.tsus+5−0
- Addedexamples/48-banned-param-mutation/example.json+1−0
- Addedexamples/48-banned-param-mutation/src/main.tsus+10−0
- Addedexamples/49-banned-untagged-error/example.json+1−0
- Addedexamples/49-banned-untagged-error/src/main.tsus+9−0
- Addedexamples/50-banned-floating-promise/example.json+1−0
- Addedexamples/50-banned-floating-promise/src/main.tsus+12−0
- Addedexamples/51-banned-unused-result/example.json+1−0
- Addedexamples/51-banned-unused-result/src/main.tsus+11−0
- Addedexamples/52-banned-ts-suppression/example.json+1−0
- Addedexamples/52-banned-ts-suppression/src/main.tsus+5−0
- Addedexamples/53-boundary-file/example.json+1−0
- Addedexamples/53-boundary-file/src/config.boundary.tsus+22−0
- Addedexamples/53-boundary-file/src/main.tsus+12−0
- Addedexamples/54-fix-roundtrip/example.json+6−0
- Addedexamples/54-fix-roundtrip/expected/main.tsus+32−0
- Addedexamples/54-fix-roundtrip/src/main.tsus+33−0
- Addedexamples/55-migrate/example.json+13−0
- Addedexamples/55-migrate/expected/inventory.tsus+37−0
- Addedexamples/55-migrate/expected/orders.tsus+38−0
- Addedexamples/55-migrate/legacy/orders.ts+34−0
- Addedexamples/55-migrate/src/inventory.ts+34−0
- Addedexamples/55-migrate/src/main.tsus+25−0
- Addedexamples/56-init/example.json+5−0
- Changedpackage.json+4−1
- Changedpackages/cli/bin/tsus.js+138−9
- Changedpackages/cli/src/build.js+1−1
- Changedpackages/cli/src/check.js+9−3
- Changedpackages/cli/src/compile.js+3−2
- Addedpackages/cli/src/explain.js
- Addedpackages/cli/src/fix.js
- Addedpackages/cli/src/init.js
- Addedpackages/cli/src/migrate.js
- Addedpackages/cli/src/rules/analysis.js
- Addedpackages/cli/src/rules/bans.js
- Addedpackages/cli/src/rules/context.js
- Addedpackages/cli/src/rules/immutability.js
- Addedpackages/cli/src/rules/index.js
- Addedpackages/cli/src/rules/project.js
- Addedpackages/cli/src/rules/registry.js
- Addedpackages/cli/src/rules/results.js
- Addedpackages/cli/src/rules/sourcemap.js
- Addedpackages/cli/templates/AGENTS.md
- Addedpackages/cli/templates/src/main.tsus
- Addedpackages/cli/templates/tsconfig.json
- Addedscripts/docs.mjs
- Changedscripts/run-examples.mjs
Changed.gitignore+1−0
| @@ -1,3 +1,4 @@ | ||
| node_modules/ | ||
| dist/ | ||
| *.log | ||
| +.examples-tmp/ | ||
AddedAGENTS.md+134−0
| @@ -0,0 +1,134 @@ | ||
| +# Writing TypeScript-Ultra-Strict (.tsus) | ||
| + | ||
| +This project uses `.tsus` files: TypeScript with the escape hatches removed. Plain `.ts` files keep working and are not checked. Everything below applies to `.tsus` only. Read it once before writing code; `tsus explain <CODE>` covers any single rule in depth. | ||
| + | ||
| +## The loop | ||
| + | ||
| +1. Write or edit `.tsus` files under `src/`. | ||
| +2. Run `tsus check --json`. Each diagnostic has a stable `code`, a position, a `hint`, and usually a `fix` with exact text edits. | ||
| +3. Run `tsus fix` to apply every safe fix (`--unsafe` adds fixes that can change behavior; review those). Or apply a diagnostic's `fix.edits` yourself: each edit replaces `[start, end)` (UTF-16 offsets into the original file) with `newText`. | ||
| +4. For anything left, run `tsus explain <CODE>` and change the code. Do not work around a rule: there is no suppression comment, and `as`, `any` and `!` are themselves errors. | ||
| +5. Repeat until `tsus check` passes, then `tsus build` emits plain ESM into `dist/`. | ||
| + | ||
| +To port a `.ts` file, run `tsus migrate src/file.ts`. It writes `src/file.tsus` next to it and lists what it could not convert. | ||
| + | ||
| +## What is not allowed | ||
| + | ||
| +No `null`, no `undefined`, no `class`, no `var`, no `throw`, no `any`, no `as` casts (except `as const`), no `!` non-null assertions, no `enum`, no `==` or `!=`, no default exports, no `@ts-ignore`/`@ts-expect-error`/`@ts-nocheck`. Do not reassign or mutate function parameters. Use `const` unless the binding really is reassigned. Every promise is awaited or returned. Every `Result` is matched, propagated or returned. `Result` error types are string literal unions or tagged unions. | ||
| + | ||
| +## Types | ||
| + | ||
| +```ts | ||
| +import { Some, None, Ok, Err, tag, type Option, type Result, type Tagged } from "@tsus/runtime"; | ||
| + | ||
| +type User = { readonly name: string; readonly email: Option<string> }; // data is plain objects | ||
| + | ||
| +const ada: User = { name: "ada", email: Some("ada@example.com") }; | ||
| +const nobody: Option<string> = None; | ||
| + | ||
| +// Errors are a closed set the caller can match on. | ||
| +type LoadError = "empty id" | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number }; | ||
| + | ||
| +const load = (id: string): Result<User, LoadError> => | ||
| + id === "" ? Err("empty id") : Err(tag("NotFound", id)); | ||
| +``` | ||
| + | ||
| +- `Option<T>`: `Some(value)` or `None`. Methods: `map`, `andThen`, `unwrapOr(fallback)`, `okOr(error)`, `isSome()`, `isNone()`. | ||
| +- `Result<T, E>`: `Ok(value)` or `Err(error)`. Methods: `map`, `mapErr`, `andThen`, `unwrapOr(fallback)`, `ok()`, `isOk()`, `isErr()`. | ||
| +- `Tagged<"Name", V>` and `tag("Name", value)` build tagged variants; any object type with a literal `tag` field works too. | ||
| +- Behavior lives in functions that take data and return new data: `const rename = (u: User, name: string): User => ({ ...u, name });`. | ||
| +- A `void` operation that can fail returns `Result<true, E>` and ends with `return Ok(true);`. | ||
| + | ||
| +## match | ||
| + | ||
| +`match` is a macro and an expression. Each arm is `Pattern => expression`, separated by commas. | ||
| + | ||
| +```ts | ||
| +const greet = (u: User): string => | ||
| + match (u.email) { | ||
| + Some(address) => `mail ${address}`, | ||
| + None => `no email for ${u.name}`, | ||
| + }; | ||
| + | ||
| +const explain = (e: LoadError): string => | ||
| + match (e) { | ||
| + "empty id" => "no id given", // literal pattern | ||
| + NotFound(id) => `no user ${id}`, // Tagged variant: binds its value | ||
| + _ => "timed out", // wildcard | ||
| + }; | ||
| +``` | ||
| + | ||
| +- Patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, any tag name `Variant(x)` (binds `.value` for `Tagged`, the whole object otherwise), string or number literals, and `_`. | ||
| +- Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm. | ||
| +- Matches nest. An arm may `await`; then write `await match (...) { ... }`. | ||
| + | ||
| +## The ? operator | ||
| + | ||
| +`?` after a `Result` or `Option` expression returns early with its `Err` or `None`, and otherwise yields the inner value. It only works inside a function whose declared return type is a `Result` or `Option` (or a `Promise` of one), and the error types must line up (use `mapErr` first if not). In async code, await first: `const user = (await load(id))?;`. | ||
| + | ||
| +```ts | ||
| +const total = (rawA: string, rawB: string): Result<number, ParseError> => { | ||
| + const a = parse(rawA)?; | ||
| + const b = parse(rawB)?; | ||
| + return Ok(a + b); | ||
| +}; | ||
| +``` | ||
| + | ||
| +## The boundary | ||
| + | ||
| +The outside world (npm, DOM, Node, `.ts` files) returns `undefined`, throws, and hands you classes. Convert it at the edge: | ||
| + | ||
| +```ts | ||
| +import { tag, type Tagged } from "@tsus/runtime"; | ||
| +import { fromNullable, wrapSync, wrapAsync } from "@tsus/runtime/boundary"; | ||
| +import { readFile } from "node:fs/promises"; | ||
| + | ||
| +const first = fromNullable([1, 2].find((n) => n > 1)); // T | null | undefined -> Option<T> | ||
| +const parseJson = wrapSync(JSON.parse); // throws -> Result<T, Error> | ||
| +const read = wrapAsync(readFile); // rejects -> Promise<Result<T, Error>> | ||
| + | ||
| +type ReadError = Tagged<"ReadFailed", string>; | ||
| +const text = (await read("a.txt", "utf8")).mapErr((e): ReadError => tag("ReadFailed", e.message)); | ||
| +``` | ||
| + | ||
| +Map `Error` into your own tagged error type right away with `mapErr`. A file named `*.boundary.tsus` may use `as` casts (after a runtime check) and default exports (for hosts such as Cloudflare Workers that require `export default`). All other rules still apply there. Keep boundary files small; validate untrusted data with a schema library such as zod and return a `Result`. | ||
| + | ||
| +## Diagnostic codes | ||
| + | ||
| +<!-- tsus:codes:start --> | ||
| +| Code | Rule | Fix | | ||
| +|---|---|---| | ||
| +| TSUS000 | Syntax error | none | | ||
| +| TSUS001 | Classes are banned | none | | ||
| +| TSUS002 | null is banned | none | | ||
| +| TSUS003 | undefined is banned | none | | ||
| +| TSUS004 | var is banned | safe | | ||
| +| TSUS005 | throw is banned | none | | ||
| +| TSUS006 | Malformed match expression | none | | ||
| +| TSUS100 | Non-exhaustive match (runtime) | none | | ||
| +| TSUS401 | any is banned | safe | | ||
| +| TSUS402 | as casts are banned outside boundary files | none | | ||
| +| TSUS403 | Non-null assertions are banned | none | | ||
| +| TSUS404 | enum is banned | unsafe | | ||
| +| TSUS405 | == and != are banned | safe | | ||
| +| TSUS406 | Default exports are banned outside boundary files | unsafe | | ||
| +| TSUS407 | Reassigning a parameter is banned | none | | ||
| +| TSUS408 | let that is never reassigned | safe | | ||
| +| TSUS409 | Mutating a parameter is banned | unsafe | | ||
| +| TSUS410 | Result error types must be tagged | none | | ||
| +| TSUS411 | Floating promises are banned | unsafe | | ||
| +| TSUS412 | Unused Result | none | | ||
| +| TSUS413 | Type-check suppressions are banned | safe | | ||
| +<!-- tsus:codes:end --> | ||
| + | ||
| +`tsus explain <CODE>` prints the rule, why it exists, a rejected and an accepted example. `tsus check --json` diagnostics look like: | ||
| + | ||
| +```json | ||
| +{ "code": "TSUS405", "message": "loose equality (== / !=) is banned in .tsus files", "hint": "Use === or !==.", | ||
| + "file": "src/main.tsus", "line": 3, "col": 48, "endLine": 3, "endCol": 50, "start": 97, "end": 99, | ||
| + "explain": "tsus explain TSUS405", | ||
| + "fix": { "description": "Replace == with ===", "safe": true, | ||
| + "edits": [{ "start": 97, "end": 99, "line": 3, "col": 48, "endLine": 3, "endCol": 50, "newText": "===" }] } } | ||
| +``` | ||
| + | ||
| +`fix` is `null` when no automatic fix exists. Safe fixes keep runtime behavior (they can surface type errors that `any` was hiding); unsafe ones (`"safe": false`) can change it. | ||
Addeddocs/rules.mdLong diff, collapsed+542−0
| @@ -0,0 +1,542 @@ | ||
| +# TSUS diagnostic codes | ||
| + | ||
| +Generated from `packages/cli/src/rules/registry.js` by `npm run docs`. Do not edit by hand; `tsus explain <CODE>` prints the same text. | ||
| + | ||
| +| Code | Rule | Fix | | ||
| +|---|---|---| | ||
| +| TSUS000 | Syntax error | none | | ||
| +| TSUS001 | Classes are banned | none | | ||
| +| TSUS002 | null is banned | none | | ||
| +| TSUS003 | undefined is banned | none | | ||
| +| TSUS004 | var is banned | safe | | ||
| +| TSUS005 | throw is banned | none | | ||
| +| TSUS006 | Malformed match expression | none | | ||
| +| TSUS100 | Non-exhaustive match (runtime) | none | | ||
| +| TSUS401 | any is banned | safe | | ||
| +| TSUS402 | as casts are banned outside boundary files | none | | ||
| +| TSUS403 | Non-null assertions are banned | none | | ||
| +| TSUS404 | enum is banned | unsafe | | ||
| +| TSUS405 | == and != are banned | safe | | ||
| +| TSUS406 | Default exports are banned outside boundary files | unsafe | | ||
| +| TSUS407 | Reassigning a parameter is banned | none | | ||
| +| TSUS408 | let that is never reassigned | safe | | ||
| +| TSUS409 | Mutating a parameter is banned | unsafe | | ||
| +| TSUS410 | Result error types must be tagged | none | | ||
| +| TSUS411 | Floating promises are banned | unsafe | | ||
| +| TSUS412 | Unused Result | none | | ||
| +| TSUS413 | Type-check suppressions are banned | safe | | ||
| + | ||
| +## TSUS000 syntax-error | ||
| + | ||
| +**Syntax error.** Every other rule runs on the parsed tree, so nothing else can be checked until the file parses. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const total = (a: number, b: number): number => a + ; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const total = (a: number, b: number): number => a + b; | ||
| +``` | ||
| + | ||
| +Hint: The file does not parse as TypeScript after macro expansion. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS001 no-class | ||
| + | ||
| +**Classes are banned.** Classes mix data, behavior, identity and mutable state, and `this` rebinding is a classic source of bugs. Plain data plus functions is easier to verify, serialize and test. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +class Counter { | ||
| + constructor(public count: number) {} | ||
| + next(): Counter { | ||
| + return new Counter(this.count + 1); | ||
| + } | ||
| +} | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +type Counter = { readonly count: number }; | ||
| + | ||
| +const createCounter = (count: number): Counter => ({ count }); | ||
| +const next = (c: Counter): Counter => ({ count: c.count + 1 }); | ||
| +``` | ||
| + | ||
| +Hint: Use plain object types and functions. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS002 no-null | ||
| + | ||
| +**null is banned.** null is an absent value that the type system lets you forget to check. Option<T> makes absence a value you have to match on. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const find = (id: number): string | null => (id === 1 ? "ada" : null); | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +import { Some, None, type Option } from "@tsus/runtime"; | ||
| + | ||
| +const find = (id: number): Option<string> => (id === 1 ? Some("ada") : None); | ||
| +``` | ||
| + | ||
| +Hint: Use Option<T> from @tsus/runtime, or fromNullable at the boundary. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS003 no-undefined | ||
| + | ||
| +**undefined is banned.** undefined is the second absent value. Having two of them doubles the checks and neither is enforced. Option<T> replaces both. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const nickname: string | undefined = undefined; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +import { None, type Option } from "@tsus/runtime"; | ||
| + | ||
| +const nickname: Option<string> = None; | ||
| +``` | ||
| + | ||
| +Hint: Use Option<T> from @tsus/runtime, or fromNullable at the boundary. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS004 no-var | ||
| + | ||
| +**var is banned.** var is function-scoped and hoisted, so a binding can be read before it is assigned and leaks out of blocks. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +var count = 0; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const count = 0; | ||
| +``` | ||
| + | ||
| +Hint: Use const (preferred) or let. | ||
| + | ||
| +Fix: `tsus fix` applies it (behavior is kept). | ||
| + | ||
| +## TSUS005 no-throw | ||
| + | ||
| +**throw is banned.** A throw is an invisible second return type. Callers cannot see it in the signature and the compiler cannot make them handle it. Result<T, E> puts the failure in the type. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const parsePort = (raw: string): number => { | ||
| + const n = Number(raw); | ||
| + if (Number.isNaN(n)) { | ||
| + throw new Error("not a number"); | ||
| + } | ||
| + return n; | ||
| +}; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| + | ||
| +const parsePort = (raw: string): Result<number, "not a number"> => { | ||
| + const n = Number(raw); | ||
| + return Number.isNaN(n) ? Err("not a number") : Ok(n); | ||
| +}; | ||
| +``` | ||
| + | ||
| +Hint: Return Result<T, E> from @tsus/runtime, or wrapSync/wrapAsync at the boundary. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS006 match-syntax | ||
| + | ||
| +**Malformed match expression.** The match macro is expanded before TypeScript parses the file, so a malformed match has to be reported by the macro itself. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const label = match (opt) { | ||
| + Some(x) -> x, | ||
| +}; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const label = match (opt) { | ||
| + Some(x) => x, | ||
| + None => "none", | ||
| +}; | ||
| +``` | ||
| + | ||
| +Hint: Arms look like: Pattern(binding) => expression, separated by commas. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS100 non-exhaustive-match | ||
| + | ||
| +**Non-exhaustive match (runtime).** A match that falls through has no value to return. Raised at runtime by __tsus_match until exhaustiveness is checked at compile time. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const name = (s: Shape): string => | ||
| + match (s) { | ||
| + Circle(c) => "circle", | ||
| + }; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const name = (s: Shape): string => | ||
| + match (s) { | ||
| + Circle(c) => "circle", | ||
| + _ => "other", | ||
| + }; | ||
| +``` | ||
| + | ||
| +Hint: Add an arm for every variant, or a _ arm. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS401 no-any | ||
| + | ||
| +**any is banned.** any switches the type checker off for every value it touches, and it spreads: anything derived from an any is any too. unknown forces a check before use. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const parse = (raw: string): any => JSON.parse(raw); | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const parse = (raw: string): unknown => JSON.parse(raw); | ||
| +``` | ||
| + | ||
| +Hint: Use unknown and narrow it, or a precise type. | ||
| + | ||
| +Fix: `tsus fix` applies it (behavior is kept). | ||
| + | ||
| +## TSUS402 no-as-cast | ||
| + | ||
| +**as casts are banned outside boundary files.** A cast is a claim the compiler cannot check. Casts belong at the boundary, where outside data is validated once, not sprinkled through the program. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const user = JSON.parse(raw) as User; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +// user.boundary.tsus: the one place outside data is trusted | ||
| +import { z } from "zod"; | ||
| +import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| + | ||
| +const UserSchema = z.object({ name: z.string() }); | ||
| +export type User = z.infer<typeof UserSchema>; | ||
| + | ||
| +export const parseUser = (input: unknown): Result<User, "invalid user"> => { | ||
| + const out = UserSchema.safeParse(input); | ||
| + return out.success ? Ok(out.data) : Err("invalid user"); | ||
| +}; | ||
| +``` | ||
| + | ||
| +Hint: Validate the value (for example with zod) and return a Result, or move the cast into a *.boundary.tsus file. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS403 no-non-null-assertion | ||
| + | ||
| +**Non-null assertions are banned.** x! tells the compiler a value cannot be absent without proving it. When the claim is wrong you get the crash Option exists to prevent. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const first = (xs: string[]): string => xs.find((x) => x.length > 0)!; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +import { fromNullable } from "@tsus/runtime/boundary"; | ||
| + | ||
| +const first = (xs: string[]): string => | ||
| + fromNullable(xs.find((x) => x.length > 0)).unwrapOr(""); | ||
| +``` | ||
| + | ||
| +Hint: Model the value as Option<T> and match on it, or use unwrapOr. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS404 no-enum | ||
| + | ||
| +**enum is banned.** enums are the one TypeScript feature that emits runtime code, numeric enums accept any number, and they do not narrow like literal unions. A union of literals is erasable, exhaustive in match, and serializes as itself. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +enum Color { | ||
| + Red = "red", | ||
| + Green = "green", | ||
| +} | ||
| +const paint = (c: Color): string => c; | ||
| +paint(Color.Red); | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +type Color = "red" | "green"; | ||
| +const paint = (c: Color): string => c; | ||
| +paint("red"); | ||
| +``` | ||
| + | ||
| +Hint: Use a union of string literals: type Color = "Red" | "Green". | ||
| + | ||
| +Fix: `tsus fix --unsafe` applies it; review the change, it can alter behavior. | ||
| + | ||
| +## TSUS405 no-loose-equality | ||
| + | ||
| +**== and != are banned.** == coerces its operands ("1" == 1, "" == 0), which is almost never intended. With null and undefined gone, the one idiom that needed it (x == null) is gone too. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const isAdmin = (role: string): boolean => role == "admin"; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const isAdmin = (role: string): boolean => role === "admin"; | ||
| +``` | ||
| + | ||
| +Hint: Use === or !==. | ||
| + | ||
| +Fix: `tsus fix` applies it (behavior is kept). | ||
| + | ||
| +## TSUS406 no-default-export | ||
| + | ||
| +**Default exports are banned outside boundary files.** A default export has no name, so every importer invents one and grep, rename and auto-import all get weaker. Named exports keep one name for one thing. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +export default function greet(name: string): string { | ||
| + return `hi ${name}`; | ||
| +} | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +export function greet(name: string): string { | ||
| + return `hi ${name}`; | ||
| +} | ||
| +``` | ||
| + | ||
| +Hint: Use a named export. Hosts that require a default export (Workers, framework pages) get a *.boundary.tsus file. | ||
| + | ||
| +Fix: `tsus fix --unsafe` applies it; review the change, it can alter behavior. | ||
| + | ||
| +## TSUS407 no-param-reassign | ||
| + | ||
| +**Reassigning a parameter is banned.** After a parameter is reassigned, the name no longer means what the caller passed, and every reader has to track which assignment is live. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const clamp = (n: number, max: number): number => { | ||
| + if (n > max) { | ||
| + n = max; | ||
| + } | ||
| + return n; | ||
| +}; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const clamp = (n: number, max: number): number => { | ||
| + const clamped = n > max ? max : n; | ||
| + return clamped; | ||
| +}; | ||
| +``` | ||
| + | ||
| +Hint: Introduce a new const with a descriptive name. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS408 prefer-const | ||
| + | ||
| +**let that is never reassigned.** let tells the reader to expect reassignment. When none happens the keyword is a false signal, and const lets the compiler hold the line. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +let total = 0; | ||
| +console.log(total); | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const total = 0; | ||
| +console.log(total); | ||
| +``` | ||
| + | ||
| +Hint: Replace let with const. | ||
| + | ||
| +Fix: `tsus fix` applies it (behavior is kept). | ||
| + | ||
| +## TSUS409 no-param-mutation | ||
| + | ||
| +**Mutating a parameter is banned.** A function that mutates its argument changes data the caller still holds, which is spooky action at a distance. Returning new values keeps every function's effect visible in its return type. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const addItem = (cart: string[], item: string): string[] => { | ||
| + cart.push(item); | ||
| + return cart; | ||
| +}; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const addItem = (cart: string[], item: string): string[] => [...cart, item]; | ||
| +``` | ||
| + | ||
| +Hint: Return a new value instead: spread objects ({ ...p, x }), and use toSorted/toReversed/toSpliced or [...xs, item] for arrays. | ||
| + | ||
| +Fix: `tsus fix --unsafe` applies it; review the change, it can alter behavior. | ||
| + | ||
| +## TSUS410 tagged-errors | ||
| + | ||
| +**Result error types must be tagged.** Result<T, string> or Result<T, Error> says that something failed but not what, so callers cannot match on the cases. A tagged error type is a closed set the caller can handle exhaustively. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const load = (id: string): Result<User, string> => | ||
| + id === "" ? Err("missing id") : Ok({ id }); | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +type LoadError = "missing id" | Tagged<"NotFound", string>; | ||
| + | ||
| +const load = (id: string): Result<User, LoadError> => | ||
| + id === "" ? Err("missing id") : Ok({ id }); | ||
| +``` | ||
| + | ||
| +Hint: Use literals (Result<T, "not found" | "timeout">) or tagged variants (Tagged<"NotFound", string> | { tag: "Timeout"; ms: number }). | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS411 no-floating-promise | ||
| + | ||
| +**Floating promises are banned.** A promise nobody awaits loses its result and its rejection. The work races the rest of the program and failures vanish. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const save = async (row: Row): Promise<Result<true, SaveError>> => write(row); | ||
| + | ||
| +const handler = async (row: Row): Promise<string> => { | ||
| + save(row); | ||
| + return "done"; | ||
| +}; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const handler = async (row: Row): Promise<string> => | ||
| + match (await save(row)) { | ||
| + Ok(_) => "done", | ||
| + Err(e) => `failed: ${e.tag}`, | ||
| + }; | ||
| +``` | ||
| + | ||
| +Hint: await it, return it, or hand it to something that owns it (for example ctx.waitUntil(promise)). | ||
| + | ||
| +Fix: `tsus fix --unsafe` applies it; review the change, it can alter behavior. | ||
| + | ||
| +## TSUS412 no-unused-result | ||
| + | ||
| +**Unused Result.** A Result carries the failure case. Calling a function that returns one and dropping it is the same bug as an empty catch block. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +const run = (): string => { | ||
| + saveConfig(config); | ||
| + return "saved"; | ||
| +}; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +const run = (): string => | ||
| + match (saveConfig(config)) { | ||
| + Ok(_) => "saved", | ||
| + Err(e) => `not saved: ${e}`, | ||
| + }; | ||
| +``` | ||
| + | ||
| +Hint: match on it, propagate it with ?, or return it. | ||
| + | ||
| +Fix: No automatic fix: the right change depends on intent. | ||
| + | ||
| +## TSUS413 no-ts-suppression | ||
| + | ||
| +**Type-check suppressions are banned.** A suppression comment switches checking off for a line or a file with no record of why, which reopens every hatch the other rules close. | ||
| + | ||
| +Rejected: | ||
| + | ||
| +```ts | ||
| +// @ts-ignore | ||
| +const port: number = process.env.PORT; | ||
| +``` | ||
| + | ||
| +Accepted: | ||
| + | ||
| +```ts | ||
| +import { fromNullable } from "@tsus/runtime/boundary"; | ||
| + | ||
| +const port: number = fromNullable(process.env.PORT).map(Number).unwrapOr(8080); | ||
| +``` | ||
| + | ||
| +Hint: Fix the type error. If outside data is the problem, validate it in a *.boundary.tsus file. | ||
| + | ||
| +Fix: `tsus fix` applies it (behavior is kept). | ||
Changedexamples/03-result-basics/src/main.tsus+1−1
| @@ -1,6 +1,6 @@ | ||
| import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| -const divide = (a: number, b: number): Result<number, string> => | ||
| +const divide = (a: number, b: number): Result<number, "division by zero"> => | ||
| b === 0 ? Err("division by zero") : Ok(a / b); | ||
| console.log(divide(10, 2).unwrapOr(-1)); | ||
Changedexamples/05-match-result/src/main.tsus+13−5
| @@ -1,20 +1,28 @@ | ||
| -import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| +import { Ok, Err, tag, type Result, type Tagged } from "@tsus/runtime"; | ||
| -const parsePort = (raw: string): Result<number, string> => { | ||
| +type PortError = Tagged<"NotANumber", string> | Tagged<"OutOfRange", number>; | ||
| + | ||
| +const parsePort = (raw: string): Result<number, PortError> => { | ||
| const n = Number(raw); | ||
| if (Number.isNaN(n)) { | ||
| - return Err(`not a number: ${raw}`); | ||
| + return Err(tag("NotANumber", raw)); | ||
| } | ||
| if (n < 1 || n > 65535) { | ||
| - return Err(`out of range: ${n}`); | ||
| + return Err(tag("OutOfRange", n)); | ||
| } | ||
| return Ok(n); | ||
| }; | ||
| +const explain = (e: PortError): string => | ||
| + match (e) { | ||
| + NotANumber(raw) => `not a number: ${raw}`, | ||
| + OutOfRange(n) => `out of range: ${n}`, | ||
| + }; | ||
| + | ||
| const report = (raw: string): string => | ||
| match (parsePort(raw)) { | ||
| Ok(port) => `listening on ${port}`, | ||
| - Err(reason) => `bad port (${reason})`, | ||
| + Err(reason) => `bad port (${explain(reason)})`, | ||
| }; | ||
| console.log(report("8080")); | ||
Changedexamples/14-ts-imports-tsus/src/lib.tsus+3−3
| @@ -1,9 +1,9 @@ | ||
| -import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| +import { Ok, Err, tag, type Result, type Tagged } from "@tsus/runtime"; | ||
| -export const parseAge = (raw: string): Result<number, string> => { | ||
| +export const parseAge = (raw: string): Result<number, Tagged<"InvalidAge", string>> => { | ||
| const n = Number(raw); | ||
| if (Number.isNaN(n) || n < 0 || n > 150) { | ||
| - return Err(`invalid age: ${raw}`); | ||
| + return Err(tag("InvalidAge", raw)); | ||
| } | ||
| return Ok(n); | ||
| }; | ||
Changedexamples/15-npm-dependency/src/main.tsus+4−4
| @@ -1,5 +1,5 @@ | ||
| import { z } from "zod"; | ||
| -import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| +import { Ok, Err, tag, type Result, type Tagged } from "@tsus/runtime"; | ||
| const UserSchema = z.object({ | ||
| name: z.string(), | ||
| @@ -8,9 +8,9 @@ | ||
| type User = z.infer<typeof UserSchema>; | ||
| -const parseUser = (input: unknown): Result<User, string> => { | ||
| +const parseUser = (input: unknown): Result<User, Tagged<"InvalidUser", string>> => { | ||
| const outcome = UserSchema.safeParse(input); | ||
| - return outcome.success ? Ok(outcome.data) : Err(outcome.error.issues[0].message); | ||
| + return outcome.success ? Ok(outcome.data) : Err(tag("InvalidUser", outcome.error.issues[0].message)); | ||
| }; | ||
| const good = parseUser({ name: "justin", age: 30 }); | ||
| @@ -18,7 +18,7 @@ | ||
| console.log(match (good) { | ||
| Ok(u) => `${u.name} is ${u.age}`, | ||
| - Err(e) => `rejected: ${e}`, | ||
| + Err(e) => `rejected: ${e.value}`, | ||
| }); | ||
| console.log(match (bad) { | ||
| Ok(u) => `${u.name} is ${u.age}`, | ||
Changedexamples/17-nested-match/src/main.tsus+1−1
| @@ -2,7 +2,7 @@ | ||
| type Config = { retries: Option<number> }; | ||
| -const loadConfig = (raw: string): Result<Config, string> => { | ||
| +const loadConfig = (raw: string): Result<Config, "empty config"> => { | ||
| if (raw === "") { | ||
| return Err("empty config"); | ||
| } | ||
Changedexamples/18-generics/src/main.tsus+1−1
| @@ -12,7 +12,7 @@ | ||
| const zip = <A, B>(a: Option<A>, b: Option<B>): Option<[A, B]> => | ||
| a.andThen((va) => b.map((vb): [A, B] => [va, vb])); | ||
| -const attempts: Result<number, string>[] = [Err("cold"), Err("colder"), Ok(7), Ok(9)]; | ||
| +const attempts: Result<number, "cold" | "colder">[] = [Err("cold"), Err("colder"), Ok(7), Ok(9)]; | ||
| console.log(firstOk(attempts).unwrapOr(-1)); | ||
| console.log(firstOk<number, string>([Err("a"), Err("b")]).unwrapOr(-1)); | ||
Changedexamples/19-async-result/src/main.tsus+5−5
| @@ -1,8 +1,8 @@ | ||
| -import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| +import { Ok, Err, tag, type Result, type Tagged } from "@tsus/runtime"; | ||
| -const fakeFetch = async (path: string): Promise<Result<string, string>> => { | ||
| +const fakeFetch = async (path: string): Promise<Result<string, Tagged<"NotFound", string>>> => { | ||
| await Promise.resolve(); | ||
| - return path === "/ok" ? Ok("payload") : Err(`404 ${path}`); | ||
| + return path === "/ok" ? Ok("payload") : Err(tag("NotFound", path)); | ||
| }; | ||
| const enrich = async (body: string): Promise<string> => { | ||
| @@ -15,11 +15,11 @@ | ||
| const goodMsg = await match (good) { | ||
| Ok(body) => await enrich(body), | ||
| - Err(e) => `failed: ${e}`, | ||
| + Err(e) => `failed: 404 ${e.value}`, | ||
| }; | ||
| const badMsg = await match (bad) { | ||
| Ok(body) => await enrich(body), | ||
| - Err(e) => `failed: ${e}`, | ||
| + Err(e) => `failed: 404 ${e.value}`, | ||
| }; | ||
| console.log(goodMsg); | ||
Changedexamples/22-mixed-project/src/repo.tsus+2−2
| @@ -1,7 +1,7 @@ | ||
| import { fromNullable } from "@tsus/runtime/boundary"; | ||
| import { type Option, type Result } from "@tsus/runtime"; | ||
| import { getRow } from "./store.ts"; | ||
| -import { validateRow, type Row } from "./validate.tsus"; | ||
| +import { validateRow, type Row, type RowError } from "./validate.tsus"; | ||
| -export const loadRow = (id: number): Option<Result<Row, string>> => | ||
| +export const loadRow = (id: number): Option<Result<Row, RowError>> => | ||
| fromNullable(getRow(id)).map(validateRow); | ||
Changedexamples/22-mixed-project/src/validate.tsus+2−1
| @@ -4,8 +4,9 @@ | ||
| const RowSchema = z.object({ name: z.string().min(1), age: z.number().min(18) }); | ||
| export type Row = z.infer<typeof RowSchema>; | ||
| +export type RowError = "invalid row"; | ||
| -export const validateRow = (input: unknown): Result<Row, string> => { | ||
| +export const validateRow = (input: unknown): Result<Row, RowError> => { | ||
| const outcome = RowSchema.safeParse(input); | ||
| return outcome.success ? Ok(outcome.data) : Err("invalid row"); | ||
| }; | ||
Changedexamples/23-cloudflare-worker/example.json+1−1
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "expect": "worker", | ||
| - "entry": "worker.js", | ||
| + "entry": "worker.boundary.js", | ||
| "requests": [ | ||
| { "path": "/", "status": 200, "body": "home sweet home" }, | ||
| { "path": "/health", "status": 200, "body": "ok" }, | ||
Addedexamples/23-cloudflare-worker/src/worker.boundary.tsus+15−0
| @@ -0,0 +1,15 @@ | ||
| +import { route } from "./router.tsus"; | ||
| + | ||
| +// Cloudflare Workers module shape: export default { fetch }. The runtime | ||
| +// requires a default export, so this file is a boundary file (*.boundary.tsus), | ||
| +// where default exports and casts are allowed. The routing logic stays in | ||
| +// router.tsus under the full rules. | ||
| +export default { | ||
| + fetch: async (request: Request): Promise<Response> => { | ||
| + const url = new URL(request.url); | ||
| + return match (route(url.pathname)) { | ||
| + Some(body) => new Response(body, { status: 200 }), | ||
| + None => new Response("not found", { status: 404 }), | ||
| + }; | ||
| + }, | ||
| +}; | ||
Removedexamples/23-cloudflare-worker/src/worker.tsus+0−12
| @@ -1,12 +0,0 @@ | ||
| -import { route } from "./router.tsus"; | ||
| - | ||
| -// Cloudflare Workers module shape: export default { fetch }. | ||
| -export default { | ||
| - fetch: async (request: Request): Promise<Response> => { | ||
| - const url = new URL(request.url); | ||
| - return match (route(url.pathname)) { | ||
| - Some(body) => new Response(body, { status: 200 }), | ||
| - None => new Response("not found", { status: 404 }), | ||
| - }; | ||
| - }, | ||
| -}; | ||
Changedexamples/28-astro/src/lib/banner.tsus+1−1
| @@ -1,7 +1,7 @@ | ||
| import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| import { suffix } from "./suffix.tsus"; | ||
| -const checkFramework = (name: string): Result<string, string> => | ||
| +const checkFramework = (name: string): Result<string, "unnamed framework"> => | ||
| name.length > 0 ? Ok(name) : Err("unnamed framework"); | ||
| export const headline = (name: string): string => | ||
Addedexamples/40-banned-any/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS401"], "fixable": ["TSUS401"] } | ||
Addedexamples/40-banned-any/src/main.tsus+4−0
| @@ -0,0 +1,4 @@ | ||
| +// any switches the checker off. tsus fix rewrites it to unknown. | ||
| +const parse = (raw: string): any => JSON.parse(raw); | ||
| + | ||
| +console.log(parse("{}")); | ||
Addedexamples/41-banned-as-cast/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS402"] } | ||
Addedexamples/41-banned-as-cast/src/main.tsus+8−0
| @@ -0,0 +1,8 @@ | ||
| +// A cast is an unchecked claim. `as const` is fine; anything else belongs in | ||
| +// a *.boundary.tsus file (see example 53). | ||
| +type User = { name: string }; | ||
| + | ||
| +const user = JSON.parse('{"name":"ada"}') as User; | ||
| +const roles = ["admin", "user"] as const; | ||
| + | ||
| +console.log(user.name, roles.length); | ||
Addedexamples/42-banned-non-null/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS403"] } | ||
Addedexamples/42-banned-non-null/src/main.tsus+4−0
| @@ -0,0 +1,4 @@ | ||
| +// x! asserts presence without proving it. Use Option and match instead. | ||
| +const first = (xs: string[]): string => xs.find((x) => x.length > 0)!; | ||
| + | ||
| +console.log(first(["", "a"])); | ||
Addedexamples/43-banned-enum/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS404"], "fixable": ["TSUS404"] } | ||
Addedexamples/43-banned-enum/src/main.tsus+10−0
| @@ -0,0 +1,10 @@ | ||
| +// enum emits runtime code and does not narrow. tsus fix --unsafe rewrites it | ||
| +// to a union of literals and inlines Color.Red as "red". | ||
| +enum Color { | ||
| + Red = "red", | ||
| + Green = "green", | ||
| +} | ||
| + | ||
| +const paint = (c: Color): string => `painted ${c}`; | ||
| + | ||
| +console.log(paint(Color.Red)); | ||
Addedexamples/44-banned-loose-equality/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS405"], "fixable": ["TSUS405"] } | ||
Addedexamples/44-banned-loose-equality/src/main.tsus+5−0
| @@ -0,0 +1,5 @@ | ||
| +// == coerces ("1" == 1). tsus fix rewrites to === and !==. | ||
| +const isAdmin = (role: string): boolean => role == "admin"; | ||
| +const isGuest = (role: string): boolean => role != "member"; | ||
| + | ||
| +console.log(isAdmin("admin"), isGuest("member")); | ||
Addedexamples/45-banned-default-export/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS406"], "fixable": ["TSUS406"] } | ||
Addedexamples/45-banned-default-export/src/main.tsus+5−0
| @@ -0,0 +1,5 @@ | ||
| +// Default exports have no name. Use a named export; hosts that insist on a | ||
| +// default export get a *.boundary.tsus file (see example 23). | ||
| +export default function greet(name: string): string { | ||
| + return `hi ${name}`; | ||
| +} | ||
Addedexamples/46-banned-param-reassign/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS407"] } | ||
Addedexamples/46-banned-param-reassign/src/main.tsus+9−0
| @@ -0,0 +1,9 @@ | ||
| +// After `n = max` the name n no longer means what the caller passed. | ||
| +const clamp = (n: number, max: number): number => { | ||
| + if (n > max) { | ||
| + n = max; | ||
| + } | ||
| + return n; | ||
| +}; | ||
| + | ||
| +console.log(clamp(12, 10)); | ||
Addedexamples/47-banned-let-never-reassigned/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS408"], "fixable": ["TSUS408"] } | ||
Addedexamples/47-banned-let-never-reassigned/src/main.tsus+5−0
| @@ -0,0 +1,5 @@ | ||
| +// let promises a reassignment that never comes. tsus fix makes it const. | ||
| +let total = 0; | ||
| +for (let n of [1, 2, 3]) { | ||
| + console.log(total + n); | ||
| +} | ||
Addedexamples/48-banned-param-mutation/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS409"] } | ||
Addedexamples/48-banned-param-mutation/src/main.tsus+10−0
| @@ -0,0 +1,10 @@ | ||
| +// Mutating an argument changes data the caller still holds. | ||
| +type Cart = { items: string[]; total: number }; | ||
| + | ||
| +const addItem = (cart: Cart, item: string, price: number): Cart => { | ||
| + cart.items.push(item); | ||
| + cart.total += price; | ||
| + return cart; | ||
| +}; | ||
| + | ||
| +console.log(addItem({ items: [], total: 0 }, "tea", 3).total); | ||
Addedexamples/49-banned-untagged-error/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS410"] } | ||
Addedexamples/49-banned-untagged-error/src/main.tsus+9−0
| @@ -0,0 +1,9 @@ | ||
| +// Result<T, string> says something failed, not what. Callers cannot match on it. | ||
| +import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| + | ||
| +const parsePort = (raw: string): Result<number, string> => { | ||
| + const n = Number(raw); | ||
| + return Number.isNaN(n) ? Err(`not a number: ${raw}`) : Ok(n); | ||
| +}; | ||
| + | ||
| +console.log(parsePort("80").unwrapOr(0)); | ||
Addedexamples/50-banned-floating-promise/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS411"], "fixable": ["TSUS411"] } | ||
Addedexamples/50-banned-floating-promise/src/main.tsus+12−0
| @@ -0,0 +1,12 @@ | ||
| +// The promise from save() is never awaited: its result and any failure vanish. | ||
| +const save = async (row: string): Promise<string> => { | ||
| + await Promise.resolve(); | ||
| + return row; | ||
| +}; | ||
| + | ||
| +const handler = async (row: string): Promise<string> => { | ||
| + save(row); | ||
| + return "done"; | ||
| +}; | ||
| + | ||
| +console.log(await handler("r1")); | ||
Addedexamples/51-banned-unused-result/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS412"] } | ||
Addedexamples/51-banned-unused-result/src/main.tsus+11−0
| @@ -0,0 +1,11 @@ | ||
| +// saveConfig returns a Result; calling it as a statement drops the failure. | ||
| +import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| + | ||
| +const saveConfig = (body: string): Result<true, "empty config"> => (body === "" ? Err("empty config") : Ok(true)); | ||
| + | ||
| +const run = (body: string): string => { | ||
| + saveConfig(body); | ||
| + return "saved"; | ||
| +}; | ||
| + | ||
| +console.log(run("")); | ||
Addedexamples/52-banned-ts-suppression/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "check-fail", "codes": ["TSUS413"], "fixable": ["TSUS413"] } | ||
Addedexamples/52-banned-ts-suppression/src/main.tsus+5−0
| @@ -0,0 +1,5 @@ | ||
| +// A suppression comment reopens every hatch the other rules close. | ||
| +// @ts-expect-error the checker is right and we are wrong | ||
| +const port: number = "8080"; | ||
| + | ||
| +console.log(port); | ||
Addedexamples/53-boundary-file/example.json+1−0
| @@ -0,0 +1 @@ | ||
| +{ "expect": "run", "output": ["localhost:8080", "config error: invalid shape", "config error: unparseable"] } | ||
Addedexamples/53-boundary-file/src/config.boundary.tsus+22−0
| @@ -0,0 +1,22 @@ | ||
| +// A boundary file (*.boundary.tsus): the one place where outside data is | ||
| +// trusted after a runtime check. Casts (TSUS402) and default exports | ||
| +// (TSUS406) are allowed here; every other rule still applies. | ||
| +import { Ok, Err, type Result } from "@tsus/runtime"; | ||
| +import { wrapSync } from "@tsus/runtime/boundary"; | ||
| + | ||
| +export type Config = { readonly port: number; readonly host: string }; | ||
| + | ||
| +export type ConfigError = "unparseable" | "invalid shape"; | ||
| + | ||
| +const parseJson = wrapSync(JSON.parse); | ||
| + | ||
| +const looksLikeConfig = (value: unknown): boolean => { | ||
| + const fields = Object(value) as { port?: unknown; host?: unknown }; | ||
| + return typeof fields.port === "number" && typeof fields.host === "string"; | ||
| +}; | ||
| + | ||
| +export const loadConfig = (raw: string): Result<Config, ConfigError> => | ||
| + match (parseJson(raw)) { | ||
| + Ok(data) => (looksLikeConfig(data) ? Ok(data as Config) : Err("invalid shape")), | ||
| + Err(e) => Err("unparseable"), | ||
| + }; | ||
Addedexamples/53-boundary-file/src/main.tsus+12−0
| @@ -0,0 +1,12 @@ | ||
| +// Ordinary .tsus code: no casts, just a typed Result from the boundary. | ||
| +import { loadConfig } from "./config.boundary.tsus"; | ||
| + | ||
| +const show = (raw: string): string => | ||
| + match (loadConfig(raw)) { | ||
| + Ok(config) => `${config.host}:${config.port}`, | ||
| + Err(e) => `config error: ${e}`, | ||
| + }; | ||
| + | ||
| +console.log(show('{"port":8080,"host":"localhost"}')); | ||
| +console.log(show('{"port":"eighty"}')); | ||
| +console.log(show("{oops")); | ||
Addedexamples/54-fix-roundtrip/example.json+6−0
| @@ -0,0 +1,6 @@ | ||
| +{ | ||
| + "expect": "fix", | ||
| + "applied": ["TSUS004", "TSUS401", "TSUS405", "TSUS405", "TSUS405", "TSUS408", "TSUS408", "TSUS413"], | ||
| + "golden": { "src/main.tsus": "expected/main.tsus" }, | ||
| + "output": ["hello ada, also known as countess", "hello grace", "visits ok", "{\"name\":\"ada\",\"visits\":3}"] | ||
| +} | ||
Addedexamples/54-fix-roundtrip/expected/main.tsus+32−0
| @@ -0,0 +1,32 @@ | ||
| +// Every problem in this file has a safe fix. The harness copies the project, | ||
| +// runs `tsus fix`, compares the result with expected/main.tsus, then builds | ||
| +// and runs it. Several fixes sit inside match arms, so their edits have to | ||
| +// map back through the macro expansion. | ||
| +import { Some, None, type Option } from "@tsus/runtime"; | ||
| + | ||
| +const greeting = "hello"; | ||
| + | ||
| +const raw: unknown = JSON.parse('{"name":"ada","visits":3}'); | ||
| + | ||
| +const nickname = (name: string): Option<string> => (name === "ada" ? Some("countess") : None); | ||
| + | ||
| +const plainGreeting = (name: string): string => { | ||
| + const text = `${greeting} ${name}`; | ||
| + return text; | ||
| +}; | ||
| + | ||
| +const describe = (name: string): string => | ||
| + match (nickname(name)) { | ||
| + Some(nick) => `${greeting} ${name}, also known as ${nick}`, | ||
| + None => (plainGreeting(name) === "" ? "nobody" : plainGreeting(name)), | ||
| + }; | ||
| + | ||
| +let visits = 0; | ||
| +for (const n of [1, 2]) { | ||
| + visits += n; | ||
| +} | ||
| + | ||
| +console.log(describe("ada")); | ||
| +console.log(describe("grace")); | ||
| +console.log(visits !== 3 ? "miscounted" : "visits ok"); | ||
| +console.log(JSON.stringify(raw)); | ||
Addedexamples/54-fix-roundtrip/src/main.tsus+33−0
| @@ -0,0 +1,33 @@ | ||
| +// Every problem in this file has a safe fix. The harness copies the project, | ||
| +// runs `tsus fix`, compares the result with expected/main.tsus, then builds | ||
| +// and runs it. Several fixes sit inside match arms, so their edits have to | ||
| +// map back through the macro expansion. | ||
| +import { Some, None, type Option } from "@tsus/runtime"; | ||
| + | ||
| +var greeting = "hello"; | ||
| + | ||
| +// @ts-ignore | ||
| +const raw: any = JSON.parse('{"name":"ada","visits":3}'); | ||
| + | ||
| +const nickname = (name: string): Option<string> => (name == "ada" ? Some("countess") : None); | ||
| + | ||
| +const plainGreeting = (name: string): string => { | ||
| + let text = `${greeting} ${name}`; | ||
| + return text; | ||
| +}; | ||
| + | ||
| +const describe = (name: string): string => | ||
| + match (nickname(name)) { | ||
| + Some(nick) => `${greeting} ${name}, also known as ${nick}`, | ||
| + None => (plainGreeting(name) == "" ? "nobody" : plainGreeting(name)), | ||
| + }; | ||
| + | ||
| +let visits = 0; | ||
| +for (let n of [1, 2]) { | ||
| + visits += n; | ||
| +} | ||
| + | ||
| +console.log(describe("ada")); | ||
| +console.log(describe("grace")); | ||
| +console.log(visits != 3 ? "miscounted" : "visits ok"); | ||
| +console.log(JSON.stringify(raw)); | ||
Addedexamples/55-migrate/example.json+13−0
| @@ -0,0 +1,13 @@ | ||
| +{ | ||
| + "expect": "migrate", | ||
| + "migrate": [ | ||
| + { "input": "src/inventory.ts", "golden": "expected/inventory.tsus", "todo": [] }, | ||
| + { | ||
| + "input": "legacy/orders.ts", | ||
| + "golden": "expected/orders.tsus", | ||
| + "todo": ["class", "check:TSUS001", "throw", "check:TSUS005", "caller"] | ||
| + } | ||
| + ], | ||
| + "remove": ["src/inventory.ts"], | ||
| + "output": ["tea x12", "true", "cocoa x2 (low)", "qty 5", "not a number", "negative quantity: -1"] | ||
| +} | ||
Addedexamples/55-migrate/expected/inventory.tsus+37−0
| @@ -0,0 +1,37 @@ | ||
| +// A legacy inventory module written before tsus: a class, var, nullable | ||
| +// returns and throws. `tsus migrate src/inventory.ts` converts all of it; | ||
| +// expected/inventory.tsus is the exact output. | ||
| +import { Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| +import { fromNullable } from "@tsus/runtime/boundary"; | ||
| + | ||
| +const LOW_STOCK = 3; | ||
| + | ||
| +export type Item = { readonly sku: string; readonly qty: number }; | ||
| + | ||
| +export const createItem = (sku: string, qty: number): Item => ({ sku, qty }); | ||
| + | ||
| +export const itemIsLow = (self: Item): boolean => { | ||
| + return self.qty < LOW_STOCK; | ||
| +}; | ||
| + | ||
| +export const itemLabel = (self: Item): string => { | ||
| + return `${self.sku} x${self.qty}${itemIsLow(self) ? " (low)" : ""}`; | ||
| +}; | ||
| + | ||
| +export function findItem(items: Item[], sku: string): Option<Item> { | ||
| + const hit = items.find((it) => it.sku === sku); | ||
| + return fromNullable(hit); | ||
| +} | ||
| + | ||
| +export const firstLow = (items: Item[]): Option<Item> => fromNullable(items.find((it) => itemIsLow(it))); | ||
| + | ||
| +export function parseQty(raw: string): Result<number, "not a number" | { tag: "RangeError"; message: string }> { | ||
| + const n = Number(raw); | ||
| + if (Number.isNaN(n)) { | ||
| + return Err("not a number"); | ||
| + } | ||
| + if (n < 0) { | ||
| + return Err({ tag: "RangeError", message: `negative quantity: ${n}` }); | ||
| + } | ||
| + return Ok(n); | ||
| +} | ||
Addedexamples/55-migrate/expected/orders.tsus+38−0
| @@ -0,0 +1,38 @@ | ||
| +// Things the codemod converts only partly; the report lists the rest. | ||
| +import { Ok, Err, type Option, type Result } from "@tsus/runtime"; | ||
| +import { fromNullable } from "@tsus/runtime/boundary"; | ||
| + | ||
| +let orderCount = 0; | ||
| + | ||
| +export class Cart { | ||
| + items: string[] = []; | ||
| + | ||
| + add(sku: string): void { | ||
| + this.items.push(sku); | ||
| + } | ||
| +} | ||
| + | ||
| +export function lookup(codes: Map<string, string>, key: string): Option<string> { | ||
| + return fromNullable(codes.get(key)); | ||
| +} | ||
| + | ||
| +export function total(prices: number[]): number { | ||
| + try { | ||
| + if (prices.length === 0) { | ||
| + throw new Error("no prices"); | ||
| + } | ||
| + return prices.reduce((a, b) => a + b, 0); | ||
| + } catch (e) { | ||
| + return 0; | ||
| + } | ||
| +} | ||
| + | ||
| +export function requirePositive(n: number): Result<true, "not positive"> { | ||
| + if (n <= 0) { | ||
| + return Err("not positive"); | ||
| + } | ||
| + orderCount = orderCount + 1; | ||
| + return Ok(true); | ||
| +} | ||
| + | ||
| +export const describe = (codes: Map<string, string>): string => lookup(codes, "a") ?? "none"; | ||
Addedexamples/55-migrate/legacy/orders.ts+34−0
| @@ -0,0 +1,34 @@ | ||
| +// Things the codemod converts only partly; the report lists the rest. | ||
| +var orderCount = 0; | ||
| + | ||
| +export class Cart { | ||
| + items: string[] = []; | ||
| + | ||
| + add(sku: string): void { | ||
| + this.items.push(sku); | ||
| + } | ||
| +} | ||
| + | ||
| +export function lookup(codes: Map<string, string>, key: string): string | undefined { | ||
| + return codes.get(key); | ||
| +} | ||
| + | ||
| +export function total(prices: number[]): number { | ||
| + try { | ||
| + if (prices.length === 0) { | ||
| + throw new Error("no prices"); | ||
| + } | ||
| + return prices.reduce((a, b) => a + b, 0); | ||
| + } catch (e) { | ||
| + return 0; | ||
| + } | ||
| +} | ||
| + | ||
| +export function requirePositive(n: number): void { | ||
| + if (n <= 0) { | ||
| + throw "not positive"; | ||
| + } | ||
| + orderCount = orderCount + 1; | ||
| +} | ||
| + | ||
| +export const describe = (codes: Map<string, string>): string => lookup(codes, "a") ?? "none"; | ||
Addedexamples/55-migrate/src/inventory.ts+34−0
| @@ -0,0 +1,34 @@ | ||
| +// A legacy inventory module written before tsus: a class, var, nullable | ||
| +// returns and throws. `tsus migrate src/inventory.ts` converts all of it; | ||
| +// expected/inventory.tsus is the exact output. | ||
| +var LOW_STOCK = 3; | ||
| + | ||
| +export class Item { | ||
| + constructor(public readonly sku: string, public readonly qty: number) {} | ||
| + | ||
| + isLow(): boolean { | ||
| + return this.qty < LOW_STOCK; | ||
| + } | ||
| + | ||
| + label(): string { | ||
| + return `${this.sku} x${this.qty}${this.isLow() ? " (low)" : ""}`; | ||
| + } | ||
| +} | ||
| + | ||
| +export function findItem(items: Item[], sku: string): Item | null { | ||
| + const hit = items.find((it) => it.sku === sku); | ||
| + return hit === undefined ? null : hit; | ||
| +} | ||
| + | ||
| +export const firstLow = (items: Item[]): Item | undefined => items.find((it) => it.isLow()); | ||
| + | ||
| +export function parseQty(raw: string): number { | ||
| + const n = Number(raw); | ||
| + if (Number.isNaN(n)) { | ||
| + throw new Error("not a number"); | ||
| + } | ||
| + if (n < 0) { | ||
| + throw new RangeError(`negative quantity: ${n}`); | ||
| + } | ||
| + return n; | ||
| +} | ||
Addedexamples/55-migrate/src/main.tsus+25−0
| @@ -0,0 +1,25 @@ | ||
| +// Written against the migrated module: findItem and firstLow now return | ||
| +// Option, parseQty returns Result, and Item is plain data plus functions. | ||
| +import { createItem, itemLabel, findItem, firstLow, parseQty } from "./inventory.tsus"; | ||
| + | ||
| +const stock = [createItem("tea", 12), createItem("cocoa", 2)]; | ||
| + | ||
| +console.log(match (findItem(stock, "tea")) { | ||
| + Some(item) => itemLabel(item), | ||
| + None => "no tea", | ||
| +}); | ||
| +console.log(findItem(stock, "coffee").isNone()); | ||
| +console.log(firstLow(stock).map(itemLabel).unwrapOr("nothing low")); | ||
| + | ||
| +const describeQty = (raw: string): string => | ||
| + match (parseQty(raw)) { | ||
| + Ok(n) => `qty ${n}`, | ||
| + Err(e) => match (e) { | ||
| + "not a number" => "not a number", | ||
| + RangeError(err) => err.message, | ||
| + }, | ||
| + }; | ||
| + | ||
| +console.log(describeQty("5")); | ||
| +console.log(describeQty("lots")); | ||
| +console.log(describeQty("-1")); | ||
Addedexamples/56-init/example.json+5−0
| @@ -0,0 +1,5 @@ | ||
| +{ | ||
| + "expect": "init", | ||
| + "files": ["AGENTS.md", "CLAUDE.md", "tsconfig.json", "package.json", ".gitignore", "src/main.tsus"], | ||
| + "output": ["ada <ada@example.com>", "grace (no email)", "no user named linus"] | ||
| +} | ||
Changedpackage.json+4−1
| @@ -6,7 +6,10 @@ | ||
| "packages/*" | ||
| ], | ||
| "scripts": { | ||
| - "examples": "node scripts/run-examples.mjs" | ||
| + "examples": "node scripts/run-examples.mjs", | ||
| + "docs": "node scripts/docs.mjs", | ||
| + "docs:check": "node scripts/docs.mjs --check", | ||
| + "test": "node scripts/docs.mjs --check && node scripts/run-examples.mjs" | ||
| }, | ||
| "dependencies": { | ||
| "typescript": "^5.5.0", | ||
Changedpackages/cli/bin/tsus.js+138−9
| @@ -1,40 +1,74 @@ | ||
| #!/usr/bin/env node | ||
| -// tsus CLI: `tsus check [dir]` and `tsus build [dir]`, both with --json. | ||
| -// Diagnostics are machine-first: stable codes, JSON mode, human text is a | ||
| -// rendering of the same data. | ||
| +// tsus CLI. Diagnostics are machine-first: stable codes, JSON mode, exact | ||
| +// fix edits; human text is a rendering of the same data. | ||
| +// | ||
| +// tsus check [dir] [--json] | ||
| +// tsus build [dir] [--json] | ||
| +// tsus fix [dir] [--unsafe] [--dry-run] [--code TSUSnnn] [--json] | ||
| +// tsus explain <CODE> [--json] | tsus explain --list | ||
| +// tsus init [dir] [--force] | ||
| +// tsus migrate <file.ts> [--stdout] [--force] [--json] | ||
| +import fs from "node:fs"; | ||
| import path from "node:path"; | ||
| import process from "node:process"; | ||
| import { checkProject, buildProject } from "../src/build.js"; | ||
| +const USAGE = `usage: | ||
| + tsus check [dir] [--json] check every .tsus file under dir/src | ||
| + tsus build [dir] [--json] check, then compile src/ to dist/ | ||
| + tsus fix [dir] [--unsafe] [--dry-run] [--code TSUSnnn] [--json] | ||
| + apply the fixes check reports (safe ones by default) | ||
| + tsus explain <CODE> [--json] the rule, why it exists, bad and good examples | ||
| + tsus explain --list every code | ||
| + tsus init [dir] [--force] scaffold AGENTS.md, tsconfig.json, package.json, src/main.tsus | ||
| + tsus migrate <file.ts> [--stdout] [--force] [--json] | ||
| + convert a .ts file and write <file>.tsus next to it`; | ||
| + | ||
| const usage = () => { | ||
| - console.error("usage: tsus <check|build> [dir] [--json]"); | ||
| + console.error(USAGE); | ||
| process.exit(2); | ||
| }; | ||
| const args = process.argv.slice(2); | ||
| const command = args[0]; | ||
| const json = args.includes("--json"); | ||
| -const dirArg = args.slice(1).find((a) => !a.startsWith("--")) ?? "."; | ||
| +const flag = (name) => args.includes(name); | ||
| +const option = (name) => { | ||
| + const i = args.indexOf(name); | ||
| + return i === -1 ? undefined : args[i + 1]; | ||
| +}; | ||
| +const positional = args.slice(1).filter((a, i, all) => !a.startsWith("--") && all[i] !== option("--code")); | ||
| +const dirArg = positional[0] ?? "."; | ||
| const rootDir = path.resolve(dirArg); | ||
| +// Diagnostics produced outside the rules pipeline (macro errors) get the | ||
| +// same shape as the rest. | ||
| +const normalize = (d) => ({ explain: `tsus explain ${d.code}`, fix: null, ...d }); | ||
| + | ||
| const renderHuman = (diagnostics) => { | ||
| for (const d of diagnostics) { | ||
| const ts = d.tsCode ? ` [TS${d.tsCode}]` : ""; | ||
| console.error(`error ${d.code}${ts}: ${d.message}`); | ||
| console.error(` --> ${d.file}:${d.line}:${d.col}`); | ||
| console.error(` hint: ${d.hint}`); | ||
| + if (d.fix) { | ||
| + console.error(` fix: ${d.fix.description} (${d.fix.safe ? "tsus fix" : "tsus fix --unsafe"})`); | ||
| + } | ||
| } | ||
| - console.error(`${diagnostics.length} error(s)`); | ||
| + const fixable = diagnostics.filter((d) => d.fix?.safe).length; | ||
| + console.error(`${diagnostics.length} error(s)${fixable ? `, ${fixable} fixable with tsus fix` : ""}`); | ||
| + console.error("run tsus explain <CODE> for the rule behind any code"); | ||
| }; | ||
| const report = (result, extra) => { | ||
| - const ok = result.diagnostics.length === 0; | ||
| + const diagnostics = result.diagnostics.map(normalize); | ||
| + const ok = diagnostics.length === 0; | ||
| if (json) { | ||
| - console.log(JSON.stringify({ ok, diagnostics: result.diagnostics, ...extra }, null, 2)); | ||
| + console.log(JSON.stringify({ ok, diagnostics, ...extra }, null, 2)); | ||
| } else if (ok) { | ||
| console.log(extra?.emitted ? `built ${extra.emitted.length} file(s)` : "check passed"); | ||
| } else { | ||
| - renderHuman(result.diagnostics); | ||
| + renderHuman(diagnostics); | ||
| } | ||
| process.exit(ok ? 0 : 1); | ||
| }; | ||
| @@ -44,6 +78,101 @@ | ||
| } else if (command === "build") { | ||
| const result = buildProject(rootDir); | ||
| report(result, { emitted: result.emitted.map((f) => path.relative(rootDir, f)) }); | ||
| +} else if (command === "fix") { | ||
| + const { fixProject } = await import("../src/fix.js"); | ||
| + const code = option("--code"); | ||
| + const result = fixProject(rootDir, { | ||
| + unsafe: flag("--unsafe"), | ||
| + dryRun: flag("--dry-run"), | ||
| + codes: code ? new Set(code.split(",").map((c) => c.toUpperCase())) : undefined, | ||
| + }); | ||
| + const diagnostics = result.diagnostics.map(normalize); | ||
| + if (json) { | ||
| + console.log(JSON.stringify({ ok: diagnostics.length === 0, applied: result.applied, diagnostics }, null, 2)); | ||
| + } else { | ||
| + const verb = flag("--dry-run") ? "would apply" : "applied"; | ||
| + for (const a of result.applied) { | ||
| + console.log(`${verb} ${a.code} ${a.file}:${a.line}:${a.col} ${a.description}`); | ||
| + } | ||
| + console.log(`${verb} ${result.applied.length} fix(es)`); | ||
| + if (diagnostics.length > 0) { | ||
| + renderHuman(diagnostics); | ||
| + } | ||
| + } | ||
| + process.exit(diagnostics.length === 0 ? 0 : 1); | ||
| +} else if (command === "explain") { | ||
| + const { explain, renderExplainText, renderList } = await import("../src/explain.js"); | ||
| + const { REGISTRY } = await import("../src/rules/registry.js"); | ||
| + if (flag("--list") || positional.length === 0) { | ||
| + console.log(json ? JSON.stringify(REGISTRY, null, 2) : renderList()); | ||
| + process.exit(0); | ||
| + } | ||
| + const rule = explain(positional[0]); | ||
| + if (!rule) { | ||
| + console.error(`unknown code ${positional[0]}; tsus explain --list shows every code`); | ||
| + process.exit(2); | ||
| + } | ||
| + console.log(json ? JSON.stringify(rule, null, 2) : renderExplainText(rule)); | ||
| +} else if (command === "init") { | ||
| + const { initProject } = await import("../src/init.js"); | ||
| + const result = initProject(rootDir, { force: flag("--force") }); | ||
| + if (json) { | ||
| + console.log(JSON.stringify(result, null, 2)); | ||
| + } else { | ||
| + for (const f of result.written) { | ||
| + console.log(`created ${path.join(dirArg, f)}`); | ||
| + } | ||
| + for (const f of result.skipped) { | ||
| + console.log(`kept existing ${path.join(dirArg, f)}`); | ||
| + } | ||
| + console.log("next: npm install, then npm start. Agents: read AGENTS.md first."); | ||
| + } | ||
| +} else if (command === "migrate") { | ||
| + const { migrateSource } = await import("../src/migrate.js"); | ||
| + const file = positional[0] ?? ""; | ||
| + if (!/\.(ts|mts)$/.test(file) || file.endsWith(".d.ts")) { | ||
| + console.error("usage: tsus migrate <file.ts> [--stdout] [--force] [--json]"); | ||
| + process.exit(2); | ||
| + } | ||
| + const input = path.resolve(file); | ||
| + const output = input.replace(/\.(ts|mts)$/, ".tsus"); | ||
| + const result = migrateSource(fs.readFileSync(input, "utf8"), path.basename(input)); | ||
| + const toStdout = flag("--stdout"); | ||
| + if (!toStdout) { | ||
| + if (fs.existsSync(output) && !flag("--force")) { | ||
| + console.error(`${path.relative(process.cwd(), output)} already exists; pass --force to overwrite`); | ||
| + process.exit(2); | ||
| + } | ||
| + fs.writeFileSync(output, result.code); | ||
| + } | ||
| + const summary = { | ||
| + input: path.relative(process.cwd(), input), | ||
| + output: toStdout ? "-" : path.relative(process.cwd(), output), | ||
| + converted: result.converted, | ||
| + unconverted: result.unconverted, | ||
| + notes: result.notes, | ||
| + }; | ||
| + if (json) { | ||
| + console.log(JSON.stringify(summary, null, 2)); | ||
| + } else { | ||
| + if (toStdout) { | ||
| + process.stdout.write(result.code); | ||
| + } | ||
| + const log = toStdout ? console.error : console.log; | ||
| + log(`migrated ${summary.input} -> ${summary.output}`); | ||
| + for (const c of result.converted) { | ||
| + log(` converted ${c.kind.padEnd(16)} ${c.name} (line ${c.line}): ${c.detail}`); | ||
| + } | ||
| + for (const u of result.unconverted) { | ||
| + const what = u.code ?? u.name; | ||
| + log(` todo ${u.kind.padEnd(16)} ${what} (line ${u.line}, output line ${u.outputLine}): ${u.reason}`); | ||
| + } | ||
| + for (const n of result.notes) { | ||
| + log(` note ${n}`); | ||
| + } | ||
| + log(`${result.converted.length} converted, ${result.unconverted.length} left to do`); | ||
| + } | ||
| + process.exit(result.unconverted.length === 0 ? 0 : 1); | ||
| } else { | ||
| usage(); | ||
| } | ||
Changedpackages/cli/src/build.js+1−1
| @@ -43,7 +43,7 @@ | ||
| continue; | ||
| } | ||
| const rel = path.relative(rootDir, file); | ||
| - const c = compileTsus(fs.readFileSync(file, "utf8"), rel); | ||
| + const c = compileTsus(fs.readFileSync(file, "utf8"), rel, { path: file }); | ||
| compiled.set(file, c); | ||
| diagnostics.push(...c.diagnostics); | ||
| } | ||
Changedpackages/cli/src/check.js+9−3
| @@ -1,6 +1,7 @@ | ||
| // The strictness checker. Runs on preprocessed (valid-TS) source of .tsus | ||
| // files only; plain .ts dependencies are exempt by design. | ||
| import ts from "typescript"; | ||
| +import { runRules } from "./rules/index.js"; | ||
| const RULES = { | ||
| TSUS001: { | ||
| @@ -27,7 +28,10 @@ | ||
| // `locate(offset)` maps an offset in `code` to a 1-based { line, col } in the | ||
| // original .tsus file; without it, positions are reported in `code` itself. | ||
| -export const checkSource = (fileName, code, locate) => { | ||
| +// options (all optional) feed the extended rules in ./rules: original (the | ||
| +// .tsus text), toSource (offset map from code to original), path (absolute | ||
| +// file path, enables cross-file rules), program (for type-aware rules). | ||
| +export const checkSource = (fileName, code, locate, options = {}) => { | ||
| const sourceFile = ts.createSourceFile( | ||
| fileName, | ||
| code, | ||
| @@ -51,6 +55,7 @@ | ||
| message: RULES[code].message, | ||
| hint: RULES[code].hint, | ||
| file: fileName, | ||
| + at: node.getStart(sourceFile), | ||
| ...where(node.getStart(sourceFile)), | ||
| }); | ||
| }; | ||
| @@ -86,10 +91,11 @@ | ||
| hint: "The file does not parse as TypeScript after macro expansion.", | ||
| tsCode: d.code, | ||
| file: fileName, | ||
| + at: d.start ?? 0, | ||
| ...where(d.start ?? 0), | ||
| }); | ||
| } | ||
| - diagnostics.sort((a, b) => a.line - b.line || a.col - b.col); | ||
| - return diagnostics; | ||
| + // Hook: the extended rule set in ./rules adds its diagnostics and fixes. | ||
| + return runRules({ ...options, fileName, code, sourceFile, legacy: diagnostics }); | ||
| }; | ||
Changedpackages/cli/src/compile.js+3−2
| @@ -9,7 +9,8 @@ | ||
| // Preprocess one .tsus source and run the syntactic rules over the result. | ||
| // Every diagnostic carries a 1-based line/col in the .tsus file. | ||
| -export const compileTsus = (source, fileName) => { | ||
| +// opts.path (absolute file path) lets the extended rules follow imports. | ||
| +export const compileTsus = (source, fileName, opts = {}) => { | ||
| const pre = preprocess(source); | ||
| const starts = lineStarts(source); | ||
| const locateSource = (offset) => { | ||
| @@ -19,7 +20,7 @@ | ||
| const locate = (offset) => locateSource(pre.toSource(offset)); | ||
| const diagnostics = [ | ||
| ...pre.diagnostics.map(({ offset, ...d }) => ({ ...d, file: fileName, ...locateSource(offset) })), | ||
| - ...checkSource(fileName, pre.code, locate), | ||
| + ...checkSource(fileName, pre.code, locate, { original: source, toSource: pre.toSource, path: opts.path }), | ||
| ]; | ||
| return { ...pre, source, fileName, locate, locateSource, diagnostics }; | ||
| }; | ||
Addedpackages/cli/src/explain.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/fix.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/init.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/migrate.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/analysis.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/bans.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/context.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/immutability.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/index.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/project.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/registry.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/results.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/src/rules/sourcemap.js
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/templates/AGENTS.md
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/templates/src/main.tsus
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedpackages/cli/templates/tsconfig.json
Not shown: this page diffs the first 60 files. View the file or the raw file.
Addedscripts/docs.mjs
Not shown: this page diffs the first 60 files. View the file or the raw file.
Changedscripts/run-examples.mjs
Not shown: this page diffs the first 60 files. View the file or the raw file.
Checks
No checks reported for this commit.
Runs
No runs for this commit.