Validators: constants without as const, Int ranges, error kinds, compact tables #64

Merged
sionzee merged 4 commits from evobug/fb3-std-validators into main 2026-11-17 00:04:48 +01:00
Owner

Round 3 of the 0.2.0 adoption feedback, std area, part 1 of 2: validators and the types they read (feedback items 1–5 of this area; "Std library" and "Performance", top-ten #6 and #10). The std helpers (items 6–14) are in a second PR, also from main.

Per feedback item

1. Validated types without a written as const: done for the feedback's shapes; partly for RTSS's full Packet type.

  • typeof X of Object.freeze(Y) is Y's type, for Y an as const value or another such const. So (typeof STATUSES)[number] with STATUSES = Object.freeze(STATUS_NAMES) works. Object.freeze({ a: 1 }) keeps its primitives' literal types, as TypeScript's freeze overload does.
  • A const holding a call of a function with a declared return type is evaluated for the arguments: a const type parameter gets the argument's literal types, one constrained to primitives gets a literal (0x10), defaults count, and a single overload signature over an untyped implementation is used (that's the cast-free way to write such a function). An object literal of spreads of such calls works too (Object.freeze({ ...slotsOf(A, 0x01, 15), ... })).
  • For that, the type evaluator now:
    • matches template literal patterns in extends (`${number}`, `${infer N extends number}`, `${infer H}${infer T}`);
    • maps over keyof a tuple (item by item over a type parameter; with as, over its index keys, checking that length and the methods are dropped);
    • spreads tuples ([...T, 0]) and reads T["length"] and [...infer R];
    • takes type-parameter defaults on aliases;
    • evaluates a conditional type whose result is another generic type in a loop rather than recursively, up to 1000 times like TypeScript. Without that, RTSS's Tuple<N> arithmetic overflowed the stack in a debug build at about 80 levels.
  • A number literal type is now its value (0x10 is 16), and only the generated type aliases the validators use are written.
  • RTSS (packages/protocol, copied to /tmp): Op, OpCode and CommandOp, built by the real slotsOf with its Add<From, N> tuple arithmetic, now evaluate, and so does codesOf's ConstName table (GroupOrderCode). tsc accepts the emitted validators against the real types. Before this PR all of them were refused with "Op isn't declared as const".
  • Not done: fromFields<Packet> for the protocol's whole Packet still can't replace trusted.ts. That type has Uint8Array fields (not JSON), a table with number keys ([Op.Hello]: {...}), and mapped types over a union of tuples ([E in F[number] as E[0]]). Each of those is a separate type-model feature, not the as const problem the feedback described.

2. Compact validator mode: done.

  • compact: true in the options (and by default, for object types with 64+ fields) generates a table per object type: each field's key, then a code for string/number/boolean/SafeInt/finite number or the field type's validator, plus flags for optional fields, odd keys and own-property keys.

  • std's jsonTable interprets it. Paths, messages, kinds, key order, unknownKeys, allErrors and finite all behave the same. compact: false writes everything out.

  • Measured with node scripts/compact-validators-size.mjs: 570 fields in 51 interfaces, a plain and a strict collecting validator, minified Vite build, Node 26. The script asserts that all bundles print identical results and errors.

    minified gzip per field validate (valid)
    compact: false (today) 163.4 kB 21.4 kB 287 B 1.7 µs
    default (only the 70-field type) 154.1 kB 18.3 kB 270 B 4.4 µs
    compact: true 39.2 kB 5.4 kB 69 B 14.9 µs
  • Trade-off: a table is about 4× smaller and up to 9× slower, because every field is a megamorphic keyed load. That's why the automatic threshold is high (RTSS's Rules has 111 direct fields; its other 58 interfaces average about 8), and why compact: true is the switch for a whole tree.

  • json-compact.test.ts runs about 200 inputs (missing, null, wrong kinds, NaN, 2^60, extra keys, a class instance with a getter, odd keys) through both modes under five option combinations and compares results and key order.

3. Validators' messages: done (kinds); not done (@error JSDoc). Every JsonProblem and JsonError has:

  • kind: missing, wrongType, unknownKey, duplicateKey, fieldCount or invalidJson;
  • expected (for missing and wrongType): what the type asks for there.

Callers word their own messages from kind, expected and the path (the docs example is in Czech). I didn't add a per-field @error JSDoc message: with the path and kind it is a lookup on the caller's side, and it would add messages to the type model and to every shared validator key. Breaking for tests that deepEqual a whole error (noted under Changed).

