Stack
A fast, small, proven core. The shipped code is TypeScript compiled to plain ESM; the verification around it (tests, spaces, fuzzers, mutation) can be as heavy as it needs to be, because none of it ships.
| Version | Role | |
|---|---|---|
| TypeScript | 7.0.2 (native compiler, tsc) | types, .d.ts, emit to dist/ |
| oxlint + oxlint-tsgolint | 1.90.0 + 7.0.2005 | lint, type-aware rules (tsgolint runs TypeScript 7) |
| vitest | 5.0.5 | test runner |
| Stryker + vitest runner | 10.1.1 | mutation testing of src/**/*.{js,ts} |
| esbuild | 0.28.2 | bundle budgets (test/bundle.test.js), the workerd test worker (test/workerd/build.mjs) |
Runtime dependencies: none, ever. Node ≥ 22.18 runs src/*.ts directly (type stripping) for tests and fuzzers; consumers get dist/ (plain .js + .d.ts), so engines.node stays >=20.
Compiler settings and why
tsconfig.json (build) is strict plus noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitReturns, noImplicitOverride, noFallthroughCasesInSwitch, noPropertyAccessFromIndexSignature, useUnknownInCatchVariables, verbatimModuleSyntax, target ES2022, module/moduleResolution nodenext.
erasableSyntaxOnly: no enums, namespaces, parameter properties or other syntax with runtime meaning. The emitted JS is the source with the types removed: zero size or speed cost, and Node can run the source as is.- Import specifiers stay
.js(import { fail } from './errors.js'even though the file iserrors.ts): thenodenextconvention.tscmaps./x.jstox.tsand emits it unchanged intodist/; vitest (Vite) resolves a.jsspecifier to the.tsfile from both.jsand.tsimporters; plain Node gets the same mapping fromtest/ts-resolve.mjs(amodule.registerHooksresolve hook: a relative./x.jsthat does not exist resolves to./x.ts, then Node ≥ 22.18 strips the types). Run fuzzers and scripts that loadsrc/asnode --import ./test/ts-resolve.mjs …; vitest's config puts it inNODE_OPTIONSso every child process and worker a test starts has it; CI setsNODE_OPTIONSfor whole jobs. Consequence: converting a module renames one file and edits no importer. (Verified on this branch:errors,limits,errors-docare.ts, imported as.jsfrom 40 JS modules,tsc, vitest andnode --import ./test/ts-resolve.mjsall resolve them.) isolatedDeclarations: every export has an explicit type, so declarations never depend on inference across files. TypeScript refuses it together withallowJs(TS5053), and TS 7.0.2 panics in declaration emit when both are set, so it runs as its own check:tsconfig.isolated.json(onlysrc/**/*.ts,allowJsoff). While unconverted.jsremains, that one check hasnoImplicitAnyoff so an import of a.jsfile is not an error there; the main check (tsconfig.check.json, every flag above) is where implicitanyis caught.allowJs(migration only):.jsand.tscoexist insrc/;checkJsis off. The ratchet (scripts/ts-ratchet.mjs, part ofnpm run typecheck): the set of.jsfiles undersrc/may only shrink. There is no list file to edit (a shared list is a merge conflict between parallel conversions): the base commit's tree is the list (RATCHET_BASEin CI, else the merge-base withorigin/main/github/main). A.jsfile the base lacks fails. When none is left, the check also fails until the migration-only lint relaxations (below) are removed.- No JSDoc types, ever. Types are TypeScript.
npm run typecheck = tsc -p tsconfig.check.json (src + test/types/*.typetest.ts, the compile-time tests: every @ts-expect-error there must remain an error) + tsc -p tsconfig.isolated.json + the TypeScript ratchet + the absence ratchet (scripts/absence-ratchet.mjs).
src/ is all TypeScript (the last file, src/index.js, became src/index.ts). The migration-only relaxation of typescript/no-unsafe-{assignment,member-access,return,call,argument} is gone with it: those rules are on, and the ratchet refuses a new .js under src/ and refuses the relaxation coming back. An indexed read the compiler cannot bound goes through absent.ts's checked read (atOr, with a domain fallback) rather than as number; the per-byte hot loops (inflate, sha1, delta, pkt-line, the pack parsers) keep their block suppressions.
Lint
npm run lint runs two profiles:
- Strict (
.oxlintrc.json,--type-aware --deny-warnings) onsrc/**/*.ts: plugins eslint, typescript, unicorn, oxc, import, promise, node; categories correctness, suspicious, pedantic, perf and restriction at error (364 rules on today's files), style off with picks. Turned off, each for a reason:oxc/no-optional-chaining,oxc/no-rest-spread-properties,oxc/no-async-await(ES5-compat restrictions; this is ES2022),no-magic-numbers(on only for parser and bounds files, as before),no-undefined(the absence ratchet is the gate: it also counts?:,?., and??, and it only moves down; see Absence),unicorn/no-null(null is a value the wire uses),no-plusplus,no-bitwise,no-continue(parsers),max-lines*/max-statements(a parser is one function),no-inline-comments(/* @__PURE__ */annotations are inline by definition),explicit-function-return-type(isolatedDeclarations already requires it where it matters, at exports),prefer-readonly-parameter-types(fires on everyUint8Array). Style picks:consistent-type-definitions: type,consistent-type-imports,array-type,no-inferrable-types,prefer-const,prefer-template,no-nested-ternary,import/no-duplicates,no-else-return,object-shorthand,numeric-separators-style,prefer-node-protocol,throw-new-error,no-array-for-each,prefer-at,import/no-default-export,import/extensions: always. Type-aware rules includeno-unsafe-type-assertion,no-floating-promises,no-unsafe-*,switch-exhaustiveness-check,restrict-template-expressions. A suppression is// oxlint-disable-next-line <rule> -- <reason>; there are three in the converted files, each at a type the compiler cannot follow (a union member built from a generic code;Object.keysof an exhaustive table;match). - Loose (
oxlint.loose.json) on unconvertedsrc/*.jsand ontest/,scripts/,examples/: the rules ply had before this stack. Verification code may be as heavy as it likes.
Rules for code in src/
- Errors are values. A function that can fail returns
Result<T, E>(src/result.ts:ok,err,map,mapErr,andThen,match,assertNever). It does not throw.throwis for programmer bugs only:assertNever, aninternalinvariant. Platform calls that throw (fetch,crypto.subtle, a socket) are caught at the edge that makes them and turned into anErr. - The error type is a closed, exhaustive union.
Code(src/errors.ts) is the closed set of codes;RETRYandCODE_DOCSare typedRecord<Code, …>, so a code without a policy or a doc does not compile.PlyErroris the discriminated union overcode;Detailholds the fields a code always carries (http→status,limit_exceeded→what/got/max,cas_conflict→expected/actual,match_count→matches,merge_conflict→conflicts), andfail(code, message, detail)requires exactly those. Aswitchover a union lists every member and has nodefault; the next statement isassertNever(x), so a new member is a type error. Anif/else ifchain on the same tag ends inassertNever.match(u, handlers)demands one handler per tag. Adding a code or a payload field re-checks every constructor and every match. - A PlyError value is an
Errorinstance with its fields (Object.assign(new Error(message), {code, …})): a stack for whoever logs it, and the shape a caller that rethrows it (if (!r.ok) throw r.error) expects from an error. Nothing reads it as a class; its type is the union. - Pure functions where possible; I/O at the edges. Parsers, encoders, validators, planners and merges take bytes/values and return values. Network, timers, crypto and the filesystem live in the transport, http and
*-node.tsmodules, and are passed in, not imported, where a pure module needs them. - State machines are tagged unions with transition functions. A stream parser is
type State = { tag: 'header'; … } | { tag: 'body'; … } | { tag: 'done'; … }andstep(state, input): Result<State, PlyError>; the driver loop is the only thing with I/O.pktStep,spStep,v2Step,streamStepalready have this shape in JS; converting them means typing the states, not rewriting them. - Bounds before allocation, as before: every wire-driven size is checked against a
limits.*value (checkLimit/parseLimitsreturnResult; a caller's limits record is parsed once at the entry into aCheckedLimits, and code past it reads plain numbers) before a buffer exists. - Bundle budgets hold. Types cost nothing; runtime helpers do. Prefer a type to a runtime check when the value is already trusted; mark unused-but-exported module-level calls
/* @__PURE__ */so esbuild drops them. - Absence is a value. See Absence below. Do not write the platform missing value, an optional member, optional chaining, or nullish coalescing outside
src/absent.ts.
Absence
There is one Option<T>: { tag: 'some', value } | { tag: 'none' } in src/result.ts, next to Result, so ply does not grow a second absence type. Result keeps its ok discriminant. Option uses tag. They compose through resultToOption, optionToResult, transposeResultOption, and transposeOptionResult: None carries no reason, so turning None into an Err requires the error the caller supplies. matchOption is exhaustive. mapOption, flatMapOption, and getOrElse are that match's two branches (map is already Result's name).
The platform's missing value is spelled only in src/absent.ts and converted there (fromNullable, fromNullish, at / atOr, mapGet, readKey, jsonDecode, byteInRange, asOption, unwrapOrAbsent). Oid is string & { brand }. The same intersection on the platform missing value is never under TypeScript 7, so it cannot carry a phantom; the file is the brand, and what leaves it is Option. Null stays a wire value (fromNullable keeps it; fromNullish is the one collapse that ?. and ?? used to do inline). The file is not under src/core/ because mutation sharding refuses a subdirectory of src/ (scripts/mutate.mjs).
scripts/absence-ratchet.mjs (part of npm run typecheck) counts, outside that file, the identifier undefined, optional members and parameters (?:), optional chaining (?.), and nullish coalescing (??), and compares the four numbers to scripts/absence-baseline.json. A rise fails. A drop fails until the same change lowers the baseline (node scripts/absence-ratchet.mjs --write, which refuses a rise). New code cannot add any of the four.
Public API policy
Today every public function throws a PlyError-shaped Error. Decision: the public API returns Result — Promise<Result<T, PlyError>> from editFile, readFile, readLog, pushTree, checkoutTree, merge, rebase, fetch*/push, the client. We are 0.x; the break is allowed, and ply-web (the consumer we own) is updated in the same step. Why: an exhaustive switch (r.error.code) at the call site is the point of the closed union; a catch gets unknown.
Migration path:
- Foundation (done). Toolchain;
result,errors,errors-doc,limitsin TypeScript. - Clusters (done). Internal functions return
Result; a throwing wrapper (orThrow) bridged what the public API still called. - Cut-over (done, 0.2.0). Public entry points return
Result;thrown,orThrowand every throwing wrapper are deleted;indexexportsfail(an Err) andplyError(the error value), not a throwing constructor. What may still raise:assertNever, aninternalinvariant, and a stream (a ReadableStream errors, an iterator rejects). A value the caller's own callback threw does not raise: it is returned as anErr(bad_request, orambiguousonce the push request was handed to the transport;what: 'callback', the value ascause; README "operation(): your body's outcomes"). In ply-web, in the same window: bump the pin, replacetry { … } catch (e) { code = e.code }withif (!r.ok)and aswitch (r.error.code)with nodefaultandassertNeverafter it (ply-web already maps codes to HTTP statuses; it becomes exhaustive), deletesrc/ply.d.ts(ply ships its own types).
Build and consumers
npm run build (= prepare) runs tsc -p tsconfig.json: src/ → dist/ (.js + .d.ts, imports rewritten to .js). package.json exports keep every subpath (., ./edit, ./read, … ./otel) with types + default conditions into dist/; files is ["dist"]. dist/ is not committed: a git-pinned consumer ("ply": "github:ivarvong/ply#<sha>") gets it from npm running prepare while it packs the git dependency. Evidence and the alternative we rejected are in the PR description.
Tests
vitest runs every test/**/*.test.js file that node --test ran before (vitest.config.ts: forks pool, files in parallel, no default timeout, as under node:test), test/workerd.test.js included (the worker bundled by esbuild). The fuzzers in test/fuzz/ stay node scripts (node --import ./test/ts-resolve.mjs test/fuzz/<f>.mjs). npm test = vitest
- the fuzzer chain. CI:
npx vitest run --shard i/4, partitioned longest-first by measured seconds per file (test/durations.json, the sequencer invitest.config.ts); each shard uploads its vitest JSON report. Mutation testing:@stryker-mutator/vitest-runnerovervitest.stryker.config.ts(the mutation-killing files, quick sizes, push-outcome on its own thread,test/stryker-parent-guard.cjspreloaded to kill a test process past 3 GB),mutate: src/**/*.{js,ts}, per-test coverage. The gate (scripts/mutate.mjs) is unchanged: changed lines plus every gated parser and bounds line on a PR, everything on main, parser and bounds survivors fatal, 16 cost-balanced shards.tsconfigFilepoints at a file that does not exist on purpose: Stryker's tsconfig preprocessor calls the TypeScript JS API (ts.parseConfigFileTextToJson), which TypeScript 7 does not ship (TypeError: ts.parseConfigFileTextToJson is not a function); the rewrite only matters forextends/references outside the sandbox, which ply has none of.
Converting a module (the brief for cluster agents)
The rules that make parallel conversions collision-free: a cluster touches only its own files. Specifiers stay .js, so no importer changes; the ratchet has no list, so no shared file changes. The shared files are src/errors.ts, src/result.ts, src/index.*, test/bundle.test.js (budgets), package.json and CI: change them only when your cluster cannot work without it, in a separate small commit, and say so in the PR body (the steward merges). Branch from stack/foundation (or main once it lands); merge main into your branch as main moves (no rebase, no force-push). Clusters and order: the T1–T7 / A1–A7 plan in lab_notebook/ply-core-audit-2026-10-31.md §11.
T (mechanical) PR, per file in the cluster:
git mv src/x.js src/x.ts. Nothing else outside the cluster changes; imports keep saying./x.js.- Type it. Exported declarations get explicit types (isolatedDeclarations). No
anywritten by hand, no!, no enums/namespaces/parameter properties (erasableSyntaxOnly), class fields declared.asonly where the compiler cannot follow, with// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- <why>. Byte buffers areUint8Array. No behavior change;// TODO(A<n>)marks what the A pass should change. - Unconverted modules keep importing
thrown as fail(the throwing constructor) from./errors.js; a converted file that still throws imports the same alias. Errors-as-values is the A pass.
A (errors as values, ADTs, state machines) PR, after its T:
- Replace
throw fail(code, …)withreturn fail(code, …)(the typed constructor from./errors.js), make the function returnResult, handle everyErrin the cluster (early return,andThen,match). A payload a code always carries goes inDetailinerrors.ts(a shared file: one-line change, own commit). - Switches over unions list every member, have no
default, and the next statement isassertNever(x); stream parsers become tagged states with a transition function.
Gate, all green before opening the PR (paste the numbers into the PR body):
npm run typecheck(tsc check + isolated declarations + ratchet) andnpm run lint(strict onsrc/**/*.ts).npx vitest run <the test files that cover the cluster>, then the fullnpx vitest run.- The fuzzers that exercise the cluster (
node --import ./test/ts-resolve.mjs test/fuzz/<f>.mjs …, the same flags asnpm test). - Bundle budgets:
npx vitest run test/bundle.test.jspasses, and the per-module bytes it prints for your files are ≤ before (types are free; a runtime helper must pay for itself). - Mutation on your files:
node scripts/mutate.mjs(mutates only files changed against main) — no new survivors in a parser or bounds function; the score on your files does not drop. npm run buildand, for the A pass of an entry module, the ply-web acceptance below.