Safe versions at the null boundary: T | null as Option, in every pack #61

Merged
sionzee merged 1 commit from evobug/safe-option into main 2026-11-16 22:04:22 +01:00
Owner

What

The feature packs' safe versions now cover the null boundary as well. A member whose declarations return T | null or take a required T | null gets a safe version in its pack's module, named by the same rule as the others:

  • Returns: Option<T>. null becomes undefined through ?? undefined, so "", 0 and false come back unchanged. In a promise, Promise<T | null> becomes Promise<Option<T>>.
  • Parameters: a required T | null takes Option<T>, and an undefined passed there reaches the original as null (function insertBefore(self, a0, a1) { return self.insertBefore(a0, a1 ?? null); }). An optional T | null is typed T and passed on unchanged, so an undefined there still means "not passed".
  • Also fails: Result<Option<T>, E>, for example dirReadSync(dir) and get(cookieStore, name).
  • Overloads and generics are kept. querySelector(document, "input") is an Option<HTMLInputElement>.

Counts

Pack Return Option Take Option Of these, also fail Safe versions added (they don't fail) null kept (nullSkipped)
browser 116 133 (6 do both) 9 234 8
Node 18 8 6 20 31
ws 1 (WebSocketServer#address) 0 0 1 0
vue-router 0 0 0 0 0

Browser categories:

  • DOM queries and attributes: querySelector, getElementById, closest, getAttribute*, insertAdjacentElement, lookupNamespaceURI
  • namespaces: createElementNS(document, undefined, name), setAttributeNS, getElementsByTagNameNS
  • tree editing and walking: insertBefore(list, item, undefined), TreeWalker, NodeIterator, XPathResult
  • collections: item, namedItem, NamedNodeMap
  • storage: getItem, key
  • get of Headers, URLSearchParams and FormData
  • URL.parse (urlParse)
  • canvas: getContext, and WebGL's bind*, delete*, is*, uniform* and getters
  • push, WebRTC, WebGPU getters
  • prompt, open, getSelection

Node categories:

  • urlParse, and get of URLSearchParams and MIMEParams
  • Server#address
  • Database#location, setAuthorizer(db, undefined)
  • setUncaughtExceptionCaptureCallback(undefined)
  • Dir#read and readSync, which also fail
  • createCipheriv's iv, ffi.dlopen(undefined)
  • stream.isReadable and isWritable
  • the TLS getters
  • readv and writev's position
  • getItem, key and get on the globals

What keeps its null, and why

Each skip is recorded with its reason in safe-api.json under nullSkipped.

  • null and undefined both in one parameter or return: they may mean different things. 10 such parameters in Node (mkdir/readFile/open with a callback, crypto.sign, readline write). 2 such returns (Agent#createConnection).
  • Overloads that disagree: null at an argument in some overloads, nothing there in others. 13 in Node (exec, execFile, computeSecret, read, ...) and 6 in the browser (texImage2D, new KeyframeEffect, addIceCandidate, ...).
  • null through a type alias: 6 in Node (WriteFileOptions, EncodingOption). It can't be removed from the type as written.
  • this parameter: MediaQueryList#addListener and removeListener declare one.

A failing member in this list keeps its Result safe version, null included.

SQLite decision: rows are not changed. NULL is a value there, not absence. The row values sit inside Record<string, SQLOutputValue>, so the generator never touches them. get(statement) returns { note: null } as the original does, and undefined only when there is no row, again as the original does. Rows go through validate<T>, as #46 set up. A test asserts this, in both the types and the runtime.

JSON and structuredClone: their values are typed any or T, so the rule never matches them. They are left as they are; std's parseJson and validate already convert.

Property decision: properties get no safe version. el.parentElement, response.body and the like stay as they are. Most reads are property accesses where ?? undefined reads naturally, and a getter turned into a function (parentElement(el)) doesn't. Methods that look like getters, such as TreeWalker#parentNode(), are callables, so they are covered.

Out of scope: RegExp#exec and String#match are language built-ins and appear in neither API map, so no pack has them. For those, the checker only offers Compare with null.

Side effects

  • For a failing member's optional x?: T | null parameter, the safe version's type drops the null (mkdirSync(path, options?)). What you pass still reaches the original unchanged.
  • In the generator, a member that gets skipped no longer leaves its imports in the declaration file.

Checker

  • no-undefined-check-for-null: when an enabled pack has the API's Option safe version, the rule's help names it. A second fix, Use the safe version, which returns an Option, rewrites the call and adds the import: localStorage.getItem(k) !== undefined becomes getItem(localStorage, k) !== undefined. This also works through the const the value was stored in.
    • The curated methods map to API members (Element#closest, Storage#getItem, ...), so re.exec(s) is never pointed at URLPattern#exec.
    • Without a pack, the rule behaves as before.
  • no-null: reports a strict comparison with null of a safe version's Option, directly or through a const. Such a comparison is always false or always true. The quick fix is Compare with undefined.
  • Elsewhere: Option safe versions are not Results, so must-use-result doesn't apply and unhandled-failure never fires on them.
  • Manifest: safe-ts.json has a new top-level option field: module → function → the members it stands for. safe now lists only what returns a Result.
  • pack-kit: the new safeModules and manifestSafe build both lists for every pack.
  • The unhandled-failure quick fix keeps working, including on members that now return Result<Option<T>, E> (cookieStore.get → get(cookieStore, ...)).

Tests

  • Drift: every pack's safe-api.test.ts covers the new members, results and options per module, nullSkipped, and the manifests.
  • Node runtime (feature-node/test/option.test.ts):
    • missing values come back as undefined; present "", 0, false and NaN come back unchanged;
    • Result<Option<Dirent>> from dirReadSync;
    • undefined reaches the original as null: the originals db.setAuthorizer(undefined) and process.setUncaughtExceptionCaptureCallback(undefined) throw ERR_INVALID_ARG_TYPE, and the safe versions work;
    • an optional parameter gets exactly what was passed;
    • SQLite rows keep null.
  • Browsers (feature-browser/test/browsers/option.test.ts, part of npm run test:browsers): the same checks in Chromium, Firefox and WebKit, on DOM queries and attributes, storage, get, urlParse, getContext, insertBefore and setAttributeNS passing null, pushState's optional url, and cookieStore.get.
  • tsc (test/types/infer.ts):
    • querySelector(document, "input") is Option<HTMLInputElement>, and "svg" is Option<SVGSVGElement>;
    • generic querySelector<HTMLDialogElement>;
    • closest(el, "form"), getContext(canvas, "2d" | "webgl2");
    • insertBefore(list, li, undefined) is HTMLLIElement;
    • createElementNS(document, undefined, "x");
    • Result<Option<...>> for get(cookieStore, ...) and dirReadSync;
    • SQLite rows still include null.
  • Checker: 5 new tests in crates/safe_ts_core/tests/fixes.rs.
  • Benchmark: get(params, key) against params.get(key), with half the keys missing, measures 1.00x. It is added to bench:check as a max ratio with a 1.0 baseline.

Docs changed

  • docs/guide/libraries.md: the new section "null becomes Option", the browser modules, and the manifest's option field
  • docs/guide/absence.md: "null from outside", with the safe versions
  • docs/rules/no-undefined-check-for-null.md
  • docs/rules/no-null.md
  • docs/rules/must-use-result.md
  • README.md: the pack table, the layout list, and the manifest notes
  • CHANGELOG.md: Unreleased
  • packages/pack-kit/README.md
  • packages/feature-browser/test/browsers/README.md

Verification

All of these pass on origin/main (1d83085) with this commit on top:

  • cargo nextest run --workspace (210 tests)
  • cargo clippy -q --workspace --all-targets: nothing new
  • npm run build
  • npm run test:std (285)
  • npm run typecheck, including typecheck:emit
  • node scripts/docs-typecheck.mjs (380 examples)
  • npm run test:docs
  • npm run test:vite
  • npm run test:browsers: errors in the three engines, plus the new option test in each
  • node scripts/verify-packages.mjs
  • npm run bench:check

🤖 Generated with Claude Code

## What The feature packs' safe versions now cover the `null` boundary as well. A member whose declarations return `T | null` or take a required `T | null` gets a safe version in its pack's module, named by the same rule as the others: - **Returns:** `Option<T>`. `null` becomes `undefined` through `?? undefined`, so `""`, `0` and `false` come back unchanged. In a promise, `Promise<T | null>` becomes `Promise<Option<T>>`. - **Parameters:** a required `T | null` takes `Option<T>`, and an `undefined` passed there reaches the original as `null` (`function insertBefore(self, a0, a1) { return self.insertBefore(a0, a1 ?? null); }`). An optional `T | null` is typed `T` and passed on unchanged, so an `undefined` there still means "not passed". - **Also fails:** `Result<Option<T>, E>`, for example `dirReadSync(dir)` and `get(cookieStore, name)`. - Overloads and generics are kept. `querySelector(document, "input")` is an `Option<HTMLInputElement>`. ### Counts | Pack | Return `Option` | Take `Option` | Of these, also fail | Safe versions added (they don't fail) | `null` kept (`nullSkipped`) | |---|---|---|---|---|---| | browser | 116 | 133 (6 do both) | 9 | 234 | 8 | | Node | 18 | 8 | 6 | 20 | 31 | | ws | 1 (`WebSocketServer#address`) | 0 | 0 | 1 | 0 | | vue-router | 0 | 0 | 0 | 0 | 0 | **Browser categories:** - DOM queries and attributes: `querySelector`, `getElementById`, `closest`, `getAttribute*`, `insertAdjacentElement`, `lookupNamespaceURI` - namespaces: `createElementNS(document, undefined, name)`, `setAttributeNS`, `getElementsByTagNameNS` - tree editing and walking: `insertBefore(list, item, undefined)`, `TreeWalker`, `NodeIterator`, `XPathResult` - collections: `item`, `namedItem`, `NamedNodeMap` - storage: `getItem`, `key` - `get` of `Headers`, `URLSearchParams` and `FormData` - `URL.parse` (`urlParse`) - canvas: `getContext`, and WebGL's `bind*`, `delete*`, `is*`, `uniform*` and getters - push, WebRTC, WebGPU getters - `prompt`, `open`, `getSelection` **Node categories:** - `urlParse`, and `get` of `URLSearchParams` and `MIMEParams` - `Server#address` - `Database#location`, `setAuthorizer(db, undefined)` - `setUncaughtExceptionCaptureCallback(undefined)` - `Dir#read` and `readSync`, which also fail - `createCipheriv`'s `iv`, `ffi.dlopen(undefined)` - `stream.isReadable` and `isWritable` - the TLS getters - `readv` and `writev`'s `position` - `getItem`, `key` and `get` on the globals ### What keeps its `null`, and why Each skip is recorded with its reason in `safe-api.json` under `nullSkipped`. - **`null` and `undefined` both in one parameter or return:** they may mean different things. 10 such parameters in Node (`mkdir`/`readFile`/`open` with a callback, `crypto.sign`, `readline` `write`). 2 such returns (`Agent#createConnection`). - **Overloads that disagree:** `null` at an argument in some overloads, nothing there in others. 13 in Node (`exec`, `execFile`, `computeSecret`, `read`, ...) and 6 in the browser (`texImage2D`, `new KeyframeEffect`, `addIceCandidate`, ...). - **`null` through a type alias:** 6 in Node (`WriteFileOptions`, `EncodingOption`). It can't be removed from the type as written. - **`this` parameter:** `MediaQueryList#addListener` and `removeListener` declare one. A failing member in this list keeps its `Result` safe version, `null` included. **SQLite decision:** rows are not changed. `NULL` is a value there, not absence. The row values sit inside `Record<string, SQLOutputValue>`, so the generator never touches them. `get(statement)` returns `{ note: null }` as the original does, and `undefined` only when there is no row, again as the original does. Rows go through `validate<T>`, as #46 set up. A test asserts this, in both the types and the runtime. **JSON and `structuredClone`:** their values are typed `any` or `T`, so the rule never matches them. They are left as they are; std's `parseJson` and `validate` already convert. **Property decision:** properties get no safe version. `el.parentElement`, `response.body` and the like stay as they are. Most reads are property accesses where `?? undefined` reads naturally, and a getter turned into a function (`parentElement(el)`) doesn't. Methods that look like getters, such as `TreeWalker#parentNode()`, are callables, so they are covered. **Out of scope:** `RegExp#exec` and `String#match` are language built-ins and appear in neither API map, so no pack has them. For those, the checker only offers *Compare with null*. ### Side effects - For a failing member's optional `x?: T | null` parameter, the safe version's type drops the `null` (`mkdirSync(path, options?)`). What you pass still reaches the original unchanged. - In the generator, a member that gets skipped no longer leaves its imports in the declaration file. ## Checker - **`no-undefined-check-for-null`:** when an enabled pack has the API's `Option` safe version, the rule's help names it. A second fix, *Use the safe version, which returns an Option*, rewrites the call and adds the import: `localStorage.getItem(k) !== undefined` becomes `getItem(localStorage, k) !== undefined`. This also works through the `const` the value was stored in. - The curated methods map to API members (`Element#closest`, `Storage#getItem`, ...), so `re.exec(s)` is never pointed at `URLPattern#exec`. - Without a pack, the rule behaves as before. - **`no-null`:** reports a strict comparison with `null` of a safe version's `Option`, directly or through a `const`. Such a comparison is always false or always true. The quick fix is *Compare with undefined*. - **Elsewhere:** `Option` safe versions are not Results, so `must-use-result` doesn't apply and `unhandled-failure` never fires on them. - **Manifest:** `safe-ts.json` has a new top-level `option` field: module → function → the members it stands for. `safe` now lists only what returns a Result. - **pack-kit:** the new `safeModules` and `manifestSafe` build both lists for every pack. - The `unhandled-failure` quick fix keeps working, including on members that now return `Result<Option<T>, E>` (`cookieStore.get` → `get(cookieStore, ...)`). ## Tests - **Drift:** every pack's `safe-api.test.ts` covers the new members, `results` and `options` per module, `nullSkipped`, and the manifests. - **Node runtime** (`feature-node/test/option.test.ts`): - missing values come back as `undefined`; present `""`, `0`, `false` and `NaN` come back unchanged; - `Result<Option<Dirent>>` from `dirReadSync`; - `undefined` reaches the original as `null`: the originals `db.setAuthorizer(undefined)` and `process.setUncaughtExceptionCaptureCallback(undefined)` throw `ERR_INVALID_ARG_TYPE`, and the safe versions work; - an optional parameter gets exactly what was passed; - SQLite rows keep `null`. - **Browsers** (`feature-browser/test/browsers/option.test.ts`, part of `npm run test:browsers`): the same checks in Chromium, Firefox and WebKit, on DOM queries and attributes, storage, `get`, `urlParse`, `getContext`, `insertBefore` and `setAttributeNS` passing `null`, `pushState`'s optional `url`, and `cookieStore.get`. - **tsc** (`test/types/infer.ts`): - `querySelector(document, "input")` is `Option<HTMLInputElement>`, and `"svg"` is `Option<SVGSVGElement>`; - generic `querySelector<HTMLDialogElement>`; - `closest(el, "form")`, `getContext(canvas, "2d" | "webgl2")`; - `insertBefore(list, li, undefined)` is `HTMLLIElement`; - `createElementNS(document, undefined, "x")`; - `Result<Option<...>>` for `get(cookieStore, ...)` and `dirReadSync`; - SQLite rows still include `null`. - **Checker:** 5 new tests in `crates/safe_ts_core/tests/fixes.rs`. - **Benchmark:** `get(params, key)` against `params.get(key)`, with half the keys missing, measures 1.00x. It is added to `bench:check` as a `max` ratio with a 1.0 baseline. ## Docs changed - `docs/guide/libraries.md`: the new section "`null` becomes `Option`", the browser modules, and the manifest's `option` field - `docs/guide/absence.md`: "`null` from outside", with the safe versions - `docs/rules/no-undefined-check-for-null.md` - `docs/rules/no-null.md` - `docs/rules/must-use-result.md` - `README.md`: the pack table, the layout list, and the manifest notes - `CHANGELOG.md`: Unreleased - `packages/pack-kit/README.md` - `packages/feature-browser/test/browsers/README.md` ## Verification All of these pass on `origin/main` (`1d83085`) with this commit on top: - `cargo nextest run --workspace` (210 tests) - `cargo clippy -q --workspace --all-targets`: nothing new - `npm run build` - `npm run test:std` (285) - `npm run typecheck`, including `typecheck:emit` - `node scripts/docs-typecheck.mjs` (380 examples) - `npm run test:docs` - `npm run test:vite` - `npm run test:browsers`: errors in the three engines, plus the new `option` test in each - `node scripts/verify-packages.mjs` - `npm run bench:check` 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Safe versions at the null boundary: T | null as Option, in every pack
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m8s
f78f126a36
Every member whose declarations return `T | null` or take a required
`T | null` gets a safe version in its pack's module, by the same naming
rule: it returns `Option<T>` (`?? undefined`; a promise's too), takes
`Option<T>` where the original takes `null` (passing `undefined` on as
`null`; optional parameters unchanged), and returns `Result<Option<T>, E>`
when it also fails. Overloads and generics are kept.

Browser: 243 members (116 return null, 133 take it, 9 also fail); Node: 26
(6 also fail); ws: 1. Where null and undefined may mean different things,
overloads disagree, or the null comes through a type alias, the null stays,
with the reason in safe-api.json (`nullSkipped`). SQLite rows keep their
null.

The checker: `no-undefined-check-for-null` suggests the Option safe version
(help and quick fix), `no-null` reports a safe version's Option compared
with null, and Option safe versions aren't Results (safe-ts.json `option`).

Tested in Node and in Chromium, Firefox and WebKit; tsc checks what the
overloads infer; bench:check measures `get(params, key)` at parity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch evobug/safe-option 2026-11-16 22:04:22 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!61
No description provided.