4. object in a conditional type's test: done. T extends object means "is an object type": an object, a dictionary, an array or a tuple. The feedback's DeepPartial works as written. object anywhere else is reported with a hint.

5. Integer ranges: done. Int<Min, Max> from std's json module:

  • validate, parseJson and fromFields check it (expected integer from 1 to 12, got 13);
  • arbitrary generates values only in the range, the ends often, shrinking towards the value closest to 0 (genIntIn);
  • it's in the docs.

Docs changed

  • docs/guide/json.md: messages of your own, integer ranges, values from constants without as const, conditional types (object, template patterns, tuples), big types / compact validators with the numbers, the type tables.
  • docs/rules/json-type.md, docs/guide/testing.md (Int row), README.md (json section and std table), CHANGELOG.md (Added, Changed).

Verification

  • npm run build: ok.
  • cargo nextest run --workspace: 214 passed.
  • cargo clippy -q --workspace --all-targets: nothing new in the changed code.
  • npm run test:std: 290 passed. New tests: compact equivalence, Int generation and shrinking, the frozen code table through fromFields/arbitrary, kinds.
  • npm run typecheck and npm run typecheck:emit: ok. typecheck:emit now includes json-compact.test.ts, so tsc checks the generated tables.
  • node scripts/docs-typecheck.mjs, npm run test:docs, npm run test:vite, npm run bench:check, node scripts/verify-packages.mjs: all ok.

🤖 Generated with Claude Code

