@orkestrel/scaffold 0.0.137 → 0.0.139
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +489 -23
- package/dist/bin/main.js +6 -6
- package/dist/host/agents/skills/orkestrel-journey/SKILL.md +33 -27
- package/dist/host/agents/skills/orkestrel-journey/references/captures.md +37 -16
- package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
- package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +628 -41
- package/dist/host/agents/skills/orkestrel-polish/references/capture-harness.md +5 -0
- package/dist/host/claude/agents/orkestrel.md +54 -54
- package/dist/host/claude/rules/typescript.md +4 -1
- package/dist/host/claude/rules/workspace.md +6 -4
- package/dist/host/guides/capture.md +442 -313
- package/dist/host/guides/contract.md +314 -210
- package/dist/host/guides/middleware.md +489 -259
- package/dist/host/guides/process.md +139 -53
- package/dist/host/guides/router.md +282 -165
- package/dist/host/guides/scaffold.md +35 -23
- package/dist/host/guides/server.md +417 -181
- package/dist/host/guides/test.md +353 -232
- package/dist/host/manifest.json +18 -18
- package/dist/host/scripts/browsers.sh +0 -0
- package/dist/host/scripts/codex.sh +0 -0
- package/dist/host/scripts/cursor.sh +0 -0
- package/dist/host/scripts/deps.sh +0 -0
- package/dist/host/scripts/npm.sh +0 -0
- package/dist/host/scripts/ollama.sh +0 -0
- package/dist/host/tests/config.test.ts +19 -27
- package/dist/src/core/index.cjs +139 -60
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +1 -1
- package/dist/src/core/index.d.ts +1 -1
- package/dist/src/core/index.js +139 -60
- package/dist/src/core/index.js.map +1 -1
- package/package.json +6 -6
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
> Schema, a guard, a parser, a strict audit, a parse report, and a generator, every one of
|
|
6
6
|
> them derived from a single owned snapshot of that declaration.
|
|
7
7
|
|
|
8
|
-
Validation is where untrusted data — an HTTP body, a parsed JSON blob, a tool argument — crosses into typed code. This module is that crossing: guards turn `unknown` into a narrowed `T` without leaking
|
|
8
|
+
Validation is where untrusted data — an HTTP body, a parsed JSON blob, a tool argument — crosses into typed code. This module is that crossing: guards turn `unknown` into a narrowed `T` without leaking an untrusted input's throw, while parsers return a typed value or `undefined` for readable invalid input. Here a **reader** is a public operation whose documented result depends on inspecting a caller-owned container, and an **advertised read** is the exact property, key, element, iteration, or reflection that operation says it observes. REQUIRED readers refuse an incomplete advertised read with a coded `ContractError`; unreadability never becomes their absence or accept-anything answer. Total guards instead answer `false`; optional lookup/coercion readers (`enumerableKeys`, `resolveField`, `parseArray`, `parseEnum`, and the `parse*Field` family) deliberately answer `undefined`. Schema inversion widens readable unsupported, depth-exhausted, or cyclic nodes to `rawShape({})`, but a traversal that fails is refused as unreadable rather than widened. **READABLE** therefore means every advertised read for the operation being discussed completes; **STABLE** means those observable reads also keep the same answers across separate calls. The module deliberately ships **flat primitives** instead of a full schema framework — every guard is a one-argument total function and parsers coerce-or-bail rather than collect errors. The `parseJSON` / `parseJSONAs` text boundary stays lazy by default; `isJSONValue`, `parseJSONValue`, `cloneJSONValue`, and the record-root `cloneJSONRecord` are explicit deep whole-tree operations. Recursive contracts remain opt-in through the shape DSL, where the tree is finite and developer-authored. Its source is [`src/core`](../src/core), surfaced through the `@src/core` barrel.
|
|
9
9
|
|
|
10
10
|
## Surface
|
|
11
11
|
|
|
@@ -21,6 +21,7 @@ These exports compose an already compiled contract and format its faults.
|
|
|
21
21
|
| `AuditFaultShape` | type | `ReturnType<FaultShaper['build']>` | Describes the closed shape built for audit faults, including paired discriminator hints. |
|
|
22
22
|
| `admitValue` | function | `<T>(contract: ContractInterface<T>, value: unknown) => Result<T, ContractRefusal>` | Admits a readable value exactly where `is` holds and returns the parser's value. |
|
|
23
23
|
| `repairValue` | function | `<T>(contract: ContractInterface<T>, value: unknown) => Result<ContractRepair<T>, ContractRefusal>` | Repairs a stable readable value with only lossless repairs and returns the parser's value. |
|
|
24
|
+
| `refusalToError` | function | `(refusal: ContractRefusal, door: string, schema?: JSONSchema) => ContractError` | Builds the `ContractError` that reports an admission refusal. |
|
|
24
25
|
| `filterUncoveredFaults` | function | `(faults: readonly AuditFault[]) => readonly AuditFault[]` | Filters out the faults a union fault covers, keeping every fault that states a fact no form shows. |
|
|
25
26
|
| `buildPathKey` | function | `(path: readonly string[], length?: number) => string` | Builds a map key from the leading segments of a path, without dispatching through array serialization. |
|
|
26
27
|
| `describeFaults` | function | `(faults: readonly AuditFault[], schema?: JSONSchema, options?: FaultTextOptions) => string` | Describes bounded faults with encoded values and a schema-derived correction summary. |
|
|
@@ -42,6 +43,45 @@ These exports compose an already compiled contract and format its faults.
|
|
|
42
43
|
refuses with every fault `audit` reports after `filterUncoveredFaults` prunes the faults a `variant` or
|
|
43
44
|
`oneOf` fault covers, bounded at `FAULT_LIMIT`. A `hidden` fault and an `extra` fault carrying `symbol`
|
|
44
45
|
stay whatever covers them. It repairs nothing: a numeric string for a number refuses.
|
|
46
|
+
`refusalToError` turns a refusal into the `ContractError` a door throws: code `structure`, a message
|
|
47
|
+
of the door's name and the `describeFaults` text, the first fault's path and every fault in
|
|
48
|
+
`context`, and the refusal's `cause`.
|
|
49
|
+
|
|
50
|
+
A contract's `own` method admits an owned snapshot in place of the caller's value, so it reads that
|
|
51
|
+
value one time. Each own enumerable string member and each present index of a plain record or array
|
|
52
|
+
is read into a frozen copy that keeps sharing and cycles, and an accessor there becomes data. A
|
|
53
|
+
member outside the enumerable view keeps its presence and its data value, and its accessor never
|
|
54
|
+
runs, so `hidden` and `extra` still report. A value at an `interfaceShape` position, any other
|
|
55
|
+
object, and every function are held by identity and never read, so a class instance at an
|
|
56
|
+
`objectShape` position refuses with a `type` fault. `own` then runs `is` over the snapshot inside
|
|
57
|
+
one evaluation scope, then `parse` when `is` holds and `audit` when it refuses, and it refuses as
|
|
58
|
+
`admitValue` does. A declared interface member is read one time on success and at most two times
|
|
59
|
+
on a refusal whose interface itself faults. Because an interface member is read live, an `audit`
|
|
60
|
+
that finds no fault after `is` refused still refuses, with a `structure` cause stating that the
|
|
61
|
+
value changed between reads. A snapshot past `CLONE_NODE_LIMIT` nodes, an unreadable member, and
|
|
62
|
+
any other throw refuse with no fault and the error as `cause`. For a stable
|
|
63
|
+
value made of data and a contract with no interface, `own` answers as `admitValue` does, in verdict,
|
|
64
|
+
value, and faults. In 0.0.24, a contract held the six keys `schema`, `is`, `parse`, `audit`,
|
|
65
|
+
`explain`, and `generate`; from 0.0.25, `Object.keys(contract)` and a spread of a contract end with
|
|
66
|
+
`own`, and a `ContractInterface` literal written by hand stops compiling until it declares `own`.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import {
|
|
70
|
+
createContract,
|
|
71
|
+
functionShape,
|
|
72
|
+
interfaceShape,
|
|
73
|
+
numberShape,
|
|
74
|
+
objectShape,
|
|
75
|
+
} from '@orkestrel/contract'
|
|
76
|
+
|
|
77
|
+
const store = { get: encodeURI, set: encodeURI }
|
|
78
|
+
const contract = createContract(
|
|
79
|
+
objectShape({ ttl: numberShape(), store: interfaceShape({ get: functionShape() }) }),
|
|
80
|
+
)
|
|
81
|
+
const owned = contract.own({ ttl: 60, store })
|
|
82
|
+
owned.success && owned.value.store === store // true — the implementation is held by identity
|
|
83
|
+
contract.own({ ttl: '60', store }).success // false — the refusal carries the type fault at ['ttl']
|
|
84
|
+
```
|
|
45
85
|
|
|
46
86
|
`repairValue` is the repairing door. It requires stable reads across its guard, reports, and parser,
|
|
47
87
|
parses once, refuses lossy repairs and capped audits, and returns the parser's ownership unchanged.
|
|
@@ -86,7 +126,7 @@ A guard is the `Guard<T>` type from [`types.ts`](../src/core/types.ts):
|
|
|
86
126
|
type Guard<T> = (value: unknown) => value is T
|
|
87
127
|
```
|
|
88
128
|
|
|
89
|
-
Every guard takes one `unknown`, returns a `boolean` TypeScript reads as a type predicate, and **never throws** — a value that doesn't fit is `false`, even on
|
|
129
|
+
Every guard takes one `unknown`, returns a `boolean` TypeScript reads as a type predicate, and **never throws** — a value that doesn't fit is `false`, even on untrusted input (cycles, untrusted prototypes). Totality is universal (`.claude/rules/patterns.md` § Validation and contracts), so any guard is safe to call on anything at any trust boundary. **Purity is not.** It holds for every guard this module builds out of its own reads, and it cannot hold for any combinator that runs YOUR code inside the guard body. The rule: **any combinator that runs code you supplied inherits whatever that code does** — whether you hand it a callback directly, as `whereOf`, `lazyOf` and `transformOf` do, or hand it a guard it composes. If you passed it, its behaviour is yours. Such a guard is exactly as pure and as order-independent as the callback you hand it: a stateful predicate that counts its own calls answers `true` and then `false` for the SAME argument, and one that appends to a log leaves the write behind. Containment keeps it total either way; what it cannot keep is "function of its argument alone". Hand pure callbacks if you want the whole family's guarantee, and read "in any order" as a promise the guards this module builds from its own reads make.
|
|
90
130
|
|
|
91
131
|
Sibling families, each with its own job:
|
|
92
132
|
|
|
@@ -98,29 +138,31 @@ The `*Field` parsers read a (possibly nested) record field through a `FieldPath`
|
|
|
98
138
|
|
|
99
139
|
### Primitive & null-ish guards
|
|
100
140
|
|
|
101
|
-
| Name | Kind | Signature
|
|
102
|
-
| ---------------------- | -------- |
|
|
103
|
-
| `isNull` | function | `(value: unknown) => value is null`
|
|
104
|
-
| `isUndefined` | function | `(value: unknown) => value is undefined`
|
|
105
|
-
| `isDefined` | function | `<T>(value: T \| null \| undefined) => value is T`
|
|
106
|
-
| `isString` | function | `(value: unknown) => value is string`
|
|
107
|
-
| `isNumber` | function | `(value: unknown) => value is number`
|
|
108
|
-
| `isFiniteNumber` | function | `(value: unknown) => value is number`
|
|
109
|
-
| `isInteger` | function | `(value: unknown) => value is number`
|
|
110
|
-
| `isNonNegativeNumber` | function | `(value: unknown) => value is number`
|
|
111
|
-
| `isNonNegativeInteger` | function | `(value: unknown) => value is number`
|
|
112
|
-
| `
|
|
113
|
-
| `
|
|
114
|
-
| `
|
|
115
|
-
| `
|
|
116
|
-
| `
|
|
117
|
-
| `
|
|
118
|
-
| `
|
|
119
|
-
| `
|
|
120
|
-
| `
|
|
121
|
-
| `
|
|
122
|
-
| `
|
|
123
|
-
| `
|
|
141
|
+
| Name | Kind | Signature | Summary |
|
|
142
|
+
| ---------------------- | -------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
143
|
+
| `isNull` | function | `(value: unknown) => value is null` | Determines whether a value is `null`. |
|
|
144
|
+
| `isUndefined` | function | `(value: unknown) => value is undefined` | Determines whether a value is `undefined`. |
|
|
145
|
+
| `isDefined` | function | `<T>(value: T \| null \| undefined) => value is T` | Determines whether a value is defined (neither `null` nor `undefined`). |
|
|
146
|
+
| `isString` | function | `(value: unknown) => value is string` | Determines whether a value is a string. |
|
|
147
|
+
| `isNumber` | function | `(value: unknown) => value is number` | Determines whether a value is a number. |
|
|
148
|
+
| `isFiniteNumber` | function | `(value: unknown) => value is number` | Determines whether a value is a finite number (excludes `NaN` and `±Infinity`). |
|
|
149
|
+
| `isInteger` | function | `(value: unknown) => value is number` | Determines whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers). |
|
|
150
|
+
| `isNonNegativeNumber` | function | `(value: unknown) => value is number` | Determines whether a value is a finite primitive number at or above positive zero. |
|
|
151
|
+
| `isNonNegativeInteger` | function | `(value: unknown) => value is number` | Determines whether a value is a non-negative finite primitive integer. |
|
|
152
|
+
| `isSafeInteger` | function | `(value: unknown) => value is number` | Determines whether a value is a primitive number that is an integer within the safe range. |
|
|
153
|
+
| `isBoolean` | function | `(value: unknown) => value is boolean` | Determines whether a value is a boolean. |
|
|
154
|
+
| `isFaultPath` | function | `(value: unknown) => value is FieldPath` | Determines whether a value is the `FieldPath` a fault carries: a key, or a dense list of keys. |
|
|
155
|
+
| `isFault` | function | `(value: unknown) => value is Fault` | Determines whether a value is exactly one `Fault`. |
|
|
156
|
+
| `isAuditFault` | function | `(value: unknown) => value is AuditFault` | Determines whether a value is exactly one `AuditFault`. |
|
|
157
|
+
| `isAuditFaults` | function | `(value: unknown) => value is readonly AuditFault[]` | Determines whether a value is a dense list of `AuditFault` values. |
|
|
158
|
+
| `isLiteralValue` | function | `(value: unknown) => value is LiteralValue` | Determines whether a value belongs to the string, number, or boolean literal domain. |
|
|
159
|
+
| `isTrue` | function | `(value: unknown) => value is true` | Determines whether a value is exactly `true`. |
|
|
160
|
+
| `isFalse` | function | `(value: unknown) => value is false` | Determines whether a value is exactly `false`. |
|
|
161
|
+
| `isBigInt` | function | `(value: unknown) => value is bigint` | Determines whether a value is a bigint. |
|
|
162
|
+
| `isSymbol` | function | `(value: unknown) => value is symbol` | Determines whether a value is a symbol. |
|
|
163
|
+
| `isNullableString` | function | `(value: unknown) => value is string \| null` | Determines whether a value is a string or `null`. |
|
|
164
|
+
| `isNullableNumber` | function | `(value: unknown) => value is number \| null` | Determines whether a value is a number or `null` (the number may be `NaN` / `±Infinity`). |
|
|
165
|
+
| `isNullableBoolean` | function | `(value: unknown) => value is boolean \| null` | Determines whether a value is a boolean or `null`. |
|
|
124
166
|
|
|
125
167
|
### Structural & collection guards
|
|
126
168
|
|
|
@@ -135,6 +177,7 @@ The `*Field` parsers read a (possibly nested) record field through a `FieldPath`
|
|
|
135
177
|
| `isDate` | function | `(value: unknown) => value is Date` | Determines whether a value is a `Date`. |
|
|
136
178
|
| `isRegExp` | function | `(value: unknown) => value is RegExp` | Determines whether a value is a `RegExp`. |
|
|
137
179
|
| `isError` | function | `(value: unknown) => value is Error` | Determines whether a value is an `Error`. |
|
|
180
|
+
| `isCodedError` | function | `(value: unknown) => value is Error & { readonly code: string; }` | Determines whether a value is an `Error` whose `code` is a string. |
|
|
138
181
|
| `isPromise` | function | `<T = unknown>(value: unknown) => value is Promise<T>` | Determines whether a value is a native `Promise` (use `isPromiseLike` for any thenable). |
|
|
139
182
|
| `isPromiseLike` | function | `<T = unknown>(value: unknown) => value is Promise<T> \| (PromiseLike<T> & { catch: unknown; finally: unknown; })` | Determines whether a value is promise-like — an object exposing callable `then`, `catch`, and `finally` methods. |
|
|
140
183
|
| `isIterable` | function | `<T = unknown>(value: unknown) => value is Iterable<T>` | Determines whether a value implements the iterable protocol (`Symbol.iterator`). |
|
|
@@ -144,9 +187,11 @@ The `*Field` parsers read a (possibly nested) record field through a `FieldPath`
|
|
|
144
187
|
|
|
145
188
|
#### Recognizing a plain record
|
|
146
189
|
|
|
147
|
-
`isRecord` must recognize a plain object from another realm — a `vm.Context`, an iframe, a worker — whose `Object.prototype` is a different object from this realm's. It therefore identifies a foreign `Object.prototype` by the own members every conformant realm puts on it (`constructor`, `hasOwnProperty`, `isPrototypeOf`, `propertyIsEnumerable`, `toLocaleString`, `toString`, `valueOf`), each read through its own descriptor so no accessor on
|
|
190
|
+
`isRecord` must recognize a plain object from another realm — a `vm.Context`, an iframe, a worker — whose `Object.prototype` is a different object from this realm's. It therefore identifies a foreign `Object.prototype` by the own members every conformant realm puts on it (`constructor`, `hasOwnProperty`, `isPrototypeOf`, `propertyIsEnumerable`, `toLocaleString`, `toString`, `valueOf`), each read through its own descriptor so no accessor on an untrusted prototype runs, and each required to be an own data property whose value is a function.
|
|
191
|
+
|
|
192
|
+
That is a structural test rather than a provenance one, and the residual is exactly this: a prototype fabricated to carry the mandated names as function-valued own data properties passes, while a prototype carrying the same names with no values is refused. A class prototype merely reparented to `null` fails, and so do `Date` and an ordinary class instance. The pass buys acceptance at brand-governed doors and nothing after it — every ownership engine builds a frozen plain record from captured data, so no class instance, class behavior, or fabricated prototype survives into a snapshot.
|
|
148
193
|
|
|
149
|
-
|
|
194
|
+
A value another package or the host returns, such as a socket or a store, can be a class instance, and `isRecord` refuses a class instance. Guard such a value by the members you read: `objectOf` builds that guard from member guards, and `interfaceShape` declares it inside a contract.
|
|
150
195
|
|
|
151
196
|
### Array & typed-array guards
|
|
152
197
|
|
|
@@ -267,23 +312,23 @@ the constant's own literal:
|
|
|
267
312
|
|
|
268
313
|
The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, while `parseJSONAs` walks only the guard shape supplied by its caller. `isJSONValue` and `parseJSONValue` are shipped explicit deep whole-tree gates; `isBoundedJSONValue` adds the fixed resource boundary, and `isBoundedJSONRecord` adds the record-root invariant. `JSONRecord` and `cloneJSONRecord` provide the record-root ownership contract required by metadata and persistence consumers, while `cloneJSONValue` owns any JSON root. A dedicated `JSONArray` alias, broad deep `isJSONObject` / `isJSONSchema` validators, and the ~50-field `JSONSchemaDefinition` remain deliberately omitted. Compose narrower shapes from the combinators and read a parsed blob field-by-field with the `parse*Field` readers when whole-tree work is unnecessary.
|
|
269
314
|
|
|
270
|
-
| Name | Kind | Signature
|
|
271
|
-
| ------------------------ | --------- |
|
|
272
|
-
| `isJSONPrimitive` | function | `(value: unknown) => value is JSONPrimitive`
|
|
273
|
-
| `isJSONValue` | function | `(value: unknown) => value is JSONValue`
|
|
274
|
-
| `isBoundedJSONValue` | function | `(value: unknown) => value is JSONValue`
|
|
275
|
-
| `isBoundedJSONRecord` | function | `(value: unknown) => value is JSONRecord`
|
|
276
|
-
| `parseJSON` | function | `(value: string) => unknown`
|
|
277
|
-
| `parseJSONAs` | function | `<T>(value: string, guard: Guard<T>) => T \| undefined`
|
|
278
|
-
| `JSON_SCHEMA_TYPES` | const | `readonly JSONSchemaType[]`
|
|
279
|
-
| `SCHEMA_ANNOTATIONS` | const | `readonly ["title", "description", "$schema", "$id", "$comment", "deprecated", "readOnly", "writeOnly", "examples"]`
|
|
280
|
-
| `STRICT_SCHEMA_KEYWORDS` | const | `readonly string[]`
|
|
281
|
-
| `JSONPrimitive` | type | `string \| number \| boolean \| null`
|
|
282
|
-
| `JSONRecord` | type | `{ readonly [key: string]: JSONValue; }`
|
|
283
|
-
| `JSONValue` | type | `JSONPrimitive \| readonly JSONValue[] \| JSONRecord`
|
|
284
|
-
| `JSONSchemaType` | type | `'null' \| 'boolean' \| 'object' \| 'array' \| 'number' \| 'integer' \| 'string'`
|
|
285
|
-
| `JSONSchema` | interface | `{ type?, description?, default?, enum?, minLength?, maxLength?, pattern?, format?, minimum?, maximum?, minItems?, maxItems?, items?, properties?, required?, additionalProperties?, anyOf?, oneOf?, not? }` | Represents a JSON Schema fragment — the supported keyword vocabulary the contract compiler emits and `RawShape` validates before embedding. |
|
|
286
|
-
| `SchemaFormat` | type | `'date-time' \| 'date' \| 'time' \| 'uuid' \| 'email' \| 'uri'`
|
|
315
|
+
| Name | Kind | Signature | Summary |
|
|
316
|
+
| ------------------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
317
|
+
| `isJSONPrimitive` | function | `(value: unknown) => value is JSONPrimitive` | Determines whether a value is a primitive JSON value. |
|
|
318
|
+
| `isJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is a cycle-safe JSON value. |
|
|
319
|
+
| `isBoundedJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is JSON-valid within the fixed container-depth limit. |
|
|
320
|
+
| `isBoundedJSONRecord` | function | `(value: unknown) => value is JSONRecord` | Determines whether a value is a depth-bounded JSON record. |
|
|
321
|
+
| `parseJSON` | function | `(value: string) => unknown` | Parses a JSON string, returning `undefined` instead of throwing. |
|
|
322
|
+
| `parseJSONAs` | function | `<T>(value: string, guard: Guard<T>) => T \| undefined` | Parses a JSON string and validates the result against a guard. |
|
|
323
|
+
| `JSON_SCHEMA_TYPES` | const | `readonly JSONSchemaType[]` | Lists the seven standard JSON Schema `type` names, frozen. |
|
|
324
|
+
| `SCHEMA_ANNOTATIONS` | const | `readonly ["title", "description", "$schema", "$id", "$comment", "deprecated", "readOnly", "writeOnly", "examples"]` | Lists the JSON Schema annotations a strict `schemaToShape` conversion admits on any node, frozen. |
|
|
325
|
+
| `STRICT_SCHEMA_KEYWORDS` | const | `readonly string[]` | Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen. |
|
|
326
|
+
| `JSONPrimitive` | type | `string \| number \| boolean \| null` | Represents a primitive JSON value — the flat leaf of any JSON document. |
|
|
327
|
+
| `JSONRecord` | type | `{ readonly [key: string]: JSONValue; }` | Represents a readonly string-keyed JSON object record. |
|
|
328
|
+
| `JSONValue` | type | `JSONPrimitive \| readonly JSONValue[] \| JSONRecord` | Represents a recursive JSON value — primitives, arrays, and object records. |
|
|
329
|
+
| `JSONSchemaType` | type | `'null' \| 'boolean' \| 'object' \| 'array' \| 'number' \| 'integer' \| 'string'` | Lists the seven standard JSON Schema `type` names. |
|
|
330
|
+
| `JSONSchema` | interface | `{ type?, description?, default?, enum?, minLength?, maxLength?, pattern?, format?, minimum?, maximum?, exclusiveMinimum?, exclusiveMaximum?, minItems?, maxItems?, items?, properties?, required?, additionalProperties?, anyOf?, oneOf?, not? }` | Represents a JSON Schema fragment — the supported keyword vocabulary the contract compiler emits and `RawShape` validates before embedding. |
|
|
331
|
+
| `SchemaFormat` | type | `'date-time' \| 'date' \| 'time' \| 'uuid' \| 'email' \| 'uri'` | Lists the closed set of string formats `stringToFormat` recognizes. |
|
|
287
332
|
|
|
288
333
|
### Helper
|
|
289
334
|
|
|
@@ -291,71 +336,75 @@ The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, wh
|
|
|
291
336
|
| ---------------------- | ----- | --------------- | --------------------------------------------------------------------------------------------- |
|
|
292
337
|
| `CONTRACT_ERROR_BRAND` | const | `unique symbol` | Holds the registry-global key used to recognize `ContractError` values across package copies. |
|
|
293
338
|
|
|
294
|
-
| Name | Kind | Signature
|
|
295
|
-
| ----------------------- | -------- |
|
|
296
|
-
| `success` | function | `<T>(value: T) => Success<T>`
|
|
297
|
-
| `failure` | function | `<E>(error: E) => Failure<E>`
|
|
298
|
-
| `isSuccess` | function | `<T, E>(result: Result<T, E>) => result is Success<T>`
|
|
299
|
-
| `isFailure` | function | `<T, E>(result: Result<T, E>) => result is Failure<E>`
|
|
300
|
-
| `attempt` | function | `<T>(callback: () => T) => Result<T>`
|
|
301
|
-
| `
|
|
302
|
-
| `
|
|
303
|
-
| `
|
|
304
|
-
| `
|
|
305
|
-
| `
|
|
306
|
-
| `
|
|
307
|
-
| `
|
|
308
|
-
| `
|
|
309
|
-
| `
|
|
310
|
-
| `
|
|
311
|
-
| `
|
|
312
|
-
| `
|
|
313
|
-
| `
|
|
314
|
-
| `
|
|
315
|
-
| `
|
|
316
|
-
| `
|
|
317
|
-
| `
|
|
318
|
-
| `
|
|
319
|
-
| `
|
|
320
|
-
| `
|
|
321
|
-
| `
|
|
322
|
-
| `
|
|
323
|
-
| `
|
|
324
|
-
| `
|
|
325
|
-
| `
|
|
326
|
-
| `
|
|
327
|
-
| `
|
|
328
|
-
| `
|
|
329
|
-
| `
|
|
330
|
-
| `
|
|
331
|
-
| `
|
|
332
|
-
| `
|
|
333
|
-
| `
|
|
334
|
-
| `
|
|
335
|
-
| `
|
|
336
|
-
| `
|
|
337
|
-
| `
|
|
338
|
-
| `
|
|
339
|
-
| `
|
|
340
|
-
| `
|
|
341
|
-
| `
|
|
342
|
-
| `
|
|
343
|
-
| `
|
|
344
|
-
| `
|
|
345
|
-
| `
|
|
346
|
-
| `
|
|
347
|
-
|
|
348
|
-
|
|
|
349
|
-
|
|
350
|
-
|
|
|
351
|
-
|
|
|
352
|
-
| `
|
|
353
|
-
| `
|
|
354
|
-
| `
|
|
355
|
-
| `
|
|
356
|
-
| `
|
|
357
|
-
| `
|
|
358
|
-
| `
|
|
339
|
+
| Name | Kind | Signature | Summary |
|
|
340
|
+
| ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
341
|
+
| `success` | function | `<T>(value: T) => Success<T>` | Boxes a value as the `Success` branch of a `Result`. |
|
|
342
|
+
| `failure` | function | `<E>(error: E) => Failure<E>` | Boxes an error as the `Failure` branch of a `Result`. |
|
|
343
|
+
| `isSuccess` | function | `<T, E>(result: Result<T, E>) => result is Success<T>` | Narrows a `Result` to its `Success` branch. |
|
|
344
|
+
| `isFailure` | function | `<T, E>(result: Result<T, E>) => result is Failure<E>` | Narrows a `Result` to its `Failure` branch. |
|
|
345
|
+
| `attempt` | function | `<T>(callback: () => T) => Result<T>` | Invokes a callback once and synchronously captures its exact outcome as a `Result`. |
|
|
346
|
+
| `settle` | function | `<T>(callback: () => T \| PromiseLike<T>) => Promise<Result<T>>` | Settles a callback's outcome, synchronous or awaited, as a `Result`. |
|
|
347
|
+
| `errorToMessage` | function | `(error: unknown) => string` | Renders a thrown value as a non-empty message. |
|
|
348
|
+
| `INTRINSICS` | const | `Readonly<{ freeze: { <T extends Function>(f: T): T; <T extends { [idx: string]: U \| null \| undefined \| object; }, U extends string \| bigint \| number \| boolean \| symbol>(o: T): Readonly<T>; <T>(o: T): Readonly<T>; }; frozen: (o: any) => boolean; keys: { (o: object): string[]; (o: {}): string[]; }; values: { <T>(o: { [s: string]: T; } \| ArrayLike<T>): T[]; (o: {}): any[]; }; own: (o: object, v: PropertyKey) => boolean; same: (value1: any, value2: any) => boolean; create: { (o: object \| null): any; (o: object \| null, properties: PropertyDescriptorMap & ThisType<any>): any; }; proxy: ProxyConstructor; describe: (o: any, p: PropertyKey) => PropertyDescriptor \| undefined; define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T; definitions: <T>(o: T, properties: PropertyDescriptorMap & ThisType<any>) => T; prototype: (o: any) => any; symbols: (o: any) => symbol[]; names: (o: any) => string[]; base: Object; reflect: Readonly<{ read: typeof Reflect.get; write: typeof Reflect.set; members: typeof Reflect.ownKeys; present: typeof Reflect.has; describe: typeof Reflect.getOwnPropertyDescriptor; define: typeof Reflect.defineProperty; prototype: typeof Reflect.getPrototypeOf; apply: typeof Reflect.apply; construct: typeof Reflect.construct; }>; finite: (number: unknown) => boolean; integer: (number: unknown) => boolean; safe: (number: unknown) => boolean; nan: (number: unknown) => boolean; array: (arg: any) => arg is any[]; stringify: { (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string \| number): string; (value: any, replacer?: (number \| string)[] \| null, space?: string \| number): string; }; decode: (text: string, reviver?: (this: any, key: string, value: any) => any) => any; floor: (x: number) => number; ceil: (x: number) => number; max: (...values: number[]) => number; min: (...values: number[]) => number; imul: (x: number, y: number) => number; text: StringConstructor; numeric: NumberConstructor; pattern: RegExpConstructor; captures: (string: string) => RegExpExecArray \| null; expression: (() => any) \| undefined; modifiers: (() => any) \| undefined; list: ArrayConstructor; order: (compareFn?: ((a: any, b: any) => number) \| undefined) => any[]; some: (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any) => boolean; every: { <S extends any>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): this is S[]; (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean; }; find: (predicate: (value: any, index: number, obj: any[]) => unknown, thisArg?: any) => number; each: (callbackfn: (value: any, index: number, array: any[]) => void, thisArg?: any) => void; from: { <T>(arrayLike: ArrayLike<T>): T[]; <T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; <T>(iterable: Iterable<T> \| ArrayLike<T>): T[]; <T, U>(iterable: Iterable<T> \| ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; }; fold: { (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any): any; (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any; <U>(callbackfn: (previousValue: U, currentValue: any, currentIndex: number, array: any[]) => U, initialValue: U): U; }; reduce: { (callbackfn: (previousValue: any, currentValue: any, currentIndex: number) => any): any; (callbackfn: (previousValue: any, currentValue: any, currentIndex: number) => any, initialValue: any): any; <U>(callbackfn: (previousValue: U, currentValue: any, currentIndex: number) => U, initialValue: U): U; }; select: { <S extends any>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]; (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]; }; project: <U>(callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any) => U[]; expand: <U, This = undefined>(callback: (this: This, value: any, index: number, array: any[]) => U \| readonly U[], thisArg?: This \| undefined) => U[]; flip: () => any[]; iterator: () => ArrayIterator<any>; indices: () => ArrayIterator<number>; advance: any; slice: (start?: number, end?: number) => string; join: (separator?: string) => string; bind: (this: Function, thisArg: any, ...argArray: any[]) => any; record: { <T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k: string]: T; }; (entries: Iterable<readonly any[]>): any; }; rebase: (o: any, proto: object \| null) => any; map: MapConstructor; fetch: (key: any) => any; store: (key: any, value: any) => Map<any, any>; keyed: (key: any) => boolean; pairs: (callbackfn: (value: any, key: any, map: Map<any, any>) => void, thisArg?: any) => void; set: SetConstructor; union: <U>(other: ReadonlySetLike<U>) => Set<any>; member: (value: any) => boolean; admit: (value: any) => Set<any>; sweep: (callbackfn: (value: any, value2: any, set: Set<any>) => void, thisArg?: any) => void; remove: (value: any) => boolean; weakMap: WeakMapConstructor; recall: (key: WeakKey) => any; retain: (key: WeakKey, value: any) => WeakMap<WeakKey, any>; weakSet: WeakSetConstructor; tracked: (value: WeakKey) => boolean; track: (value: WeakKey) => WeakSet<WeakKey>; untrack: (value: WeakKey) => boolean; error: ErrorConstructor; date: DateConstructor; instant: () => number; now: () => number; }>` | Captures every host operation this package dispatches through, while this module evaluates. |
|
|
349
|
+
| `contain` | function | `<T>(callback: () => T, door: string, options?: ContainOptions) => T` | Runs a public door's whole body and publishes only this package's error class. |
|
|
350
|
+
| `appendEntries` | function | `<T>(target: T[], source: readonly T[]) => void` | Appends every element of one array onto another, by index. |
|
|
351
|
+
| `limitEntries` | function | `<T>(entries: readonly T[], limit: number) => readonly T[]` | Takes at most `limit` leading elements of an array, by index. |
|
|
352
|
+
| `comparePrimitives` | function | `<T extends string \| number>(left: T, right: T) => number` | Orders two primitive keys or indices ascending. |
|
|
353
|
+
| `sortValues` | function | `<T extends string \| number>(values: readonly T[]) => readonly T[]` | Orders primitive keys or indices deterministically, on an owned copy, through the captured sort. |
|
|
354
|
+
| `pathOf` | function | `(path: readonly string[], ...segments: ReadonlyArray<string \| undefined>) => readonly string[]` | Builds a diagnostic path from an existing path and further segments, without dispatching through array iteration. |
|
|
355
|
+
| `readValue` | function | `<T>(callback: () => T, reader: string, options?: ReadValueOptions) => T` | Reads a value through the shared containment boundary or refuses it with the contract module's uniform read diagnostic. |
|
|
356
|
+
| `collectArrayEntries` | function | `<T>(value: readonly T[]) => ArrayRead<T>` | Collects an array's entries through its reflected own-index population. |
|
|
357
|
+
| `readArrayEntries` | function | `<T>(value: readonly T[]) => Result<ArrayRead<T>>` | Snapshots an array through its reflected own-index population. |
|
|
358
|
+
| `readGuardShape` | function | `(shape: GuardsShape, optional: readonly string[] \| true \| undefined, reader: string) => GuardShapeRead` | Snapshots a guard shape and its optional-key mode for a shape combinator. |
|
|
359
|
+
| `holds` | function | `(callback: () => boolean) => boolean` | Invokes a predicate through the sanctioned never-throw boundary. |
|
|
360
|
+
| `enumerableKeys` | function | `(value: object) => readonly string[] \| undefined` | Snapshots an object's own enumerable string keys through a total boundary. |
|
|
361
|
+
| `matchesEnumerableKeys` | function | `(value: object, keys: readonly string[]) => boolean` | Checks whether an object owns no key outside the enumerable string keys already read from it. |
|
|
362
|
+
| `readOptions` | function | `<T extends object>(source: T \| undefined, keys: ReadonlyArray<keyof T & string>, builder: string, shape: string) => T \| undefined` | Validates and snapshots a shape-builder options record through every reflective operation the builder relies on. |
|
|
363
|
+
| `refuseOptionKeys` | function | `(source: object \| undefined, keys: readonly string[], builder: string, shape: string) => void` | Refuses an options record that holds a key its builder does not read. |
|
|
364
|
+
| `refuseValue` | function | `<T>(value: unknown, guard: Guard<T>, door: string, options: RefuseValueOptions) => asserts value is T` | Refuses a value that fails a guard with a located, uniform diagnostic, and narrows it when the guard holds. |
|
|
365
|
+
| `drawRandom` | function | `(random: RandomFunction, shape: string) => number` | Draws and validates one generator random sample. |
|
|
366
|
+
| `enumerableSymbolCount` | function | `(value: object) => number` | Counts the enumerable own-symbol keys on a value. |
|
|
367
|
+
| `matchesJSONValue` | function | `(entry: unknown, ancestors: WeakSet<object>, budget?: { left: number; }) => entry is JSONValue` | Matches an unknown value against the recursive JSON value structure. |
|
|
368
|
+
| `matchesRecordBrand` | function | `(value: unknown) => boolean` | Determines whether a value carries the plain-record brand, raising an untrusted prototype observation instead of answering it. |
|
|
369
|
+
| `matchesJSONDepth` | function | `(value: unknown) => boolean` | Determines whether a readable value stays within the fixed JSON container-depth limit. |
|
|
370
|
+
| `resolveField` | function | `(record: Readonly<Record<string, unknown>>, path: FieldPath) => unknown` | Resolves a (possibly nested) field value from a record by a key or key path. |
|
|
371
|
+
| `seededRandom` | function | `(seed: number) => RandomFunction` | Builds a deterministic pseudo-random source seeded from a single number. |
|
|
372
|
+
| `schemaToParameters` | function | `(schema: JSONSchema) => Readonly<Record<string, unknown>> \| undefined` | Narrows a compiled `JSONSchema` down to the open `Readonly<Record<string, unknown>>` shape tool definitions advertise as `parameters` — through the `isRecord` boundary guard, never an assertion, as `.claude/rules/patterns.md` § Validation and contracts requires. |
|
|
373
|
+
| `schemaToObject` | function | `(schema: JSONSchema) => JSONSchema` | Wraps a non-object `JSONSchema` root in a single-property object schema, so an inferred primitive/array/union schema can flow into `schemaToParameters` as an MCP-compatible `inputSchema`. |
|
|
374
|
+
| `collectMembers` | function | `(values: readonly unknown[]) => Set<unknown>` | Collects an array's entries into a membership collection this package owns. |
|
|
375
|
+
| `matchesMember` | function | `(members: ReadonlySet<unknown>, value: unknown) => boolean` | Determines whether a value is a member of a collected vocabulary, by SameValueZero. |
|
|
376
|
+
| `admitMember` | function | `(members: Set<unknown>, value: unknown) => void` | Collects one more member into a vocabulary that grows as a walk proceeds. |
|
|
377
|
+
| `matchesVisited` | function | `(visited: WeakSet<object>, value: object) => boolean` | Determines whether an object is already on a traversal's active path. |
|
|
378
|
+
| `admitVisited` | function | `(visited: WeakSet<object>, value: object) => void` | Records an object as entered on a traversal's active path. |
|
|
379
|
+
| `omitVisited` | function | `(visited: WeakSet<object>, value: object) => void` | Records an object as exited from a traversal's active path. |
|
|
380
|
+
| `retainDepth` | function | `<T>(memo: WeakMap<object, Map<number, T>>, node: object, depth: number, answer: T) => void` | Records one node's answer at one remaining-depth allowance in a shared memo. |
|
|
381
|
+
| `collectEntries` | function | `(target: unknown[][]) => EntryCollectorFunction` | Builds the collector a captured `forEach` sweep appends through. |
|
|
382
|
+
| `readSetEntries` | function | `(value: ReadonlySet<unknown>) => Result<readonly unknown[]>` | Snapshots the genuine contents of a caller's `Set` without running an iterator. |
|
|
383
|
+
| `readMapEntries` | function | `(value: ReadonlyMap<unknown, unknown>) => Result<ReadonlyArray<readonly unknown[]>>` | Snapshots the genuine entries of a caller's `Map` without running an iterator. |
|
|
384
|
+
| `matchesPattern` | function | `(pattern: RegExp, value: string) => boolean` | Determines whether a string is in the language of a pattern this package owns. |
|
|
385
|
+
| `matchesStringLength` | function | `(value: string, min: number \| undefined, max: number \| undefined) => boolean` | Checks whether a string's length in code points falls within optional bounds. |
|
|
386
|
+
| `computeSurrogatePairs` | function | `(value: string, limit: number) => number` | Counts the surrogate pairs in a string, stopping at a limit. |
|
|
387
|
+
| `escapeRegExp` | function | `(value: string) => string` | Escapes every regular-expression metacharacter in a text, so the text matches literally inside a larger `RegExp` source. |
|
|
388
|
+
| `readPatternSource` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's source text through the captured accessor. |
|
|
389
|
+
| `readPatternFlags` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's flag text through the captured accessor. |
|
|
390
|
+
| `readPattern` | function | `(pattern: RegExp) => RegExp` | Rebuilds a caller's regular expression as a stateless pattern this package owns. |
|
|
391
|
+
| `ownPattern` | function | `(pattern: RegExp, reader: string) => RegExp` | Rebuilds a declaration's regular expression as a stateless pattern this package owns, and refuses an unreadable one under the reader's own name. |
|
|
392
|
+
| `pinMembers` | function | `(prototype: object, owner: string) => void` | Pins every own member of a class prototype as a non-configurable member — non-writable too when it is a data property — and verify the pin took. |
|
|
393
|
+
| `refuseExpansion` | function | `(expansion: number \| undefined) => void` | Refuses a validated declaration whose compiled expansion exceeds `COMPILE_NODE_LIMIT`. |
|
|
394
|
+
|
|
395
|
+
| Name | Kind | Signature | Summary |
|
|
396
|
+
| -------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
|
|
397
|
+
| `iterateIndices` | function | `(read: LengthReader) => Generator<number, void, unknown>` | Iterates indices while rereading the upper bound before every step. |
|
|
398
|
+
| `encodeParts` | function | `(members: readonly unknown[], keys: readonly string[] \| undefined, encodings: WeakMap<object, string>) => Generator<string, void, unknown>` | Encodes ordered members, stopping before the first unencodable member. |
|
|
399
|
+
| `previewParts` | function | `(source: string, index: number, capacity: number, quoted: boolean) => readonly string[]` | Builds bounded escaped preview parts without splitting a surrogate pair. |
|
|
400
|
+
| `previewText` | function | `(source: string, capacity: number, quoted: boolean) => string` | Encodes a bounded window of a source text as preview tokens in one pass. |
|
|
401
|
+
| `escapeControls` | function | `(text: string) => string` | Replaces each DEL, C1 control, U+2028, and U+2029 in a text with its `\u` sequence. |
|
|
402
|
+
| `buildPositions` | function | `(names: readonly string[]) => Readonly<Record<string, number>>` | Builds a null-prototype lookup from names to their last index. |
|
|
403
|
+
| `readPresence` | function | `(names: readonly string[], positions: Readonly<Record<string, number>>) => number` | Derives the bit mask of names present in an indexed lookup. |
|
|
404
|
+
| `LengthReader` | type | `() => number` | Reads the current upper bound of an indexed walk. |
|
|
405
|
+
| `EvaluationFunction` | type | `(value: unknown, path: readonly string[]) => T` | Evaluates a compiled node at one diagnostic path. |
|
|
406
|
+
| `parseEnumValues` | function | `<const T extends LiteralValue>(values: readonly unknown[], allowed: readonly T[]) => Generator<T \| undefined, void, unknown>` | Parses indexed enum members, ending after the first undefined result. |
|
|
407
|
+
| `readIndexView` | function | `(values: readonly unknown[]) => object` | Exposes indexed reads through a non-array receiver without species dispatch. |
|
|
359
408
|
|
|
360
409
|
`matchesJSONDepth` is deliberately depth-only: active cycles terminate successfully at the depth layer but remain invalid JSON, honest sparse holes add no child depth but fail the dense `isJSONValue` contract, and readable exotics pass as leaves but fail JSON validity. `isBoundedJSONValue` therefore performs two total sequential observations — fixed depth first, then the existing JSON guard — rather than promising an atomic snapshot of caller-owned state. It validates but does not own; use `cloneJSONValue` / `cloneJSONRecord` when an independent frozen snapshot is required. The fixed cap is package safety mechanism, not configurable product policy: byte budgets, key budgets, configured wire depth, unsafe-name rejection, descriptor policy, and application-specific limits remain with their consuming package.
|
|
361
410
|
|
|
@@ -379,25 +428,25 @@ So `matchesMember` / `admitMember` / `collectMembers` own literal, enum and key
|
|
|
379
428
|
|
|
380
429
|
The scope claim, stated so it can be checked rather than trusted: **no membership answer this package publishes — literal, enum, pattern, set, map, intersection, record key, declared key, or schema keyword — is decided by a property lookup on any object a caller can reach.** The standing proof is `tests/src/core/integration.test.ts`, which sweeps every membership door against every lying host member, against both accessors of `RegExp.prototype`, and against every writable prototype member of every value this package exports as a constructor. That last population is not empty: an earlier sentence here said it was "empty, because each of those classes pins its prototype while it is defined", which ran a true claim about the CLASSES together with a false one about the population. The rule draws from every exported callable, and an ordinary exported FUNCTION's `.prototype.constructor` is writable and always will be — so the corpus is one row per exported plain function and zero rows per exported class. The sweep asserts what it always asserted, that no door consults any of them. The suite pins the corpus's composition against the barrel rather than against a remembered number: every exported plain function contributes exactly one row, every row is a `.prototype.constructor`, and no exported class contributes any. A count stated here drifted for a round after further functions were exported, which is why no number stands here.
|
|
381
430
|
|
|
382
|
-
What that claim does NOT cover is named rather than left to be discovered: the load-order precondition
|
|
431
|
+
What that claim does NOT cover is named rather than left to be discovered: the load-order precondition that follows, and a caller who replaces a door's own method and then calls that door, which is their arrangement rather than this package's defect.
|
|
383
432
|
|
|
384
433
|
### Threat model
|
|
385
434
|
|
|
386
435
|
Stated as a LIMIT, because a security claim that names no boundary is not checkable.
|
|
387
436
|
|
|
388
|
-
**This package does not defend against an adversary who can modify shared intrinsics in its own realm.** A caller who can assign `String.prototype.trim`, `Object.freeze`, or `Set.prototype.has` is already running arbitrary code in the same realm as this package and can replace the package outright — swap the module, wrap every export, or answer the verification read that any self-check performs. Defending is impossible in principle rather than merely unimplemented, and it is the assumption every comparable validation library makes. The same argument covers the load-order precondition
|
|
437
|
+
**This package does not defend against an adversary who can modify shared intrinsics in its own realm.** A caller who can assign `String.prototype.trim`, `Object.freeze`, or `Set.prototype.has` is already running arbitrary code in the same realm as this package and can replace the package outright — swap the module, wrap every export, or answer the verification read that any self-check performs. Defending is impossible in principle rather than merely unimplemented, and it is the assumption every comparable validation library makes. The same argument covers the earlier load-order precondition: a module that evaluates first chooses what `INTRINSICS` captures, and nothing inside the package can reach code that ran before the package existed.
|
|
389
438
|
|
|
390
|
-
The hardening that exists for that adversary anyway — `contain`, `INTRINSICS`, the module-scope membership functions, `pinMembers`, the indexed publication walks — **stays, raises attacker cost, and is not claimed to be complete.** Its sweeps in `tests/src/core/integration.test.ts` are regression guards over work already paid for, not acceptance gates: a
|
|
439
|
+
The hardening that exists for that adversary anyway — `contain`, `INTRINSICS`, the module-scope membership functions, `pinMembers`, the indexed publication walks — **stays, raises attacker cost, and is not claimed to be complete.** Its sweeps in `tests/src/core/integration.test.ts` are regression guards over work already paid for, not acceptance gates: a discovered intrinsic vector is recorded as a boundary case rather than treated as a release blocker.
|
|
391
440
|
|
|
392
|
-
What IS guaranteed, with honest intrinsics and
|
|
441
|
+
What IS guaranteed, with honest intrinsics and untrusted DATA:
|
|
393
442
|
|
|
394
443
|
- **Guards are total.** Every `is*` and every combinator-built guard answers a `boolean` for any input — a throwing getter, a revoked or trap-throwing `Proxy`, a cycle, a 200,000-deep graph, a foreign realm, an exotic host — and never propagates a throw.
|
|
395
444
|
- **Published snapshots are frozen and faithful.** A builder freezes what it returns and copies what you hand it; `cloneShape` / `cloneSchema` / `cloneJSONValue` publish deeply frozen graphs that retain no caller reference, and a snapshot that cannot be faithful refuses instead of normalizing.
|
|
396
445
|
- **`is`, `parse`, `audit` and `explain` agree.** No input is certified clean by one door and refused by another: the laws in Domains hold for readable, stably-read values, and where a door must perform a read that can fail, every door that answers about the same value performs it.
|
|
397
|
-
- **
|
|
398
|
-
- **A shared reference costs one visit, a published bound, or nothing at all.** Declaration capture has a per-door-call budget of `CLONE_NODE_LIMIT` (262,144): each retained edge and each copied default node spends one unit, including edges in a container shared by several owners. Ownership and validation-only walks enforce this before retention and refuse with `clone`; a shape-valued `is` reports the refusal as `false`. `COMPILE_DEPTH_LIMIT`, `GUARD_DEPTH_LIMIT`, `FAULT_LIMIT`, `INFER_DEPTH_LIMIT`, `INFER_BREADTH_LIMIT`, `CLONE_NODE_LIMIT` and `COMPILE_NODE_LIMIT` are the published bounds, and where a bound is the wrong instrument the walk carries an identity memo instead. Sharing arrives on BOTH sides and both are answered: `COMPILE_NODE_LIMIT` caps what a shared-child DECLARATION expands into (see Compilers), and `is`, `audit` and `explain` answer a shared-reference VALUE in one visit per (compiled node, object) pair however many paths reach that object. Both halves are needed: without the value-side memo an ordinary graph with several references per level — a few hundred bytes, no attacker, shared references are normal data — costs node reads exponential in its depth. A faulted node is re-walked at its new path, because a fault carries one, and stays bounded by `FAULT_LIMIT`. `cloneJSONValue` and `parse` deliberately still expand and each says so here: `cloneJSONValue` duplicates an alias by contract and caps that at `CLONE_NODE_LIMIT`, and `parse` materializes a tree — see the line
|
|
446
|
+
- **Untrusted data is refused with a coded `ContractError`.** Cycles, excessive depth, exotic objects, foreign realms, revoked proxies, throwing accessors and unstable reads reach a coded refusal or a documented non-match, never a raw host error and never an unbounded walk.
|
|
447
|
+
- **A shared reference costs one visit, a published bound, or nothing at all.** Declaration capture has a per-door-call budget of `CLONE_NODE_LIMIT` (262,144): each retained edge and each copied default node spends one unit, including edges in a container shared by several owners. Ownership and validation-only walks enforce this before retention and refuse with `clone`; a shape-valued `is` reports the refusal as `false`. `COMPILE_DEPTH_LIMIT`, `GUARD_DEPTH_LIMIT`, `FAULT_LIMIT`, `INFER_DEPTH_LIMIT`, `INFER_BREADTH_LIMIT`, `CLONE_NODE_LIMIT` and `COMPILE_NODE_LIMIT` are the published bounds, and where a bound is the wrong instrument the walk carries an identity memo instead. Sharing arrives on BOTH sides and both are answered: `COMPILE_NODE_LIMIT` caps what a shared-child DECLARATION expands into (see Compilers), and `is`, `audit` and `explain` answer a shared-reference VALUE in one visit per (compiled node, object) pair however many paths reach that object. Both halves are needed: without the value-side memo an ordinary graph with several references per level — a few hundred bytes, no attacker, shared references are normal data — costs node reads exponential in its depth. A faulted node is re-walked at its new path, because a fault carries one, and stays bounded by `FAULT_LIMIT`. `cloneJSONValue` and `parse` deliberately still expand and each says so here: `cloneJSONValue` duplicates an alias by contract and caps that at `CLONE_NODE_LIMIT`, and `parse` materializes a tree — see the following line. The claim is about those doors, not about a guard a caller composes: nesting `arrayOf` twenty levels deep builds a walker of your own, and it pays per path.
|
|
399
448
|
|
|
400
|
-
What is NOT guaranteed, beyond the realm assumption
|
|
449
|
+
What is NOT guaranteed, beyond the earlier realm assumption: a value whose observable reads CHANGE between two calls can leave any two-call law unsatisfied (see Domains), `Date` and `undefined` fall outside the round-trip law, and `schemaToShape`'s memo is ancestor-context-sensitive across graphs (see its row). Two more follow from the preceding memo and are named rather than left to be discovered. `parse` returns a TREE, so it pays for the tree its input expands into: eighteen shared arrays parse into 262,143 of them in about 370 ms, where `is`, `audit` and `explain` answer the same value in under a millisecond and `cloneJSONValue` refuses that exact graph at `CLONE_NODE_LIMIT`. That cost is the RESULT rather than the walk, which is why it carries no cap — a cap here would refuse a value the caller asked to be handed — so measure an untrusted graph's expansion before parsing it. And within ONE call, `is`, `audit` and `explain` read a given object once per compiled node rather than once per path, so a value whose reads change BETWEEN two reads of the same node can answer differently than it did when every path re-read it. Both are consequences of trading repeated reads for bounded work, and the trade is stated so it can be checked rather than discovered. A third limit belongs to the guards you compose YOURSELF: the preceding memo lives in a compiled artifact, so a chain you build by hand out of combinators — `arrayOf(arrayOf(...))` and its siblings — has no shared ledger between its independently constructed links and re-reads a shared object once per PATH. Measured: a depth-18 hand-composed chain over an 18-level shared graph answers in about 250 ms, growing fourfold every two levels, where the same value through `createContract` answers in under a millisecond. Compile the declaration when the value may share references; the compiled route is the one this bound covers.
|
|
401
450
|
|
|
402
451
|
`cloneShape` and `validateShape` agree on acceptance. Their refusal diagnoses agree only below the capture limit: ownership may spend that allowance before depth diagnosis, so an excessive declaration can report `clone` through ownership and `depth` through validation.
|
|
403
452
|
|
|
@@ -443,11 +492,11 @@ What is NOT guaranteed, beyond the realm assumption above: a value whose observa
|
|
|
443
492
|
|
|
444
493
|
### `ContractError`
|
|
445
494
|
|
|
446
|
-
`CONTRACT_ERROR_BRAND` is the registry-global symbol captured while `constants.ts` evaluates. The constructor stores the error itself under that key, and `isContractError` requires the descriptor value to be the value under inspection. That identity check keeps cross-copy recognition and refuses accidental property lookalikes and transparent wrappers: a proxy forwards a descriptor that stores its target, not the proxy. The registry
|
|
495
|
+
`CONTRACT_ERROR_BRAND` is the registry-global symbol captured while `constants.ts` evaluates. The constructor stores the error itself under that key, and `isContractError` requires the descriptor value to be the value under inspection. That identity check keeps cross-copy recognition and refuses accidental property lookalikes and transparent wrappers: a proxy forwards a descriptor that stores its target, not the proxy. The registry lets any code fake the stamp, by design. A complete `Error` subclass fake with a declared code, valid context, and its own identity stored under `Symbol.for('@orkestrel/contract.ContractError')` passes recognition. The brand is therefore a cross-copy recognition marker, not proof that this package constructed the value.
|
|
447
496
|
|
|
448
|
-
The one error class thrown across this module — an `Error` subclass carrying a machine-readable `code`, optional structured `context`, and an exact optional `cause`, from [`errors.ts`](../src/core/errors.ts). Omitting `cause` creates no own cause property; supplying `cause: undefined` creates an own property whose value is exactly `undefined`; every other cause retains its identity. Both optional options are read as OWN properties and ownership is established before the value is read at all, so an inherited `cause` or `context` counts as omission: an unqualified read of an absent option would leave the container and land on `Object.prototype`, which any caller can write, and would let that caller decide what a refusal an engine authored carries. `code` is required by the options type, so an internal literal always carries it own; a caller who hands in a container that INHERITS `code` still gets the inherited value, because the type promised a value rather than an own property, and that caller is choosing what its own error carries. `name` defaults to `'ContractError'` and a subclass may override it; `code` and `context` are readonly. The constructor stamps the global own-property brand `Symbol.for('@orkestrel/contract.ContractError')`. `isContractError` requires that brand plus the native `Error` base, a prototype other than `Error.prototype`, an own declared `ContractCode` read through captured ownership and reflection, and valid optional context members read through captured own-property checks. A context may be a class instance or callable object with the declared fields. Array paths are checked by index without retrieving their iterator. Numeric limits admit every number, including non-finite values. Inherited optional context fields count as omission. It never reads `name`, so a subclass with a different name remains recognized. The global symbol registry makes recognition work across duplicate installations and ESM/CommonJS module copies at 0.0.13 or later. A copy earlier than 0.0.13 stamps no brand, so its errors remain outside the type. An ordinary `Error`, a plain object, or a partial property lookalike remains outside the type.
|
|
497
|
+
The one error class thrown across this module — an `Error` subclass carrying a machine-readable `code`, optional structured `context`, and an exact optional `cause`, from [`errors.ts`](../src/core/errors.ts). Omitting `cause` creates no own cause property; supplying `cause: undefined` creates an own property whose value is exactly `undefined`; every other cause retains its identity. Both optional options are read as OWN properties and ownership is established before the value is read at all, so an inherited `cause` or `context` counts as omission: an unqualified read of an absent option would leave the container and land on `Object.prototype`, which any caller can write, and would let that caller decide what a refusal an engine authored carries. `code` is required by the options type, so an internal literal always carries it own; a caller who hands in a container that INHERITS `code` still gets the inherited value, because the type promised a value rather than an own property, and that caller is choosing what its own error carries. `name` defaults to `'ContractError'` and a subclass may override it; `code` and `context` are readonly. The constructor stamps the global own-property brand `Symbol.for('@orkestrel/contract.ContractError')`. `isContractError` requires that brand plus the native `Error` base, a prototype other than `Error.prototype`, an own declared `ContractCode` read through captured ownership and reflection, and valid optional context members read through captured own-property checks. A context may be a class instance or callable object with the declared fields. Array paths are checked by index without retrieving their iterator. Numeric limits admit every number, including non-finite values. An own `faults` must pass `isAuditFaults`, a dense array whose every element passes `isAuditFault`; in 0.0.24, `isContractError` read no `faults` and answered `true` for an error whose context held `faults: [7]`, and from 0.0.25 it answers `false`. `readValue` copies a `faults` member of its `context` option into the refusal's context only when that member passes `isAuditFaults`, where 0.0.24 dropped it; 0.0.25 copied every `faults` value, so a malformed one published an error `isContractError` refused, and from 0.0.26 the refusal omits it and keeps every other context member. Inherited optional context fields count as omission. It never reads `name`, so a subclass with a different name remains recognized. The global symbol registry makes recognition work across duplicate installations and ESM/CommonJS module copies at 0.0.13 or later. A copy earlier than 0.0.13 stamps no brand, so its errors remain outside the type. An ordinary `Error`, a plain object, or a partial property lookalike remains outside the type.
|
|
449
498
|
|
|
450
|
-
These refusal families may throw, and whenever they do they throw only this class: REQUIRED READS (`readValue` and the public inferer/helper/combinator/compiler readers layered over it — normally `structure` with `<reader>: <subject> could not be read`, while `RegExp` readers use `pattern`), shape CONSTRUCTION (every builder validates every runtime argument position before returning — `bound` / `range` / `empty` / `placement` / `pattern` / `literal` / `structure`), CLONING (`cloneJSONValue` / `cloneJSONRecord` for inexact JSON data, cycles, or
|
|
499
|
+
These refusal families may throw, and whenever they do they throw only this class: REQUIRED READS (`readValue` and the public inferer/helper/combinator/compiler readers layered over it — normally `structure` with `<reader>: <subject> could not be read`, while `RegExp` readers use `pattern`), shape CONSTRUCTION (every builder validates every runtime argument position before returning — `bound` / `range` / `empty` / `placement` / `pattern` / `literal` / `structure`), CLONING (`cloneJSONValue` / `cloneJSONRecord` for inexact JSON data, cycles, or untrusted traversal; `cloneSchema` / `cloneShape` / `ownShape`, and `rawShape` through its snapshot — `clone` plus declaration-policy codes), VALIDATION (`validateShape` and `ShapeValidator` — `range` / `empty` / `placement` / `structure` / `literal` / `cycle` / `bound` / `pattern`), the COMPILATION gate (every `compile*` export plus `createContract` routes through that same `validateShape` — the same declaration-policy codes, plus `depth`), and GENERATION (`compileGenerator` on an unsatisfiable request — `generate`; `drawRandom` on a broken sample source — `random`). Every message opens with the reader that OWNS the rule it enforces, never the engine that happened to run it. A declaration rule belongs to the shared gate and reads `validateShape: …` wherever it is applied, including inside `ShapeCloner`, which enforces the same rules while capturing; `cloneShape: …` is reserved for the ownership rules the cloner itself owns — own data discriminants, inherited fields, accessors, read stability, unreadable property maps, and a failed snapshot; and `ShapeCloner.clone: …`, `SchemaCloner.clone: …`, `JSONCloner.clone: …` and `ShapeValidator.validate: …` name a refusal about the CALL rather than the declaration, such as reentry. One rule therefore has one diagnostic at each of those doors: `cloneShape`, `ownShape`, `validateShape`, `ShapeValidator`, every `compile*` export and `createContract` report the same malformed declaration with the same code and the same message, across every declaration-policy family the gate owns (`placement`, `range`, `bound`, `pattern`, `empty`, `literal`, `cycle`, `depth`, `structure`). That is a statement about those doors and those families, enforced by a sweep rather than asserted: it says nothing about a door outside the list. `createContract` observes its caller’s source twice — once as the declaration, once while cloning it — so a LIVE declaration that changes between those walks can be refused by ownership rather than by the gate, and each refusal names the boundary that owns the rule it broke. An error adopted by identity from another engine keeps the prefix that engine gave it. Hand-authored string declarations use the same unflagged-pattern policy as builders: a stable genuine `RegExp` carrying flags is a `pattern` refusal, and inline pattern constructs are the supported alternative. Total guards and optional readers use their non-throwing outcomes; `compileReporter` contains its diagnostic walk, while required `parse`/`audit` reads and schema inversion refuse traversal failure. Root ownership, including the frozen-state probe itself, is contained before standalone compilation begins: a revoked `Proxy`, throwing getter, or caller-thrown value becomes a coded `clone` / `structure` `ContractError`. Malformed containers, untrusted proxies, and wrong primitives at any builder position become coded `ContractError` values. Every public door that can refuse runs its whole body through `contain`, which republishes anything that is not this class under the door's own name with the exact thrown value as `cause`; a door whose body cannot throw carries no boundary, because wrapping code that cannot fail misreports where the refusals are. A boundary placed per STATEMENT is only ever as complete as the last sweep, while a boundary at the door covers whatever the body reaches, enumerated or not. Its limits are named rather than promised away. A boundary covers a BODY, so it cannot reach a parameter-default initializer, which is evaluated in the function environment before the first statement runs: the one such default this package had (`compileGenerator`'s wall-clock seed) was moved into the contained body, and any future computed default belongs there too. And a boundary is not a fidelity guarantee: containment answers what a door may THROW, while what a door PUBLISHES under a redirect that lies instead of throwing is the separate job of `INTRINSICS`, the module-scope membership functions layered over it, and the indexed publication walks. Every such site is reached from the captured table — which is a claim a sweep checks, not a claim this sentence makes.
|
|
451
500
|
|
|
452
501
|
```ts
|
|
453
502
|
import { ContractError, isContractError } from '@orkestrel/contract'
|
|
@@ -464,16 +513,17 @@ isContractError(error) // true
|
|
|
464
513
|
| `isContractError` | function | `(value: unknown) => value is ContractError` | Checks whether an unknown value is a `ContractError`. |
|
|
465
514
|
| `ContractCode` | type | `'bound' \| 'range' \| 'empty' \| 'placement' \| 'structure' \| 'literal' \| 'cycle' \| 'pattern' \| 'generate' \| 'random' \| 'clone' \| 'depth' \| 'expansion'` | Names the machine-readable category carried by a `ContractError`. |
|
|
466
515
|
| `CONTRACT_CODES` | const | `readonly ContractCode[]` | Lists every declared `ContractCode` refusal category, frozen. |
|
|
467
|
-
| `ContractErrorContext` | interface | `{ path?, shape?, limit?, received? }`
|
|
516
|
+
| `ContractErrorContext` | interface | `{ path?, shape?, limit?, received?, faults? }` | Represents the optional structured details carried by a `ContractError`. |
|
|
517
|
+
| `RefuseValueOptions` | interface | `{ path, limit, code? }` | Groups the options for `refuseValue`. |
|
|
468
518
|
| `ContractErrorOptions` | interface | `{ code, context?, cause? }` | Represents the construction options for a `ContractError`. |
|
|
469
519
|
|
|
470
520
|
### Cloners
|
|
471
521
|
|
|
472
|
-
`JSONCloner` is the public state-owning JSON engine. Its constructor only retains the source; the first `clone()` performs the iterative snapshot and settles once. A successful instance replays the exact same deeply frozen root without another source read, while a failed instance releases partial traversal working state and rethrows its exact class-owned `ContractError` without another read, retaining the source and exact error for replay. That terminal settlement is nonredirectable, which needs each of these: its ownership record and error construction dispatch only through intrinsics captured while the module evaluated, AND every optional diagnostic option is read as an own property, so a construction never consults a prototype chain the caller can write. Neither replacing an intrinsic after construction nor installing a `cause`, `context` or `path` accessor on `Object.prototype` can make the first call escape with a raw value or make the replay disagree with it — including when the caller arms the pollution from inside its own reflective trap, after the walk has begun. A redirected working-state member is contained instead, and settles as an ordinary owned refusal. Active reentry permanently
|
|
522
|
+
`JSONCloner` is the public state-owning JSON engine. Its constructor only retains the source; the first `clone()` performs the iterative snapshot and settles once. A successful instance replays the exact same deeply frozen root without another source read, while a failed instance releases partial traversal working state and rethrows its exact class-owned `ContractError` without another read, retaining the source and exact error for replay. That terminal settlement is nonredirectable, which needs each of these: its ownership record and error construction dispatch only through intrinsics captured while the module evaluated, AND every optional diagnostic option is read as an own property, so a construction never consults a prototype chain the caller can write. Neither replacing an intrinsic after construction nor installing a `cause`, `context` or `path` accessor on `Object.prototype` can make the first call escape with a raw value or make the replay disagree with it — including when the caller arms the pollution from inside its own reflective trap, after the walk has begun. A redirected working-state member is contained instead, and settles as an ordinary owned refusal. Active reentry permanently invalidates nested, outer, and later calls with one cause-free `JSONCloner.clone: JSON cloning may not be reentered` error (`clone`, `{ shape: 'json' }`), even when untrusted source code catches the nested throw. Distinct instances are independent. `cloneJSONValue` constructs a fresh instance on every call, so every eager call re-observes its source and produces a distinct composite root or distinct diagnostic when identity is observable.
|
|
473
523
|
|
|
474
|
-
`SchemaCloner` is the corresponding public state-owning JSON Schema engine. Its inert constructor retains one schema graph; the first `clone()` performs an iterative identity-memoized snapshot and settles once. Success replays the exact deeply frozen root, preserving shared and cyclic edges; failure rethrows the exact class-owned `ContractError`. Both outcomes release traversal frames and the active memo through preconstructed replacement state before nonredirectable terminal publication, while retaining the source and exact terminal result. Nonredirectable carries the same requirements here, and the diagnostic `path` is read as an own property too, so a translated foreign failure reports no path rather than one a polluted prototype supplied. Active reentry permanently
|
|
524
|
+
`SchemaCloner` is the corresponding public state-owning JSON Schema engine. Its inert constructor retains one schema graph; the first `clone()` performs an iterative identity-memoized snapshot and settles once. Success replays the exact deeply frozen root, preserving shared and cyclic edges; failure rethrows the exact class-owned `ContractError`. Both outcomes release traversal frames and the active memo through preconstructed replacement state before nonredirectable terminal publication, while retaining the source and exact terminal result. Nonredirectable carries the same requirements here, and the diagnostic `path` is read as an own property too, so a translated foreign failure reports no path rather than one a polluted prototype supplied. Active reentry permanently invalidates nested, outer, and later calls with one cause-free `SchemaCloner.clone: schema cloning may not be reentered` error (`clone`, `{ shape: 'schema' }`), including when untrusted source code catches the nested throw and continues. Enumeration refusal is cause-free; property-read refusal retains the exact thrown cause, including an explicit `undefined`; unexpected foreign failures are translated once. Only errors created by that instance replay as terminal errors. Distinct instances are independent, while `cloneSchema` constructs a fresh instance for every eager call.
|
|
475
525
|
|
|
476
|
-
`ShapeCloner` is the public state-owning contract-shape engine. Its source-only constructor is inert; the first `clone()` requires every node to satisfy the realm-neutral plain-record brand before discriminant observation, then iteratively captures and wires the graph, composes raw nodes through `SchemaCloner`, freezes the completed root, validates that exact root through `ShapeValidator`, and only then applies deferred source-fidelity refusal. Success and failure replay the exact terminal root or class-owned/adopted `ContractError` without rereading the source. Active reentry permanently
|
|
526
|
+
`ShapeCloner` is the public state-owning contract-shape engine. Its source-only constructor is inert; the first `clone()` requires every node to satisfy the realm-neutral plain-record brand before discriminant observation, then iteratively captures and wires the graph, composes raw nodes through `SchemaCloner`, freezes the completed root, validates that exact root through `ShapeValidator`, and only then applies deferred source-fidelity refusal. Success and failure replay the exact terminal root or class-owned/adopted `ContractError` without rereading the source. Active reentry permanently invalidates nested, outer, and later calls with one cause-free `ShapeCloner.clone: shape cloning may not be reentered` error (`clone`, `{ shape: 'shape' }`), including caught reentry. Only errors created by this instance or adopted directly from its schema cloner or validator may replay by identity; unexpected foreign failures become `cloneShape: failed to create an owned shape snapshot` with the exact cause. Terminal settlement releases graph-working state through preconstructed replacement state before nonredirectable terminal publication, while retaining the source and exact terminal result. Distinct instances are independent, while `cloneShape` constructs a fresh instance for every eager call.
|
|
477
527
|
|
|
478
528
|
| Name | Kind | Signature | Summary |
|
|
479
529
|
| ----------------------- | --------- | ---------------------------------------------------- | ------------------------------------------------------------------------- |
|
|
@@ -488,7 +538,7 @@ isContractError(error) // true
|
|
|
488
538
|
|
|
489
539
|
`ownShape` returns a successful independent eager snapshot for both frozen and unfrozen sources. After failure it rethrows a non-`clone` `ContractError` or any failure for an unfrozen source. For a frozen source whose clone failure is `clone`-coded or foreign, it validates the source with a fresh `ShapeValidator`, prefers that validator's `ContractError` when present, and otherwise rethrows the original clone failure.
|
|
490
540
|
|
|
491
|
-
The machinery behind owned snapshots (see Shape builders,
|
|
541
|
+
The machinery behind owned snapshots (see Shape builders, later) — from [`JSONCloner.ts`](../src/core/JSONCloner.ts), [`SchemaCloner.ts`](../src/core/SchemaCloner.ts), [`ShapeCloner.ts`](../src/core/ShapeCloner.ts), and the eager boundaries in [`cloners.ts`](../src/core/cloners.ts). The JSON cloner accepts only exact acyclic JSON data, rejects sparse or decorated arrays and non-data record properties without invoking accessors, and builds deeply frozen standard arrays plus null-prototype records. “Decorated” means the array own-key set contains anything other than intrinsic `length` and every canonical index, including an extra, substituted, symbol, hidden, or accessor key. Index writability and configurability are normalized rather than treated as JSON data, so frozen arrays and nonwritable data indices remain valid. Because JSON persistence is a tree, repeated noncyclic source aliases are duplicated into distinct equal output branches; active-path back-edges fail as cycles. A refusal that names a member or a container carries the complete `path` in its context beside `received`, which holds the value's preview, or the label `accessor` or the label `threw` where a member's descriptor holds no value or could not be read, and its message ends with `at` and the path `renderPath` renders, so a caller key reaches the text encoded and bounded. A symbol key adds no segment: the refusal sits at its record and names the symbol in its text, as `cloneJSONValue: record has a symbol property Symbol(s) at settings`. A refusal at the root carries the empty path and no suffix, and the node-limit refusal carries no path. A replaced array or `RegExp` member does not change a refusal's text, its path, or its replay. `cloneJSONRecord` adds record-root validation over the same engine, and a nested refusal keeps its `cloneJSONValue:` message through it. `cloneSchema` preserves shared-child identity and closes cyclic schema edges onto its clone; `cloneShape` preserves sharing, carries one accepted declaration population into its clone, and runs the complete declaration gate on that carried clone before returning, so a cyclic shape is refused with the same `cycle` diagnosis as every other shape entry. A key literally named `__proto__` stays own data. From 0.0.26 the JSON cloner reads each node's members by index with no iterator and assigns each into its fresh clone, where 0.0.25 stepped a generator and defined each member through a descriptor, and its snapshots, refusals, paths, and replays are unchanged. Every untrusted reflective operation is contained through the sanctioned total boundary, and so is every caller-reachable dispatch on the declaration gate's own path: `ShapeValidator.validate` and `validateShape` translate a failure they did not author into a coded `ContractError` carrying the exact thrown value, rather than rethrowing it verbatim. JSON reflection failures and schema enumeration failures remain cause-free. A schema property-read failure instead retains the exact thrown value as its cause, including an explicit `undefined`; caller-owned errors never become terminal errors by identity. Only the exact errors owned or explicitly adopted by an engine can replay by terminal identity.
|
|
492
542
|
|
|
493
543
|
| Name | Kind | Signature | Summary |
|
|
494
544
|
| ------------------ | -------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
@@ -530,7 +580,7 @@ schemaCloner.clone() === schema // true — terminal success replays exactly
|
|
|
530
580
|
|
|
531
581
|
### Shape builders
|
|
532
582
|
|
|
533
|
-
Declarative constructors for the `ContractShape` union (`src/core/shapers.ts`). The `deriveLengthBounds` and `deriveRangeBounds` rows sit in this section because schema inversion consumes them, and they live in `src/core/helpers.ts`: they build no shape, they reduce a keyword pair to a numeric bound. One shape compiles into a JSON Schema, a guard, a parser, a strict audit, a parse report, and a generator (see the compilers,
|
|
583
|
+
Declarative constructors for the `ContractShape` union (`src/core/shapers.ts`). The `deriveLengthBounds` and `deriveRangeBounds` rows sit in this section because schema inversion consumes them, and they live in `src/core/helpers.ts`: they build no shape, they reduce a keyword pair to a numeric bound. The `readShapeMap` row sits here too, because `objectShape` and `interfaceShape` read their maps through it. One shape compiles into a JSON Schema, a guard, a parser, a strict audit, a parse report, and a generator (see the compilers, later). Builders omit absent options from the produced shape object: an option left `undefined` is not present as a key, so `Object.keys`, `in` checks, and spreads see only the options actually provided.
|
|
534
584
|
|
|
535
585
|
**The snapshot-ownership model.** A builder freezes the node it returns and copies every collection you hand it — a `values` list, a `properties` map, a variant list, a `rawShape` fragment — while a `pattern` is captured and re-exposed as a fresh frozen `RegExp` per read, so editing your originals afterwards cannot reach the shape. `objectShape` enumerates a caller-owned property declaration once and carries that key/value snapshot. `cloneShape`, which must also validate a hand-authored graph, first requires every node to be a plain, null-prototype, or foreign-realm record before it reads the discriminant, then captures each declared field through own descriptors plus two agreeing reads before it builds the shell. Missing fields are carried as absent without a read; inherited fields and ordinary accessors are refused without invocation. The documented `pattern` accessor is the one exception, and its two frozen genuine-RegExp results must independently expose agreeing primitive-string `source` and `flags` pairs; no caller scalar object or conversion hook is retained. Structural children, literal values, variants, property maps, and raw-schema roots are then wired only from those captured references, never by rereading the source node. Property maps retain their separate stability mechanism: `cloneShape` compares exactly two caller enumerations and refuses second-population disagreement, while the first enumeration obtains every property child's own data descriptor and requires its value plus two reads to agree by identity. The complete declaration gate validates the carried cloned root; it does not repair or replace a captured population. Consequently, `createContract` reads a property entry exactly as often as `cloneShape` does — twice, and the two readings must agree — because it reaches the declaration the same way: there is no discarded pre-ownership walk, so there is no second caller population to disagree with the captured one. That single captured clone controls every artifact, an invalid captured population is refused by the gate that runs over the clone, and no third caller value read occurs. `ownShape` retains the already-performed `cloneShape` result for frozen and unfrozen inputs alike, so no caller-owned root or reference-bearing child is returned by identity. Thus a malformed value container, raw-schema child, discriminant, scalar, or structural slot cannot become plausible merely because copying would normalize it. A hand-authored `{ category: 'string', pattern }` node receives the same accessor-owned pattern snapshot as builder output and must likewise use an unflagged genuine local- or foreign-realm `RegExp`; inline constructs express the supported flag-like behavior. `createContract` takes its own `cloneShape` snapshot of the whole graph, unless the builders made all of it, when it is frozen all the way down and no snapshot could add anything, so its `schema` / `is` / `parse` / `audit` / `explain` / `generate` are fixed by the declaration at construction and cannot drift with a later edit to the shape you passed. The practical rule: build shapes with the builders, and treat a shape you assemble by hand as caller-owned until a compiler or `ownShape` has copied it.
|
|
536
586
|
|
|
@@ -552,10 +602,14 @@ Declarative constructors for the `ContractShape` union (`src/core/shapers.ts`).
|
|
|
552
602
|
| `nullableShape` | function | `<S extends ContractShape>(inner: S) => NullableShape<S>` | Wraps a shape so it may be `null`. |
|
|
553
603
|
| `jsonShape` | function | `(options?: JSONShapeOptions) => JSONShape` | Builds a `JSONShape`. |
|
|
554
604
|
| `functionShape` | function | `(options?: FunctionShapeOptions) => FunctionShape` | Builds a `FunctionShape`. |
|
|
605
|
+
| `undefinedShape` | function | `(options?: UndefinedShapeOptions) => UndefinedShape` | Builds an `UndefinedShape`. |
|
|
606
|
+
| `interfaceShape` | function | `<P extends Readonly<Record<string, ContractShape>>>(members: P, options?: InterfaceShapeOptions) => InterfaceShape<P>` | Builds an `InterfaceShape` from a member map. |
|
|
555
607
|
| `rawShape` | function | `(schema: JSONSchema) => RawShape` | Builds a `RawShape` from a supported JSON Schema fragment. |
|
|
556
608
|
| `schemaToShape` | function | `(schema: JSONSchema, options?: SchemaToShapeOptions) => ContractShape` | Converts a runtime `JSONSchema` value into a validating `ContractShape` — the inverse of `compileSchema`. Unlike direct `rawShape` construction, which rejects malformed supported-vocabulary keywords, the lenient conversion is total and widens an inexpressible input to a valid raw `{}`, and a strict conversion refuses that input. |
|
|
557
609
|
| `deriveLengthBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of non-negative-integer JSON Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`). |
|
|
558
610
|
| `deriveRangeBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of finite-number JSON Schema range keywords (`minimum`/`maximum`). |
|
|
611
|
+
| `matchesEmptyRange` | function | `(bounds: NumberShapeOptions) => boolean` | Checks whether no number satisfies a set of number bounds. |
|
|
612
|
+
| `readShapeMap` | function | `<P extends Readonly<Record<string, ContractShape>>>(map: P, door: string, field: string, shape: string) => P` | Reads a shape builder's map of child shapes into a frozen null-prototype snapshot. |
|
|
559
613
|
|
|
560
614
|
An ordinary `oneOfShape` parser returns the input itself when exactly one arm accepts it. It makes no defensive copy: mutating the result mutates the input. Object key order, prototype, and frozen state are retained. Hidden and symbol members are retained only through an arm with `additionalProperties: true`, because every other object arm refuses them. Copy explicitly if you need an independent result. Primitive and JSON-valued arms, no-match and ambiguous refusals, and the prohibition on defaults under unions keep their existing behavior. A required literal discriminator can still select an arm for coercion.
|
|
561
615
|
|
|
@@ -578,13 +632,33 @@ booking.audit({ arrival: '2026-02-30' })
|
|
|
578
632
|
booking.schema.properties?.arrival // { type: 'string', format: 'date' }
|
|
579
633
|
```
|
|
580
634
|
|
|
581
|
-
**Function members.** `functionShape` declares a member that holds a function, such as a callback in an options record. Its guard is `isFunction`, so every callable passes, a class constructor included, and no arity is checked; its parser returns the value by identity. A string sent there reports `upgrade: type; expected function; received "migrate"` through `describeFaults`, and the summary names the member `"upgrade"?: function`. JSON carries no function, so the emitted schema is `{ not: {}, format: 'function' }`, which no JSON instance satisfies: `not` holds the answer for a validator, `format` names the member for a reader, and `description` appears only when you author one. `generate` returns one frozen function, the same one under every seed. `Infer` resolves the member to `(...args: never[]) => unknown`: a `(name: string) => string` callback assigns to it and a call passing `42` does not compile, while a call with no argument still does. A strict `schemaToShape` reads that leaf back as `functionShape()` and refuses every other `not`; a lenient one widens
|
|
635
|
+
**Function members.** `functionShape` declares a member that holds a function, such as a callback in an options record. Its guard is `isFunction`, so every callable passes, a class constructor included, and no arity is checked; its parser returns the value by identity. A string sent there reports `upgrade: type; expected function; received "migrate"` through `describeFaults`, and the summary names the member `"upgrade"?: function`. JSON carries no function, so the emitted schema is `{ not: {}, format: 'function' }`, which no JSON instance satisfies: `not` holds the answer for a validator, `format` names the member for a reader, and `description` appears only when you author one. `generate` returns one frozen function, the same one under every seed. `Infer` resolves the member to `(...args: never[]) => unknown`: a `(name: string) => string` callback assigns to it and a call passing `42` does not compile, while a call with no argument still does. A strict `schemaToShape` reads that leaf back as `functionShape()`, reads the `undefined` leaf as `undefinedShape()`, and refuses every other `not`; a lenient one widens both to `rawShape`.
|
|
636
|
+
|
|
637
|
+
**Undefined members.** `undefinedShape` declares a member whose value may be `undefined`; compose it as a union arm, such as `unionShape(numberShape(), undefinedShape())`. Its guard is `isUndefined`, and `Infer` resolves it to `undefined`. A container keeps a present `undefined` wherever its child admits one: the leaf, a union with such an arm, or a `nullable` over such an inner, where a `oneOf` union admits it only when exactly one arm does. An object property present as `undefined` keeps its key in the parsed record, while an absent required property still reports `missing` with `expected: 'undefined'`. An array element and a record value keep a present `undefined` the same way, and a hole in an array whose element admits `undefined` reports `missing` at its index. Every other container answers as before: `{ max: undefined }` against `optionalShape(numberShape())` fails `is`, and `audit` reports a `type` fault. JSON carries no `undefined`, so the emitted schema is `{ not: {}, format: 'undefined' }`, and `generate` returns `undefined`. `optionalShape` keeps declaring a member that may be absent.
|
|
638
|
+
|
|
639
|
+
**Interface members.** `interfaceShape` declares an implementation another package hands you, such as a store or a signal, by the members you call or read on it. Its guard admits a non-array object or a function and reads each declared member one time through `Reflect.get`, so a class instance whose methods sit on its prototype, an object whose prototype carries the members, a getter-backed member, and a function carrying the members all pass, while an undeclared member is never read. A member wrapped in `optionalShape` passes when it reads `undefined`; any other member that reads `undefined` reports `missing` at its path unless its shape admits `undefined`. The guard is the audit returning no fault, and `parse` returns the value by identity when it holds, so nothing is copied, coerced, or filled; a member whose read throws makes `audit` and `parse` refuse with code `structure`. Because `explain` mirrors `parse`, an `extra` or `hidden` fault under a member reports there as one `type` fault at that member. The emitted schema is `{ type: 'object', format: 'interface', properties, required, additionalProperties: true }`, and `generate` returns a frozen plain record of generated members. A member may not carry a `default`, and an interface may not sit under a union at any depth, because each arm would read its members again; both refuse with code `placement`. Declare a plain data record you own with `objectShape`, and an implementation with `interfaceShape`.
|
|
640
|
+
|
|
641
|
+
This compiles a store declaration and shows what it admits and where it reports a missing member.
|
|
642
|
+
|
|
643
|
+
```ts
|
|
644
|
+
import { createContract, functionShape, interfaceShape } from '@orkestrel/contract'
|
|
645
|
+
|
|
646
|
+
const store = createContract(
|
|
647
|
+
interfaceShape({ get: functionShape(), set: functionShape(), delete: functionShape() }),
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
store.is(new Map()) // true — Map.prototype carries the three methods
|
|
651
|
+
store.parse(new Map()) instanceof Map // true — returned by identity
|
|
652
|
+
store.audit({ get() {}, set() {} })
|
|
653
|
+
// [{ reason: 'missing', path: ['delete'], expected: 'function' }]
|
|
654
|
+
store.schema.format // 'interface'
|
|
655
|
+
```
|
|
582
656
|
|
|
583
657
|
**Field defaults.** `optionalShape(inner, { default })` lets a declaration state what an absent field reads as. The compiled parser fills the default where the property is absent or `undefined`, through the inner parser, on a fresh copy when the default is a container, so nested defaults apply and two parses share no tree. A default on a `jsonShape`, a `rawShape`, or a union inner reaches you as a frozen copy, because those parsers return their input by identity. `is`, `audit`, `explain`, and `generate` do not read a default: an absent optional stays canonical, so `is({})` is `true`, and `generate` keeps omitting the key or drawing from `inner`. The emitted property schema carries the keyword. `null` is a value and fills; a present `undefined` is a `structure` refusal, because absence is not a value.
|
|
584
658
|
|
|
585
659
|
The builder and `cloneShape` own a frozen copy of a value that passes `isJSONValue`, so a stored shape survives a JSON round trip. Every compiler refuses a default its `inner` guard refuses, refinements included, with code `structure` at `[…path, 'default']`: a restored declaration never met a builder, and `validateShape` judges structure only. A shape holding a default builds the guard family for that check whichever artifact you read first; a shape holding none builds what it always built.
|
|
586
660
|
|
|
587
|
-
|
|
661
|
+
Four positions refuse with code `placement`. A default under a `union` ancestor refuses, because a union's parser returns a guard-valid value by identity, so `{ n: 5 }` would never fill while `{ n: '5' }` filled unreported. A default below an `interface` ancestor refuses, because an interface's parser returns the implementation by identity, so the default never fills. A default on a property of an open object refuses, because `{ licenced: false }` would pass as an extra and fill `licensed` with `audit` and `explain` both empty. A default on an optional whose inner shape admits `undefined` refuses, because a present `undefined` keeps its key, so `{ max: undefined }` would never fill while `{}` filled. A `nullable` ancestor, an array ancestor, and an open object's tail shape are legal. Because a shared node is discovered through one route alone, the validator asks these questions over the captured graph, after discovery, so an earlier domain refusal outranks them.
|
|
588
662
|
|
|
589
663
|
This compiles a defaulted field, showing the parser fill it while `is` stays on canonical absence.
|
|
590
664
|
|
|
@@ -601,23 +675,23 @@ retries.is({}) // true — an absent optional stays canonical
|
|
|
601
675
|
retries.schema.properties?.limit?.default // 3
|
|
602
676
|
```
|
|
603
677
|
|
|
604
|
-
Raw-schema validation is deliberately structural and vocabulary-domain validation, not a full JSON Schema solver. It checks that every keyword is supported, every keyword value has the declared runtime domain, arrays are dense and vocabularies unique where required, every member captured from a present `properties`, dense `anyOf`, or dense `oneOf` population is a plain record, patterns compile, `not` holds the empty schema `{}` alone, and the graph stays acyclic and within the depth limit. A `default` keyword must hold a JSON value, so a present `undefined` is refused, and neither the node's guard nor its parser reads it. Population is determined by membership, so a present member valued `undefined` is refused rather than erased as absence; omitted optional keywords, plus explicitly `undefined` `items` and `additionalProperties`, retain their absence behavior. It does not resolve cross-keyword contradictions such as `minLength: 5` with `maxLength: 1`, require each `required` name to appear in `properties`, enforce keyword/type coherence, compare `enum` members with `type`, or restrict `format` to a known vocabulary; those semantic interactions remain the responsibility of a full JSON Schema implementation.
|
|
678
|
+
Raw-schema validation is deliberately structural and vocabulary-domain validation, not a full JSON Schema solver. It checks that every keyword is supported, every keyword value has the declared runtime domain, arrays are dense and vocabularies unique where required, every member captured from a present `properties`, dense `anyOf`, or dense `oneOf` population is a plain record, patterns compile, `not` holds the empty schema `{}` alone, and the graph stays acyclic and within the depth limit. `exclusiveMinimum` and `exclusiveMaximum` are supported keywords from 0.0.25; in 0.0.24, `rawShape` refused either as an unsupported keyword. A `default` keyword must hold a JSON value, so a present `undefined` is refused, and neither the node's guard nor its parser reads it. Population is determined by membership, so a present member valued `undefined` is refused rather than erased as absence; omitted optional keywords, plus explicitly `undefined` `items` and `additionalProperties`, retain their absence behavior. It does not resolve cross-keyword contradictions such as `minLength: 5` with `maxLength: 1`, require each `required` name to appear in `properties`, enforce keyword/type coherence, compare `enum` members with `type`, or restrict `format` to a known vocabulary; those semantic interactions remain the responsibility of a full JSON Schema implementation.
|
|
605
679
|
|
|
606
|
-
`rawShape` first validates the caller-visible fragment, clones it exactly once, validates that exact owned clone, and returns that same frozen clone. A caller phase change that makes the captured population invalid is therefore refused; a valid captured population is the one published, and failures during the single clone retain the established `cloneSchema` diagnostic.
|
|
680
|
+
`rawShape` first validates the caller-visible fragment, clones it exactly once, validates that exact owned clone, and returns that same frozen clone. A caller phase change that makes the captured population invalid is therefore refused; a valid captured population is the one published, and failures during the single clone retain the established `cloneSchema` diagnostic. The `rawShape` guard admits every defined value whatever the fragment publishes, so `rawShape({ type: 'string' })` admits `1`; where the guard must check what the schema publishes, declare an implementation with `interfaceShape` and convert a foreign schema with a strict `schemaToShape`.
|
|
607
681
|
|
|
608
682
|
Direct declaration populations are dense data arrays too. A sparse literal is refused immediately with `validateShape: values must be a dense data array` at the container path `[…path, 'values']`; a sparse union is refused symmetrically with `validateShape: variants must be a dense data array` at `[…path, 'variants']`. Both are cause-free `structure` diagnostics, before any descriptor/stability walk. Raw `enum`, `required`, `anyOf`, and `oneOf` retain their existing dense-array vocabulary and apply it to the same bounded reflected snapshot.
|
|
609
683
|
|
|
610
684
|
`schemaToShape` is the sole entry point for the conversion. The walk behind it is interned, so the door's name is the only one a refusal ever carries and the caller reaches the host failure through one `cause`.
|
|
611
685
|
|
|
612
|
-
The precedence
|
|
686
|
+
The following precedence assumes a readable node and a lenient conversion. A readable malformed keyword is ignored and widens according to the listed rule; a keyword access, enumeration, or recursive traversal that throws is not malformed schema vocabulary and is refused with `ContractError { code: 'structure', context: { shape: 'schema' } }`.
|
|
613
687
|
|
|
614
|
-
`schemaToShape`'s precedence, top-down at each node (every keyword read is type-guarded; a malformed keyword is IGNORED, not thrown): (0) `$ref` widens the node to `rawShape` before anything beside it is read, because this walk resolves no reference and under draft-07 a reference replaces its siblings. (1) `enum` partitions its entries: finite string/number/boolean entries → `literalShape`, a `null` entry wraps it in `nullableShape`, `null` alone → `nullShape`, and any object, array, or non-finite entry widens the node to `rawShape`, because dropping it would narrow; an empty list falls through. (2) `oneOf` (≥ 1 arm) → `unionShape` over the recursed arms, PROVIDED the arm count is at or under `INFER_BREADTH_LIMIT`; over the cap, building a subset union would be strictly narrower than the schema's full union, so the node widens to `rawShape` instead of sampling a subset. The union is inclusive because this walk does not read `const`, `pattern`, `format`, or `multipleOf`: arms those keywords keep apart overlap here, and exactly-one over them refuses a value the schema accepts, as a Pydantic discriminated union showed. (3) `anyOf` identically → `unionShape`, with the same over-cap widen-to-`rawShape` rule rather than a subset union. In both, a `true` arm is a `rawShape({})` variant in declaration order, a `false` arm is dropped because it admits nothing, and a list its `false` arms leave empty widens to `rawShape`. Two arms, one of them `{ type: 'null' }`, read as `nullableShape` of the other, which therefore stays outside a union: a default under it fills, and `nullableShape` over a defaulted object survives its own schema. Only a strict `oneOf` keeps the union, for its exactly-one. A `description` beside the keyword carries onto the union, or onto the arm of a nullable, overriding that arm's own text, because `NullableShape` holds no description and the keyword describes the field. (4) An array-valued `type` → `unionShape` over each distinct recognized name, converting `{ ...schema, type: member }` at the same depth so bounds, `items`, `properties`, and `description` apply to each member. A single distinct name returns its shape directly. Two distinct names, one of them `null`, read as `nullableShape` of the other in both lenient and strict conversions, because the list means what the `anyOf` spelling in rule (3) means and has no exactly-one to keep. An empty array or any unrecognized member widens the whole node to `rawShape`, even when `properties` is present; no member is dropped to narrow the union. The distinct-name count is checked against `INFER_BREADTH_LIMIT`; the recognized vocabulary fits below that cap, so repeated names do not exhaust it. This is runtime conversion support: the declared `JSONSchema.type` remains a single name because direct raw-schema validation supports only that vocabulary. (5) `type: 'string'/'number'/'integer'/'boolean'/'null'` → the matching primitive shape, with `minLength`/`maxLength`/`minimum`/`maximum` bounds kept only when well-formed and non-contradictory (a malformed
|
|
688
|
+
`schemaToShape`'s precedence, top-down at each node (every keyword read is type-guarded; a malformed keyword is IGNORED, not thrown): (0) `$ref` widens the node to `rawShape` before anything beside it is read, because this walk resolves no reference and under draft-07 a reference replaces its siblings. (1) `enum` partitions its entries: finite string/number/boolean entries → `literalShape`, a `null` entry wraps it in `nullableShape`, `null` alone → `nullShape`, and any object, array, or non-finite entry widens the node to `rawShape`, because dropping it would narrow; an empty list falls through. (2) `oneOf` (≥ 1 arm) → `unionShape` over the recursed arms, PROVIDED the arm count is at or under `INFER_BREADTH_LIMIT`; over the cap, building a subset union would be strictly narrower than the schema's full union, so the node widens to `rawShape` instead of sampling a subset. The union is inclusive because this walk does not read `const`, `pattern`, `format`, or `multipleOf`: arms those keywords keep apart overlap here, and exactly-one over them refuses a value the schema accepts, as a Pydantic discriminated union showed. (3) `anyOf` identically → `unionShape`, with the same over-cap widen-to-`rawShape` rule rather than a subset union. In both, a `true` arm is a `rawShape({})` variant in declaration order, a `false` arm is dropped because it admits nothing, and a list its `false` arms leave empty widens to `rawShape`. Two arms, one of them `{ type: 'null' }`, read as `nullableShape` of the other, which therefore stays outside a union: a default under it fills, and `nullableShape` over a defaulted object survives its own schema. Only a strict `oneOf` keeps the union, for its exactly-one. A `description` beside the keyword carries onto the union, or onto the arm of a nullable, overriding that arm's own text, because `NullableShape` holds no description and the keyword describes the field. (4) An array-valued `type` → `unionShape` over each distinct recognized name, converting `{ ...schema, type: member }` at the same depth so bounds, `items`, `properties`, and `description` apply to each member. A single distinct name returns its shape directly. Two distinct names, one of them `null`, read as `nullableShape` of the other in both lenient and strict conversions, because the list means what the `anyOf` spelling in rule (3) means and has no exactly-one to keep. An empty array or any unrecognized member widens the whole node to `rawShape`, even when `properties` is present; no member is dropped to narrow the union. The distinct-name count is checked against `INFER_BREADTH_LIMIT`; the recognized vocabulary fits below that cap, so repeated names do not exhaust it. This is runtime conversion support: the declared `JSONSchema.type` remains a single name because direct raw-schema validation supports only that vocabulary. (5) `type: 'string'/'number'/'integer'/'boolean'/'null'` → the matching primitive shape, with `minLength`/`maxLength`/`minimum`/`maximum`/`exclusiveMinimum`/`exclusiveMaximum` bounds kept only when well-formed and non-contradictory (a malformed bound reads as absent, and a `min > max` pair, or a numeric range no number satisfies, drops to unbounded — widening, never narrowing). In 0.0.24, a lenient conversion ignored `exclusiveMinimum` and `exclusiveMaximum`, so `{ type: 'number', exclusiveMinimum: 0 }` admitted `0`; from 0.0.25 it refuses `0`. (6) `type: 'array'` → `arrayShape`, recursing into a record-valued `items` (else `rawShape`), with `minItems`/`maxItems` bounds. A present `prefixItems` makes the element shape `rawShape({})`, because `items` then applies only past the prefix. (7) `type: 'object'` → `objectShape`; no `type`/`enum`/`oneOf`/`anyOf` but a record `properties` → `unionShape` of that object first, then `stringShape`, `numberShape`, `booleanShape`, `nullShape`, and `arrayShape(rawShape({}))`, because `properties` and `required` constrain only an object, so `5` is valid there, while a rejected field stays rejected because no arm admits every object. The object branch: a property not listed in `required` is wrapped `optionalShape`; `additionalProperties: false` closes, a record value recurses into it (`objectShape` validates extras against that shape directly — no widening needed), and `true` / ABSENT / anything malformed leaves it open (`true`) — absent matches JSON Schema's own default, and `valueToSchema` / `samplesToSchema` always emit the keyword explicitly, so an absent value only arises from a hand-written schema. A present `patternProperties` reads the object open whatever its own `additionalProperties` says, because a key that keyword admits is unread here; `propertyNames` exempts no key from `additionalProperties`, so it opens nothing. When `properties` has MORE keys than `INFER_BREADTH_LIMIT`, the schema's own `additionalProperties` is OVERRIDDEN and forced open (`true`) regardless of `false` or a record value — a key dropped past the sampling cap was never checked against a closed or record-valued rest shape, so forcing the object open is the only sound widening — mirroring the inferers' own `truncated ? true : !closed` rule. (8) Everything else — `{}`, an unrecognized `type`, exhausted depth (`INFER_DEPTH_LIMIT`), or a cyclic re-encounter — widens to `rawShape` (NOT `jsonShape`: `{}` is JSON Schema’s accept-anything schema, and `rawShape` is its exact inverse — its guard accepts every defined value and it re-emits `{}` verbatim, whereas `jsonShape`’s `isJSONValue` guard would reject the exotic originals (`Map`, `Set`, a class instance, a function, `NaN`) whose inferred schema is exactly `{}`). A `WeakMap` memo (keyed by schema-node identity + remaining depth), mirroring the inferers, guards a shared-reference schema DAG against exponential re-conversion. **Its key does not carry the active-ancestor set, and that is observable**: a node first reached through a CYCLIC path is cached with the shape it widened to at the back-edge, and a later ACYCLIC path is served that cached shape instead of descending further. Two schemas differing only in which sibling holds the cyclic node therefore convert to different shapes. Every such difference is a WIDENING — an accept-anything `rawShape` — so no value is wrongly rejected and the round-trip law is unaffected; what it costs is determinism ACROSS graphs, not within one, because the same input always converts the same way. This is stated as a limit rather than repaired because both repairs (dropping the ancestor set, or threading a cycle-affected flag through three public signatures) change the published surface.
|
|
615
689
|
|
|
616
|
-
**The lenient law.** A value a JSON Schema accepts is never refused by the shape a lenient conversion builds from it, and the conversion always compiles: a schema that would expand past `COMPILE_NODE_LIMIT` keeps only its root rather than leave a real tool uncallable: the root's type, an array's bounds, and an object's required keys and closure, with every value below them `rawShape({})`. A root with none of those, such as a union, widens whole. The check costs a validator pass only for a schema large enough to reach the limit or one that shares a node. `nullable: true`, the OpenAPI keyword `JSONSchema` does not declare, wraps the converted node in `nullableShape`. The walk leaves `const`, `multipleOf`, `
|
|
690
|
+
**The lenient law.** A value a JSON Schema accepts is never refused by the shape a lenient conversion builds from it, and the conversion always compiles: a schema that would expand past `COMPILE_NODE_LIMIT` keeps only its root rather than leave a real tool uncallable: the root's type, an array's bounds, and an object's required keys and closure, with every value below them `rawShape({})`. A root with none of those, such as a union, widens whole. The check costs a validator pass only for a schema large enough to reach the limit or one that shares a node. `nullable: true`, the OpenAPI keyword `JSONSchema` does not declare, wraps the converted node in `nullableShape`. The walk leaves `const`, `multipleOf`, `allOf`, `$ref`, `$defs`, `not`, `if`, `contains`, `uniqueItems`, `minProperties`, `maxProperties`, `dependentRequired`, `unevaluatedProperties`, `pattern`, and `format` unread, and an unread keyword widens: an untrusted `pattern` is never compiled. The advertised schema stays the host's own record, so `oneOf` still reaches a model verbatim.
|
|
617
691
|
|
|
618
692
|
A lenient conversion carries a property's `default` when the key is not in `required`, the object is closed with no union ancestor, and the value is one the property's primitive or literal guard accepts. It drops every other `default`, because a carried default that cannot compile would end the conversion's totality.
|
|
619
693
|
|
|
620
|
-
**Strict conversion.** `schemaToShape(schema, { strict: true })` is the door for a foreign schema. It refuses, with code `structure` and the keyword's path, what the lenient walk would widen or read past: every node the walk would widen to `rawShape` (an empty schema, a `type` typo at any depth, a non-record child, an array with no `items`, exhausted depth, and a cycle), a keyword outside `STRICT_SCHEMA_KEYWORDS` (`$ref`, `$defs`, `definitions`, `const`, `allOf`, `$anchor`, `$dynamicAnchor`, the `content*` keywords, `nullable`, `discriminator`, `example`, `patternProperties`, `propertyNames`, and `prefixItems`), `pattern` and every `format` but `'date'` on a string node and `'function'` beside `not: {}`, which no compiled shape asserts, every `not` outside
|
|
694
|
+
**Strict conversion.** `schemaToShape(schema, { strict: true })` is the door for a foreign schema. It refuses, with code `structure` and the keyword's path, what the lenient walk would widen or read past: every node the walk would widen to `rawShape` (an empty schema, a `type` typo at any depth, a non-record child, an array with no `items`, exhausted depth, and a cycle), a keyword outside `STRICT_SCHEMA_KEYWORDS` (`$ref`, `$defs`, `definitions`, `const`, `allOf`, `$anchor`, `$dynamicAnchor`, the `content*` keywords, `nullable`, `discriminator`, `example`, `patternProperties`, `propertyNames`, and `prefixItems`), `pattern` and every `format` but `'date'` on a string node, `'interface'` on an object node, and `'function'` or `'undefined'` beside `not: {}`, which no compiled shape asserts, every `not` outside those two leaves, a keyword beside a leaf other than its annotations and a `default`, a `format: 'date'` whose length bounds exclude length 10, a malformed keyword value or annotation, a boolean schema, an `enum` entry that is neither a finite primitive nor `null`, a contradictory or malformed bound, a keyword the node's type never reads, a `type` beside a union, a pair of keywords only one of which the walk would keep, an enum member its `type` contradicts, a `required` name not in `properties`, breadth past `INFER_BREADTH_LIMIT`, and a `default` with no optional property to fill or one its schema refuses. `oneOf` keeps exactly-one here, because this walk reads every keyword that could keep two arms apart. An object with no `additionalProperties` closes, unlike JSON Schema's own default, because a misspelled key at a foreign door must reach `audit`; an explicit `true` or schema value stays open. Below a `oneOf` it refuses instead, at any depth, because closing it could change which arms match: two arms declaring optional `a` and `b` both match `{ a: 'x' }` as written, and only one does after closing. It accepts the annotations a schema generator emits, which assert nothing and which the shape drops: `title`, `$schema`, `$id`, and `$comment` when strings, `examples` when an array, and `deprecated`, `readOnly`, and `writeOnly` when booleans. A default under a union, on an open object, or on a property whose schema admits `undefined` refuses with `placement` at its path in the schema, ending `properties`, the key, and `default`. An object node with `format: 'interface'` reads back as `interfaceShape`, each property outside `required` an optional member; it refuses with `structure` without `additionalProperties: true`, and with `placement` under a union or with a member `default`. A lenient conversion reads that node as an open object. A strict conversion reads `exclusiveMinimum` and `exclusiveMaximum` on a number node as `over` and `under`; in 0.0.24, it refused either keyword.
|
|
621
695
|
|
|
622
696
|
**Round-trip law:** for any READABLE value `v` — including `NaN`, `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a bigint, and readable cyclic hosts — `compileGuard(schemaToShape(valueToSchema(v)))(v) === true`, with widening as the ONLY source of looseness, never narrowing. An unreadable host is refused before the law produces a schema. The law otherwise retains its three limits: JSON absence, `Date` serialization, and unstable reads between inference and validation. A widened node cannot be auto-generated: `createContract(schemaToShape(x)).generate()` throws when the conversion widened anywhere; its parser returns `undefined` for readable invalid input and propagates the shared coded refusal when a required read fails.
|
|
623
697
|
|
|
@@ -638,44 +712,52 @@ contract.parse({ id: 'nope', name: 'x' }) // undefined
|
|
|
638
712
|
A resolver whose value is a multi-branch conditional carries none, and its `Summary` states
|
|
639
713
|
what the resolution produces.
|
|
640
714
|
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
|
646
|
-
|
|
|
647
|
-
| `
|
|
648
|
-
| `
|
|
649
|
-
| `
|
|
650
|
-
| `
|
|
651
|
-
| `
|
|
652
|
-
| `
|
|
653
|
-
| `
|
|
654
|
-
| `
|
|
655
|
-
| `
|
|
656
|
-
| `
|
|
657
|
-
| `
|
|
658
|
-
| `
|
|
659
|
-
| `
|
|
660
|
-
| `
|
|
661
|
-
| `
|
|
662
|
-
| `
|
|
663
|
-
| `
|
|
664
|
-
| `
|
|
665
|
-
| `
|
|
666
|
-
| `
|
|
667
|
-
| `
|
|
668
|
-
| `
|
|
669
|
-
| `
|
|
670
|
-
| `
|
|
671
|
-
| `
|
|
672
|
-
| `
|
|
673
|
-
| `
|
|
674
|
-
| `
|
|
715
|
+
`ContractShape` gains `UndefinedShape` and `InterfaceShape` in 0.0.25, so a `switch` over
|
|
716
|
+
`category` that the 0.0.24 members exhausted stops compiling until it handles `'undefined'` and
|
|
717
|
+
`'interface'`.
|
|
718
|
+
|
|
719
|
+
| Name | Kind | Signature | Summary |
|
|
720
|
+
| ----------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
721
|
+
| `ContractShape` | type | `StringShape \| NumberShape \| BooleanShape \| NullShape \| LiteralShape \| ArrayShape \| ObjectShape \| UnionShape \| OptionalShape \| NullableShape \| JSONShape \| ShapeShape \| FunctionShape \| UndefinedShape \| InterfaceShape \| RawShape` | Describes a value declaratively — a declaration the shape builders build and the compilers turn into a guard, a parser, a JSON Schema, and a generator. |
|
|
722
|
+
| `StringShape` | interface | `{ category, min?, max?, pattern?, date?, description? }` | Describes a string with optional length, pattern, and calendar-date constraints. |
|
|
723
|
+
| `NumberShape` | interface | `{ category, min?, over?, max?, under?, integer?, description? }` | Describes a number with optional bounds; `integer` restricts to whole numbers. |
|
|
724
|
+
| `BooleanShape` | interface | `{ category, description? }` | Describes a boolean — accepts only `true` or `false`. |
|
|
725
|
+
| `NullShape` | interface | `{ category, description? }` | Describes a null value — accepts only `null`. |
|
|
726
|
+
| `LiteralShape` | interface | `{ category, values, description? }` | Describes a literal — accepts exactly one of a fixed set of primitive values. |
|
|
727
|
+
| `ArrayShape` | interface | `{ category, items, min?, max?, description? }` | Describes an array with an element shape and optional length bounds. |
|
|
728
|
+
| `ObjectShape` | interface | `{ category, properties, additionalProperties?, description? }` | Describes an object — a map of property names to child shapes. |
|
|
729
|
+
| `UnionShape` | interface | `{ category, variants, mode?, description? }` | Describes a union — accepts a value matching any one variant (first match wins). |
|
|
730
|
+
| `OptionalShape` | interface | `{ category, inner, default? }` | Wraps an inner shape that may be absent (`undefined`). |
|
|
731
|
+
| `NullableShape` | interface | `{ category, inner }` | Wraps an inner shape that may be `null`. |
|
|
732
|
+
| `JSONShape` | interface | `{ category, description? }` | Describes a JSON passthrough — accepts any JSON value. |
|
|
733
|
+
| `FunctionShape` | interface | `{ category, description? }` | Describes a callable value — accepts every function, a class constructor included. |
|
|
734
|
+
| `InterfaceShape` | interface | `{ category, members, description? }` | Describes an implementation — a non-array object or a function that carries each declared member. |
|
|
735
|
+
| `UndefinedShape` | interface | `{ category, description? }` | Describes the `undefined` value — accepts only `undefined`. |
|
|
736
|
+
| `RawShape` | interface | `{ category, schema }` | Describes a validated raw JSON Schema passthrough — embeds a supported schema fragment directly. |
|
|
737
|
+
| `Infer` | type | `[ContractShape] extends [S] ? unknown : S extends ShapeShape ? ContractShape : S extends FunctionShape ? (...args: never[]) => unknown : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends { readonly category: 'literal'; readonly values: infer V; } ? V extends ReadonlyArray<infer L> ? L : never : S extends { readonly category: 'array'; readonly items: infer I; } ? I extends ContractShape ? ReadonlyArray<Infer<I>> : never : S extends ObjectShape<infer P, infer A> ? P extends Readonly<Record<string, ContractShape>> ? [A] extends [boolean \| ContractShape] ? InferObject<P, A> : never : never : S extends { readonly category: 'union'; readonly variants: infer V; } ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| undefined : never : S extends { readonly category: 'nullable'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| null : never : S extends JSONShape ? JSONValue : S extends UndefinedShape ? undefined : S extends InterfaceShape<infer P> ? Readonly<{ [K in keyof P as P[K] extends { readonly category: 'optional'; } ? never : K]: Infer<P[K]>; } & { [K in keyof P as P[K] extends { readonly category: 'optional'; } ? K : never]?: P[K] extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| undefined : never : never; }> : unknown` | Resolves the static TypeScript type a `ContractShape` describes. |
|
|
738
|
+
| `InferObject` | type | `[keyof P] extends [never] ? [A] extends [false] ? Readonly<Record<never, never>> : InferIndex<A> : Readonly<{ [K in keyof P as P[K] extends { readonly category: 'optional'; } ? never : K]: Infer<P[K]>; } & { [K in keyof P as P[K] extends { readonly category: 'optional'; } ? K : never]?: P[K] extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> : never : never; }> & InferOpenIndex<A>` | Resolves `Infer` of an object shape's `properties` — the required keys, plus the `optional`-wrapped keys as optional members, plus the index-signature contribution of `additionalProperties` (see `InferIndex`). |
|
|
739
|
+
| `InferIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: Infer<A>; } : unknown` | Computes the index-signature contribution of a pure record shape's `additionalProperties` — the `recordShape` case, where `properties` is empty. |
|
|
740
|
+
| `InferOpenIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: unknown; } : unknown` | Computes the index-signature contribution of a MIXED object shape's `additionalProperties` — one with both fixed `properties` and an open tail. |
|
|
741
|
+
| `InferMutable` | type | `{ -readonly [K in keyof Infer<S>]: Infer<S>[K]; }` | Strips the TOP-LEVEL `readonly` modifiers from `Infer` (a shallow strip — nested object/array properties stay readonly) — for consumers writing the parsed value's own fields. |
|
|
742
|
+
| `InferUnion` | type | `V extends ReadonlyArray<infer U> ? (U extends ContractShape ? Infer<U> : never) : never` | Resolves `Infer` of a union shape's `variants` — the union of each variant's inferred type. |
|
|
743
|
+
| `StringShapeOptions` | interface | `{ min?, max?, pattern?, date?, description? }` | Groups the options for `StringShape` (through `stringShape`). |
|
|
744
|
+
| `NumberShapeOptions` | interface | `{ min?, over?, max?, under?, integer?, description? }` | Groups the options for `NumberShape` (through `numberShape` / `integerShape`). |
|
|
745
|
+
| `BooleanShapeOptions` | interface | `{ description? }` | Groups the options for `BooleanShape` (through `booleanShape`). |
|
|
746
|
+
| `NullShapeOptions` | interface | `{ description? }` | Groups the options for `NullShape` (through `nullShape`). |
|
|
747
|
+
| `JSONShapeOptions` | interface | `{ description? }` | Groups the options for `JSONShape` (through `jsonShape`). |
|
|
748
|
+
| `FunctionShapeOptions` | interface | `{ description? }` | Configures the description of a function-valued declaration. |
|
|
749
|
+
| `InterfaceShapeOptions` | interface | `{ description? }` | Configures the description of an implementation declaration. |
|
|
750
|
+
| `UndefinedShapeOptions` | interface | `{ description? }` | Configures the description of an `undefined`-valued declaration. |
|
|
751
|
+
| `LiteralShapeOptions` | interface | `{ description? }` | Groups the options for `LiteralShape` (through `literalShape`). |
|
|
752
|
+
| `ArrayShapeOptions` | interface | `{ min?, max?, description? }` | Groups the options for `ArrayShape` (through `arrayShape`). |
|
|
753
|
+
| `ObjectShapeOptions` | interface | `{ additionalProperties?, description? }` | Groups the options for `ObjectShape` (through `objectShape`). |
|
|
754
|
+
| `RecordShapeOptions` | interface | `{ description? }` | Groups the options for record shapes (through `recordShape`). |
|
|
755
|
+
| `OptionalShapeOptions` | interface | `{ default? }` | Groups the options for `OptionalShape` (through `optionalShape`). |
|
|
756
|
+
| `SchemaToShapeOptions` | interface | `{ strict? }` | Groups the options for converting a JSON Schema (through `schemaToShape`). |
|
|
675
757
|
|
|
676
758
|
### Compilers
|
|
677
759
|
|
|
678
|
-
Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `parse` / `audit` / `explain` / `generate` (`src/core/compilers.ts`). `createContract` is the one door in this section that returns an entity rather than a compiled projection, so it lives in `src/core/factories.ts` over the same engine. Two engines sit under those functions. `ShapeValidator` owns the sole stateful declaration walk; `validateShape` constructs a fresh validator as its eager function boundary, while `cloners.ts`, `ShapeCloner`, and the shape builders use the class directly so lower validation no longer imports the compiler module. `ContractCompiler` owns ownership, preparation, and the six artifact families; every function in this section is a real typed door over it that requests exactly the root it is named for, so asking for a guard never compiles a generator. LOCKSTEP here means DERIVED FROM ONE SNAPSHOT, not equal in what they accept: `createContract` compiles all six from a single owned copy of the declaration, so no later edit to the shape you passed can move one of them without the others. It does not mean the six accept the same values — deliberately, they do not (see Domains,
|
|
760
|
+
Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `parse` / `audit` / `explain` / `generate` (`src/core/compilers.ts`). `createContract` is the one door in this section that returns an entity rather than a compiled projection, so it lives in `src/core/factories.ts` over the same engine. Two engines sit under those functions. `ShapeValidator` owns the sole stateful declaration walk; `validateShape` constructs a fresh validator as its eager function boundary, while `cloners.ts`, `ShapeCloner`, and the shape builders use the class directly so lower validation no longer imports the compiler module. `ContractCompiler` owns ownership, preparation, and the six artifact families; every function in this section is a real typed door over it that requests exactly the root it is named for, so asking for a guard never compiles a generator. LOCKSTEP here means DERIVED FROM ONE SNAPSHOT, not equal in what they accept: `createContract` compiles all six from a single owned copy of the declaration, so no later edit to the shape you passed can move one of them without the others. It does not mean the six accept the same values — deliberately, they do not (see Domains, later). The individual compilers return untyped runtime functions; `createContract` is the typed entry point — its `is` / `parse` / `generate` carry `Infer<S>` by inferring once, at the boundary (so the recursion stays cheap). `compileGuard` / `compileParser` / `compileReporter` / `compileAuditor` reuse the existing combinators and parsers rather than re-implementing them: `literalOf` IS the literal match at all four (one SameValueZero implementation, taking its vocabulary as an array), and each leaf's refinements (`min` / `max` / `pattern`) are read off the one shape node rather than restated per artifact — `compileGuard` and `compileParser` compose them through the **same** combinators (`stringOf` for a string's length and pattern, `boundsOf` for a number's value and an array's length), while `compileReporter` and `compileAuditor` check those same three against that same node inline, so each violated refinement can carry its own fault; the pattern test is the same flag-stripped owned `RegExp` in every artifact (`matchOf` for the two reports, the identical construction inside `stringOf` for the guard and parser). No artifact — not `compileGuard`, not `compileParser`, not `compileReporter`, not `compileAuditor` — holds a bound of its own to drift from the other three. What the four do NOT share is the leaf TYPE test: `compileGuard` and `compileAuditor` demand a `string`, `compileParser` and `compileReporter` accept whatever `parseString` coerces — which is where the two domains part company. Every entry point reaches the same declaration-rule set through validation or ownership, and `cloneShape` asks that claim of the carried cloned root after its node fields have completed descriptor/two-read capture and its property map has completed its separate enumeration and child-capture checks. The validator mirrors the ownership boundary by rejecting ordinary declared-field accessors before `Reflect.get`, while preserving the documented `pattern` exception. No entry can therefore launder a malformed property/variant/value container, discriminant, scalar accessor, vocabulary, raw-schema child, or structural child into a plausible contract. Every compiled object artifact — guard, parser, reporter, auditor, and the inference direction too — reads an object through the one `enumerableKeys` property view (own enumerable string keys, the set `JSON.stringify` serializes), so all of them see the SAME enumerable key set; the guard and the auditor of a closed or tail-shaped object also read its own names and symbols. Those two refuse and report an own member outside that view, a non-enumerable string key or a symbol key, while `parse` and `explain` keep the view: `is` answers `false`, `audit` reports a declared such member as `'hidden'` where `explain` reports `'missing'`, an undeclared one as `'extra'` when closed and `'hidden'` under a tail shape, and each symbol key as `'extra'` at the object with `symbol` naming it. An object with `additionalProperties: true` runs no own-key count: it admits an undeclared non-enumerable or symbol member, while a declared member outside the enumerable view still reads as absent, so `is` answers `false` for a required one and `audit` and `explain` report it `'missing'`. What each does with an undeclared key in that set differs by design: for a CLOSED object `is` rejects the object, `audit` reports an `'extra'` fault at the key, `parse` drops the key WITHOUT reading it, `explain` says nothing about it, and `schema` forbids it with `additionalProperties: false`. For an OPEN one they all READ it, including under `additionalProperties: true` where nothing constrains the value: open means unconstrained, not unobserved, and the parser copies every such key into its result. Skipping that read on three of the four doors is how `is`, `audit` and `explain` all certified a value clean that `parse` then refused as unreadable.
|
|
679
761
|
|
|
680
762
|
| Name | Kind | Signature | Summary |
|
|
681
763
|
| --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
@@ -687,13 +769,15 @@ Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `pa
|
|
|
687
769
|
| `compileSchema` | function | `(shape: ContractShape) => JSONSchema` | Compiles a `ContractShape` into a JSON Schema document. |
|
|
688
770
|
| `compileGenerator` | function | `(<S extends ContractShape>(shape: S, random?: RandomFunction) => Infer<S>) & ((shape: ContractShape, random?: RandomFunction) => unknown)` | Compiles a `ContractShape` into a deterministic seed value. |
|
|
689
771
|
| `createContract` | function | `(<S extends ContractShape>(shape: S) => ContractInterface<Infer<S>>) & ((shape: ContractShape) => ContractInterface<unknown>)` | Compiles a `ContractShape` into a `ContractInterface` — the lockstep outputs from one declaration, lockstep meaning derived from one owned snapshot rather than accepting the same values. |
|
|
690
|
-
| `ContractInterface` | interface | `{ schema, is, parse(), audit(), explain(), generate() }`
|
|
772
|
+
| `ContractInterface` | interface | `{ schema, is, parse(), audit(), explain(), generate(), own() }` | Represents a compiled contract — the lockstep outputs derived from one shape. |
|
|
691
773
|
| `ContractCompiler` | class | `new <S extends ContractShape = ContractShape>(shape: S) => ContractCompilerInterface<S>` | Owns one contract shape's artifacts and their bundle, compiled lazily. |
|
|
692
|
-
| `ContractCompilerInterface` | interface | `{ schema, guard, parser, auditor, reporter, generator, contract }`
|
|
774
|
+
| `ContractCompilerInterface` | interface | `{ schema, guard, parser, auditor, reporter, generator, owner, contract }` | Owns one contract shape's compiled artifacts plus their bundle, lazily. |
|
|
693
775
|
| `RandomFunction` | type | `() => number` | Represents a deterministic random source returning a value in `[0, 1)`. |
|
|
694
776
|
| `AuditorFunction` | type | `(value: unknown, path?: readonly string[]) => readonly AuditFault[]` | Represents a compiled strict-domain diagnostic — the shape of `compileAuditor` bound to one shape. |
|
|
695
777
|
| `ReporterFunction` | type | `(value: unknown, path?: readonly string[]) => readonly Fault[]` | Represents a compiled coercive-domain diagnostic — the shape of `compileReporter` bound to one shape. |
|
|
696
778
|
| `SeederFunction` | type | `(random?: RandomFunction) => T` | Represents a compiled seed-data source — the shape of `compileGenerator` bound to one shape. |
|
|
779
|
+
| `OwnerFunction` | interface | `{ <V extends T>(value: V): Result<V, ContractRefusal>, (value: unknown): Result<T, ContractRefusal> }` | Represents a compiled owning admission — the `own` member of a `ContractInterface`. |
|
|
780
|
+
| `CapturePlan` | interface | `{ held, properties, tail, items }` | Represents where an owned snapshot holds a value by identity instead of copying it. |
|
|
697
781
|
| `GENERATION_ATTEMPT_LIMIT` | const | `32` | Caps at `32` the number of candidate-generation attempts for a constrained generated value, frozen. |
|
|
698
782
|
| `COMPILE_DEPTH_LIMIT` | const | `512` | Caps at `512` the supported nesting depth of a compiled contract shape, frozen. |
|
|
699
783
|
| `COMPILE_NODE_LIMIT` | const | `16384` | Caps at `16384` the number of nodes a compiled artifact may expand a shape into, frozen. |
|
|
@@ -710,17 +794,17 @@ A compiled closed-object guard keeps the plans of the key orders it accepts unti
|
|
|
710
794
|
`ContractCompilerInterface` declares no call-signature member, so it has no Methods table: its
|
|
711
795
|
whole surface is the readonly data properties — `schema` (a `JSONSchema`), `guard` (a
|
|
712
796
|
`Guard<Infer<S>>`), `parser` (a `Parser<Infer<S>>`), `auditor` (an `AuditorFunction`), `reporter`
|
|
713
|
-
(a `ReporterFunction`), `generator` (a `SeederFunction<Infer<S>>`),
|
|
714
|
-
`ContractInterface<Infer<S>>`). `contract` is the
|
|
715
|
-
`schema`, `is`, `parse`, `audit`, `explain`,
|
|
716
|
-
|
|
717
|
-
identity rather than as a copy of it.
|
|
797
|
+
(a `ReporterFunction`), `generator` (a `SeederFunction<Infer<S>>`), `owner` (an
|
|
798
|
+
`OwnerFunction<Infer<S>>`), and `contract` (a `ContractInterface<Infer<S>>`). `contract` is the
|
|
799
|
+
frozen bundle whose own enumerable keys are `schema`, `is`, `parse`, `audit`, `explain`,
|
|
800
|
+
`generate`, and `own` in that order, each holding the exact value the corresponding getter
|
|
801
|
+
publishes — `contract.is` is exactly `compiler.guard`, by identity rather than as a copy of it.
|
|
718
802
|
|
|
719
|
-
Compilation costs ONE ownership and ONE validation per call, not one per node. Every `compile*` entry and `createContract` construct a `ContractCompiler`, which owns the declaration once, validates that owned graph once, and indexes each unique node and structural edge once; the artifact families are postorder passes over that index. A builder records what it validated, so wrapping a built child observes only the new node, and a declaration made entirely by builders is compiled as it stands, with no snapshot and no walk. A hand-written node anywhere in the graph, or a field a node may leave out appearing on `Object.prototype`, takes the whole walk instead, and that walk authors every refusal, so a refusal reads the same and fires at the same call either way. This is what replaced the arrangement where each recursive invocation re-ran `ownShape` AND `validateShape` over the subgraph it received — quadratic work for a linear declaration, and the reason a 129-node depth chain used to measure 6.3 ms of gate plus 7.9 ms of ownership and a 257-node chain 26.0 + 41.9 ms. A 30-alias depth-100 declaration
|
|
803
|
+
Compilation costs ONE ownership and ONE validation per call, not one per node. Every `compile*` entry and `createContract` construct a `ContractCompiler`, which owns the declaration once, validates that owned graph once, and indexes each unique node and structural edge once; the artifact families are postorder passes over that index. A builder records what it validated, so wrapping a built child observes only the new node, and a declaration made entirely by builders is compiled as it stands, with no snapshot and no walk. A hand-written node anywhere in the graph, or a field a node may leave out appearing on `Object.prototype`, takes the whole walk instead, and that walk authors every refusal, so a refusal reads the same and fires at the same call either way. This is what replaced the arrangement where each recursive invocation re-ran `ownShape` AND `validateShape` over the subgraph it received — quadratic work for a linear declaration, and the reason a 129-node depth chain used to measure 6.3 ms of gate plus 7.9 ms of ownership and a 257-node chain 26.0 + 41.9 ms. A 30-alias depth-100 declaration compiles a guard in 3 ms and a whole contract in 4 ms, against 640 ms and 1.87 s before. Every artifact compiles once, so `audit`, `explain` and `generate` re-walk and re-gate nothing on a later call either; `contract.audit` and `compileAuditor` run the same compiled plan reached by different names. A union whose arms are all objects declaring a required literal property answers through one arm when a value's own property exactly equals a literal only that arm holds: `explain` and `audit` report that arm's faults at their real paths in place of `variant`, and `parse` repairs through it alone, so `{ operation: 'find', limit: '5' }` parses to `limit: 5` however many arms precede it. `is` answers from that arm alone as well, in both modes, so `is`, `parse`, `audit`, and `explain` agree on that value and the three laws hold. When the property reads as its own descriptor states, no other arm's guard could accept that value, so `is` answers as every arm would, and an accepted or refused value costs one arm rather than every arm. A value that names no one arm, because its property is absent, matches no literal, or matches one two arms share, keeps `variant` or `oneOf`, with `key` and `expected` naming the property and what it may hold. `oneOfShape` behaves the same way: its parser refuses to coerce only because an ambiguous value has no target, and a named arm is one. An arm that is not an object, a discriminator that is optional or inside a nullable, and a nested union all change nothing at that union. `createContract` over a declaration made entirely by builders compiles its schema at that call and its function members together on the first call to any of them, so a module can declare contracts as data and pay only for the ones it uses; any other declaration, and a bare leaf, compiles every member at that call. Every refusal a declaration can earn still fires at `createContract` either way, because preparation and the schema ask them all, and each member is one plain function, so destructuring and spreading compile nothing. A member compiling after the call reads its declaration through own fields, so a field added to `Object.prototype` since cannot reach it. A host member replaced since is the one thing that can stop it: compiling there would outlive the replacement, so the member refuses to compile until the host is restored, with its guard answering `false`, its parser `undefined`, and its diagnostics and generator refusing, and the next call on a restored host compiles as usual. A first call near the stack limit recovers the same way. A compiled artifact is no longer a TREE either. Each family holds one entry per unique node and a parent points at its children, so a shared child is compiled once and the emitted schema preserves that sharing — which is why the cap boundary stopped being expensive: `createContract` over the two-edge-per-level DAG at the 16,383-node boundary takes under a millisecond where it took 1,342 ms, because it compiles fourteen nodes rather than sixteen thousand. Cost tracks AUTHORED nodes and edges instead: measured here, a depth-100 chain and a 30-alias depth-100 staircase answer every door in 1–5 ms, and a flat 10,001-node object takes 52–68 ms per artifact and 110 ms for a whole contract. One level past the cap boundary — 32,767 emitted nodes over thirty-one authored ones — still refuses in about two milliseconds with code `expansion`, because the count is measured over the captured graph rather than by walking the expansion. What the cap protects is the consumer's side of the artifacts rather than the compiler's: `generate` materializes the whole tree, and so does serializing the schema. The JSON cloner is capped for the opposite reason — it DUPLICATES a shared alias by contract rather than re-walking it: see `CLONE_NODE_LIMIT`. The `samplesToSchema` family is not on this list and was never meant to be reachable: its record path carried neither an ancestor set nor a memo, so an ordinary shared reference bought `k^depth` visits; it memoizes a single-row slot on `(row, remaining depth)` exactly as the record branch of `valueToSchema` does. Everything earlier in this section is the DECLARATION side, and for one release that was the only side measured. A compiled artifact applies each child artifact once per OCCURRENCE, which is right for a tree and wrong for a graph, so a value whose levels each held two references to one object was walked once per PATH: twenty-two shared arrays against a twenty-three-node chain of `arrayShape` — zero aliases in the declaration, every published limit satisfied — cost 524,286 node reads, 4.4 s for `is` and 8.4 s for `audit`, growing fourfold per two levels, while the same declaration over a TREE value answered instantly and `valueToSchema` answered the same graph in 4 ms because it already memoized. The verdict families carry a per-CALL identity memo keyed by `(compiled node, value object)`, and the same value costs thirty-six reads and under a millisecond. These details are exact rather than incidental. The guard reuses either answer while the auditor and reporter reuse only the CLEAN one, because a fault carries the path it was found at and emptiness carries nothing — a faulted node is re-walked and bounded by `FAULT_LIMIT` instead. The active synchronous call owns each node's memo and releases the scope on settlement, so an answer never survives into a later call where the caller may have changed the value. And a leaf is not tracked at all: it descends into no child, so tracking one would buy nothing and would replace the package's own guards and parsers in the artifacts a leaf-rooted declaration publishes. `parse` is deliberately absent from that list, because its result IS the expansion; the threat model names what that costs.
|
|
720
804
|
|
|
721
|
-
String and array length bounds deliberately use the builders' FULL rule — every present bound is a non-negative safe integer — rather than merely checking finiteness. A finiteness-only gate would close the `NaN` / infinity
|
|
805
|
+
String and array length bounds deliberately use the builders' FULL rule — every present bound is a non-negative safe integer — rather than merely checking finiteness. A finiteness-only gate would close the `NaN` / infinity gap but still admit hand-authored negative, fractional, and unsafe-integer length keywords that no builder can produce and that are not valid JSON Schema length bounds. Matching the builders costs compatibility only for those already-malformed hand-authored shapes; it preserves every legitimate builder output and keeps guard, parser, audit, and schema semantics on one domain.
|
|
722
806
|
|
|
723
|
-
> A shape nesting a `rawShape` or a pattern-constrained `stringShape` still compiles cleanly (`compileSchema` / `compileGuard` / `compileParser` all succeed) — only `generate()` throws at CALL time,
|
|
807
|
+
> A shape nesting a `rawShape` or a pattern-constrained `stringShape` still compiles cleanly (`compileSchema` / `compileGuard` / `compileParser` all succeed) — only `generate()` throws at CALL time, after it walks down into that leaf, because a `rawShape`'s embedded schema is arbitrary and a pattern the generator cannot satisfy has no auto-generatable sample.
|
|
724
808
|
|
|
725
809
|
The depth gate is why a pathological shape fails as a diagnosis rather than as a stack overflow — and it holds whether you reach the compilers through `createContract` or call one directly:
|
|
726
810
|
|
|
@@ -735,7 +819,7 @@ validateShape(deep) // throws a ContractError with code 'depth'
|
|
|
735
819
|
compileGuard(deep) // the same throw — every compile* entry fidelity-checks ownership, then gates
|
|
736
820
|
```
|
|
737
821
|
|
|
738
|
-
Every builder validates every runtime argument position before freezing its result. At every options position, a primitive or readable array/class instance throws a `structure` `ContractError` saying that the builder's options must be a plain record. A failure while reading any option key that builder consumes, or while snapshotting the options record, routes through the shared constructor as `<builder>: options could not be read`; no failed read becomes an absent option. Each consumed option is read once and its one non-`undefined` answer is copied into the snapshot as own enumerable data, including inherited and non-enumerable answers;
|
|
822
|
+
Every builder validates every runtime argument position before freezing its result. At every options position, a primitive or readable array/class instance throws a `structure` `ContractError` saying that the builder's options must be a plain record. A failure while reading any option key that builder consumes, or while snapshotting the options record, routes through the shared constructor as `<builder>: options could not be read`; no failed read becomes an absent option. Each consumed option is read once and its one non-`undefined` answer is copied into the snapshot as own enumerable data, including inherited and non-enumerable answers. Every builder, and `stringOf`, `valueToSchema`, `samplesToSchema`, and `describeFaults`, refuses an own enumerable string key it does not read through `refuseOptionKeys`, with code `structure` and that key as the path, so a misspelled option cannot read as an absent one; an inherited or symbol-keyed member is not refused. In 0.0.24, only `dateShape`, `optionalShape`, and `schemaToShape` refused such a key; every other builder and those four functions ignored it and returned their result, so `stringShape({ nickname: 'Ada' })` built a string shape and `integerShape({ integer: true })` built an integer shape, where 0.0.25 throws for both. Two options differ, because each decides what a contract accepts rather than how it describes itself: `optionalShape`'s `default` and `schemaToShape`'s `strict` count only as own keys. `{}` is accepted and constrains nothing. Invalid bounds use the total `preview` diagnostic, so even an untrusted `Symbol.toPrimitive` receives the existing `bound` refusal instead of leaking its raw error. The wider construction gate also covers `description` domains, child-shape slots, finite/ranged bounds, non-empty dense unique literal/union vocabularies, integer-range satisfiability, optional placement, and `rawShape`'s recursive supported-schema vocabulary. A malformed builder call therefore throws a coded `ContractError` at construction instead of leaking a raw host error or returning a node that only a later compiler rejects. Hand-authored declarations remain checked at ownership and by `validateShape` before artifact recursion.
|
|
739
823
|
|
|
740
824
|
```ts
|
|
741
825
|
import type { ContractShape } from '@orkestrel/contract'
|
|
@@ -805,7 +889,7 @@ schemaToParameters(valueToSchema(row)) // the open record a tool advertises as `
|
|
|
805
889
|
|
|
806
890
|
### Reporting
|
|
807
891
|
|
|
808
|
-
One diagnostic for each artifact that answers yes-or-no. `compileReporter` is the counterpart of `compileParser`: instead of a coerced value it returns every structured `Fault` a value has against a shape — MIRROR-PARSE semantics, so it reuses the exact leaf parsers/guards `compileParser` uses and the soundness invariant `explain(v).length === 0 ⟺ parse(v) !== undefined` holds structurally for READABLE input (`explain` mirrors `parse`'s coercion leniency, not the stricter `is`). `compileAuditor` is the counterpart of `compileGuard`: instead of a `boolean` it returns every `AuditFault` a value has against the STRICT domain, reusing the leaf guards `compileGuard` uses, so `audit(v).length === 0 ⟺ is(v)`. Each report mirrors exactly one artifact, and neither mirrors both, because `is` and `parse` accept different values — which is the subject of the next section. Before either pair compiles, `validateShape` rejects structural and bound-domain malformations; the laws are evaluated only for a valid declaration. Both biconditionals span two separate calls, so both require STABLE reads; the parse biconditional additionally requires the read to succeed rather than raise its coded refusal (see Domains).
|
|
892
|
+
One diagnostic for each artifact that answers yes-or-no. `compileReporter` is the counterpart of `compileParser`: instead of a coerced value it returns every structured `Fault` a value has against a shape — MIRROR-PARSE semantics, so it reuses the exact leaf parsers/guards `compileParser` uses and the soundness invariant `explain(v).length === 0 ⟺ parse(v) !== undefined` holds structurally for READABLE input, where an `undefined` that `is` admits parses to itself (`explain` mirrors `parse`'s coercion leniency, not the stricter `is`). `compileAuditor` is the counterpart of `compileGuard`: instead of a `boolean` it returns every `AuditFault` a value has against the STRICT domain, reusing the leaf guards `compileGuard` uses, so `audit(v).length === 0 ⟺ is(v)`. Each report mirrors exactly one artifact, and neither mirrors both, because `is` and `parse` accept different values — which is the subject of the next section. Before either pair compiles, `validateShape` rejects structural and bound-domain malformations; the laws are evaluated only for a valid declaration. Both biconditionals span two separate calls, so both require STABLE reads; the parse biconditional additionally requires the read to succeed rather than raise its coded refusal (see Domains).
|
|
809
893
|
|
|
810
894
|
| Name | Kind | Signature | Summary |
|
|
811
895
|
| ----------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -818,6 +902,7 @@ One diagnostic for each artifact that answers yes-or-no. `compileReporter` is th
|
|
|
818
902
|
| `matchesExactKeys` | function | `(value: object, required: readonly string[], optional?: readonly string[]) => boolean` | Determines whether an object holds exactly the named own keys. |
|
|
819
903
|
| `selectClosestFaults` | function | `<T extends AuditFault>(reports: ReadonlyArray<readonly T[]>) => readonly T[]` | Selects the report of the variant that came closest to matching. |
|
|
820
904
|
| `shapeToKind` | function | `(shape: ContractShape) => FaultKind` | Projects a `ContractShape` to the `FaultKind` it describes. |
|
|
905
|
+
| `matchesUndefinedNode` | function | `(category: unknown, mode: unknown, children: readonly boolean[]) => boolean` | Checks whether a shape node admits `undefined`, from its category, its union mode, and its children's answers. |
|
|
821
906
|
| `preview` | function | `(value: unknown) => string` | Renders a value as a bounded single-line string for a `Fault`'s `received` field, running a `Proxy` object's `getPrototypeOf` trap. |
|
|
822
907
|
| `FAULT_KINDS` | const | `readonly FaultKind[]` | Lists every `FaultKind`, frozen. |
|
|
823
908
|
| `FAULT_CONSTRAINTS` | const | `readonly FaultConstraint[]` | Lists every `FaultConstraint`, frozen. |
|
|
@@ -827,8 +912,13 @@ One diagnostic for each artifact that answers yes-or-no. `compileReporter` is th
|
|
|
827
912
|
| `ExtraFault` | interface | `{ reason, path, symbol? }` | Represents a key present on a value that its closed object shape does not declare, or an own key other than an index or `length` on a value its array shape describes. |
|
|
828
913
|
| `HiddenFault` | interface | `{ reason, path }` | Represents an own member outside the enumerable view that a closed or tail-shaped object refuses. |
|
|
829
914
|
| `AuditFault` | type | `Fault \| ExtraFault \| HiddenFault` | Covers every fault an audit reports — the parse faults plus undeclared and hidden keys. |
|
|
830
|
-
| `FaultKind` | type | `'string' \| 'date' \| 'number' \| 'integer' \| 'boolean' \| 'null' \| 'literal' \| 'array' \| 'object' \| 'union' \| 'json' \| 'shape' \| 'function'`
|
|
831
|
-
| `FaultConstraint` | type | `'min' \| 'max' \| 'pattern' \| 'date' \| 'integer'`
|
|
915
|
+
| `FaultKind` | type | `'string' \| 'date' \| 'number' \| 'integer' \| 'boolean' \| 'null' \| 'literal' \| 'array' \| 'object' \| 'union' \| 'json' \| 'shape' \| 'function' \| 'undefined'` | Names the kind of value a `Fault` expected — the shape-projected counterpart of a `ContractShape`'s `category`. |
|
|
916
|
+
| `FaultConstraint` | type | `'min' \| 'over' \| 'max' \| 'under' \| 'pattern' \| 'date' \| 'integer'` | Names the refinement a `Fault` of reason `'constraint'` violates. |
|
|
917
|
+
|
|
918
|
+
`FAULT_KINDS` gains `'undefined'` and `FAULT_CONSTRAINTS` gains `'over'` and `'under'` in 0.0.25. In
|
|
919
|
+
0.0.24, `isFault`, `isAuditFault`, and a contract over `auditFaultShape()` answered `false` for a
|
|
920
|
+
fault whose `expected` is `'undefined'` or whose `constraint` is `'over'` or `'under'`; from 0.0.25
|
|
921
|
+
they answer `true`.
|
|
832
922
|
|
|
833
923
|
#### How a union is audited and reported
|
|
834
924
|
|
|
@@ -838,7 +928,7 @@ An `anyOf` union stops at the FIRST variant that reports nothing, in declaration
|
|
|
838
928
|
|
|
839
929
|
An `anyOf` union with no matching variant reports one `'variant'` summary plus the closest variant's own faults — fewest faults, ties favouring the lowest index. A `oneOf` union runs every variant plan, because its verdict is the match count rather than the first acceptance, and reports `'oneOf'` with the raw guard-match count; a count of `0` also appends the closest variant's faults, and a count of `2` or more stands alone. A value a later `oneOf` variant cannot read therefore still reaches the same coded refusal.
|
|
840
930
|
|
|
841
|
-
Arrays report from the shared owned sparse snapshot: an owned hole retains its per-index fault,
|
|
931
|
+
Arrays report from the shared owned sparse snapshot: an owned hole retains its per-index fault, an untrusted absent source index is never read, and a failed snapshot retains the root array type fault. The auditor stops after `FAULT_LIMIT` faults exist, so even a native-maximum sparse length performs no absent source-index reads.
|
|
842
932
|
|
|
843
933
|
#### Supplying a rebuilt pattern
|
|
844
934
|
|
|
@@ -860,7 +950,9 @@ explain(v).length === 0 ⟺ parse(v) !== undefined
|
|
|
860
950
|
parse(v) !== undefined ⟹ is(parse(v))
|
|
861
951
|
```
|
|
862
952
|
|
|
863
|
-
|
|
953
|
+
A contract whose `is` admits `undefined`, such as `createContract(unionShape(numberShape(), undefinedShape()))`, answers `parse(undefined)` with `undefined` as the parsed value rather than as a refusal, so for that one input read `parse` as succeeding where `is` holds; `admitValue` answers it as a success.
|
|
954
|
+
|
|
955
|
+
Under the module-wide READABLE and STABLE definitions at the top of this guide, all three laws require stable reads, and the two parse laws additionally require readable input. Each relates two separate calls, and every call reads the value it is handed, so each holds for a value whose observable reads succeed and do not change between calls. A failed required read raises the shared coded refusal instead of producing the `undefined` result used for honest invalidity, and the read population is the same at every door: a read one door performs and another skips is a two-call law falsified in one call, which is what an unread open-object extra and `parseRecord`'s eager whole-record probe each produced. A getter that answers `'allowed'` on its first read and `42` on its second, or a `Proxy` whose traps change behavior mid-flight, can leave `audit` empty and still fail `is` — the audit read one value and `is` read another. No law spanning two calls can promise otherwise, and no artifact re-reads a value to close the gap. `Object.freeze` alone does not establish those conditions because it is shallow and does not stabilize accessors. `explain`'s invariant carries both preconditions; `audit`'s carries stability for the identical two-call reason.
|
|
864
956
|
|
|
865
957
|
The ordering between the two reports follows from those three rather than standing as a fourth law: `audit(v).length === 0 ⟹ explain(v).length === 0`. Every value in the canonical domain is inside `parse`'s preimage, so a clean audit implies a clean explain; the converse fails for exactly the inputs `parse` had to work on. Reach for `audit` when you need to know what `parse` silently repaired, and for `explain` when you need to know why it gave up.
|
|
866
958
|
|
|
@@ -899,11 +991,11 @@ The public surface includes these declarations:
|
|
|
899
991
|
| `ShapeShapeOptions` | interface | `{ description? }` | Configures the description of a shape-valued declaration. |
|
|
900
992
|
| `SHAPE_FIELDS` | const | `Readonly<Record<string, readonly string[]>>` | Lists the fields recognized for every contract declaration category, frozen. |
|
|
901
993
|
|
|
902
|
-
The category table drives both validation and the emitted category enum. `Infer` of a `ShapeShape` is `ContractShape`; refusal diagnostics use the `shape` fault kind at the containing field.
|
|
994
|
+
The category table drives both validation and the emitted category enum. In 0.0.24, `SHAPE_FIELDS` held neither the `undefined` nor the `interface` category and listed `integer`, `min`, `max`, and `description` for `number`; from 0.0.25 it holds both categories, the emitted enum ends `'undefined', 'interface'`, and `number` lists `over` and `under` beside `min` and `max`. `Infer` of a `ShapeShape` is `ContractShape`; refusal diagnostics use the `shape` fault kind at the containing field.
|
|
903
995
|
|
|
904
996
|
## Methods
|
|
905
997
|
|
|
906
|
-
The public methods of each behavioral interface — one table per type, keyed by its backticked name, every call-signature member listed (its `readonly` data members, `schema` / `is`, stay in the Surface row
|
|
998
|
+
The public methods of each behavioral interface — one table per type, keyed by its backticked name, every call-signature member listed (its `readonly` data members, `schema` / `is`, stay in the earlier Surface row). `ContractInterface` has no implementing class: `createContract` builds it as a plain object whose shape conforms to the interface exactly, so the following table is its per-instance surface (`AGENTS.md`, Documentation contract).
|
|
907
999
|
|
|
908
1000
|
#### `JSONClonerInterface`
|
|
909
1001
|
|
|
@@ -950,30 +1042,31 @@ because neither measured one. `validateShape` reads it to apply `COMPILE_NODE_LI
|
|
|
950
1042
|
|
|
951
1043
|
Cycle detection precedes depth measurement. A cyclic graph reports structure before cycle; an acyclic graph reports depth before structure and domain diagnoses. Within a string declaration the fixed domain order is invalid `min`, invalid `max`, flagged pattern, then contradictory range.
|
|
952
1044
|
|
|
953
|
-
Every nested and outer call inside an active pass shares the exact reentry
|
|
1045
|
+
Every nested and outer call inside an active pass shares the exact reentry refusal object, which carries no own cause. Cleanup restores idle state, so a later independent call observes the source again. A failed pass, including a caught-reentry-invalidated outer pass, leaves `expansion` undefined, and a later successful pass replaces it.
|
|
954
1046
|
|
|
955
1047
|
The whole traversal is contained, and its cleanup builds its active-path set from an intrinsic captured at module evaluation, so no caller-reachable dispatch on the path can put a raw value through this door. A contained failure this class did not author is translated into `validateShape: shape reflection failed` (code `structure`, root path) carrying the exact thrown value as its cause.
|
|
956
1048
|
|
|
957
1049
|
#### `ContractInterface`
|
|
958
1050
|
|
|
959
|
-
| Method | Returns
|
|
960
|
-
| ---------- |
|
|
961
|
-
| `parse` | `T \| undefined`
|
|
962
|
-
| `audit` | `readonly AuditFault[]`
|
|
963
|
-
| `explain` | `readonly Fault[]`
|
|
964
|
-
| `generate` | `T`
|
|
1051
|
+
| Method | Returns | Summary |
|
|
1052
|
+
| ---------- | ---------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
1053
|
+
| `parse` | `T \| undefined` | Coerces a readable value to the contract's type, or returns `undefined`. |
|
|
1054
|
+
| `audit` | `readonly AuditFault[]` | Reports every strict fault a value has against this contract. |
|
|
1055
|
+
| `explain` | `readonly Fault[]` | Reports every structured parse fault a value has against this contract. |
|
|
1056
|
+
| `generate` | `T` | Produces deterministic seed data for this contract. |
|
|
1057
|
+
| `own` | `Result<V, ContractRefusal>` | Admits an owned snapshot of a value and returns the parser's value, at the argument's static type. |
|
|
965
1058
|
|
|
966
1059
|
## Contract
|
|
967
1060
|
|
|
968
1061
|
These invariants hold across `src/core` ↔ `contract.md`:
|
|
969
1062
|
|
|
970
1063
|
1. **DOC ↔ SOURCE bijection.** Every `function` / `type` row in the `## Surface` tables is a real export of the contract source tree, and every contract-module export appears as a Surface row — exhaustive, both directions (`AGENTS.md`, Documentation contract). Adding, renaming, or removing a guard breaks the parity gate until the doc is reconciled.
|
|
971
|
-
2. **Guards are total.** `.claude/rules/patterns.md` § Validation and contracts requires it: every guard takes one `unknown`, returns a `boolean` type predicate, and **never throws** —
|
|
1064
|
+
2. **Guards are total.** `.claude/rules/patterns.md` § Validation and contracts requires it: every guard takes one `unknown`, returns a `boolean` type predicate, and **never throws** — untrusted input yields `false`. The only deferral is `lazyOf`, whose thunk runs per call; `whereOf` / `lazyOf` / `transformOf` contain a callback throw as a non-match through the core `attempt` helper.
|
|
972
1065
|
3. **Parse ↔ guard soundness.** `.claude/rules/patterns.md` § Validation and contracts mandates it. On readable input, each standalone leaf parser (`parseString`, …) pairs with the guard for its **output type**: a guard-valid input is returned unchanged (by identity, never rejected), and every non-`undefined` output satisfies that type guard. Coercion of otherwise-invalid inputs is a bonus on top, not a violation; a failed required read is a coded refusal, not an `undefined` parse result. The **compiled** contract goes further: `compileParser` (and thus `createContract`'s `parse`) re-applies every leaf REFINEMENT after coercion through the same combinators (`stringOf` / `boundsOf`) `compileGuard` uses — so a non-`undefined` `contract.parse` always satisfies `contract.is`, refinements (`min` / `max` / `pattern`) included. That law is about parse's OUTPUT. Its readable INPUT domain is deliberately wider than `is` — a coercible leaf, a closed object's extra key — and no amount of shared machinery closes that gap, because it is the feature. What cannot drift is `compileGuard` and `compileParser`, both compiled from one snapshot; what differs, permanently, is the set each accepts (see Domains). `audit` is the report for the stricter of the two.
|
|
973
1066
|
4. **Types are the source of truth.** `Guard`, `Parser`, and the guard-shape types are declared in [`types.ts`](../src/core/types.ts) first; guards and parsers conform to them, never the reverse.
|
|
974
|
-
5. **`createContract` validates before it compiles.** The declaration is owned once and that OWNED graph is validated once, or was already by the builders that made it, before any artifact is built, and the same is true at every `compile*` entry — a malformed shape (a structural child that is not a shape, `min > max`, a non-finite number bound, an empty integer range, an empty literal/union, a literal shape holding a non-finite number value, an `optionalShape` placed anywhere but a direct object-property value, a `default` under a union or on a property of an open object, a `default` its inner shape refuses, a structural cycle, or nesting past `COMPILE_DEPTH_LIMIT`) throws a coded `ContractError` immediately instead of silently producing a wrong guard, parser, schema, audit, report, or generator. `optionalShape` is legal in exactly
|
|
1067
|
+
5. **`createContract` validates before it compiles.** The declaration is owned once and that OWNED graph is validated once, or was already by the builders that made it, before any artifact is built, and the same is true at every `compile*` entry — a malformed shape (a structural child that is not a shape, `min > max`, a non-finite number bound, an empty integer range, an empty literal/union, a literal shape holding a non-finite number value, an `optionalShape` placed anywhere but a direct object-property or interface-member value, a `default` under a union, below an interface, or on a property of an open object, an interface under a union, a `default` its inner shape refuses, a structural cycle, or nesting past `COMPILE_DEPTH_LIMIT`) throws a coded `ContractError` immediately instead of silently producing a wrong guard, parser, schema, audit, report, or generator. `optionalShape` is legal in exactly two positions: as the value of an object property and as the value of an interface member. ONE population, one rule set: ownership refuses a malformed structural slot, scalar field, or bound rather than normalizing it, so the graph the gate judges is the graph the artifacts compile from — there is no earlier reading of the caller's live source that is validated and then thrown away.
|
|
975
1068
|
6. **DOC ↔ SOURCE method bijection.** Every behavioral interface's `## Methods` table lists exactly its public methods (call-signature members) — exhaustive, both directions — and each implementing class exposes the same public methods, no more (`AGENTS.md`, Documentation contract). A renamed / added / removed method breaks the gate until the table is reconciled.
|
|
976
|
-
7. **Compilation owns its input.** A builder freezes what it produces, copies what you hand it, and re-exposes a `pattern` as a fresh frozen `RegExp` per read; every `compile*` entry point and `createContract` take their argument through `ownShape`, which always returns an independent clone, unless the builders made all of it, when it is frozen and validated all the way down already and nothing a caller holds can change it. Ownership refuses a non-record node before discriminant normalization and retains only primitive-string RegExp `source` / `flags` pairs. A shape you keep a reference to can never change what an already-compiled artifact does, and a compiled `schema` is deeply frozen — so the
|
|
1069
|
+
7. **Compilation owns its input.** A builder freezes what it produces, copies what you hand it, and re-exposes a `pattern` as a fresh frozen `RegExp` per read; every `compile*` entry point and `createContract` take their argument through `ownShape`, which always returns an independent clone, unless the builders made all of it, when it is frozen and validated all the way down already and nothing a caller holds can change it. Ownership refuses a non-record node before discriminant normalization and retains only primitive-string RegExp `source` / `flags` pairs. A shape you keep a reference to can never change what an already-compiled artifact does, and a compiled `schema` is deeply frozen — so the outputs stay in lockstep with the declaration they came from, lockstep meaning derived from that one snapshot rather than agreeing on which values to accept.
|
|
977
1070
|
|
|
978
1071
|
The `parseJSON` / `parseJSONAs` text boundary is **lazy by default**: keep the result unknown, validate only a supplied shape, or read fields individually. Whole-tree work is explicit through the shipped `isJSONValue`, fixed-cap `isBoundedJSONValue` / `isBoundedJSONRecord`, `parseJSONValue`, `cloneJSONValue`, and record-root `cloneJSONRecord`; `JSONRecord` is the reusable record-root type. A dedicated `JSONArray` alias and broad deep JSON-Schema validators / `JSONSchemaDefinition` remain omitted; compose any narrower contract a consumer actually needs.
|
|
979
1072
|
|
|
@@ -981,7 +1074,7 @@ The `parseJSON` / `parseJSONAs` text boundary is **lazy by default**: keep the r
|
|
|
981
1074
|
|
|
982
1075
|
### Capturing synchronous outcomes losslessly
|
|
983
1076
|
|
|
984
|
-
`attempt` records one synchronous callback invocation without interpreting the result. `Result<T>` resolves to `Result<T, unknown>` through the safe default, so the failure branch must be narrowed before member access. Domain boundaries can preserve that unknown value as an exact cause. Promises and thenables remain ordinary return values; handle their later settlement separately.
|
|
1077
|
+
`attempt` records one synchronous callback invocation without interpreting the result. `Result<T>` resolves to `Result<T, unknown>` through the safe default, so the failure branch must be narrowed before member access. Domain boundaries can preserve that unknown value as an exact cause. Promises and thenables remain ordinary return values; handle their later settlement separately. `settle` is the awaited form: it runs the callback one time, awaits its result, and answers a `Failure` carrying the exact thrown value for a synchronous throw, a rejection, or a thenable whose `then` throws, so the promise it returns never rejects.
|
|
985
1078
|
|
|
986
1079
|
```ts
|
|
987
1080
|
import { attempt, ContractError } from '@orkestrel/contract'
|
|
@@ -1134,6 +1227,17 @@ import { matchesJSONValue } from '@orkestrel/contract'
|
|
|
1134
1227
|
matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true
|
|
1135
1228
|
```
|
|
1136
1229
|
|
|
1230
|
+
To own JSON data, call `own` on a JSON contract. It answers a frozen copy, or a refusal that carries
|
|
1231
|
+
every fault the audit found, where `cloneJSONValue` throws at the first value that is not JSON data.
|
|
1232
|
+
|
|
1233
|
+
```ts
|
|
1234
|
+
import { createContract, jsonShape } from '@orkestrel/contract'
|
|
1235
|
+
|
|
1236
|
+
const json = createContract(jsonShape())
|
|
1237
|
+
json.own({ name: 'Ada', tags: ['admin'] }) // { success: true, value: { name: 'Ada', tags: ['admin'] } }
|
|
1238
|
+
json.own({ joined: new Date(0) }).success // false
|
|
1239
|
+
```
|
|
1240
|
+
|
|
1137
1241
|
### Declaring a shape
|
|
1138
1242
|
|
|
1139
1243
|
Declare an object shape from the builders, then derive its static type with `Infer`.
|
|
@@ -1240,7 +1344,7 @@ compiler.guard === compiler.guard // true — every getter replays its exact art
|
|
|
1240
1344
|
compiler.contract.is === compiler.guard // true — the bundle holds these exact values
|
|
1241
1345
|
```
|
|
1242
1346
|
|
|
1243
|
-
One declaration; the schema, guard, parser, both reports, and the generator are all derived from one owned snapshot of it, so no later edit to the shape can move one of them without the others. Derived together is not the same as equal, though, and the block
|
|
1347
|
+
One declaration; the schema, guard, parser, both reports, and the generator are all derived from one owned snapshot of it, so no later edit to the shape can move one of them without the others. Derived together is not the same as equal, though, and the preceding block is the proof: `is` rejects the undeclared key, `schema` forbids it, `audit` names it, `parse` drops it, and `explain` has nothing to say. See Domains for the three laws that hold between them.
|
|
1244
1348
|
|
|
1245
1349
|
When you want one artifact, hold the artifact rather than the compiler. A compiler releases its working set — the owned graph, the node index, the order, and every family plan — after every family exists, so a compiler read for one artifact and then kept holds all of it for as long as you keep the compiler. Each compiled artifact closes over the child entries its family needed while that family was built, so it answers on its own and outlives the compiler that produced it. The following block reads one guard and keeps no reference to the compiler behind it:
|
|
1246
1350
|
|
|
@@ -1326,7 +1430,7 @@ contract.explain({ id: 'nope', name: 'x', role: 'y' })
|
|
|
1326
1430
|
|
|
1327
1431
|
- **Guards narrow, parsers coerce.** `isNumber('36')` is `false`. Need `'36'` → `36`? Use `parseNumber`.
|
|
1328
1432
|
- **`isNumber` accepts `NaN`; reach for `isFiniteNumber`** (or `isInteger`) when `NaN` / `±Infinity` must be rejected.
|
|
1329
|
-
- **`isObject` is broad, `isRecord` is strict.** Arrays and ordinary class instances satisfy `isObject` but fail `isRecord` — use `isRecord` for plain config / JSON-style objects. `isRecord` is a structural brand, not a provenance check, so a class whose prototype has been
|
|
1433
|
+
- **`isObject` is broad, `isRecord` is strict.** Arrays and ordinary class instances satisfy `isObject` but fail `isRecord` — use `isRecord` for plain config / JSON-style objects. `isRecord` is a structural brand, not a provenance check, so a class whose prototype has been fabricated into a realm prototype — with the seven mandated names carried as function-valued own data properties — passes it; see `matchesRecordBrand` for that residual and its exact cost.
|
|
1330
1434
|
- **`recordOf` is exact.** Extra keys fail by default; declare optional keys with a key list or `true`, and derive related shapes with `pickOf` / `omitOf`.
|
|
1331
1435
|
- **`objectOf` is open.** Use it for objects or callables a foreign interface returns when only the declared members belong to this package's check.
|
|
1332
1436
|
- **Use `lazyOf` for self-referential guards** — never reference a guard inside its own definition without it.
|
|
@@ -1335,26 +1439,26 @@ contract.explain({ id: 'nope', name: 'x', role: 'y' })
|
|
|
1335
1439
|
## Tests
|
|
1336
1440
|
|
|
1337
1441
|
- [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` bijection (value and type exports), the `## Methods` ↔ implementing-class bijection read from the real prototypes, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Compiling a contract` fence against the `@example` block of that title (pinned so the titled pair cannot be retired silently), and the README pitch against this guide's tagline. It also runs the flagship fences and asserts the values their comments claim.
|
|
1338
|
-
- [`tests/src/core/JSONCloner.test.ts`](../tests/src/core/JSONCloner.test.ts) — direct root-imported `JSONCloner`/interface contract: inert construction, exact prototype, terminal identity and zero rereads, failure working-set release, atomic settlement while every terminal-path intrinsic is redirected, caught/uncaught reentry
|
|
1442
|
+
- [`tests/src/core/JSONCloner.test.ts`](../tests/src/core/JSONCloner.test.ts) — direct root-imported `JSONCloner`/interface contract: inert construction, exact prototype, terminal identity and zero rereads, failure working-set release, atomic settlement while every terminal-path intrinsic is redirected, caught/uncaught reentry invalidation, independent instances, eager parity, caller-error containment, graph/descriptor/order/freeze/mutation behavior, and iterative depth.
|
|
1339
1443
|
- [`tests/src/core/SchemaCloner.test.ts`](../tests/src/core/SchemaCloner.test.ts) — direct root-imported `SchemaCloner`/interface contract: inert construction, exact prototype, terminal replay and zero rereads, caught/uncaught reentry precedence, independent instances, exact provenance and paths, enumerable-string observation, aliases/cycles, shells/order/freeze/depth, atomic settlement while every terminal-path intrinsic is redirected, and success/failure working-state release with a real collection control.
|
|
1340
1444
|
- [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — eager JSON and schema behavior plus the shape function boundaries: fresh `cloneShape` roots/failures/source observation, overload/runtime and compact class parity, and genuine `ownShape` frozen-failure precedence and independent-success behavior.
|
|
1341
|
-
- [`tests/src/core/combinators.test.ts`](../tests/src/core/combinators.test.ts) — guard-combinator semantics, refinement composition, exact records/tuples, open-object and member-carrying-callable controls including the prototype-accessor proof, lazy recursion, thrown-value containment, dense array membership, genuine foreign-pattern ownership/flag stripping, and the unreadable-brand versus proxy/
|
|
1342
|
-
- [`tests/src/core/ContractCompiler.test.ts`](../tests/src/core/ContractCompiler.test.ts) — the lazy engine's own contract: the pinned getters, construction that observes nothing, per-root replay identity and the frozen bundle, one entry per unique node, terminal adoption/reentry
|
|
1445
|
+
- [`tests/src/core/combinators.test.ts`](../tests/src/core/combinators.test.ts) — guard-combinator semantics, refinement composition, exact records/tuples, open-object and member-carrying-callable controls including the prototype-accessor proof, lazy recursion, thrown-value containment, dense array membership, genuine foreign-pattern ownership/flag stripping, and the unreadable-brand versus proxy/fake diagnostic split.
|
|
1446
|
+
- [`tests/src/core/ContractCompiler.test.ts`](../tests/src/core/ContractCompiler.test.ts) — the lazy engine's own contract: the pinned getters, construction that observes nothing, per-root replay identity and the frozen bundle, one entry per unique node, terminal adoption/reentry invalidation, release, the shared-edge staircase and the bounded expansion refusal, door-versus-getter agreement across every shape category, and field defaults: the fill at both absence sites, a distinct tree per parse for every inner category, nested defaults, the emitted keyword, the JSON round trip, the refusal at every door with its path, and what `generate` does with a default.
|
|
1343
1447
|
- [`tests/src/core/KeyPlanCache.test.ts`](../tests/src/core/KeyPlanCache.test.ts) — the interned `KeyPlanCache` class reached by relative source path: a recall that misses on a reordered key list and on a prefix, the oldest plans kept and every key order past `KEY_PLAN_LIMIT` plans missed, one plan per held key order, no plan for a key list holding an undeclared key, and the `retain` method under polluted array construction.
|
|
1344
|
-
- [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — the `compile*` exports and `createContract`, including schema/guard/parser/generator behavior, the public depth boundary, strict auditor and coercive reporter fault semantics,
|
|
1345
|
-
- [`tests/src/core/errors.test.ts`](../tests/src/core/errors.test.ts) — cross-copy `ContractError` recognition through distinct source-module instances, including transparent-wrapper, stripped-brand subclass, plain-error, complete self-branded
|
|
1448
|
+
- [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — the `compile*` exports and `createContract`, including schema/guard/parser/generator behavior, the public depth boundary, strict auditor and coercive reporter fault semantics, untrusted input containment, and contract wiring. It binds genuine foreign patterns through every compiler, exact captured property populations read twice (including refusal of an invalid captured population, and the absence of any further caller read), and the validator/cloner/compiler/contract fake matrix. The explicit declaration matrix covers non-record roots and children, object-valued RegExp `source` / `flags`, present raw `undefined` populations, and flagged-pattern refusal, with plain/null-prototype/foreign records plus valid local/foreign/accessor patterns as controls; no generated message inventory or source pin participates.
|
|
1449
|
+
- [`tests/src/core/errors.test.ts`](../tests/src/core/errors.test.ts) — cross-copy `ContractError` recognition through distinct source-module instances, including transparent-wrapper, stripped-brand subclass, plain-error, complete self-branded fake, and undeclared-code controls.
|
|
1346
1450
|
- [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — the entity door `createContract` driven directly: an eager bundle whose roots are data properties carrying one artifact identity through destructuring and through a spread, the generic overload and the widened-`ContractShape` overload each answering at every root, a malformed declaration refused at the call itself with the authoring door's own diagnosis rather than a rewrap, and `is` agreeing with `compileGuard` over a corpus that exercises each verdict.
|
|
1347
|
-
- [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — helper behavior including `attempt`, reflected reads, fixed JSON-depth boundaries/aliases/cycles/sparse populations/
|
|
1451
|
+
- [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — helper behavior including `attempt`, reflected reads, fixed JSON-depth boundaries/aliases/cycles/sparse populations/untrusted hosts, option capture, random/schema utilities, `preview`, and `shapeToKind`; it also owns `ContractError` construction, exhaustive `ContractCode` preservation, exact causes, and `isContractError` containment.
|
|
1348
1452
|
- [`tests/src/core/SampleInferer.test.ts`](../tests/src/core/SampleInferer.test.ts) — the interned `SampleInferer` reached by relative source path: the ordered row-prefix memo served to a slot collecting the same rows in the same order and missed by slots whose rows arrive in a different order or at a different remaining depth, no memo carried across two walks over one row list, and the closed flag reaching the emitted opening.
|
|
1349
1453
|
- [`tests/src/core/ValueInferer.test.ts`](../tests/src/core/ValueInferer.test.ts) — the interned `ValueInferer` reached by relative source path and driven with the depth and breadth budgets its door sanitizes away: a container root widened at every budget not above zero, a leaf root classified without consulting the budget, one level of descent on a fractional budget, descent past the cap the door imposes, and a negative breadth budget that samples no member and forces the record open.
|
|
1350
|
-
- [`tests/src/core/inferers.test.ts`](../tests/src/core/inferers.test.ts) — schema inference, unification, depth/breadth limits, deterministic sampling, readable widening,
|
|
1454
|
+
- [`tests/src/core/inferers.test.ts`](../tests/src/core/inferers.test.ts) — schema inference, unification, depth/breadth limits, deterministic sampling, readable widening, untrusted traversal, sparse populations, and canonical serialization, including direct/public/consumer failed-prototype classification plus readable record/exotic controls.
|
|
1351
1455
|
- [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — the one explicit layout exception: genuine public cross-module composition, seeded generation/guard/parser/schema round trips, guard-combinator integration, and the three laws over shapes that carry a default, curated and seeded. Unit and type-carrier behavior remains in mirrored suites.
|
|
1352
1456
|
- [`tests/src/core/parsers.test.ts`](../tests/src/core/parsers.test.ts) — coercion, field parsing, parse/guard soundness, reflected dense arrays, record/JSON boundaries, and coded unreadable-input refusal.
|
|
1353
1457
|
- [`tests/src/core/SchemaShaper.test.ts`](../tests/src/core/SchemaShaper.test.ts) — the interned `SchemaShaper` reached by relative source path: a node two branches share converted exactly once and re-converted at a different remaining depth, a cyclic schema widened at the re-encountered node instead of recursed into, an unreadable keyword's read failure escaping the walk carrying no door name of its own, the lenient `default` carry and drop tables with a shared node beside and below a union, the foreign-schema table with an authored expectation per row, the `oneOf`, boolean-arm, `enum`, `nullable`, `patternProperties`, `prefixItems`, typeless-`properties`, two-arm-null, carried-description, and large-schema rows, and the strict refusal and annotation tables with the path each row names.
|
|
1354
|
-
- [`tests/src/core/ShapeCloner.test.ts`](../tests/src/core/ShapeCloner.test.ts) — canonical direct root-imported `ShapeCloner`/interface contract: inert source-only construction, exact prototype, terminal success/failure replay without rereads, caught/uncaught/replacement reentry
|
|
1355
|
-
- [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — builders and `Infer`/`InferMutable`, with explicit `BUILDER_CASES` option positions and public keys driving real plain/frozen/null-prototype and
|
|
1356
|
-
- [`tests/src/core/ShapeValidator.test.ts`](../tests/src/core/ShapeValidator.test.ts) — direct public validator behavior: inert construction, repeatable live passes and reentry
|
|
1357
|
-
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — primitive, non-negative numeric, structural, bounded-JSON, and JSON/record/RegExp guards; genuine `node:vm` record/RegExp values; depth-versus-validity and sequential-observation controls; zero-read duck/tag/accessor/proxy/revoked opposites;
|
|
1458
|
+
- [`tests/src/core/ShapeCloner.test.ts`](../tests/src/core/ShapeCloner.test.ts) — canonical direct root-imported `ShapeCloner`/interface contract: inert source-only construction, exact prototype, terminal success/failure replay without rereads, caught/uncaught/replacement reentry invalidation, independent instances, exact error provenance and foreign containment, plain-record branding before discriminant observation, category/field/population observation and ordering, sharing/paths/optional placement, raw-schema composition, completed-root validation before deferred fidelity, primitive RegExp scalar ownership without coercion, freezing/mutation isolation, iterative depth refusal, atomic settlement while every terminal-path intrinsic is redirected, symmetric terminal working-state release with a real three-reference collection control, and the frozen owned copy of a `default` with its non-JSON, present-`undefined`, accessor, and inherited refusals.
|
|
1459
|
+
- [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — builders and `Infer`/`InferMutable`, with explicit `BUILDER_CASES` option positions and public keys driving real plain/frozen/null-prototype and untrusted get/has/descriptor/own-key/revoked controls. It also covers caller/post-clone raw-schema populations and diagnostic precedence, genuine foreign-pattern ownership and flag policy, inverse schema construction, inference depth/breadth behavior, and the `optionalShape` `default` option, without reading or parsing project source.
|
|
1460
|
+
- [`tests/src/core/ShapeValidator.test.ts`](../tests/src/core/ShapeValidator.test.ts) — direct public validator behavior: inert construction, repeatable live passes and reentry invalidation, precedence, depth/cycle handling, dense populations, raw-schema keywords, the present-`undefined` rule — an own raw-population member holding `undefined` is a present declaration rather than an absent one, so it is validated — flagged-pattern observation/order/repair, default placement over every route to a shared node, and the raw `default` keyword.
|
|
1461
|
+
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — primitive, non-negative numeric, structural, bounded-JSON, and JSON/record/RegExp guards; genuine `node:vm` record/RegExp values; depth-versus-validity and sequential-observation controls; zero-read duck/tag/accessor/proxy/revoked opposites; untrusted-value totality; and parser/guard soundness corpora.
|
|
1358
1462
|
|
|
1359
1463
|
## See also
|
|
1360
1464
|
|