Round 3 of the 0.2.0 adoption feedback, std area, part 1 of 2: **validators and the types they read** (feedback items 1–5 of this area; "Std library" and "Performance", top-ten #6 and #10). The std helpers (items 6–14) are in a second PR, also from `main`. ## Per feedback item **1. Validated types without a written `as const`: done for the feedback's shapes; partly for RTSS's full `Packet` type.** - `typeof X` of `Object.freeze(Y)` is `Y`'s type, for `Y` an `as const` value or another such `const`. So `(typeof STATUSES)[number]` with `STATUSES = Object.freeze(STATUS_NAMES)` works. `Object.freeze({ a: 1 })` keeps its primitives' literal types, as TypeScript's `freeze` overload does. - A `const` holding a call of a function with a declared return type is evaluated for the arguments: a `const` type parameter gets the argument's literal types, one constrained to primitives gets a literal (`0x10`), defaults count, and a single overload signature over an untyped implementation is used (that's the cast-free way to write such a function). An object literal of spreads of such calls works too (`Object.freeze({ ...slotsOf(A, 0x01, 15), ... })`). - For that, the type evaluator now: - matches template literal patterns in `extends` (`` `${number}` ``, `` `${infer N extends number}` ``, `` `${infer H}${infer T}` ``); - maps over `keyof` a tuple (item by item over a type parameter; with `as`, over its index keys, checking that `length` and the methods are dropped); - spreads tuples (`[...T, 0]`) and reads `T["length"]` and `[...infer R]`; - takes type-parameter defaults on aliases; - evaluates a conditional type whose result is another generic type in a loop rather than recursively, up to 1000 times like TypeScript. Without that, RTSS's `Tuple<N>` arithmetic overflowed the stack in a debug build at about 80 levels. - A number literal type is now its value (`0x10` is `16`), and only the generated type aliases the validators use are written. - RTSS (`packages/protocol`, copied to /tmp): `Op`, `OpCode` and `CommandOp`, built by the real `slotsOf` with its `Add<From, N>` tuple arithmetic, now evaluate, and so does `codesOf`'s `ConstName` table (`GroupOrderCode`). `tsc` accepts the emitted validators against the real types. Before this PR all of them were refused with "`Op` isn't declared `as const`". - Not done: `fromFields<Packet>` for the protocol's whole `Packet` still can't replace `trusted.ts`. That type has `Uint8Array` fields (not JSON), a table with number keys (`[Op.Hello]: {...}`), and mapped types over a union of tuples (`[E in F[number] as E[0]]`). Each of those is a separate type-model feature, not the `as const` problem the feedback described. **2. Compact validator mode: done.** - `compact: true` in the options (and by default, for object types with 64+ fields) generates a table per object type: each field's key, then a code for string/number/boolean/`SafeInt`/finite number or the field type's validator, plus flags for optional fields, odd keys and own-property keys. - std's `jsonTable` interprets it. Paths, messages, kinds, key order, `unknownKeys`, `allErrors` and `finite` all behave the same. `compact: false` writes everything out. - Measured with `node scripts/compact-validators-size.mjs`: 570 fields in 51 interfaces, a plain and a strict collecting validator, minified Vite build, Node 26. The script asserts that all bundles print identical results and errors. | | minified | gzip | per field | validate (valid) | |---|---|---|---|---| | `compact: false` (today) | 163.4 kB | 21.4 kB | 287 B | 1.7 µs | | default (only the 70-field type) | 154.1 kB | 18.3 kB | 270 B | 4.4 µs | | `compact: true` | 39.2 kB | 5.4 kB | 69 B | 14.9 µs | - Trade-off: a table is about 4× smaller and up to 9× slower, because every field is a megamorphic keyed load. That's why the automatic threshold is high (RTSS's `Rules` has 111 direct fields; its other 58 interfaces average about 8), and why `compact: true` is the switch for a whole tree. - `json-compact.test.ts` runs about 200 inputs (missing, `null`, wrong kinds, `NaN`, 2^60, extra keys, a class instance with a getter, odd keys) through both modes under five option combinations and compares results and key order. **3. Validators' messages: done (kinds); not done (`@error` JSDoc).** Every `JsonProblem` and `JsonError` has: - `kind`: `missing`, `wrongType`, `unknownKey`, `duplicateKey`, `fieldCount` or `invalidJson`; - `expected` (for `missing` and `wrongType`): what the type asks for there. Callers word their own messages from `kind`, `expected` and the path (the docs example is in Czech). I didn't add a per-field `@error` JSDoc message: with the path and kind it is a lookup on the caller's side, and it would add messages to the type model and to every shared validator key. **Breaking for tests** that `deepEqual` a whole error (noted under Changed). **4. `object` in a conditional type's test: done.** `T extends object` means "is an object type": an object, a dictionary, an array or a tuple. The feedback's `DeepPartial` works as written. `object` anywhere else is reported with a hint. **5. Integer ranges: done.** `Int<Min, Max>` from std's json module: - `validate`, `parseJson` and `fromFields` check it (`expected integer from 1 to 12, got 13`); - `arbitrary` generates values only in the range, the ends often, shrinking towards the value closest to 0 (`genIntIn`); - it's in the docs. ## Docs changed - `docs/guide/json.md`: messages of your own, integer ranges, values from constants without `as const`, conditional types (`object`, template patterns, tuples), big types / compact validators with the numbers, the type tables. - `docs/rules/json-type.md`, `docs/guide/testing.md` (`Int` row), `README.md` (json section and std table), `CHANGELOG.md` (Added, Changed). ## Verification - `npm run build`: ok. - `cargo nextest run --workspace`: 214 passed. - `cargo clippy -q --workspace --all-targets`: nothing new in the changed code. - `npm run test:std`: 290 passed. New tests: compact equivalence, `Int` generation and shrinking, the frozen code table through `fromFields`/`arbitrary`, kinds. - `npm run typecheck` and `npm run typecheck:emit`: ok. `typecheck:emit` now includes `json-compact.test.ts`, so tsc checks the generated tables. - `node scripts/docs-typecheck.mjs`, `npm run test:docs`, `npm run test:vite`, `npm run bench:check`, `node scripts/verify-packages.mjs`: all ok. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Validators: constants without as const, Int ranges, error kinds, compact tables
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m13s
daf68775ff
- Validated types read constants built without `as const`: Object.freeze of an
  `as const` value (and `(typeof FROZEN)[number]`), frozen object literals, and calls
  of functions with a declared return type (evaluated for the arguments; a single
  overload signature counts), also as spreads. For code tables built from name lists,
  the evaluator matches template literal patterns (`${number}`, `${infer N extends
  number}`), maps over `keyof` a tuple, spreads tuples, reads `T["length"]` and
  `[...infer R]`, takes type-parameter defaults, and evaluates tail-recursive
  conditional types in a loop (up to 1000, as TypeScript).
- `T extends object` in a conditional type's test.
- `Int<Min, Max>`: validated and generated in range.
- `kind` and `expected` on every JSON problem, for messages of your own.
- Compact validators: a table of fields checked by std's `jsonTable`, with the same
  results and errors; `compact: true/false`, default for object types with 64+ fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Compact validators: opt-in only
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m5s
5caba5462f
A table is about 4x smaller but up to 9x slower to validate, so turning it on
by size (64+ fields) would make an existing project's big validators slower on
upgrade, unasked. Now only `compact: true` gives a table; without it every
type is written out, as before. Docs, README, std's doc comment, the CHANGELOG
and the size script say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
std json: RawJson's errors carry a kind, like every JSON problem
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m25s
95e7464179
Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch evobug/fb3-std-validators 2026-11-17 00:04:48 +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!64
No description provided.