@orkestrel/contract 0.0.5 → 0.0.7

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.
@@ -1,8 +1,3565 @@
1
- export type * from './types.js';
2
- export * from './constants.js';
3
- export * from './helpers.js';
4
- export * from './combinators.js';
5
- export * from './compilers.js';
6
- export * from './parsers.js';
7
- export * from './shapers.js';
8
- export * from './validators.js';
1
+ /**
2
+ * Combine two guards with logical AND — passes only when both pass.
3
+ *
4
+ * @remarks
5
+ * Use {@link whereOf} when the right side refines an already-narrowed type; use
6
+ * `andOf` to combine two independent guards.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const isShortString = andOf(isString, isNonEmptyString)
11
+ * ```
12
+ */
13
+ export declare function andOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A & B>;
14
+
15
+ export declare function andOf<T, U extends T>(left: Guard<T>, right: (value: T) => value is U): Guard<U>;
16
+
17
+ export declare function andOf<T>(left: Guard<T>, right: (value: T) => boolean): Guard<T>;
18
+
19
+ export declare function andOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
20
+
21
+ /** An async function accepting any arguments and returning a `Promise`. */
22
+ export declare type AnyAsyncFunction = (...args: unknown[]) => Promise<unknown>;
23
+
24
+ /**
25
+ * Any constructor signature that produces instances of `T`.
26
+ *
27
+ * @remarks
28
+ * Uses `unknown[]` parameters to stay maximally assignable from specific
29
+ * constructors without resorting to `any`.
30
+ */
31
+ export declare type AnyConstructor<T = unknown> = new (...args: unknown[]) => T;
32
+
33
+ /** A function accepting any arguments and returning `unknown`. */
34
+ export declare type AnyFunction = (...args: unknown[]) => unknown;
35
+
36
+ /**
37
+ * Build a guard that accepts arrays whose every element satisfies `elementGuard`.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const isStringArray = arrayOf(isString)
42
+ * isStringArray(['a', 'b']) // true
43
+ * isStringArray(['a', 1]) // false
44
+ * ```
45
+ */
46
+ export declare function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>;
47
+
48
+ export declare function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>;
49
+
50
+ /** An array shape with an element shape and optional length bounds. */
51
+ export declare interface ArrayShape<S extends ContractShape = ContractShape> {
52
+ readonly type: 'array';
53
+ readonly items: S;
54
+ readonly min?: number;
55
+ readonly max?: number;
56
+ readonly description?: string;
57
+ }
58
+
59
+ /**
60
+ * Build an {@link ArrayShape} from an element shape.
61
+ *
62
+ * @param items - The element shape
63
+ * @param options - Optional length bounds and `description`
64
+ * @returns An array shape
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const tags = arrayShape(stringShape(), { max: 10 })
69
+ * ```
70
+ */
71
+ export declare function arrayShape<S extends ContractShape>(items: S, options?: ArrayShapeOptions): ArrayShape<S>;
72
+
73
+ /** Options for {@link ArrayShape} (via `arrayShape`). */
74
+ export declare interface ArrayShapeOptions {
75
+ readonly min?: number;
76
+ readonly max?: number;
77
+ readonly description?: string;
78
+ }
79
+
80
+ /**
81
+ * Invoke a callback and capture its outcome as a {@link Result}, never letting
82
+ * a throw escape.
83
+ *
84
+ * @remarks
85
+ * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
86
+ * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
87
+ * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
88
+ * `boolean`. This converts a throwing callback into a `Failure` so the
89
+ * surrounding guard can treat it as a non-match instead of propagating the
90
+ * exception, written once and shared rather than copy-pasted as ad-hoc
91
+ * `try`/`catch`.
92
+ *
93
+ * @param callback - The callback to invoke with no arguments
94
+ * @returns A `Success` carrying the return value, or a `Failure` carrying the
95
+ * thrown reason normalised to an `Error`
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const outcome = attempt(() => predicate(value))
100
+ * return outcome.success && outcome.value
101
+ * ```
102
+ */
103
+ export declare function attempt<T>(callback: () => T): Result<T>;
104
+
105
+ /** A boolean shape — accepts only `true` or `false`. */
106
+ export declare interface BooleanShape {
107
+ readonly type: 'boolean';
108
+ readonly description?: string;
109
+ }
110
+
111
+ /**
112
+ * Build a {@link BooleanShape}.
113
+ *
114
+ * @param options - Optional `description`
115
+ * @returns A boolean shape
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * const active = booleanShape({ description: 'Whether the record is active' })
120
+ * ```
121
+ */
122
+ export declare function booleanShape(options?: BooleanShapeOptions): BooleanShape;
123
+
124
+ /** Options for {@link BooleanShape} (via `booleanShape`). */
125
+ export declare interface BooleanShapeOptions {
126
+ readonly description?: string;
127
+ }
128
+
129
+ /**
130
+ * Build a guard that accepts finite numbers within an inclusive `[min, max]`
131
+ * range.
132
+ *
133
+ * @remarks
134
+ * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /
135
+ * `±Infinity` are rejected before any comparison runs. An absent bound never
136
+ * constrains that side. Reused for a number's own value AND, applied to a
137
+ * `.length`, for string and array length refinements — the single source of the
138
+ * bound logic shared by the compiled guard and parser (compilers.ts).
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const inRange = boundsOf(1, 5)
143
+ * inRange(3) // true
144
+ * inRange(0) // false — below min
145
+ * inRange(6) // false — above max
146
+ *
147
+ * const atLeastTwo = boundsOf(2)
148
+ * atLeastTwo(2) // true — unbounded above
149
+ * ```
150
+ */
151
+ export declare function boundsOf(min?: number, max?: number): Guard<number>;
152
+
153
+ /**
154
+ * Build an {@link ObjectShape} from a JSON Schema object node's `properties` /
155
+ * `required` / `additionalProperties` keywords — the object-specialized branch
156
+ * of {@link buildShapeFromNode}.
157
+ *
158
+ * @remarks
159
+ * `properties` (when a record) contributes one child shape per own key, capped
160
+ * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
161
+ * unless it appears as a string entry of `required`. A property whose value is
162
+ * not itself a record widens to {@link jsonShape}. `additionalProperties`:
163
+ * `false` closes the object; a record value recurses into it (`objectShape`
164
+ * validates extras against that shape); anything else — `true`, absent, or
165
+ * malformed — leaves the object OPEN (`true`), matching JSON Schema's own
166
+ * absent-means-open default and the fact that {@link valueToSchema} /
167
+ * {@link samplesToSchema} always emit the keyword explicitly, so an absent
168
+ * value only arises from a hand-written schema. When `properties` has MORE
169
+ * keys than {@link INFER_BREADTH_LIMIT}, the schema's own
170
+ * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
171
+ * a dropped key's value could otherwise fail a `false` or record-valued rest
172
+ * shape it was never checked against — mirroring `inferObject`'s
173
+ * `truncated ? true : !closed` rule (inferers.ts:485). The accumulator uses a
174
+ * null-prototype record so a property literally named `__proto__` becomes an
175
+ * own data key rather than mutating the prototype, mirroring
176
+ * {@link inferObject} (inferers.ts).
177
+ *
178
+ * @param schema - The object schema node
179
+ * @param depth - Remaining descent budget passed to child properties
180
+ * @param visited - The ancestor set guarding against cycles — recursion
181
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
182
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
183
+ * supported usage
184
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
185
+ * recursion state owned by the {@link schemaToShape} entry point; passing
186
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
187
+ * supported usage
188
+ * @param description - The node's already-extracted `description`, if any
189
+ * @returns The built object shape
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * buildObjectShape(
194
+ * { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
195
+ * INFER_DEPTH_LIMIT,
196
+ * new WeakSet(),
197
+ * new WeakMap(),
198
+ * undefined,
199
+ * )
200
+ * // objectShape({ id: integerShape() }, { additionalProperties: true })
201
+ * ```
202
+ */
203
+ export declare function buildObjectShape(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>, description: string | undefined): ContractShape;
204
+
205
+ /**
206
+ * Build a {@link ContractShape} for one JSON Schema node — the recursive
207
+ * spine of {@link schemaToShape}, shared with per-child recursion via
208
+ * {@link schemaNodeToShape}.
209
+ *
210
+ * @remarks
211
+ * Every keyword is read defensively (the node's static `JSONSchema` type is
212
+ * NOT trusted at runtime — a caller-supplied node may be adversarial), so a
213
+ * malformed keyword falls through to the next rule instead of throwing.
214
+ * Precedence, top-down:
215
+ *
216
+ * 1. `enum` — an array with at least one string/number/boolean entry (finite
217
+ * numbers only) becomes a {@link literalShape} over the filtered entries.
218
+ * Non-primitive / non-finite entries are dropped; an empty result falls
219
+ * through.
220
+ * 2. `oneOf` — an array with at least one record entry becomes an
221
+ * {@link oneOfShape} over the recursively-built variants, provided the
222
+ * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
223
+ * limit, building a subset union would be strictly narrower than the
224
+ * schema's full union (a value matching only a dropped variant would be
225
+ * wrongly rejected), so the whole node widens to {@link jsonShape} instead
226
+ * of sampling a subset.
227
+ * 3. `anyOf` — identically, via {@link unionShape}.
228
+ * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
229
+ * the matching primitive shape, with length/range bounds derived via
230
+ * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node
231
+ * additionally drops its bounds when they describe an EMPTY integer range
232
+ * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
233
+ * rejects — so the result is always a valid shape.
234
+ * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
235
+ * a record-valued `items` (widening to {@link jsonShape} otherwise), with
236
+ * bounds from `minItems` / `maxItems`.
237
+ * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
238
+ * record-valued `properties` — delegates to {@link buildObjectShape}.
239
+ * 7. Everything else — an empty schema, an unrecognized/absent `type`,
240
+ * exhausted depth/breadth, or an attempt failure — widens to
241
+ * {@link jsonShape} (the exact inverse of `compileSchema(jsonShape())`,
242
+ * and where the inferers themselves bottom out at their own limits).
243
+ *
244
+ * `format` and `pattern` are NEVER read into the compiled shape — `format` is
245
+ * annotation-only and `pattern` compiling an attacker-supplied string into a
246
+ * `RegExp` is a ReDoS vector. `description`, when a string, carries through to
247
+ * the produced shape's `description` option.
248
+ *
249
+ * @param schema - The schema node to convert
250
+ * @param depth - Remaining descent budget (0 halts recursion with `jsonShape()`)
251
+ * @param visited - The ancestor set guarding against cycles — recursion
252
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
253
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
254
+ * supported usage
255
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache
256
+ * guarding against exponential re-conversion of a
257
+ * shared-reference schema DAG — recursion state owned by the
258
+ * {@link schemaToShape} entry point; passing a shared or
259
+ * pre-populated `WeakMap` changes caching behavior and is not
260
+ * supported usage
261
+ * @returns The built shape for `schema`
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
266
+ * // stringShape({ min: 1 })
267
+ * ```
268
+ */
269
+ export declare function buildShapeFromNode(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>): ContractShape;
270
+
271
+ /**
272
+ * Render a value as a deterministic, key-sorted JSON string.
273
+ *
274
+ * @remarks
275
+ * The stable-stringify backing {@link unifySchemas}'s de-duplication and
276
+ * ordering: unlike `JSON.stringify`, object keys are sorted before encoding
277
+ * (recursively, at every nesting level), so two structurally-equal
278
+ * `JSONSchema` fragments built independently always canonicalize to the same
279
+ * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.
280
+ *
281
+ * @param value - The value to canonicalize (a `JSONSchema` fragment, or any
282
+ * nested piece of one)
283
+ * @returns A deterministic string encoding of `value`
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * canonicalStringify({ type: 'object', properties: {} }) ===
288
+ * canonicalStringify({ properties: {}, type: 'object' }) // true
289
+ * ```
290
+ */
291
+ export declare function canonicalStringify(value: unknown): string;
292
+
293
+ /**
294
+ * Compile a {@link ContractShape} into a deterministic seed value.
295
+ *
296
+ * @remarks
297
+ * The same shape and the same `random` source always produce the same value, so
298
+ * seed data is reproducible. Defaults to a {@link seededRandom} source seeded
299
+ * from the wall clock when none is supplied. Throws on a degenerate empty
300
+ * `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose
301
+ * generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded
302
+ * schema is arbitrary and cannot be auto-generated) — a programmer error that
303
+ * cannot generate a value (AGENTS §12). `createContract` runs
304
+ * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /
305
+ * bounded shape is normally caught there; these throws remain here as defense
306
+ * for standalone `compileGenerator` use.
307
+ *
308
+ * @param shape - The shape to generate from
309
+ * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)
310
+ * @returns A value matching the shape
311
+ *
312
+ * @example
313
+ * ```ts
314
+ * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)
315
+ * ```
316
+ */
317
+ export declare function compileGenerator<S extends ContractShape>(shape: S, random?: RandomFunction): Infer<S>;
318
+
319
+ export declare function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown;
320
+
321
+ /**
322
+ * Compile a {@link ContractShape} into a runtime type guard.
323
+ *
324
+ * @remarks
325
+ * Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,
326
+ * `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,
327
+ * and `whereOf` for constraint refinement. Like every guard it is total — it
328
+ * never throws (AGENTS §14).
329
+ *
330
+ * @param shape - The shape to compile
331
+ * @returns A guard narrowing to the shape's inferred type
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * const isUser = compileGuard(objectShape({ name: stringShape() }))
336
+ * isUser({ name: 'Ada' }) // true
337
+ * ```
338
+ */
339
+ export declare function compileGuard<S extends ContractShape>(shape: S): Guard<Infer<S>>;
340
+
341
+ export declare function compileGuard(shape: ContractShape): Guard<unknown>;
342
+
343
+ /**
344
+ * Compile a {@link ContractShape} into an input parser.
345
+ *
346
+ * @remarks
347
+ * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /
348
+ * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a
349
+ * whole on any required-field failure; a union returns a guard-valid value
350
+ * unchanged, otherwise the first variant that both parses and guards wins.
351
+ *
352
+ * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same
353
+ * combinators `compileGuard` uses — `stringOf` for a string's length/pattern and
354
+ * `boundsOf` for a number's value and an array's length — so a value that coerces
355
+ * but violates a bound parses to `undefined`. The result is full parse↔guard
356
+ * soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's
357
+ * `is`, refinements included.
358
+ *
359
+ * @param shape - The shape to compile
360
+ * @returns A parser yielding the shape's inferred type or `undefined`
361
+ *
362
+ * @example
363
+ * ```ts
364
+ * const parseUser = compileParser(objectShape({ name: stringShape() }))
365
+ * parseUser({ name: 'Ada' }) // { name: 'Ada' }
366
+ * ```
367
+ */
368
+ export declare function compileParser<S extends ContractShape>(shape: S): Parser<Infer<S>>;
369
+
370
+ export declare function compileParser(shape: ContractShape): Parser<unknown>;
371
+
372
+ /**
373
+ * Compile a {@link ContractShape} into a structured fault report for a value —
374
+ * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.
375
+ *
376
+ * @remarks
377
+ * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards
378
+ * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /
379
+ * `isJSONValue` / …), so the soundness invariant
380
+ * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`
381
+ * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a
382
+ * coercible value like `'42'` against a `numberShape` reports no fault, the
383
+ * same leniency `parse` grants, even though the strict guard would reject it).
384
+ *
385
+ * Faults are collected in stable pre-order (declared key/index order); every
386
+ * call — object, array, and union alike, including a union's `oneOf` "no
387
+ * match" / "no consensus" summary fault prepended to its closest variant's
388
+ * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the
389
+ * bound holds at every level of nesting, not just the outermost container, on
390
+ * adversarial input (a huge array, a wide record, a wide union of wide
391
+ * records). A closed object's extra keys never
392
+ * fault — `parse` silently drops them, so `explain` mirrors that leniency; an
393
+ * open object with a constraining `additionalProperties` shape recurses extras
394
+ * against it instead. A hostile getter or throwing `Proxy` trap is contained
395
+ * via {@link attempt} and surfaces as a single top-level type fault, never a
396
+ * throw (AGENTS §14).
397
+ *
398
+ * @param shape - The shape to report against
399
+ * @param value - The value to check
400
+ * @param path - The path prefix for faults produced at this call (defaults to the root)
401
+ * @returns The faults found, empty when the value parses successfully
402
+ *
403
+ * @example
404
+ * ```ts
405
+ * const user = objectShape({ name: stringShape({ min: 1 }) })
406
+ * compileReporter(user, { name: '' })
407
+ * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '""' }]
408
+ * compileReporter(user, { name: 'Ada' }) // []
409
+ * ```
410
+ */
411
+ export declare function compileReporter(shape: ContractShape, value: unknown, path?: string[]): readonly Fault[];
412
+
413
+ /**
414
+ * Compile a {@link ContractShape} into a JSON Schema document.
415
+ *
416
+ * @remarks
417
+ * Object shapes emit `additionalProperties: false` (unless opened) and list only
418
+ * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
419
+ * 'null' }`. Emission only — it never inspects a runtime value.
420
+ *
421
+ * @param shape - The shape to compile
422
+ * @returns The emitted JSON Schema
423
+ *
424
+ * @example
425
+ * ```ts
426
+ * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }
427
+ * ```
428
+ */
429
+ export declare function compileSchema(shape: ContractShape): JSONSchema;
430
+
431
+ /**
432
+ * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass
433
+ * `base` but not `excluded`.
434
+ *
435
+ * @example
436
+ * ```ts
437
+ * const isNonEmpty = complementOf(isString, isEmptyString)
438
+ * isNonEmpty('hi') // true
439
+ * isNonEmpty('') // false
440
+ * ```
441
+ */
442
+ export declare function complementOf<TBase, TExcluded extends TBase>(base: Guard<TBase>, excluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded)): Guard<Exclude<TBase, TExcluded>>;
443
+
444
+ /**
445
+ * A compiled contract — the four lockstep outputs derived from one shape.
446
+ *
447
+ * @remarks
448
+ * Built by `createContract`: `is` narrows, `parse` coerces (returning the typed
449
+ * value or `undefined`), `schema` is the emitted JSON Schema, and `generate`
450
+ * produces deterministic seed data from a {@link RandomFunction} (defaulting to
451
+ * a wall-clock-seeded source when none is supplied).
452
+ */
453
+ export declare interface ContractInterface<T> {
454
+ readonly schema: JSONSchema;
455
+ readonly is: Guard<T>;
456
+ parse(value: unknown): T | undefined;
457
+ /**
458
+ * Report every structured parse fault a value has against this contract.
459
+ *
460
+ * @remarks
461
+ * An empty report means the value is valid. Soundness invariant:
462
+ * `explain(v).length === 0` if and only if `parse(v) !== undefined` — explain
463
+ * mirrors `parse`'s coercion, not the stricter `is`. Faults are listed in
464
+ * stable pre-order (declared key/index order).
465
+ *
466
+ * @param value - The value to check
467
+ * @returns The faults found, empty when the value parses successfully
468
+ */
469
+ explain(value: unknown): readonly Fault[];
470
+ generate(random?: RandomFunction): T;
471
+ }
472
+
473
+ /**
474
+ * A contract shape — a declarative description of a value, built with the shape
475
+ * builders and compiled into a guard, a parser, a JSON Schema, and a generator.
476
+ *
477
+ * @remarks
478
+ * A discriminated union keyed on `type`. Shapes nest (an `ArrayShape` holds an
479
+ * element shape, an `ObjectShape` a map of them), so a contract is a finite,
480
+ * developer-authored tree — never cyclic.
481
+ */
482
+ export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape;
483
+
484
+ /**
485
+ * Compile a {@link ContractShape} into a {@link ContractInterface} — the four
486
+ * lockstep outputs from one declaration.
487
+ *
488
+ * @remarks
489
+ * Runs {@link validateShape} first — a malformed shape throws immediately
490
+ * rather than compiling into a silently-wrong contract (AGENTS §12). Then
491
+ * precompiles the schema, guard, and parser once; `generate` walks the shape
492
+ * per call with the supplied random source, and `explain` compiles the
493
+ * diagnostic report via {@link compileReporter} at zero added compile-time cost
494
+ * (it re-walks the shape per call, exactly like `generate`).
495
+ *
496
+ * @param shape - The shape to compile
497
+ * @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * const user = createContract(objectShape({ name: stringShape(), age: integerShape() }))
502
+ * user.is({ name: 'Ada', age: 36 }) // true
503
+ * user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 }
504
+ * user.schema // { type: 'object', properties: { … }, … }
505
+ * ```
506
+ */
507
+ export declare function createContract<S extends ContractShape>(shape: S): ContractInterface<Infer<S>>;
508
+
509
+ export declare function createContract(shape: ContractShape): ContractInterface<unknown>;
510
+
511
+ /**
512
+ * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
513
+ * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
514
+ *
515
+ * @remarks
516
+ * Total and pure. Either keyword is used only when it is a non-negative
517
+ * integer (`isInteger` + `>= 0`); a malformed value (a string, a negative
518
+ * number, `NaN`, `Infinity`, a fraction) is dropped as if absent. When both
519
+ * bounds are present and `min` exceeds `max`, the PAIR is dropped entirely
520
+ * (an unbounded shape is always a legal widening of a contradictory schema).
521
+ *
522
+ * @param min - The raw `minLength` / `minItems` keyword value
523
+ * @param max - The raw `maxLength` / `maxItems` keyword value
524
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
525
+ *
526
+ * @example
527
+ * ```ts
528
+ * deriveLengthBounds(1, 10) // { min: 1, max: 10 }
529
+ * deriveLengthBounds(10, 1) // {} — contradictory, dropped
530
+ * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped
531
+ * ```
532
+ */
533
+ export declare function deriveLengthBounds(min: unknown, max: unknown): {
534
+ readonly min?: number;
535
+ readonly max?: number;
536
+ };
537
+
538
+ /**
539
+ * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema
540
+ * range keywords (`minimum`/`maximum`).
541
+ *
542
+ * @remarks
543
+ * Total and pure. Either keyword is used only when it is a finite number
544
+ * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when
545
+ * both bounds are present and `min` exceeds `max`, the PAIR is dropped
546
+ * entirely, the same contradiction rule {@link deriveLengthBounds} applies.
547
+ *
548
+ * @param min - The raw `minimum` keyword value
549
+ * @param max - The raw `maximum` keyword value
550
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * deriveRangeBounds(0, 120) // { min: 0, max: 120 }
555
+ * deriveRangeBounds(5, 1) // {} — contradictory, dropped
556
+ * ```
557
+ */
558
+ export declare function deriveRangeBounds(min: unknown, max: unknown): {
559
+ readonly min?: number;
560
+ readonly max?: number;
561
+ };
562
+
563
+ /**
564
+ * Count the enumerable own-symbol keys on a value.
565
+ *
566
+ * @remarks
567
+ * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose
568
+ * descriptor is `enumerable` are counted. Backs the object-emptiness guards
569
+ * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an
570
+ * enumerable symbol is not mistaken for empty.
571
+ *
572
+ * @param value - The object to inspect
573
+ * @returns The number of enumerable own-symbol keys
574
+ *
575
+ * @example
576
+ * ```ts
577
+ * const flag = Symbol('flag')
578
+ * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1
579
+ * enumerableSymbolCount({}) // 0
580
+ * ```
581
+ */
582
+ export declare function enumerableSymbolCount(value: object): number;
583
+
584
+ /**
585
+ * Build a guard from a native `enum` or any object whose values are strings or
586
+ * numbers.
587
+ *
588
+ * @example
589
+ * ```ts
590
+ * enum Direction { Up = 'up', Down = 'down' }
591
+ * const isDirection = enumOf(Direction)
592
+ * isDirection('up') // true
593
+ * isDirection('left') // false
594
+ * ```
595
+ */
596
+ export declare function enumOf<const E extends Record<string, string | number>>(enumeration: E): Guard<E[keyof E]>;
597
+
598
+ /**
599
+ * Discriminated failure branch of a {@link Result}.
600
+ *
601
+ * @remarks
602
+ * Carries the error value when an operation does not succeed.
603
+ */
604
+ export declare interface Failure<E> {
605
+ readonly success: false;
606
+ readonly error: E;
607
+ }
608
+
609
+ /**
610
+ * A single structured parse-failure diagnostic — one entry of an
611
+ * {@link ContractInterface.explain} report.
612
+ *
613
+ * @remarks
614
+ * A discriminated union on `reason`:
615
+ * - `'type'` — the value could not coerce to `expected` at all.
616
+ * - `'missing'` — a required object property was absent.
617
+ * - `'constraint'` — the value coerced to `expected` but violated one
618
+ * refinement (`min` / `max` / `pattern` / `integer`); `limit` carries the
619
+ * violated bound/pattern when applicable.
620
+ * - `'variant'` — an `anyOf`-mode union matched no variant; `variants` is the
621
+ * variant count, followed (in the report) by the closest variant's own faults.
622
+ * - `'oneOf'` — a `oneOf`-mode union matched zero or two-or-more variants;
623
+ * `matched` is the raw match count.
624
+ */
625
+ export declare type Fault = {
626
+ readonly reason: 'type';
627
+ readonly path: FieldPath;
628
+ readonly expected: FaultKind;
629
+ readonly received: string;
630
+ } | {
631
+ readonly reason: 'missing';
632
+ readonly path: FieldPath;
633
+ readonly expected: FaultKind;
634
+ } | {
635
+ readonly reason: 'constraint';
636
+ readonly path: FieldPath;
637
+ readonly expected: FaultKind;
638
+ readonly constraint: FaultConstraint;
639
+ readonly limit?: number | string;
640
+ readonly received: string;
641
+ } | {
642
+ readonly reason: 'variant';
643
+ readonly path: FieldPath;
644
+ readonly variants: number;
645
+ } | {
646
+ readonly reason: 'oneOf';
647
+ readonly path: FieldPath;
648
+ readonly matched: number;
649
+ };
650
+
651
+ /**
652
+ * The maximum number of {@link Fault} entries a single `explain` report ever
653
+ * returns, frozen.
654
+ *
655
+ * @remarks
656
+ * Bounds the report against adversarial input (a giant array, a wide record) —
657
+ * `compileReporter` collects faults in stable pre-order and stops once this cap
658
+ * is reached, so the report size (and the work to build it) stays finite and
659
+ * deterministic regardless of the input's size.
660
+ */
661
+ export declare const FAULT_LIMIT = 64;
662
+
663
+ /** The refinement a {@link Fault} of reason `'constraint'` violates. */
664
+ export declare type FaultConstraint = 'min' | 'max' | 'pattern' | 'integer';
665
+
666
+ /** The kind of value a {@link Fault} expected — the shape-projected counterpart of a `ContractShape`'s `type`. */
667
+ export declare type FaultKind = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'literal' | 'array' | 'object' | 'union' | 'json';
668
+
669
+ /**
670
+ * A field path into a record: a single key, or an ordered list of keys to
671
+ * descend through nested objects.
672
+ *
673
+ * @remarks
674
+ * A single `string` is ONE key — it is never split on `.`, so keys that contain
675
+ * dots stay safe. Use a `readonly string[]` to descend into nested objects.
676
+ */
677
+ export declare type FieldPath = string | readonly string[];
678
+
679
+ /**
680
+ * The maximum string length {@link stringToFormat} attempts to classify,
681
+ * frozen.
682
+ *
683
+ * @remarks
684
+ * Bounds per-string format-detection work: a value longer than this returns
685
+ * `undefined` immediately, before any pattern match runs. 128 sits
686
+ * comfortably above the longest real format token — an RFC 3339 date-time
687
+ * with fractional seconds and a UTC offset — so no legitimate classification
688
+ * changes; only pathologically long strings (a multi-megabyte payload passed
689
+ * as a candidate email/URI) are skipped.
690
+ */
691
+ export declare const FORMAT_MAX_LENGTH = 128;
692
+
693
+ /**
694
+ * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats
695
+ * (`uuid` / `email` / `uri`), frozen as data.
696
+ *
697
+ * @remarks
698
+ * The ISO-8601 date/time formats are NOT listed here — they additionally
699
+ * require an attempt-guarded `Date` validity check, so their pattern lives
700
+ * inline in `stringToFormat` rather than as reusable standalone data.
701
+ */
702
+ export declare const FORMAT_PATTERNS: Readonly<Record<'uuid' | 'email' | 'uri', RegExp>>;
703
+
704
+ /** Resolve a {@link GuardsShape} to a readonly object type of its guarded property types. */
705
+ export declare type FromGuards<G extends GuardsShape> = Readonly<{
706
+ [K in keyof G]: GuardType<G[K]>;
707
+ }>;
708
+
709
+ /** A runtime type guard: returns `true` when `value` satisfies `T` and narrows it. */
710
+ export declare type Guard<T> = (value: unknown) => value is T;
711
+
712
+ /**
713
+ * A mapping of string keys to guards.
714
+ *
715
+ * @remarks
716
+ * The shape parameter for the `recordOf`, `pickOf`, and `omitOf` combinators.
717
+ */
718
+ export declare type GuardsShape = Readonly<Record<string, Guard<unknown>>>;
719
+
720
+ /** Extract the guarded type `T` from a `Guard<T>`. */
721
+ export declare type GuardType<G> = G extends Guard<infer T> ? T : never;
722
+
723
+ /**
724
+ * Infer the static TypeScript type a {@link ContractShape} describes.
725
+ *
726
+ * @remarks
727
+ * Structural and recursive: optional object fields surface as optional
728
+ * properties, nullable wrappers add `| null`, and a literal tuple becomes a
729
+ * string/number/boolean-literal union.
730
+ *
731
+ * The first, non-distributive branch bails out to `unknown` when `S` is the
732
+ * full widened {@link ContractShape} union. Five members of that union recurse
733
+ * back into the whole union through their defaulted generics, so inferring the
734
+ * full union is a fixed point that can never shrink — the compiler would fan
735
+ * out until it aborts with TS2589. Bailing out lazily short-circuits that
736
+ * fixed point (the untaken branch is never instantiated) while every narrow
737
+ * shape and every partial union still flows through the exact chain below.
738
+ *
739
+ * The `ObjectShape` branch's `additionalProperties` guard (`[A] extends
740
+ * [boolean | ContractShape]`) is likewise wrapped in a tuple to stay
741
+ * non-distributive: a naked `A extends boolean | ContractShape` distributes
742
+ * over a union `A`, fanning a wide `additionalProperties` type into one
743
+ * {@link InferObject} instantiation per union member instead of one
744
+ * instantiation over the whole union — the same TS2589 risk under repeated
745
+ * nesting. {@link InferIndex} and {@link InferOpenIndex} apply the identical
746
+ * tuple guard to their own `A` parameter for the same reason.
747
+ */
748
+ export declare type Infer<S extends ContractShape> = [ContractShape] extends [S] ? unknown : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends {
749
+ readonly type: 'literal';
750
+ readonly values: infer V;
751
+ } ? V extends readonly (infer L)[] ? L : never : S extends {
752
+ readonly type: 'array';
753
+ readonly items: infer I;
754
+ } ? I extends ContractShape ? readonly 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 {
755
+ readonly type: 'union';
756
+ readonly variants: infer V;
757
+ } ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends {
758
+ readonly type: 'optional';
759
+ readonly inner: infer I;
760
+ } ? I extends ContractShape ? Infer<I> | undefined : never : S extends {
761
+ readonly type: 'nullable';
762
+ readonly inner: infer I;
763
+ } ? I extends ContractShape ? Infer<I> | null : never : S extends JSONShape ? JSONValue : unknown;
764
+
765
+ /**
766
+ * The default maximum number of object properties / array elements
767
+ * {@link valueToSchema} samples per container, frozen.
768
+ *
769
+ * @remarks
770
+ * Bounds the work (and the emitted schema's size) against a wide record or a
771
+ * huge array — properties/elements beyond this cap are never inspected.
772
+ * Overridable per call via {@link ValueToSchemaOptions.maxProperties}.
773
+ */
774
+ export declare const INFER_BREADTH_LIMIT = 256;
775
+
776
+ /**
777
+ * The default maximum object/array nesting depth {@link valueToSchema} walks,
778
+ * frozen.
779
+ *
780
+ * @remarks
781
+ * Bounds inference against adversarial or cyclic runtime input — once the
782
+ * remaining depth budget reaches zero, inference stops descending and emits
783
+ * the empty accept-anything schema `{}` for that branch instead of recursing
784
+ * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.
785
+ */
786
+ export declare const INFER_DEPTH_LIMIT = 32;
787
+
788
+ /**
789
+ * The default maximum number of distinct values a multi-sample slot may hold
790
+ * before enum inference gives up and falls back to a bare `type`, frozen.
791
+ *
792
+ * @remarks
793
+ * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}
794
+ * will emit — a slot with distinct-value count at or above this limit is
795
+ * treated as unbounded (an ID column, not a category) and never gets an
796
+ * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}
797
+ * (which gates whether enum inference runs at all).
798
+ */
799
+ export declare const INFER_ENUM_LIMIT = 12;
800
+
801
+ /**
802
+ * Infer a `JSONSchema` array fragment from an array's sampled elements.
803
+ *
804
+ * @remarks
805
+ * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the
806
+ * first `breadth` elements are classified via {@link inferValue} (one less
807
+ * depth) and unified with {@link unifySchemas}: a single distinct element
808
+ * schema becomes `items` directly; multiple distinct schemas become
809
+ * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of
810
+ * `value` both yield the empty schema `{}` instead of descending. A sparse
811
+ * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before
812
+ * sampling so every slot — including a hole — is visited as an explicit
813
+ * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left
814
+ * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.
815
+ *
816
+ * ALL reads of `value` — including its `length` — happen inside
817
+ * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose
818
+ * `get` trap throws) is exactly as contained as a throwing own-getter element
819
+ * or a Proxy-over-array element access, and cannot escape as a thrown error.
820
+ * On failure — or when the sampled/classified list ends up empty — this
821
+ * returns `{ type: 'array' }` (no `items`), since `value` is still known to
822
+ * be an array, mirroring the empty-array emission. A same-object
823
+ * re-inference at the same remaining `depth` is served from `memo` instead
824
+ * of recomputing (guards a shared-reference DAG against exponential blowup).
825
+ *
826
+ * @param value - The array to infer from
827
+ * @param depth - Remaining descent budget
828
+ * @param breadth - The maximum number of elements sampled
829
+ * @param closed - Threaded through to nested object elements
830
+ * @param format - Threaded through to nested string/`Date` elements
831
+ * @param visited - The ancestor set guarding against cycles
832
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
833
+ * against exponential re-inference of a shared-reference DAG
834
+ * @returns The inferred array schema
835
+ *
836
+ * @example
837
+ * ```ts
838
+ * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())
839
+ * // { type: 'array', items: { type: 'number' } }
840
+ * ```
841
+ */
842
+ export declare function inferArray(value: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet<object>, memo: WeakMap<object, Map<number, JSONSchema>>): JSONSchema;
843
+
844
+ /**
845
+ * The index-signature contribution of a pure record shape's `additionalProperties`
846
+ * — the `recordShape` case, where `properties` is empty.
847
+ *
848
+ * @remarks
849
+ * `false` (closed) contributes `unknown`, which collapses away in an
850
+ * intersection — a closed object's {@link Infer} is unaffected. `true` (open,
851
+ * unconstrained) contributes an `unknown`-valued index signature. A
852
+ * {@link ContractShape} (open, constrained) contributes an index signature
853
+ * typed to that shape's own `Infer` — sound here because there are no fixed
854
+ * properties for the index to collide with.
855
+ *
856
+ * @remarks
857
+ * The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay
858
+ * non-distributive, matching {@link Infer}'s own object-branch guard — see
859
+ * that type's remarks for why a naked `extends` here would fan a wide `A`
860
+ * into a union of `InferIndex` instantiations instead of one.
861
+ */
862
+ export declare type InferIndex<A extends boolean | ContractShape> = [A] extends [false] ? unknown : [A] extends [true] ? {
863
+ readonly [k: string]: unknown;
864
+ } : [A] extends [ContractShape] ? {
865
+ readonly [k: string]: Infer<A>;
866
+ } : unknown;
867
+
868
+ /** {@link Infer} with its TOP-LEVEL `readonly` modifiers stripped (a shallow strip — nested object/array properties stay readonly) — for consumers writing the parsed value's own fields. */
869
+ export declare type InferMutable<S extends ContractShape> = {
870
+ -readonly [K in keyof Infer<S>]: Infer<S>[K];
871
+ };
872
+
873
+ /**
874
+ * {@link Infer} of an object shape's `properties` — the required keys, plus the
875
+ * `optional`-wrapped keys as optional members, plus the index-signature
876
+ * contribution of `additionalProperties` (see {@link InferIndex}).
877
+ *
878
+ * @remarks
879
+ * The `[keyof P] extends [never]` split is hoisted to the front (rather than
880
+ * folded into the intersection's second operand) so a pure record shape
881
+ * (`P` empty) short-circuits straight to {@link InferIndex} without ever
882
+ * building the `Readonly<{} & {}>` intersection shell — the clean
883
+ * `Readonly<Record<string, V>>` {@link InferIndex} already returns. A closed
884
+ * empty object (`P` empty, `A` `false`/absent) still resolves through
885
+ * {@link InferIndex}'s own `[A] extends [false]` branch to
886
+ * `Readonly<Record<never, never>>`, preserving the empty-closed-object result.
887
+ * A shape with fixed properties always routes through {@link InferOpenIndex}.
888
+ */
889
+ export declare type InferObject<P extends Readonly<Record<string, ContractShape>>, A extends boolean | ContractShape = false> = [keyof P] extends [never] ? [A] extends [false] ? Readonly<Record<never, never>> : InferIndex<A> : Readonly<{
890
+ [K in keyof P as P[K] extends {
891
+ readonly type: 'optional';
892
+ } ? never : K]: Infer<P[K]>;
893
+ } & {
894
+ [K in keyof P as P[K] extends {
895
+ readonly type: 'optional';
896
+ } ? K : never]?: P[K] extends {
897
+ readonly type: 'optional';
898
+ readonly inner: infer I;
899
+ } ? I extends ContractShape ? Infer<I> : never : never;
900
+ }> & InferOpenIndex<A>;
901
+
902
+ /**
903
+ * Infer a `JSONSchema` object fragment from a plain record's sampled
904
+ * properties.
905
+ *
906
+ * @remarks
907
+ * Own enumerable string keys via `Object.keys`, sorted lexicographically for
908
+ * deterministic output, capped at `breadth`. Each property value is read
909
+ * through {@link attempt} so a hostile getter cannot escape as a thrown
910
+ * error; a property whose value is `undefined` (hostile-getter failure
911
+ * included) is treated as ABSENT — it contributes neither a `properties`
912
+ * entry nor a `required` entry. Every other present key is required (single-
913
+ * value mode). Emits `additionalProperties: false` when `closed`, `true`
914
+ * otherwise — mirroring {@link compileSchema}'s object-emission convention —
915
+ * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means
916
+ * the sampled schema no longer describes every property `value` actually
917
+ * carries, so `additionalProperties` is forced to `true` regardless of
918
+ * `closed` (a closed schema built from a truncated sample would otherwise
919
+ * reject the very object it was inferred from). Depth exhaustion or a cyclic
920
+ * re-encounter of `value` both yield `{}`. A same-object re-inference at the
921
+ * same remaining `depth` is served from `memo` instead of recomputing
922
+ * (guards a shared-reference DAG against exponential blowup).
923
+ *
924
+ * @param value - The record to infer from
925
+ * @param depth - Remaining descent budget
926
+ * @param breadth - The maximum number of properties sampled
927
+ * @param closed - Whether the emitted schema closes to unknown keys
928
+ * @param format - Threaded through to nested string/`Date` properties
929
+ * @param visited - The ancestor set guarding against cycles
930
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
931
+ * against exponential re-inference of a shared-reference DAG
932
+ * @returns The inferred object schema
933
+ *
934
+ * @example
935
+ * ```ts
936
+ * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())
937
+ * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],
938
+ * // additionalProperties: false }
939
+ * ```
940
+ */
941
+ export declare function inferObject(value: Record<string, unknown>, depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet<object>, memo: WeakMap<object, Map<number, JSONSchema>>): JSONSchema;
942
+
943
+ /**
944
+ * The index-signature contribution of a MIXED object shape's
945
+ * `additionalProperties` — one with both fixed `properties` and an open tail.
946
+ *
947
+ * @remarks
948
+ * A typed index (`{ readonly [k: string]: Infer<A> }`) collapses any
949
+ * differently-typed fixed property to `never` on intersection and makes the
950
+ * object type unconstructable — TypeScript rejects assigning any property
951
+ * whose type differs from the index value type. So when `A` is a
952
+ * {@link ContractShape} here, the index is deliberately widened to
953
+ * `{ readonly [k: string]: unknown }`: the static type stops over-claiming the
954
+ * extra-key type while the runtime guard still validates extras against `A`.
955
+ * `false` / `true` behave exactly as {@link InferIndex}.
956
+ *
957
+ * @remarks
958
+ * The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay
959
+ * non-distributive, matching {@link Infer}'s own object-branch guard and
960
+ * {@link InferIndex}'s tail — see {@link Infer}'s remarks for why a naked
961
+ * `extends` here would fan a wide `A` into a union of instantiations.
962
+ */
963
+ export declare type InferOpenIndex<A extends boolean | ContractShape> = [A] extends [false] ? unknown : [A] extends [true] ? {
964
+ readonly [k: string]: unknown;
965
+ } : [A] extends [ContractShape] ? {
966
+ readonly [k: string]: unknown;
967
+ } : unknown;
968
+
969
+ /**
970
+ * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated
971
+ * primitive slot — the multi-sample-only counterpart to
972
+ * {@link stringToFormat} ({@link valueToSchema} never emits `enum`).
973
+ *
974
+ * @remarks
975
+ * Fires only when ALL of: every value is the same primitive kind (all string
976
+ * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed
977
+ * slot never qualifies, and a slot containing `NaN` / `±Infinity` never
978
+ * qualifies either, since {@link canonicalStringify} collapses `NaN` to
979
+ * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2
980
+ * values are given; the distinct-by-{@link canonicalStringify} count is LESS
981
+ * than the value count (repetition required — separates a categorical column
982
+ * from an ID column); and the distinct count is at most `limit`. The emitted
983
+ * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s
984
+ * `literalShape` emission. Members are sorted by canonical key for
985
+ * deterministic output.
986
+ *
987
+ * @param values - The collected slot values
988
+ * @param limit - The maximum distinct-value count before giving up
989
+ * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
990
+ *
991
+ * @example
992
+ * ```ts
993
+ * inferPrimitiveEnum(['active', 'inactive', 'active'], 12)
994
+ * // { enum: ['active', 'inactive'] }
995
+ * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition
996
+ * ```
997
+ */
998
+ export declare function inferPrimitiveEnum(values: readonly unknown[], limit: number): JSONSchema | undefined;
999
+
1000
+ /**
1001
+ * Infer a `JSONSchema` object fragment from a set of plain-record samples
1002
+ * (e.g. database rows) — the record-specialized branch of
1003
+ * {@link samplesToSchema}.
1004
+ *
1005
+ * @remarks
1006
+ * `properties` is the union of every sample's own keys (sorted, capped at
1007
+ * `breadth`); a key is `required` only when present (and non-`undefined`) in
1008
+ * EVERY sample. Each key's schema is inferred over the collected values for
1009
+ * that key via {@link inferSamples} itself (one less depth), so a
1010
+ * property that is itself an array/object of varying shape across rows is
1011
+ * unified the same way the top level is, and the same `format` / `enum`
1012
+ * gating applies per key. Unlike {@link inferObject}/
1013
+ * {@link inferArray}, this path carries no `visited` `WeakSet` — a value
1014
+ * shared by reference across multiple sample rows is legitimate (not a
1015
+ * cycle back to an ancestor), so termination on cyclic row data relies on
1016
+ * the decrementing `depth` budget alone. When the union of sample keys
1017
+ * exceeds `breadth`, the key list is truncated and `additionalProperties` is
1018
+ * forced to `true` regardless of `closed` — the same truncation-opens-the-
1019
+ * schema rule {@link inferObject} applies, so a closed schema built from a
1020
+ * truncated key union never rejects the very rows it was inferred from. A
1021
+ * hostile getter on ONE sample row drops that key for ALL rows (the whole
1022
+ * per-key value collection is a single {@link attempt}-contained walk) —
1023
+ * this is a deliberate all-or-nothing scope, not a per-row partial failure.
1024
+ *
1025
+ * @param samples - The plain-record samples
1026
+ * @param depth - Remaining descent budget
1027
+ * @param breadth - The maximum number of properties sampled
1028
+ * @param closed - Whether the emitted schema closes to unknown keys
1029
+ * @param format - Whether a unanimous string column gains a `format` keyword
1030
+ * @param enumOn - Whether a low-cardinality column may emit `enum`
1031
+ * @returns The inferred object schema
1032
+ *
1033
+ * @example
1034
+ * ```ts
1035
+ * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)
1036
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
1037
+ * // required: ['id'], additionalProperties: false }
1038
+ * ```
1039
+ */
1040
+ export declare function inferRecordSamples(samples: readonly Record<string, unknown>[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean): JSONSchema;
1041
+
1042
+ /**
1043
+ * Infer a `JSONSchema` for a collected slot of sample values — the shared
1044
+ * non-record recursion step behind {@link samplesToSchema} (top level) and
1045
+ * {@link inferRecordSamples} (per collected property).
1046
+ *
1047
+ * @remarks
1048
+ * When every value is itself a plain record, delegates to
1049
+ * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when
1050
+ * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,
1051
+ * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins
1052
+ * outright (ENUM > FORMAT > bare string). Failing that, each value is
1053
+ * classified independently via {@link inferValue} with `format` FORCED OFF
1054
+ * (the multi-sample seam: nested formats never compound into an `anyOf`) and
1055
+ * unified with {@link unifySchemas}; only when that unified result is exactly
1056
+ * `{ type: 'string' }` and the outer `format` flag is on does
1057
+ * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.
1058
+ *
1059
+ * @param samples - The collected slot values
1060
+ * @param depth - Remaining descent budget
1061
+ * @param breadth - The maximum number of properties/elements sampled per nested container
1062
+ * @param closed - Whether nested objects close to unknown keys
1063
+ * @param format - Whether a unanimous string slot gains a `format` keyword
1064
+ * @param enumOn - Whether low-cardinality primitive slots may emit `enum`
1065
+ * @returns The inferred schema for the slot
1066
+ *
1067
+ * @example
1068
+ * ```ts
1069
+ * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)
1070
+ * // { type: 'string', format: 'date' }
1071
+ * ```
1072
+ */
1073
+ export declare function inferSamples(samples: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean): JSONSchema;
1074
+
1075
+ /** {@link Infer} of a union shape's `variants` — the union of each variant's inferred type. */
1076
+ export declare type InferUnion<V extends readonly ContractShape[]> = V extends readonly (infer U)[] ? U extends ContractShape ? Infer<U> : never : never;
1077
+
1078
+ /**
1079
+ * Infer a `JSONSchema` fragment for one runtime value — the recursive spine
1080
+ * shared by {@link valueToSchema} and, per collected property/element, by
1081
+ * {@link inferArray} / {@link inferObject}.
1082
+ *
1083
+ * @remarks
1084
+ * Total: never throws, and terminates on cyclic input via `visited`. Leaf
1085
+ * classification order: `null`, boolean, integer (`Number.isInteger`
1086
+ * semantics — `-0` counts), finite non-integer number, non-finite number
1087
+ * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
1088
+ * `format` keyword when `format` is on and {@link stringToFormat} matches),
1089
+ * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
1090
+ * plus `format: 'date-time'` when `format` is on); everything else
1091
+ * (function, symbol, bigint, `undefined`, and other non-plain objects such as
1092
+ * `Map` / `Set`) is the empty accept-anything schema `{}`.
1093
+ *
1094
+ * @param value - The value to classify
1095
+ * @param depth - Remaining descent budget (0 halts recursion with `{}`)
1096
+ * @param breadth - The per-container sampling cap passed through to children
1097
+ * @param closed - Whether descended objects emit `additionalProperties: false`
1098
+ * @param format - Whether a string/`Date` leaf gains a `format` keyword
1099
+ * @param visited - The ancestor set guarding against cycles
1100
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
1101
+ * against exponential re-inference of a shared-reference DAG
1102
+ * @returns The inferred schema fragment for `value`
1103
+ *
1104
+ * @example
1105
+ * ```ts
1106
+ * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }
1107
+ * ```
1108
+ */
1109
+ export declare function inferValue(value: unknown, depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet<object>, memo: WeakMap<object, Map<number, JSONSchema>>): JSONSchema;
1110
+
1111
+ /**
1112
+ * Build a guard that accepts instances of the provided constructor.
1113
+ *
1114
+ * @remarks
1115
+ * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,
1116
+ * so passing an arrow function does not silently produce a broken guard.
1117
+ *
1118
+ * @example
1119
+ * ```ts
1120
+ * const isDateValue = instanceOf(Date)
1121
+ * isDateValue(new Date()) // true
1122
+ * isDateValue({}) // false
1123
+ * ```
1124
+ */
1125
+ export declare function instanceOf<C extends abstract new (...args: never) => object>(ctor: C): Guard<InstanceType<C>>;
1126
+
1127
+ /**
1128
+ * Build an integer {@link NumberShape} — forces `integer: true`.
1129
+ *
1130
+ * @remarks
1131
+ * The emitted JSON Schema uses `"type": "integer"` and the guard rejects
1132
+ * fractional numbers.
1133
+ *
1134
+ * @param options - Optional bounds and `description` (no `integer` key)
1135
+ * @returns An integer number shape
1136
+ */
1137
+ export declare function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape;
1138
+
1139
+ /** Intersection of the types guarded by a tuple of guards — backs `intersectionOf`. */
1140
+ export declare type IntersectionFromGuards<Gs extends ReadonlyArray<Guard<unknown>>> = UnionToIntersection<GuardType<Gs[number]>>;
1141
+
1142
+ /**
1143
+ * Build a guard that accepts values matching ALL of the provided guards — the
1144
+ * variadic form of {@link andOf}.
1145
+ *
1146
+ * @example
1147
+ * ```ts
1148
+ * const isNonEmpty = intersectionOf(isString, isNonEmptyString)
1149
+ * ```
1150
+ */
1151
+ export declare function intersectionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<IntersectionFromGuards<Gs>>;
1152
+
1153
+ export declare function intersectionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>;
1154
+
1155
+ /** Determine whether a value is an array.
1156
+ *
1157
+ * @example
1158
+ * ```ts
1159
+ * isArray([1, 2]) // true
1160
+ * isArray('12') // false
1161
+ * ```
1162
+ */
1163
+ export declare function isArray<T = unknown>(value: unknown): value is readonly T[];
1164
+
1165
+ /** Determine whether a value is an `ArrayBuffer`.
1166
+ *
1167
+ * @example
1168
+ * ```ts
1169
+ * isArrayBuffer(new ArrayBuffer(8)) // true
1170
+ * isArrayBuffer([]) // false
1171
+ * ```
1172
+ */
1173
+ export declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
1174
+
1175
+ /** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).
1176
+ *
1177
+ * @example
1178
+ * ```ts
1179
+ * isArrayBufferView(new Uint8Array(4)) // true
1180
+ * isArrayBufferView([1, 2, 3, 4]) // false
1181
+ * ```
1182
+ */
1183
+ export declare function isArrayBufferView(value: unknown): value is ArrayBufferView;
1184
+
1185
+ /**
1186
+ * Determine whether a value is a native `async function`.
1187
+ *
1188
+ * @remarks
1189
+ * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is
1190
+ * unreliable across realms. The `?.` keeps the guard total (§14): a function
1191
+ * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.
1192
+ *
1193
+ * @example
1194
+ * ```ts
1195
+ * isAsyncFunction(async () => {}) // true
1196
+ * isAsyncFunction(() => {}) // false
1197
+ * ```
1198
+ */
1199
+ export declare function isAsyncFunction(value: unknown): value is AnyAsyncFunction;
1200
+
1201
+ /** Determine whether a value is an async generator function (`async function*`).
1202
+ *
1203
+ * @example
1204
+ * ```ts
1205
+ * isAsyncGeneratorFunction(async function* () {}) // true
1206
+ * isAsyncGeneratorFunction(function* () {}) // false
1207
+ * ```
1208
+ */
1209
+ export declare function isAsyncGeneratorFunction(value: unknown): value is (...args: unknown[]) => AsyncGenerator<unknown, unknown, unknown>;
1210
+
1211
+ /** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).
1212
+ *
1213
+ * @example
1214
+ * ```ts
1215
+ * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true
1216
+ * isAsyncIterable([1, 2]) // false
1217
+ * ```
1218
+ */
1219
+ export declare function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T>;
1220
+
1221
+ /** Determine whether a value is a bigint.
1222
+ *
1223
+ * @example
1224
+ * ```ts
1225
+ * isBigInt(1n) // true
1226
+ * isBigInt(1) // false
1227
+ * ```
1228
+ */
1229
+ export declare function isBigInt(value: unknown): value is bigint;
1230
+
1231
+ /**
1232
+ * Determine whether a value is a `BigInt64Array`.
1233
+ *
1234
+ * @remarks
1235
+ * Guards the global existence of `BigInt64Array` first — safe in environments
1236
+ * that pre-date the BigInt typed-array additions.
1237
+ *
1238
+ * @example
1239
+ * ```ts
1240
+ * isBigInt64Array(new BigInt64Array(2)) // true
1241
+ * isBigInt64Array(new Float64Array(2)) // false
1242
+ * ```
1243
+ */
1244
+ export declare function isBigInt64Array(value: unknown): value is BigInt64Array;
1245
+
1246
+ /**
1247
+ * Determine whether a value is a `BigUint64Array`.
1248
+ *
1249
+ * @remarks
1250
+ * Guards the global existence of `BigUint64Array` first — safe in environments
1251
+ * that pre-date the BigInt typed-array additions.
1252
+ *
1253
+ * @example
1254
+ * ```ts
1255
+ * isBigUint64Array(new BigUint64Array(2)) // true
1256
+ * isBigUint64Array(new BigInt64Array(2)) // false
1257
+ * ```
1258
+ */
1259
+ export declare function isBigUint64Array(value: unknown): value is BigUint64Array;
1260
+
1261
+ /** Determine whether a value is a boolean.
1262
+ *
1263
+ * @example
1264
+ * ```ts
1265
+ * isBoolean(true) // true
1266
+ * isBoolean(1) // false
1267
+ * ```
1268
+ */
1269
+ export declare function isBoolean(value: unknown): value is boolean;
1270
+
1271
+ /**
1272
+ * Determine whether a value can be used as a `new`-target constructor.
1273
+ *
1274
+ * @remarks
1275
+ * Probes with `Reflect.construct(String, [], value)`: a real constructor
1276
+ * succeeds, while arrow functions, plain functions, and non-functions throw
1277
+ * and yield `false`. Never throws. Backs the `instanceOf` combinator.
1278
+ *
1279
+ * @example
1280
+ * ```ts
1281
+ * isConstructor(class X {}) // true
1282
+ * isConstructor(() => {}) // false
1283
+ * ```
1284
+ */
1285
+ export declare function isConstructor(value: unknown): value is AnyConstructor<object>;
1286
+
1287
+ /** Determine whether a value is a `DataView`.
1288
+ *
1289
+ * @example
1290
+ * ```ts
1291
+ * isDataView(new DataView(new ArrayBuffer(8))) // true
1292
+ * isDataView(new ArrayBuffer(8)) // false
1293
+ * ```
1294
+ */
1295
+ export declare function isDataView(value: unknown): value is DataView<ArrayBufferLike>;
1296
+
1297
+ /** Determine whether a value is a `Date`.
1298
+ *
1299
+ * @example
1300
+ * ```ts
1301
+ * isDate(new Date()) // true
1302
+ * isDate('2024-01-01') // false
1303
+ * ```
1304
+ */
1305
+ export declare function isDate(value: unknown): value is Date;
1306
+
1307
+ /** Determine whether a value is defined (neither `null` nor `undefined`).
1308
+ *
1309
+ * @example
1310
+ * ```ts
1311
+ * isDefined('hi') // true
1312
+ * isDefined(null) // false
1313
+ * isDefined(undefined) // false
1314
+ * ```
1315
+ */
1316
+ export declare function isDefined<T>(value: T | null | undefined): value is T;
1317
+
1318
+ /** Determine whether a value is an empty array.
1319
+ *
1320
+ * @example
1321
+ * ```ts
1322
+ * isEmptyArray([]) // true
1323
+ * isEmptyArray([1]) // false
1324
+ * ```
1325
+ */
1326
+ export declare function isEmptyArray(value: unknown): value is readonly [];
1327
+
1328
+ /** Determine whether a value is an empty `Map`.
1329
+ *
1330
+ * @example
1331
+ * ```ts
1332
+ * isEmptyMap(new Map()) // true
1333
+ * isEmptyMap(new Map([['a', 1]])) // false
1334
+ * ```
1335
+ */
1336
+ export declare function isEmptyMap(value: unknown): value is ReadonlyMap<never, never>;
1337
+
1338
+ /** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).
1339
+ *
1340
+ * @example
1341
+ * ```ts
1342
+ * isEmptyObject({}) // true
1343
+ * isEmptyObject({ a: 1 }) // false
1344
+ * ```
1345
+ */
1346
+ export declare function isEmptyObject(value: unknown): value is Record<string | symbol, never>;
1347
+
1348
+ /** Determine whether a value is an empty `Set`.
1349
+ *
1350
+ * @example
1351
+ * ```ts
1352
+ * isEmptySet(new Set()) // true
1353
+ * isEmptySet(new Set([1])) // false
1354
+ * ```
1355
+ */
1356
+ export declare function isEmptySet(value: unknown): value is ReadonlySet<never>;
1357
+
1358
+ /** Determine whether a value is the empty string `''`.
1359
+ *
1360
+ * @example
1361
+ * ```ts
1362
+ * isEmptyString('') // true
1363
+ * isEmptyString('a') // false
1364
+ * ```
1365
+ */
1366
+ export declare function isEmptyString(value: unknown): value is '';
1367
+
1368
+ /** Determine whether a value is an `Error`.
1369
+ *
1370
+ * @example
1371
+ * ```ts
1372
+ * isError(new Error('boom')) // true
1373
+ * isError('boom') // false
1374
+ * ```
1375
+ */
1376
+ export declare function isError(value: unknown): value is Error;
1377
+
1378
+ /** Determine whether a value is exactly `false`.
1379
+ *
1380
+ * @example
1381
+ * ```ts
1382
+ * isFalse(false) // true
1383
+ * isFalse(true) // false
1384
+ * ```
1385
+ */
1386
+ export declare function isFalse(value: unknown): value is false;
1387
+
1388
+ /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).
1389
+ *
1390
+ * @example
1391
+ * ```ts
1392
+ * isFiniteNumber(42) // true
1393
+ * isFiniteNumber(Number.NaN) // false
1394
+ * isFiniteNumber(Infinity) // false
1395
+ * ```
1396
+ */
1397
+ export declare function isFiniteNumber(value: unknown): value is number;
1398
+
1399
+ /** Determine whether a value is a `Float32Array`.
1400
+ *
1401
+ * @example
1402
+ * ```ts
1403
+ * isFloat32Array(new Float32Array(2)) // true
1404
+ * isFloat32Array(new Float64Array(2)) // false
1405
+ * ```
1406
+ */
1407
+ export declare function isFloat32Array(value: unknown): value is Float32Array;
1408
+
1409
+ /** Determine whether a value is a `Float64Array`.
1410
+ *
1411
+ * @example
1412
+ * ```ts
1413
+ * isFloat64Array(new Float64Array(2)) // true
1414
+ * isFloat64Array(new Float32Array(2)) // false
1415
+ * ```
1416
+ */
1417
+ export declare function isFloat64Array(value: unknown): value is Float64Array;
1418
+
1419
+ /** Determine whether a value is callable.
1420
+ *
1421
+ * @example
1422
+ * ```ts
1423
+ * isFunction(() => {}) // true
1424
+ * isFunction({}) // false
1425
+ * ```
1426
+ */
1427
+ export declare function isFunction(value: unknown): value is AnyFunction;
1428
+
1429
+ /** Determine whether a value is a generator function (`function*`).
1430
+ *
1431
+ * @example
1432
+ * ```ts
1433
+ * isGeneratorFunction(function* () {}) // true
1434
+ * isGeneratorFunction(() => {}) // false
1435
+ * ```
1436
+ */
1437
+ export declare function isGeneratorFunction(value: unknown): value is (...args: unknown[]) => Generator<unknown, unknown, unknown>;
1438
+
1439
+ /**
1440
+ * Determine whether a value is an instance of a constructor, contained against
1441
+ * a throwing `instanceof` check.
1442
+ *
1443
+ * @remarks
1444
+ * The low-level total helper every `instanceof`-based guard in this file (and
1445
+ * the `instanceOf` combinator) routes through. A bare `value instanceof X` is
1446
+ * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
1447
+ * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
1448
+ * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
1449
+ * wraps the check in {@link attempt} (see ./helpers.js) so any such throw
1450
+ * yields `false` instead of escaping.
1451
+ *
1452
+ * @param value - The value to test
1453
+ * @param ctor - The constructor to test against
1454
+ * @returns `true` when `value instanceof ctor`, `false` on a non-match or a
1455
+ * contained throw
1456
+ *
1457
+ * @example
1458
+ * ```ts
1459
+ * isInstance(new Date(), Date) // true
1460
+ * isInstance({}, Date) // false
1461
+ * ```
1462
+ */
1463
+ export declare function isInstance<C>(value: unknown, ctor: C): value is InstanceType<C & AnyConstructor<object>>;
1464
+
1465
+ /** Determine whether a value is an `Int16Array`.
1466
+ *
1467
+ * @example
1468
+ * ```ts
1469
+ * isInt16Array(new Int16Array(2)) // true
1470
+ * isInt16Array(new Int8Array(2)) // false
1471
+ * ```
1472
+ */
1473
+ export declare function isInt16Array(value: unknown): value is Int16Array;
1474
+
1475
+ /** Determine whether a value is an `Int32Array`.
1476
+ *
1477
+ * @example
1478
+ * ```ts
1479
+ * isInt32Array(new Int32Array(2)) // true
1480
+ * isInt32Array(new Int16Array(2)) // false
1481
+ * ```
1482
+ */
1483
+ export declare function isInt32Array(value: unknown): value is Int32Array;
1484
+
1485
+ /** Determine whether a value is an `Int8Array`.
1486
+ *
1487
+ * @example
1488
+ * ```ts
1489
+ * isInt8Array(new Int8Array(2)) // true
1490
+ * isInt8Array(new Uint8Array(2)) // false
1491
+ * ```
1492
+ */
1493
+ export declare function isInt8Array(value: unknown): value is Int8Array;
1494
+
1495
+ /** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).
1496
+ *
1497
+ * @example
1498
+ * ```ts
1499
+ * isInteger(3) // true
1500
+ * isInteger(3.5) // false
1501
+ * ```
1502
+ */
1503
+ export declare function isInteger(value: unknown): value is number;
1504
+
1505
+ /**
1506
+ * Determine whether a value implements the iterable protocol (`Symbol.iterator`).
1507
+ *
1508
+ * @remarks
1509
+ * Strings are explicitly included: a string has a callable `Symbol.iterator`
1510
+ * but is not an object, so the generic object path alone would miss it.
1511
+ *
1512
+ * @example
1513
+ * ```ts
1514
+ * isIterable([1, 2]) // true
1515
+ * isIterable('abc') // true
1516
+ * isIterable({ a: 1 }) // false
1517
+ * ```
1518
+ */
1519
+ export declare function isIterable<T = unknown>(value: unknown): value is Iterable<T>;
1520
+
1521
+ /**
1522
+ * Determine whether a value is a primitive JSON value.
1523
+ *
1524
+ * @remarks
1525
+ * The flat leaf of any JSON document: `null`, a string, a **finite** number, or
1526
+ * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON
1527
+ * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.
1528
+ *
1529
+ * The recursive {@link isJSONValue} guard is shipped and stays total with
1530
+ * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and
1531
+ * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with
1532
+ * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.
1533
+ *
1534
+ * @param value - The value to test
1535
+ * @returns `true` when `value` is `null`, a string, a finite number, or a boolean
1536
+ *
1537
+ * @example
1538
+ * ```ts
1539
+ * isJSONPrimitive(null) // true
1540
+ * isJSONPrimitive('hi') // true
1541
+ * isJSONPrimitive(42) // true
1542
+ * isJSONPrimitive(Number.NaN) // false — not representable in JSON
1543
+ * isJSONPrimitive({}) // false
1544
+ * ```
1545
+ */
1546
+ export declare function isJSONPrimitive(value: unknown): value is JSONPrimitive;
1547
+
1548
+ /**
1549
+ * Determine whether a value is a cycle-safe JSON value.
1550
+ *
1551
+ * @remarks
1552
+ * Total guard: never throws, returns `false` for cycles, functions, `Date`
1553
+ * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
1554
+ * are walked with an ancestor set so recursive input fails instead of hanging.
1555
+ * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a
1556
+ * record property, or a revoked `Proxy` anywhere in the structure, is caught
1557
+ * and yields `false` instead of escaping as a thrown error.
1558
+ *
1559
+ * @param value - The value to test
1560
+ * @returns `true` when the value has a JSON representation
1561
+ *
1562
+ * @example
1563
+ * ```ts
1564
+ * isJSONValue({ nested: [1, 'x', null] }) // true
1565
+ * isJSONValue(Number.NaN) // false
1566
+ * ```
1567
+ */
1568
+ export declare function isJSONValue(value: unknown): value is JSONValue;
1569
+
1570
+ /** Determine whether a value is a `Map`.
1571
+ *
1572
+ * @example
1573
+ * ```ts
1574
+ * isMap(new Map()) // true
1575
+ * isMap({}) // false
1576
+ * ```
1577
+ */
1578
+ export declare function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V>;
1579
+
1580
+ /** Determine whether a value is a non-empty array (at least one element).
1581
+ *
1582
+ * @example
1583
+ * ```ts
1584
+ * isNonEmptyArray([1]) // true
1585
+ * isNonEmptyArray([]) // false
1586
+ * ```
1587
+ */
1588
+ export declare function isNonEmptyArray<T = unknown>(value: unknown): value is readonly [T, ...T[]];
1589
+
1590
+ /** Determine whether a value is a non-empty `Map` (at least one entry).
1591
+ *
1592
+ * @example
1593
+ * ```ts
1594
+ * isNonEmptyMap(new Map([['a', 1]])) // true
1595
+ * isNonEmptyMap(new Map()) // false
1596
+ * ```
1597
+ */
1598
+ export declare function isNonEmptyMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V>;
1599
+
1600
+ /** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).
1601
+ *
1602
+ * @example
1603
+ * ```ts
1604
+ * isNonEmptyObject({ a: 1 }) // true
1605
+ * isNonEmptyObject({}) // false
1606
+ * ```
1607
+ */
1608
+ export declare function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown>;
1609
+
1610
+ /** Determine whether a value is a non-empty `Set` (at least one element).
1611
+ *
1612
+ * @example
1613
+ * ```ts
1614
+ * isNonEmptySet(new Set([1])) // true
1615
+ * isNonEmptySet(new Set()) // false
1616
+ * ```
1617
+ */
1618
+ export declare function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T>;
1619
+
1620
+ /** Determine whether a value is a non-empty string (at least one character).
1621
+ *
1622
+ * @example
1623
+ * ```ts
1624
+ * isNonEmptyString('a') // true
1625
+ * isNonEmptyString('') // false
1626
+ * ```
1627
+ */
1628
+ export declare function isNonEmptyString(value: unknown): value is string;
1629
+
1630
+ /** Determine whether a value is `null`.
1631
+ *
1632
+ * @example
1633
+ * ```ts
1634
+ * isNull(null) // true
1635
+ * isNull(undefined) // false
1636
+ * ```
1637
+ */
1638
+ export declare function isNull(value: unknown): value is null;
1639
+
1640
+ /** Determine whether a value is a boolean or `null`.
1641
+ *
1642
+ * @example
1643
+ * ```ts
1644
+ * isNullableBoolean(true) // true
1645
+ * isNullableBoolean(null) // true
1646
+ * isNullableBoolean(1) // false
1647
+ * ```
1648
+ */
1649
+ export declare function isNullableBoolean(value: unknown): value is boolean | null;
1650
+
1651
+ /** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).
1652
+ *
1653
+ * @example
1654
+ * ```ts
1655
+ * isNullableNumber(42) // true
1656
+ * isNullableNumber(null) // true
1657
+ * isNullableNumber('hi') // false
1658
+ * ```
1659
+ */
1660
+ export declare function isNullableNumber(value: unknown): value is number | null;
1661
+
1662
+ /** Determine whether a value is a string or `null`.
1663
+ *
1664
+ * @example
1665
+ * ```ts
1666
+ * isNullableString('hi') // true
1667
+ * isNullableString(null) // true
1668
+ * isNullableString(42) // false
1669
+ * ```
1670
+ */
1671
+ export declare function isNullableString(value: unknown): value is string | null;
1672
+
1673
+ /**
1674
+ * Determine whether a value is a number.
1675
+ *
1676
+ * @remarks
1677
+ * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.
1678
+ *
1679
+ * @example
1680
+ * ```ts
1681
+ * isNumber(42) // true
1682
+ * isNumber(Number.NaN) // true — NaN is still a number
1683
+ * isNumber('42') // false
1684
+ * ```
1685
+ */
1686
+ export declare function isNumber(value: unknown): value is number;
1687
+
1688
+ /**
1689
+ * Determine whether a value is a non-null object.
1690
+ *
1691
+ * @remarks
1692
+ * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use
1693
+ * {@link isRecord} when you need a plain-record check.
1694
+ *
1695
+ * @example
1696
+ * ```ts
1697
+ * isObject({}) // true
1698
+ * isObject([]) // true
1699
+ * isObject(null) // false
1700
+ * ```
1701
+ */
1702
+ export declare function isObject(value: unknown): value is object;
1703
+
1704
+ /** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).
1705
+ *
1706
+ * @example
1707
+ * ```ts
1708
+ * isPromise(Promise.resolve()) // true
1709
+ * isPromise({ then() {} }) // false
1710
+ * ```
1711
+ */
1712
+ export declare function isPromise<T = unknown>(value: unknown): value is Promise<T>;
1713
+
1714
+ /**
1715
+ * Determine whether a value is promise-like — an object exposing callable
1716
+ * `then`, `catch`, and `finally` methods.
1717
+ *
1718
+ * @remarks
1719
+ * Accepts any object with all three methods, not only native `Promise`
1720
+ * instances. Use {@link isPromise} when you specifically need `instanceof Promise`.
1721
+ *
1722
+ * @example
1723
+ * ```ts
1724
+ * isPromiseLike(Promise.resolve()) // true
1725
+ * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true
1726
+ * isPromiseLike({ then() {} }) // false
1727
+ * ```
1728
+ */
1729
+ export declare function isPromiseLike<T = unknown>(value: unknown): value is Promise<T> | (PromiseLike<T> & {
1730
+ catch: unknown;
1731
+ finally: unknown;
1732
+ });
1733
+
1734
+ /**
1735
+ * Determine whether a value is a plain record (object literal or null-prototype),
1736
+ * not an array or class instance.
1737
+ *
1738
+ * @remarks
1739
+ * Use instead of {@link isObject} to distinguish a plain `{}` /
1740
+ * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
1741
+ * test is realm-agnostic: rather than comparing against the current realm's
1742
+ * `Object.prototype` (which a plain object from another `vm.Context`, iframe,
1743
+ * or worker would fail), it accepts any value whose prototype is `null`, OR
1744
+ * whose prototype's own prototype is `null` — the shape every plain object
1745
+ * has in every realm, since `Object.prototype` itself always sits one step
1746
+ * above `null`. Arrays and class instances are still rejected: an array's
1747
+ * prototype chain runs through `Array.prototype` before `null`, and a class
1748
+ * instance's runs through the class's own prototype. The whole body runs
1749
+ * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
1750
+ * `getPrototypeOf` trap cannot escape as a thrown error.
1751
+ *
1752
+ * @example
1753
+ * ```ts
1754
+ * isRecord({ a: 1 }) // true
1755
+ * isRecord(Object.create(null)) // true
1756
+ * isRecord([]) // false
1757
+ * isRecord(new Date()) // false
1758
+ * ```
1759
+ */
1760
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
1761
+
1762
+ /** Determine whether a value is a `RegExp`.
1763
+ *
1764
+ * @example
1765
+ * ```ts
1766
+ * isRegExp(/a/) // true
1767
+ * isRegExp('a') // false
1768
+ * ```
1769
+ */
1770
+ export declare function isRegExp(value: unknown): value is RegExp;
1771
+
1772
+ /** Determine whether a value is a `Set`.
1773
+ *
1774
+ * @example
1775
+ * ```ts
1776
+ * isSet(new Set()) // true
1777
+ * isSet([]) // false
1778
+ * ```
1779
+ */
1780
+ export declare function isSet<T = unknown>(value: unknown): value is ReadonlySet<T>;
1781
+
1782
+ /**
1783
+ * Determine whether a value is a `SharedArrayBuffer`.
1784
+ *
1785
+ * @remarks
1786
+ * Guards the global existence of `SharedArrayBuffer` first — safe where it is
1787
+ * absent or disabled (e.g. a context that is not cross-origin isolated).
1788
+ *
1789
+ * @example
1790
+ * ```ts
1791
+ * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true
1792
+ * isSharedArrayBuffer(new ArrayBuffer(8)) // false
1793
+ * ```
1794
+ */
1795
+ export declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer;
1796
+
1797
+ /** Determine whether a value is a string.
1798
+ *
1799
+ * @example
1800
+ * ```ts
1801
+ * isString('hi') // true
1802
+ * isString(42) // false
1803
+ * ```
1804
+ */
1805
+ export declare function isString(value: unknown): value is string;
1806
+
1807
+ /** Determine whether a value is a symbol.
1808
+ *
1809
+ * @example
1810
+ * ```ts
1811
+ * isSymbol(Symbol('x')) // true
1812
+ * isSymbol('x') // false
1813
+ * ```
1814
+ */
1815
+ export declare function isSymbol(value: unknown): value is symbol;
1816
+
1817
+ /** Determine whether a value is exactly `true`.
1818
+ *
1819
+ * @example
1820
+ * ```ts
1821
+ * isTrue(true) // true
1822
+ * isTrue(false) // false
1823
+ * ```
1824
+ */
1825
+ export declare function isTrue(value: unknown): value is true;
1826
+
1827
+ /** Determine whether a value is a `Uint16Array`.
1828
+ *
1829
+ * @example
1830
+ * ```ts
1831
+ * isUint16Array(new Uint16Array(2)) // true
1832
+ * isUint16Array(new Int16Array(2)) // false
1833
+ * ```
1834
+ */
1835
+ export declare function isUint16Array(value: unknown): value is Uint16Array;
1836
+
1837
+ /** Determine whether a value is a `Uint32Array`.
1838
+ *
1839
+ * @example
1840
+ * ```ts
1841
+ * isUint32Array(new Uint32Array(2)) // true
1842
+ * isUint32Array(new Int32Array(2)) // false
1843
+ * ```
1844
+ */
1845
+ export declare function isUint32Array(value: unknown): value is Uint32Array;
1846
+
1847
+ /** Determine whether a value is a `Uint8Array`.
1848
+ *
1849
+ * @example
1850
+ * ```ts
1851
+ * isUint8Array(new Uint8Array(2)) // true
1852
+ * isUint8Array(new Int8Array(2)) // false
1853
+ * ```
1854
+ */
1855
+ export declare function isUint8Array(value: unknown): value is Uint8Array;
1856
+
1857
+ /** Determine whether a value is a `Uint8ClampedArray`.
1858
+ *
1859
+ * @example
1860
+ * ```ts
1861
+ * isUint8ClampedArray(new Uint8ClampedArray(2)) // true
1862
+ * isUint8ClampedArray(new Uint8Array(2)) // false
1863
+ * ```
1864
+ */
1865
+ export declare function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray;
1866
+
1867
+ /** Determine whether a value is `undefined`.
1868
+ *
1869
+ * @example
1870
+ * ```ts
1871
+ * isUndefined(undefined) // true
1872
+ * isUndefined(null) // false
1873
+ * ```
1874
+ */
1875
+ export declare function isUndefined(value: unknown): value is undefined;
1876
+
1877
+ /**
1878
+ * Determine whether an ISO-8601-shaped string parses to a valid instant.
1879
+ *
1880
+ * @remarks
1881
+ * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never
1882
+ * throws on a string input, but a value like `2020-13-45` parses to an
1883
+ * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation
1884
+ * step behind {@link stringToFormat}'s `date` / `date-time` / `time`
1885
+ * branches, which pattern-match the shape first and confirm validity here.
1886
+ *
1887
+ * @param value - The candidate ISO-8601 string
1888
+ * @returns `true` when `value` parses to a real instant
1889
+ *
1890
+ * @example
1891
+ * ```ts
1892
+ * isValidISOInstant('2020-01-01') // true
1893
+ * isValidISOInstant('2020-13-45') // false
1894
+ * ```
1895
+ */
1896
+ export declare function isValidISOInstant(value: string): boolean;
1897
+
1898
+ /** Determine whether a value is a `WeakMap`.
1899
+ *
1900
+ * @example
1901
+ * ```ts
1902
+ * isWeakMap(new WeakMap()) // true
1903
+ * isWeakMap({}) // false
1904
+ * ```
1905
+ */
1906
+ export declare function isWeakMap(value: unknown): value is WeakMap<object, unknown>;
1907
+
1908
+ /** Determine whether a value is a `WeakSet`.
1909
+ *
1910
+ * @example
1911
+ * ```ts
1912
+ * isWeakSet(new WeakSet()) // true
1913
+ * isWeakSet({}) // false
1914
+ * ```
1915
+ */
1916
+ export declare function isWeakSet(value: unknown): value is WeakSet<object>;
1917
+
1918
+ /** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).
1919
+ *
1920
+ * @example
1921
+ * ```ts
1922
+ * isZeroArg(() => {}) // true
1923
+ * isZeroArg((a) => a) // false
1924
+ * ```
1925
+ */
1926
+ export declare function isZeroArg(value: unknown): value is ZeroArgFunction;
1927
+
1928
+ /** Determine whether a value is a zero-argument async function.
1929
+ *
1930
+ * @example
1931
+ * ```ts
1932
+ * isZeroArgAsync(async () => {}) // true
1933
+ * isZeroArgAsync(async (a) => a) // false
1934
+ * ```
1935
+ */
1936
+ export declare function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction;
1937
+
1938
+ /** Determine whether a value is a zero-argument async generator function.
1939
+ *
1940
+ * @example
1941
+ * ```ts
1942
+ * isZeroArgAsyncGenerator(async function* () {}) // true
1943
+ * isZeroArgAsyncGenerator(async function* (a) {}) // false
1944
+ * ```
1945
+ */
1946
+ export declare function isZeroArgAsyncGenerator(value: unknown): value is () => AsyncGenerator<unknown, unknown, unknown>;
1947
+
1948
+ /** Determine whether a value is a zero-argument generator function.
1949
+ *
1950
+ * @example
1951
+ * ```ts
1952
+ * isZeroArgGenerator(function* () {}) // true
1953
+ * isZeroArgGenerator(function* (a) {}) // false
1954
+ * ```
1955
+ */
1956
+ export declare function isZeroArgGenerator(value: unknown): value is () => Generator<unknown, unknown, unknown>;
1957
+
1958
+ /**
1959
+ * Build a guard that accepts any iterable whose every element satisfies
1960
+ * `elementGuard`.
1961
+ *
1962
+ * @example
1963
+ * ```ts
1964
+ * const isNumberIterable = iterableOf(isNumber)
1965
+ * isNumberIterable([1, 2, 3]) // true
1966
+ * isNumberIterable(new Set([1, 2])) // true
1967
+ * isNumberIterable([1, 'two']) // false
1968
+ * ```
1969
+ */
1970
+ export declare function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>;
1971
+
1972
+ export declare function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>;
1973
+
1974
+ /**
1975
+ * The seven standard JSON Schema `type` names, frozen.
1976
+ *
1977
+ * @remarks
1978
+ * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose
1979
+ * it with the shipped primitives instead of reaching for a bespoke guard:
1980
+ * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and
1981
+ * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`
1982
+ * is the parser.
1983
+ *
1984
+ * @example
1985
+ * ```ts
1986
+ * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'
1987
+ *
1988
+ * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>
1989
+ * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined
1990
+ * ```
1991
+ */
1992
+ export declare const JSON_SCHEMA_TYPES: readonly JSONSchemaType[];
1993
+
1994
+ /**
1995
+ * A primitive JSON value — the flat leaf of any JSON document.
1996
+ *
1997
+ * @remarks
1998
+ * The recursive {@link JSONValue} tree type is shipped for consumers that need a
1999
+ * reusable JSON metadata contract. Dedicated `JSONObject` / `JSONArray` aliases
2000
+ * remain unshipped; compose those narrower shapes with the combinators, or keep
2001
+ * an untrusted parse result as `unknown` and narrow it.
2002
+ */
2003
+ export declare type JSONPrimitive = string | number | boolean | null;
2004
+
2005
+ /**
2006
+ * A JSON Schema fragment — the subset of keywords the contract compiler emits
2007
+ * and {@link RawShape} embeds.
2008
+ *
2009
+ * @remarks
2010
+ * Intentionally lean (not the full ~50-keyword vocabulary): it carries only the
2011
+ * keywords {@link Infer}-driven `compileSchema` produces, plus `format` —
2012
+ * emitted by the {@link stringToFormat} / {@link samplesToFormat} inference
2013
+ * heuristics (`valueToSchema` / `samplesToSchema`), never by `compileSchema`.
2014
+ * Recursive via `items` / `properties` / `additionalProperties` / `anyOf` /
2015
+ * `oneOf`, but every walk is over a finite, developer-authored shape — there
2016
+ * is no cycle/depth risk.
2017
+ */
2018
+ export declare interface JSONSchema {
2019
+ readonly type?: JSONSchemaType;
2020
+ readonly description?: string;
2021
+ readonly enum?: readonly (string | number | boolean)[];
2022
+ readonly minLength?: number;
2023
+ readonly maxLength?: number;
2024
+ readonly pattern?: string;
2025
+ readonly format?: string;
2026
+ readonly minimum?: number;
2027
+ readonly maximum?: number;
2028
+ readonly minItems?: number;
2029
+ readonly maxItems?: number;
2030
+ readonly items?: JSONSchema;
2031
+ readonly properties?: Readonly<Record<string, JSONSchema>>;
2032
+ readonly required?: readonly string[];
2033
+ readonly additionalProperties?: boolean | JSONSchema;
2034
+ readonly anyOf?: readonly JSONSchema[];
2035
+ readonly oneOf?: readonly JSONSchema[];
2036
+ }
2037
+
2038
+ /** The seven standard JSON Schema `type` names. */
2039
+ export declare type JSONSchemaType = 'null' | 'boolean' | 'object' | 'array' | 'number' | 'integer' | 'string';
2040
+
2041
+ /**
2042
+ * A JSON passthrough shape — accepts any JSON value.
2043
+ *
2044
+ * @remarks
2045
+ * The compiled guard is a sound {@link isJSONValue} check (rejecting cycles,
2046
+ * functions, `NaN`, and `±Infinity`); the parser gates through that guard; the
2047
+ * schema is the empty schema `{}` (matches any JSON instance); the generator
2048
+ * emits a small deterministic {@link JSONValue}. Unlike {@link RawShape}, whose
2049
+ * guard accepts anything, this shape validates that a value is real JSON.
2050
+ */
2051
+ export declare interface JSONShape {
2052
+ readonly type: 'json';
2053
+ readonly description?: string;
2054
+ }
2055
+
2056
+ /**
2057
+ * Build a {@link JSONShape}.
2058
+ *
2059
+ * @remarks
2060
+ * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
2061
+ * schema fragment and accepts anything at runtime, while `jsonShape` validates
2062
+ * that a value is real JSON (via {@link isJSONValue}).
2063
+ *
2064
+ * @param options - Optional `description`
2065
+ * @returns A JSON passthrough shape
2066
+ *
2067
+ * @example
2068
+ * ```ts
2069
+ * const payload = jsonShape({ description: 'Arbitrary JSON payload' })
2070
+ * ```
2071
+ */
2072
+ export declare function jsonShape(options?: JSONShapeOptions): JSONShape;
2073
+
2074
+ /** Options for {@link JSONShape} (via `jsonShape`). */
2075
+ export declare interface JSONShapeOptions {
2076
+ readonly description?: string;
2077
+ }
2078
+
2079
+ /**
2080
+ * A recursive JSON value — primitives, arrays, and object records.
2081
+ *
2082
+ * @remarks
2083
+ * The static type admits any `number` because TypeScript cannot express
2084
+ * finiteness. The {@link isJSONValue} guard rejects `NaN` and `±Infinity` since
2085
+ * they have no JSON representation.
2086
+ *
2087
+ * @example
2088
+ * ```ts
2089
+ * const value: JSONValue = { nested: [1, 'x', null] }
2090
+ * ```
2091
+ */
2092
+ export declare type JSONValue = JSONPrimitive | readonly JSONValue[] | {
2093
+ readonly [key: string]: JSONValue;
2094
+ };
2095
+
2096
+ /**
2097
+ * Build a guard that accepts values that are own keys of the provided object.
2098
+ *
2099
+ * @remarks
2100
+ * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys
2101
+ * (`toString`, `constructor`, …) are rejected. An own property that shadows a
2102
+ * prototype name is accepted.
2103
+ *
2104
+ * @example
2105
+ * ```ts
2106
+ * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const
2107
+ * const isColorKey = keyOf(COLORS)
2108
+ * isColorKey('red') // true
2109
+ * isColorKey('purple') // false
2110
+ * isColorKey('toString') // false — inherited, not an own key
2111
+ * ```
2112
+ */
2113
+ export declare function keyOf<const O extends Readonly<Record<PropertyKey, unknown>>>(value: O): Guard<keyof O>;
2114
+
2115
+ /**
2116
+ * Defer guard creation until first use by calling `thunk()` on every
2117
+ * invocation.
2118
+ *
2119
+ * @remarks
2120
+ * `thunk` is called on every guard call, not cached — this lets it close over a
2121
+ * binding assigned *after* `lazyOf` is called, the primary use case for
2122
+ * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
2123
+ * it resolves to) is contained and reported as a non-match.
2124
+ *
2125
+ * A recursive guard built this way has no cycle/depth detection: a cyclic or
2126
+ * pathologically deep input is stack-bounded — the overflow is contained and the
2127
+ * guard returns `false` rather than throwing, but it is not validated correctly
2128
+ * past that bound.
2129
+ *
2130
+ * @example
2131
+ * ```ts
2132
+ * type Tree = { value: number; children: Tree[] }
2133
+ * let isTree: Guard<Tree>
2134
+ * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })
2135
+ * ```
2136
+ */
2137
+ export declare function lazyOf<T>(thunk: () => Guard<T>): Guard<T>;
2138
+
2139
+ /**
2140
+ * Build a guard that accepts values identical (via `Object.is`) to one of the
2141
+ * provided literal primitives.
2142
+ *
2143
+ * @example
2144
+ * ```ts
2145
+ * const isRole = literalOf('admin', 'member', 'guest')
2146
+ * isRole('admin') // true
2147
+ * isRole('owner') // false
2148
+ * ```
2149
+ */
2150
+ export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(...literals: Literals): Guard<Literals[number]>;
2151
+
2152
+ /** A literal shape — accepts exactly one of a fixed set of primitive values. */
2153
+ export declare interface LiteralShape<T extends readonly (string | number | boolean)[] = readonly (string | number | boolean)[]> {
2154
+ readonly type: 'literal';
2155
+ readonly values: T;
2156
+ readonly description?: string;
2157
+ }
2158
+
2159
+ /**
2160
+ * Build a literal shape from a fixed set of primitive values.
2161
+ *
2162
+ * @param values - The permitted literals
2163
+ * @param options - Optional `description`
2164
+ * @returns A literal shape whose `Infer` is the union of `values`
2165
+ *
2166
+ * @example
2167
+ * ```ts
2168
+ * const role = literalShape(['admin', 'member', 'guest'])
2169
+ * // Infer<typeof role> = 'admin' | 'member' | 'guest'
2170
+ *
2171
+ * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
2172
+ * ```
2173
+ */
2174
+ export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<T>;
2175
+
2176
+ /** Options for {@link LiteralShape} (via `literalShape`). */
2177
+ export declare interface LiteralShapeOptions {
2178
+ readonly description?: string;
2179
+ }
2180
+
2181
+ /**
2182
+ * Build a guard that accepts `Map` instances where every key satisfies
2183
+ * `keyGuard` and every value satisfies `valueGuard`.
2184
+ *
2185
+ * @example
2186
+ * ```ts
2187
+ * const isStringNumberMap = mapOf(isString, isNumber)
2188
+ * isStringNumberMap(new Map([['a', 1]])) // true
2189
+ * isStringNumberMap(new Map([[1, 'a']])) // false
2190
+ * ```
2191
+ */
2192
+ export declare function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<ReadonlyMap<K, V>>;
2193
+
2194
+ export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard<ReadonlyMap<unknown, unknown>>;
2195
+
2196
+ /**
2197
+ * Build a guard that accepts strings matching a regular expression.
2198
+ *
2199
+ * @example
2200
+ * ```ts
2201
+ * const isHex = matchOf(/^[0-9a-f]+$/)
2202
+ * isHex('1a2f') // true
2203
+ * isHex('xyz') // false
2204
+ * ```
2205
+ */
2206
+ export declare function matchOf(pattern: RegExp): Guard<string>;
2207
+
2208
+ /**
2209
+ * Negate a guard or predicate — passes when `guard` returns `false`.
2210
+ *
2211
+ * @remarks
2212
+ * Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use
2213
+ * {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.
2214
+ *
2215
+ * @example
2216
+ * ```ts
2217
+ * const isNotNull = notOf(isNull)
2218
+ * ```
2219
+ */
2220
+ export declare function notOf(guard: (value: unknown) => boolean): Guard<unknown>;
2221
+
2222
+ /**
2223
+ * Extend a guard to also allow `null`.
2224
+ *
2225
+ * @example
2226
+ * ```ts
2227
+ * const isNullableString = nullableOf(isString)
2228
+ * isNullableString('hi') // true
2229
+ * isNullableString(null) // true
2230
+ * isNullableString(42) // false
2231
+ * ```
2232
+ */
2233
+ export declare function nullableOf<T>(guard: Guard<T>): Guard<T | null>;
2234
+
2235
+ /** A nullable wrapper — the inner shape may be `null`. */
2236
+ export declare interface NullableShape<S extends ContractShape = ContractShape> {
2237
+ readonly type: 'nullable';
2238
+ readonly inner: S;
2239
+ }
2240
+
2241
+ /**
2242
+ * Wrap a shape so it may be `null`.
2243
+ *
2244
+ * @param inner - The wrapped shape
2245
+ * @returns A nullable shape
2246
+ *
2247
+ * @example
2248
+ * ```ts
2249
+ * const bio = nullableShape(stringShape())
2250
+ * // Infer<typeof bio> = string | null
2251
+ * ```
2252
+ */
2253
+ export declare function nullableShape<S extends ContractShape>(inner: S): NullableShape<S>;
2254
+
2255
+ /** A null shape — accepts only `null`. */
2256
+ export declare interface NullShape {
2257
+ readonly type: 'null';
2258
+ readonly description?: string;
2259
+ }
2260
+
2261
+ /**
2262
+ * Build a {@link NullShape}.
2263
+ *
2264
+ * @param options - Optional `description`
2265
+ * @returns A null shape
2266
+ *
2267
+ * @example
2268
+ * ```ts
2269
+ * const empty = nullShape()
2270
+ * ```
2271
+ */
2272
+ export declare function nullShape(options?: NullShapeOptions): NullShape;
2273
+
2274
+ /** Options for {@link NullShape} (via `nullShape`). */
2275
+ export declare interface NullShapeOptions {
2276
+ readonly description?: string;
2277
+ }
2278
+
2279
+ /** A numeric shape with optional bounds; `integer` restricts to whole numbers. */
2280
+ export declare interface NumberShape {
2281
+ readonly type: 'number';
2282
+ readonly min?: number;
2283
+ readonly max?: number;
2284
+ readonly integer?: boolean;
2285
+ readonly description?: string;
2286
+ }
2287
+
2288
+ /**
2289
+ * Build a numeric {@link NumberShape}.
2290
+ *
2291
+ * @param options - Optional bounds (`min` / `max`), `integer`, and `description`
2292
+ * @returns A number shape
2293
+ *
2294
+ * @example
2295
+ * ```ts
2296
+ * const age = numberShape({ min: 0, max: 120 })
2297
+ * ```
2298
+ */
2299
+ export declare function numberShape(options?: NumberShapeOptions): NumberShape;
2300
+
2301
+ /** Options for {@link NumberShape} (via `numberShape` / `integerShape`). */
2302
+ export declare interface NumberShapeOptions {
2303
+ readonly min?: number;
2304
+ readonly max?: number;
2305
+ readonly integer?: boolean;
2306
+ readonly description?: string;
2307
+ }
2308
+
2309
+ /**
2310
+ * An object shape — a map of property names to child shapes.
2311
+ *
2312
+ * @remarks
2313
+ * A property whose shape is an {@link OptionalShape} may be absent; all others
2314
+ * are required. `additionalProperties` controls unknown keys: `undefined` /
2315
+ * `false` rejects them (closed), `true` accepts them as-is, a `ContractShape`
2316
+ * validates them.
2317
+ */
2318
+ export declare interface ObjectShape<P extends Readonly<Record<string, ContractShape>> = Readonly<Record<string, ContractShape>>, A extends boolean | ContractShape = boolean | ContractShape> {
2319
+ readonly type: 'object';
2320
+ readonly properties: P;
2321
+ readonly additionalProperties?: A;
2322
+ readonly description?: string;
2323
+ }
2324
+
2325
+ /**
2326
+ * Build an {@link ObjectShape} from a property map.
2327
+ *
2328
+ * @remarks
2329
+ * Wrap any property in {@link optionalShape} to allow its absence. By default
2330
+ * the compiled guard rejects unknown keys; pass `additionalProperties` to open
2331
+ * the object.
2332
+ *
2333
+ * @param properties - Map of property names to child shapes
2334
+ * @param options - Optional `additionalProperties` and `description`
2335
+ * @returns An object shape
2336
+ *
2337
+ * @example
2338
+ * ```ts
2339
+ * const user = objectShape({
2340
+ * name: stringShape({ min: 1 }),
2341
+ * age: integerShape({ min: 0, max: 120 }),
2342
+ * bio: optionalShape(stringShape()),
2343
+ * })
2344
+ * ```
2345
+ */
2346
+ export declare function objectShape<P extends Readonly<Record<string, ContractShape>>, const A extends boolean | ContractShape = false>(properties: P, options?: ObjectShapeOptions<A>): ObjectShape<P, A>;
2347
+
2348
+ /** Options for {@link ObjectShape} (via `objectShape`). */
2349
+ export declare interface ObjectShapeOptions<A extends boolean | ContractShape = boolean | ContractShape> {
2350
+ readonly additionalProperties?: A;
2351
+ readonly description?: string;
2352
+ }
2353
+
2354
+ /**
2355
+ * Build a new guard shape by removing the listed keys — the structural
2356
+ * equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.
2357
+ *
2358
+ * @example
2359
+ * ```ts
2360
+ * const full = { name: isString, age: isNumber, role: isString }
2361
+ * const isPublic = recordOf(omitOf(full, ['role']))
2362
+ * isPublic({ name: 'Ada', age: 36 }) // true
2363
+ * ```
2364
+ */
2365
+ export declare function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, keys: K): Omit<S, K[number]>;
2366
+
2367
+ /**
2368
+ * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
2369
+ *
2370
+ * @remarks
2371
+ * Unlike {@link unionShape} (`anyOf` — at least one variant matches),
2372
+ * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:
2373
+ *
2374
+ * - **Guard**: accepts the value only when exactly one variant's guard
2375
+ * accepts it. A value matching two-or-more variants — which would violate
2376
+ * the emitted `oneOf` schema — is rejected, even though it would pass
2377
+ * {@link unionShape}'s guard.
2378
+ * - **Parser**: judged on the RAW input's guard matches only, with NO
2379
+ * coercion fallback for an ambiguous input. When exactly one variant's
2380
+ * guard accepts the raw value, that variant's parser runs. Zero matches or
2381
+ * two-or-more matches both parse to `undefined` — a value ambiguous
2382
+ * between variants has no well-defined coercion target.
2383
+ *
2384
+ * Prefer {@link unionShape} when a value may legitimately satisfy more than
2385
+ * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer
2386
+ * `oneOfShape` when overlap between variants indicates malformed input that
2387
+ * must be rejected.
2388
+ *
2389
+ * @param variants - The candidate shapes
2390
+ * @returns A union shape with `mode: 'oneOf'`
2391
+ *
2392
+ * @example
2393
+ * ```ts
2394
+ * const id = oneOfShape(numberShape(), integerShape())
2395
+ * // 3 fails — matches both numberShape and integerShape
2396
+ * // 3.5 passes — matches numberShape only
2397
+ * ```
2398
+ */
2399
+ export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
2400
+
2401
+ /**
2402
+ * Like {@link FromGuards}, but every key listed in `K` becomes a true optional
2403
+ * member (`?`) rather than a required key widened with `| undefined`.
2404
+ *
2405
+ * @remarks
2406
+ * A key present in `K` may be omitted entirely; if present, its value must
2407
+ * still satisfy the key's guard — a present key holding `undefined` is not
2408
+ * accepted.
2409
+ *
2410
+ * @typeParam S - The full guard shape
2411
+ * @typeParam K - Tuple of keys to make optional
2412
+ */
2413
+ export declare type OptionalFromGuards<S extends GuardsShape, K extends ReadonlyArray<keyof S>> = Readonly<{
2414
+ [P in Exclude<keyof S, K[number]>]: FromGuards<S>[P];
2415
+ } & {
2416
+ [P in Extract<keyof S, K[number]>]?: FromGuards<S>[P];
2417
+ }>;
2418
+
2419
+ /**
2420
+ * Extend a guard to also allow `undefined` — the optional counterpart of
2421
+ * {@link nullableOf}.
2422
+ *
2423
+ * @example
2424
+ * ```ts
2425
+ * const isOptionalString = optionalOf(isString)
2426
+ * isOptionalString('hi') // true
2427
+ * isOptionalString(undefined) // true
2428
+ * isOptionalString(null) // false
2429
+ * ```
2430
+ */
2431
+ export declare function optionalOf<T>(guard: Guard<T>): Guard<T | undefined>;
2432
+
2433
+ /** An optional wrapper — the inner shape may be absent (`undefined`). */
2434
+ export declare interface OptionalShape<S extends ContractShape = ContractShape> {
2435
+ readonly type: 'optional';
2436
+ readonly inner: S;
2437
+ }
2438
+
2439
+ /**
2440
+ * Wrap a shape so it may be absent (`undefined`).
2441
+ *
2442
+ * @remarks
2443
+ * As an {@link objectShape} property, the field becomes a true optional property
2444
+ * in the inferred type.
2445
+ *
2446
+ * @param inner - The wrapped shape
2447
+ * @returns An optional shape
2448
+ */
2449
+ export declare function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S>;
2450
+
2451
+ /**
2452
+ * Combine two guards with logical OR — passes when at least one passes. For more
2453
+ * than two variants prefer {@link unionOf}.
2454
+ *
2455
+ * @example
2456
+ * ```ts
2457
+ * const isStringOrNumber = orOf(isString, isNumber)
2458
+ * ```
2459
+ */
2460
+ export declare function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B>;
2461
+
2462
+ export declare function orOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
2463
+
2464
+ /**
2465
+ * Parse an unknown value to an array — the input reference, never cloned —
2466
+ * optionally guarding every element.
2467
+ *
2468
+ * @remarks
2469
+ * Without a `guard`, element types are NOT verified; let `T` default to
2470
+ * `unknown` rather than asserting a specific element type.
2471
+ *
2472
+ * @param value - The value to parse
2473
+ * @param guard - Optional element guard
2474
+ * @returns The array, or `undefined`
2475
+ *
2476
+ * @example
2477
+ * ```ts
2478
+ * parseArray([1, 2]) // [1, 2]
2479
+ * parseArray([1, 'x'], isNumber) // undefined
2480
+ * ```
2481
+ */
2482
+ export declare function parseArray<T = unknown>(value: unknown, guard?: Guard<T>): readonly T[] | undefined;
2483
+
2484
+ /**
2485
+ * Read and parse an array field from a record by key or nested key path,
2486
+ * optionally guarding elements.
2487
+ *
2488
+ * @param record - The source record
2489
+ * @param path - A property key, or a key path descending into nested objects
2490
+ * @param guard - Optional element guard
2491
+ * @returns An array, or `undefined`
2492
+ *
2493
+ * @example
2494
+ * ```ts
2495
+ * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]
2496
+ * parseArrayField({}, 'tags') // undefined
2497
+ * ```
2498
+ */
2499
+ export declare function parseArrayField<T = unknown>(record: Record<string, unknown>, path: FieldPath, guard?: Guard<T>): readonly T[] | undefined;
2500
+
2501
+ /**
2502
+ * Parse an unknown value to a boolean.
2503
+ *
2504
+ * @remarks
2505
+ * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /
2506
+ * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything
2507
+ * else → `undefined`.
2508
+ *
2509
+ * @param value - The value to parse
2510
+ * @returns A boolean, or `undefined`
2511
+ *
2512
+ * @example
2513
+ * ```ts
2514
+ * parseBoolean(true) // true
2515
+ * parseBoolean('1') // true
2516
+ * parseBoolean('nope') // undefined
2517
+ * ```
2518
+ */
2519
+ export declare function parseBoolean(value: unknown): boolean | undefined;
2520
+
2521
+ /**
2522
+ * Read and parse a boolean field from a record by key or nested key path.
2523
+ *
2524
+ * @param record - The source record
2525
+ * @param path - A property key, or a key path descending into nested objects
2526
+ * @returns A boolean, or `undefined`
2527
+ *
2528
+ * @example
2529
+ * ```ts
2530
+ * parseBooleanField({ on: 'true' }, 'on') // true
2531
+ * parseBooleanField({}, 'on') // undefined
2532
+ * ```
2533
+ */
2534
+ export declare function parseBooleanField(record: Record<string, unknown>, path: FieldPath): boolean | undefined;
2535
+
2536
+ /**
2537
+ * Parse an unknown value as one of the allowed literal primitives.
2538
+ *
2539
+ * @remarks
2540
+ * Pairs with {@link literalOf} — both match by `Object.is`, so the
2541
+ * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
2542
+ * (string, number, or boolean), not only strings. Matching is identity, never
2543
+ * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
2544
+ *
2545
+ * @param value - The value to parse
2546
+ * @param allowed - The permitted literal values
2547
+ * @returns The matched literal (by identity), or `undefined`
2548
+ *
2549
+ * @example
2550
+ * ```ts
2551
+ * parseEnum('b', ['a', 'b', 'c']) // 'b'
2552
+ * parseEnum('z', ['a', 'b', 'c']) // undefined
2553
+ * ```
2554
+ */
2555
+ export declare function parseEnum<const T extends string | number | boolean>(value: unknown, allowed: readonly T[]): T | undefined;
2556
+
2557
+ /**
2558
+ * Read and parse an enum field from a record by key or nested key path.
2559
+ *
2560
+ * @param record - The source record
2561
+ * @param path - A property key, or a key path descending into nested objects
2562
+ * @param allowed - The permitted literal values
2563
+ * @returns The matched literal, or `undefined`
2564
+ */
2565
+ export declare function parseEnumField<const T extends string | number | boolean>(record: Record<string, unknown>, path: FieldPath, allowed: readonly T[]): T | undefined;
2566
+
2567
+ /**
2568
+ * Parse an unknown value to a finite integer.
2569
+ *
2570
+ * @remarks
2571
+ * Accepts whatever {@link parseNumber} accepts, then requires the result to have
2572
+ * no fractional part. `3.14` / `'3.14'` → `undefined`.
2573
+ *
2574
+ * @param value - The value to parse
2575
+ * @returns A finite integer, or `undefined`
2576
+ *
2577
+ * @example
2578
+ * ```ts
2579
+ * parseInteger(42) // 42
2580
+ * parseInteger(3.14) // undefined
2581
+ * ```
2582
+ */
2583
+ export declare function parseInteger(value: unknown): number | undefined;
2584
+
2585
+ /**
2586
+ * Read and parse a finite-integer field from a record by key or nested key path.
2587
+ *
2588
+ * @param record - The source record
2589
+ * @param path - A property key, or a key path descending into nested objects
2590
+ * @returns A finite integer, or `undefined`
2591
+ */
2592
+ export declare function parseIntegerField(record: Record<string, unknown>, path: FieldPath): number | undefined;
2593
+
2594
+ /**
2595
+ * Parse a JSON string, returning `undefined` instead of throwing.
2596
+ *
2597
+ * @remarks
2598
+ * The safe boundary for untrusted JSON text: a malformed string yields
2599
+ * `undefined`, never an exception. Returns `unknown` — a successful parse proves
2600
+ * nothing about shape, so narrow the result with a guard (or use
2601
+ * {@link parseJSONAs}). A large document is not walked here; parsing is shallow
2602
+ * and lazy validation is the caller's to compose.
2603
+ *
2604
+ * @param value - The JSON string to parse
2605
+ * @returns The parsed value, or `undefined` when `value` is not valid JSON
2606
+ */
2607
+ export declare function parseJSON(value: string): unknown;
2608
+
2609
+ /**
2610
+ * Parse a JSON string and validate the result against a guard.
2611
+ *
2612
+ * @remarks
2613
+ * The lazy, safe path from an untrusted string to a typed `T`: parse, then check
2614
+ * the parsed value with the guard you bring — typically one composed from the
2615
+ * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is
2616
+ * validated, so a large document is never walked in full unless the guard does.
2617
+ *
2618
+ * @param value - The JSON string to parse
2619
+ * @param guard - The guard for the expected shape
2620
+ * @returns The parsed value when it satisfies `guard`, otherwise `undefined`
2621
+ *
2622
+ * @example
2623
+ * ```ts
2624
+ * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })
2625
+ * parseJSONAs('{"host":"localhost","tags":["a"]}', isConfig) // { host: 'localhost', tags: ['a'] }
2626
+ * parseJSONAs('{"host":"localhost"}', isConfig) // undefined — guard fails
2627
+ * parseJSONAs('not json', isConfig) // undefined — never throws
2628
+ * ```
2629
+ */
2630
+ export declare function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined;
2631
+
2632
+ /**
2633
+ * Parse an unknown value to a cycle-safe JSON value — the input reference,
2634
+ * never cloned.
2635
+ *
2636
+ * @remarks
2637
+ * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it
2638
+ * walks the entire tree via {@link isJSONValue} rather than checking only the
2639
+ * top-level shape. That walk is cycle-safe and total (never throws) because
2640
+ * `isJSONValue` runs its own probe inside a guard, so an adversarial
2641
+ * structure (a cycle, a hostile getter) yields `undefined` instead of hanging
2642
+ * or throwing.
2643
+ *
2644
+ * @param value - The value to parse
2645
+ * @returns The value, or `undefined` when it is not a valid JSON value
2646
+ *
2647
+ * @example
2648
+ * ```ts
2649
+ * parseJSONValue({ a: 1 }) // { a: 1 }
2650
+ * parseJSONValue(Number.NaN) // undefined
2651
+ * ```
2652
+ */
2653
+ export declare function parseJSONValue(value: unknown): JSONValue | undefined;
2654
+
2655
+ /**
2656
+ * Read and parse a JSON-value field from a record by key or nested key path.
2657
+ *
2658
+ * @remarks
2659
+ * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that
2660
+ * function's remarks for why this differs from the shallow
2661
+ * {@link parseRecordField} / {@link parseArrayField}.
2662
+ *
2663
+ * @param record - The source record
2664
+ * @param path - A property key, or a key path descending into nested objects
2665
+ * @returns The value, or `undefined`
2666
+ *
2667
+ * @example
2668
+ * ```ts
2669
+ * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }
2670
+ * parseJSONValueField({}, 'data') // undefined
2671
+ * ```
2672
+ */
2673
+ export declare function parseJSONValueField(record: Record<string, unknown>, path: FieldPath): JSONValue | undefined;
2674
+
2675
+ /**
2676
+ * Parse an unknown value to `null`.
2677
+ *
2678
+ * @remarks
2679
+ * A successful parse returns `null` itself — distinct from the `undefined`
2680
+ * failure sentinel every other parser in this file uses. Only `null` passes;
2681
+ * every other value (including `undefined`) → `undefined`.
2682
+ *
2683
+ * @param value - The value to parse
2684
+ * @returns `null` on a successful parse, or `undefined`
2685
+ *
2686
+ * @example
2687
+ * ```ts
2688
+ * parseNull(null) // null
2689
+ * parseNull(undefined) // undefined
2690
+ * ```
2691
+ */
2692
+ export declare function parseNull(value: unknown): null | undefined;
2693
+
2694
+ /**
2695
+ * Read and parse a `null` field from a record by key or nested key path.
2696
+ *
2697
+ * @remarks
2698
+ * A successful parse returns `null` itself — distinct from the `undefined`
2699
+ * failure sentinel, which also covers a missing field.
2700
+ *
2701
+ * @param record - The source record
2702
+ * @param path - A property key, or a key path descending into nested objects
2703
+ * @returns `null` on a successful parse, or `undefined`
2704
+ *
2705
+ * @example
2706
+ * ```ts
2707
+ * parseNullField({ value: null }, 'value') // null
2708
+ * parseNullField({}, 'value') // undefined
2709
+ * ```
2710
+ */
2711
+ export declare function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined;
2712
+
2713
+ /**
2714
+ * Parse an unknown value to a finite number.
2715
+ *
2716
+ * @remarks
2717
+ * A finite number is returned unchanged; a non-blank numeric string is parsed
2718
+ * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every
2719
+ * other type → `undefined`.
2720
+ *
2721
+ * @param value - The value to parse
2722
+ * @returns A finite number, or `undefined`
2723
+ *
2724
+ * @example
2725
+ * ```ts
2726
+ * parseNumber(42) // 42
2727
+ * parseNumber('42') // 42
2728
+ * parseNumber('abc') // undefined
2729
+ * ```
2730
+ */
2731
+ export declare function parseNumber(value: unknown): number | undefined;
2732
+
2733
+ /**
2734
+ * Read and parse a finite-number field from a record by key or nested key path.
2735
+ *
2736
+ * @param record - The source record
2737
+ * @param path - A property key, or a key path descending into nested objects
2738
+ * @returns A finite number, or `undefined`
2739
+ *
2740
+ * @example
2741
+ * ```ts
2742
+ * parseNumberField({ age: '42' }, 'age') // 42
2743
+ * parseNumberField({}, 'age') // undefined
2744
+ * ```
2745
+ */
2746
+ export declare function parseNumberField(record: Record<string, unknown>, path: FieldPath): number | undefined;
2747
+
2748
+ /**
2749
+ * A parser: coerces an unknown value to `T`, or returns `undefined`.
2750
+ *
2751
+ * @remarks
2752
+ * The runtime parallel of {@link Guard}. A parser pairs soundly with the guard
2753
+ * for its output type: a guard-valid input is returned unchanged, and every
2754
+ * non-`undefined` output satisfies that guard.
2755
+ */
2756
+ export declare type Parser<T> = (value: unknown) => T | undefined;
2757
+
2758
+ /**
2759
+ * Parse an unknown value to a plain record — the input reference, never cloned.
2760
+ *
2761
+ * @param value - The value to parse
2762
+ * @returns The record, or `undefined`
2763
+ */
2764
+ export declare function parseRecord(value: unknown): Record<string, unknown> | undefined;
2765
+
2766
+ /**
2767
+ * Read and parse a nested record field from a record by key or nested key path.
2768
+ *
2769
+ * @param record - The source record
2770
+ * @param path - A property key, or a key path descending into nested objects
2771
+ * @returns A plain record, or `undefined`
2772
+ */
2773
+ export declare function parseRecordField(record: Record<string, unknown>, path: FieldPath): Record<string, unknown> | undefined;
2774
+
2775
+ /**
2776
+ * Parse an unknown value to a string.
2777
+ *
2778
+ * @remarks
2779
+ * A string is returned unchanged; a finite number is coerced to its decimal
2780
+ * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.
2781
+ *
2782
+ * @param value - The value to parse
2783
+ * @returns A string, or `undefined`
2784
+ *
2785
+ * @example
2786
+ * ```ts
2787
+ * parseString('hi') // 'hi'
2788
+ * parseString(42) // '42'
2789
+ * parseString(true) // undefined
2790
+ * ```
2791
+ */
2792
+ export declare function parseString(value: unknown): string | undefined;
2793
+
2794
+ /**
2795
+ * Read and parse a string field from a record by key or nested key path.
2796
+ *
2797
+ * @param record - The source record
2798
+ * @param path - A property key, or a key path descending into nested objects
2799
+ * @returns A string, or `undefined`
2800
+ */
2801
+ export declare function parseStringField(record: Record<string, unknown>, path: FieldPath): string | undefined;
2802
+
2803
+ /**
2804
+ * Build a new guard shape by keeping only the listed keys — the structural
2805
+ * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.
2806
+ *
2807
+ * @example
2808
+ * ```ts
2809
+ * const full = { name: isString, age: isNumber, role: isString }
2810
+ * const isName = recordOf(pickOf(full, ['name']))
2811
+ * isName({ name: 'Ada' }) // true
2812
+ * ```
2813
+ */
2814
+ export declare function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, keys: K): Pick<S, K[number]>;
2815
+
2816
+ /**
2817
+ * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
2818
+ * `received` field.
2819
+ *
2820
+ * @remarks
2821
+ * A primitive renders as its literal: a string is `JSON.stringify`-escaped and
2822
+ * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when
2823
+ * clipped); a number / boolean / bigint / symbol renders via `String`; `null`
2824
+ * and `undefined` render as their own name. Everything else — a plain object,
2825
+ * an array, a function, a class instance, a `Map` — is NEVER traversed or
2826
+ * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),
2827
+ * so a hostile or enormous structure can never blow up the preview.
2828
+ *
2829
+ * @param value - The value to preview
2830
+ * @returns A short descriptive string, always safe to embed in a diagnostic
2831
+ *
2832
+ * @example
2833
+ * ```ts
2834
+ * preview('hi') // '"hi"'
2835
+ * preview(42) // '42'
2836
+ * preview(null) // 'null'
2837
+ * preview({ a: 1 }) // 'object'
2838
+ * preview([1, 2, 3]) // 'object'
2839
+ * ```
2840
+ */
2841
+ export declare function preview(value: unknown): string;
2842
+
2843
+ /**
2844
+ * The maximum character length of a {@link preview}-rendered string, frozen.
2845
+ *
2846
+ * @remarks
2847
+ * A previewed string longer than this is clipped with a trailing `…` so a
2848
+ * {@link Fault}'s `received` field never embeds an unbounded amount of
2849
+ * untrusted text.
2850
+ */
2851
+ export declare const PREVIEW_LIMIT = 64;
2852
+
2853
+ /** A deterministic random source returning a value in `[0, 1)`. */
2854
+ export declare type RandomFunction = () => number;
2855
+
2856
+ /**
2857
+ * A raw JSON Schema passthrough — embeds a schema fragment directly.
2858
+ *
2859
+ * @remarks
2860
+ * For values the shape DSL can't express. The compiled guard accepts any value
2861
+ * and the parser passes it through unchanged; the schema is emitted verbatim.
2862
+ */
2863
+ export declare interface RawShape {
2864
+ readonly type: 'raw';
2865
+ readonly schema: JSONSchema;
2866
+ }
2867
+
2868
+ /**
2869
+ * Build a {@link RawShape} from a JSON Schema fragment.
2870
+ *
2871
+ * @remarks
2872
+ * For values the shape DSL can't express. The compiled guard accepts any value;
2873
+ * the parser passes it through; the schema is emitted verbatim.
2874
+ *
2875
+ * @param schema - The JSON Schema fragment to embed
2876
+ * @returns A raw shape
2877
+ *
2878
+ * @example
2879
+ * ```ts
2880
+ * const custom = rawShape({ type: 'string', format: 'uuid' })
2881
+ * ```
2882
+ */
2883
+ export declare function rawShape(schema: JSONSchema): RawShape;
2884
+
2885
+ export declare function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>;
2886
+
2887
+ export declare function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, optional: K): Guard<OptionalFromGuards<S, K>>;
2888
+
2889
+ export declare function recordOf<S extends GuardsShape>(shape: S, optional: true): Guard<Readonly<{
2890
+ [P in keyof S]?: FromGuards<S>[P];
2891
+ }>>;
2892
+
2893
+ /**
2894
+ * Build an open {@link ObjectShape} with no fixed properties — a dictionary.
2895
+ *
2896
+ * @remarks
2897
+ * Every value is validated against `values`; keys are unconstrained. Equivalent
2898
+ * to `objectShape({}, { additionalProperties: values })`.
2899
+ *
2900
+ * @param values - The shape every value must match
2901
+ * @param options - Optional `description`
2902
+ * @returns An open object shape
2903
+ *
2904
+ * @example
2905
+ * ```ts
2906
+ * const bindings = recordShape(numberShape()) // ~ Record<string, number>
2907
+ * ```
2908
+ */
2909
+ export declare function recordShape<S extends ContractShape>(values: S, options?: RecordShapeOptions): ObjectShape<Record<never, never>, S>;
2910
+
2911
+ /** Options for record shapes (via `recordShape`). */
2912
+ export declare interface RecordShapeOptions {
2913
+ readonly description?: string;
2914
+ }
2915
+
2916
+ /**
2917
+ * Resolve a (possibly nested) field value from a record by a key or key path.
2918
+ *
2919
+ * @remarks
2920
+ * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a
2921
+ * string array descends left-to-right through nested objects. Intermediates may
2922
+ * be any object — records, class instances, or arrays indexed by string. Returns
2923
+ * `undefined` the moment a segment is missing or lands on a non-object, so the
2924
+ * lookup is total — even against a hostile getter or Proxy trap that throws on
2925
+ * read, contained via {@link attempt} so the throw never escapes.
2926
+ *
2927
+ * @param record - The source record
2928
+ * @param path - A property key, or a key path descending into nested objects
2929
+ * @returns The resolved value, or `undefined`
2930
+ *
2931
+ * @example
2932
+ * ```ts
2933
+ * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'
2934
+ * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)
2935
+ * resolveField({ a: 1 }, ['a', 'b']) // undefined
2936
+ * ```
2937
+ */
2938
+ export declare function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown;
2939
+
2940
+ /** Discriminated union for operations that can succeed or fail without throwing. */
2941
+ export declare type Result<T, E = Error> = Success<T> | Failure<E>;
2942
+
2943
+ /**
2944
+ * Classify a list of sample values against the {@link SchemaFormat}
2945
+ * vocabulary, requiring unanimity.
2946
+ *
2947
+ * @remarks
2948
+ * A format is returned ONLY IF every value is a string AND every one maps to
2949
+ * the SAME {@link stringToFormat} result (including all mapping to
2950
+ * `undefined`, which itself returns `undefined` here). A single disagreeing
2951
+ * value, a non-string value, or an empty list all yield `undefined` — the
2952
+ * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})
2953
+ * relies on this unanimity so a slot with mixed string shapes emits a bare
2954
+ * `{ type: 'string' }` rather than an `anyOf` of formats.
2955
+ *
2956
+ * @param values - The sample values to classify
2957
+ * @returns The unanimous {@link SchemaFormat}, or `undefined`
2958
+ *
2959
+ * @example
2960
+ * ```ts
2961
+ * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'
2962
+ * samplesToFormat(['2024-01-01', 'not a date']) // undefined
2963
+ * samplesToFormat([]) // undefined
2964
+ * ```
2965
+ */
2966
+ export declare function samplesToFormat(values: readonly unknown[]): SchemaFormat | undefined;
2967
+
2968
+ /**
2969
+ * Infer a `JSONSchema` from a set of example values — the multi-example
2970
+ * counterpart of {@link valueToSchema} (e.g. inferring one schema from
2971
+ * several database rows).
2972
+ *
2973
+ * @remarks
2974
+ * An empty `samples` array infers the empty accept-anything schema `{}`.
2975
+ * When every sample is a plain record, properties/required are unified
2976
+ * per-key across all samples (see {@link inferRecordSamples}) — a key
2977
+ * required iff present and non-`undefined` in every sample. Otherwise the
2978
+ * slot is inferred via {@link inferSamples} (independent {@link valueToSchema}
2979
+ * per sample, unified with {@link unifySchemas} — the same de-duplication and
2980
+ * `anyOf` ordering {@link inferArray} applies to element schemas). `format`
2981
+ * and `enum` (both default `false`) opt a low-cardinality/unanimous-format
2982
+ * slot into the corresponding keyword — see {@link inferSamples} for the
2983
+ * precedence and the multi-sample format-disabling seam. `maxDepth` /
2984
+ * `maxProperties` are sanitized via {@link sanitizeBudget} the same way
2985
+ * {@link valueToSchema} sanitizes them — see there for why.
2986
+ *
2987
+ * @param samples - The example values to infer a schema from
2988
+ * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds
2989
+ * @returns The inferred `JSONSchema`
2990
+ *
2991
+ * @example
2992
+ * ```ts
2993
+ * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])
2994
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
2995
+ * // required: ['id'], additionalProperties: false }
2996
+ * samplesToSchema([]) // {}
2997
+ * ```
2998
+ */
2999
+ export declare function samplesToSchema(samples: readonly unknown[], options?: ValueToSchemaOptions): JSONSchema;
3000
+
3001
+ /**
3002
+ * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to
3003
+ * a finite non-negative integer, falling back to a default for anything else.
3004
+ *
3005
+ * @remarks
3006
+ * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or
3007
+ * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard
3008
+ * (`NaN <= 0` is `false`, so recursion never halts), and a negative
3009
+ * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key
3010
+ * instead of capping the list (a fractional value has a similarly undefined
3011
+ * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`
3012
+ * is `false` — since an unbounded budget is exactly the adversarial case the
3013
+ * caps exist to prevent. A valid finite non-negative integer passes through
3014
+ * unchanged.
3015
+ *
3016
+ * @param value - The candidate budget value
3017
+ * @param fallback - The default to use when `value` is not a finite
3018
+ * non-negative integer
3019
+ * @returns A finite non-negative integer budget
3020
+ *
3021
+ * @example
3022
+ * ```ts
3023
+ * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT
3024
+ * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT
3025
+ * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4
3026
+ * ```
3027
+ */
3028
+ export declare function sanitizeBudget(value: number | undefined, fallback: number): number;
3029
+
3030
+ /**
3031
+ * The closed set of string formats {@link stringToFormat} recognizes.
3032
+ *
3033
+ * @remarks
3034
+ * Lowercase spec literals, matching the JSON Schema `format` vocabulary for
3035
+ * the subset the inferers detect: `'date-time'` / `'date'` / `'time'` are
3036
+ * ISO-8601 (validity-checked via `Date`, not pattern-only), `'uuid'` matches
3037
+ * RFC-4122 hex layout, `'email'` and `'uri'` are pragmatic (not full-spec)
3038
+ * shape checks. See {@link FORMAT_PATTERNS}.
3039
+ */
3040
+ export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'email' | 'uri';
3041
+
3042
+ /**
3043
+ * Convert one JSON Schema node into a {@link ContractShape} — the recursion
3044
+ * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for
3045
+ * every child (`items`, `properties` values, `additionalProperties`,
3046
+ * `oneOf` / `anyOf` variants).
3047
+ *
3048
+ * @remarks
3049
+ * Total: never throws. Guards depth exhaustion, a non-record node (the
3050
+ * node's static `JSONSchema` type is not trusted at runtime), and a cyclic
3051
+ * re-encounter of `schema` — all three widen to {@link jsonShape}. The
3052
+ * ancestor set is added to and removed from around the WHOLE subtree
3053
+ * conversion (not permanently), so a DAG-shaped schema reached twice via two
3054
+ * different, non-cyclic paths does not false-positive as a cycle. The
3055
+ * subtree conversion itself runs inside {@link attempt}, so a hostile
3056
+ * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
3057
+ * — it degrades to {@link jsonShape} instead. A same-node re-conversion at
3058
+ * the same remaining `depth` is served from `memo` (guards a
3059
+ * shared-reference schema DAG against exponential blowup), mirroring
3060
+ * {@link inferObject} / {@link inferArray} (inferers.ts).
3061
+ *
3062
+ * @param schema - The schema node to convert
3063
+ * @param depth - Remaining descent budget
3064
+ * @param visited - The ancestor set guarding against cycles — recursion
3065
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3066
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3067
+ * supported usage
3068
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
3069
+ * recursion state owned by the {@link schemaToShape} entry point; passing
3070
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
3071
+ * supported usage
3072
+ * @returns The built shape for `schema`, or {@link jsonShape} on any failure
3073
+ *
3074
+ * @example
3075
+ * ```ts
3076
+ * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
3077
+ * // booleanShape()
3078
+ * ```
3079
+ */
3080
+ export declare function schemaNodeToShape(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>): ContractShape;
3081
+
3082
+ /**
3083
+ * Wrap a non-object `JSONSchema` root in a single-property object schema, so
3084
+ * an inferred primitive/array/union schema can flow into {@link schemaToParameters}
3085
+ * as an MCP-compatible `inputSchema`.
3086
+ *
3087
+ * @remarks
3088
+ * Total and deterministic. `schema.type === 'object'` passes through
3089
+ * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only
3090
+ * schema with no `type`, or the empty `{}`) is wrapped as a single required
3091
+ * `value` property: `{ type: 'object', properties: { value: schema },
3092
+ * required: ['value'], additionalProperties: false }`. Composition:
3093
+ * `schemaToParameters(schemaToObject(valueToSchema(payload)))`.
3094
+ *
3095
+ * @param schema - The schema to wrap
3096
+ * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema
3097
+ *
3098
+ * @example
3099
+ * ```ts
3100
+ * schemaToObject({ type: 'string' })
3101
+ * // { type: 'object', properties: { value: { type: 'string' } },
3102
+ * // required: ['value'], additionalProperties: false }
3103
+ * schemaToObject({ type: 'object', properties: {} }) // unchanged
3104
+ * ```
3105
+ */
3106
+ export declare function schemaToObject(schema: JSONSchema): JSONSchema;
3107
+
3108
+ /**
3109
+ * Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape
3110
+ * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never
3111
+ * an assertion (AGENTS §14).
3112
+ *
3113
+ * @remarks
3114
+ * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a
3115
+ * tool advertises its `parameters` as an open record. The two are structurally compatible but not
3116
+ * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema
3117
+ * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's
3118
+ * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open
3119
+ * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.
3120
+ *
3121
+ * @param schema - The compiled JSON Schema (a contract's `schema`)
3122
+ * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record
3123
+ *
3124
+ * @example
3125
+ * ```ts
3126
+ * import { createContract, schemaToParameters } from '@src/core'
3127
+ *
3128
+ * const contract = createContract(shape)
3129
+ * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises
3130
+ * ```
3131
+ */
3132
+ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<string, unknown>> | undefined;
3133
+
3134
+ /**
3135
+ * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}
3136
+ * — the inverse of {@link compileSchema}, and the validating sibling of
3137
+ * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).
3138
+ *
3139
+ * @remarks
3140
+ * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
3141
+ * outright hostile (throwing-getter Proxy) `schema` value all degrade to
3142
+ * {@link jsonShape} rather than escaping as an error, so
3143
+ * `createContract(schemaToShape(x))` is safe to call for any `x`. See
3144
+ * {@link buildShapeFromNode} for the exact per-keyword precedence.
3145
+ *
3146
+ * `format` and `pattern` are NEVER asserted by the compiled shape — `format`
3147
+ * is annotation-only (per the JSON Schema spec, it never narrows validation
3148
+ * on its own) and compiling an attacker-controlled `pattern` string into a
3149
+ * `RegExp` is a ReDoS vector; both keywords are read only far enough to be
3150
+ * ignored. Any node the walk cannot express — an empty `{}`, an
3151
+ * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
3152
+ * cyclic re-encounter — widens to {@link jsonShape} (accept any JSON), never
3153
+ * narrows: the round trip `compileGuard(schemaToShape(valueToSchema(v)))(v)`
3154
+ * holds for every `v`, with widening as the only source of looseness.
3155
+ *
3156
+ * @param schema - The JSON Schema value to convert
3157
+ * @returns The built {@link ContractShape}
3158
+ *
3159
+ * @example
3160
+ * ```ts
3161
+ * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }])
3162
+ * const contract = createContract(schemaToShape(schema))
3163
+ * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' }
3164
+ * contract.parse({ id: 'nope' }) // undefined
3165
+ * ```
3166
+ */
3167
+ export declare function schemaToShape(schema: JSONSchema): ContractShape;
3168
+
3169
+ /**
3170
+ * Build a deterministic pseudo-random source seeded from a single number.
3171
+ *
3172
+ * @remarks
3173
+ * A mulberry32 generator — the same seed always yields the same sequence, so
3174
+ * generated seed data is reproducible across runs. Used as the default random
3175
+ * source for {@link compileGenerator}, seeded from the wall clock so casual
3176
+ * callers still get varied output without passing a source themselves.
3177
+ *
3178
+ * @param seed - The seed for the sequence
3179
+ * @returns A {@link RandomFunction} returning values in `[0, 1)`
3180
+ *
3181
+ * @example
3182
+ * ```ts
3183
+ * const random = seededRandom(42)
3184
+ * random() // always the same first value for seed 42
3185
+ * ```
3186
+ */
3187
+ export declare function seededRandom(seed: number): RandomFunction;
3188
+
3189
+ /**
3190
+ * Build a guard that accepts `Set` instances whose every element satisfies
3191
+ * `elementGuard`.
3192
+ *
3193
+ * @example
3194
+ * ```ts
3195
+ * const isStringSet = setOf(isString)
3196
+ * isStringSet(new Set(['a', 'b'])) // true
3197
+ * isStringSet(new Set(['a', 1])) // false
3198
+ * ```
3199
+ */
3200
+ export declare function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>;
3201
+
3202
+ export declare function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>;
3203
+
3204
+ /**
3205
+ * Project a {@link ContractShape} to the {@link FaultKind} it describes.
3206
+ *
3207
+ * @remarks
3208
+ * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
3209
+ * `expected` field: most shapes map to their own `type` (`numberShape` maps to
3210
+ * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
3211
+ * `nullableShape` project through to their inner shape's kind, and `rawShape`
3212
+ * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
3213
+ *
3214
+ * @param shape - The shape to project
3215
+ * @returns The shape's {@link FaultKind}
3216
+ *
3217
+ * @example
3218
+ * ```ts
3219
+ * shapeToKind(stringShape()) // 'string'
3220
+ * shapeToKind(integerShape()) // 'integer'
3221
+ * shapeToKind(optionalShape(nullShape())) // 'null'
3222
+ * ```
3223
+ */
3224
+ export declare function shapeToKind(shape: ContractShape): FaultKind;
3225
+
3226
+ /**
3227
+ * Build a guard that accepts strings satisfying optional length and pattern
3228
+ * refinements — `min` / `max` length and a `pattern`.
3229
+ *
3230
+ * @remarks
3231
+ * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
3232
+ * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns
3233
+ * the bare {@link isString} guard (the unconstrained fast path), so an
3234
+ * unrefined string leaf pays no wrapping cost. The single source of the string
3235
+ * refinement shared by the compiled guard and parser (compilers.ts).
3236
+ *
3237
+ * @example
3238
+ * ```ts
3239
+ * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })
3240
+ * isSlug('hello-world') // true
3241
+ * isSlug('') // false — below min
3242
+ * isSlug('Hello') // false — pattern miss
3243
+ *
3244
+ * stringOf() // identical to isString
3245
+ * ```
3246
+ */
3247
+ export declare function stringOf(options?: {
3248
+ min?: number;
3249
+ max?: number;
3250
+ pattern?: RegExp;
3251
+ }): Guard<string>;
3252
+
3253
+ /** A string shape with optional length and pattern constraints. */
3254
+ export declare interface StringShape {
3255
+ readonly type: 'string';
3256
+ readonly min?: number;
3257
+ readonly max?: number;
3258
+ readonly pattern?: RegExp;
3259
+ readonly description?: string;
3260
+ }
3261
+
3262
+ /**
3263
+ * Build a string {@link StringShape}.
3264
+ *
3265
+ * @param options - Optional length (`min` / `max`), `pattern`, and `description`
3266
+ * @returns A string shape
3267
+ *
3268
+ * @example
3269
+ * ```ts
3270
+ * const name = stringShape({ min: 1, max: 80, description: 'Display name' })
3271
+ * ```
3272
+ */
3273
+ export declare function stringShape(options?: StringShapeOptions): StringShape;
3274
+
3275
+ /** Options for {@link StringShape} (via `stringShape`). */
3276
+ export declare interface StringShapeOptions {
3277
+ readonly min?: number;
3278
+ readonly max?: number;
3279
+ readonly pattern?: RegExp;
3280
+ readonly description?: string;
3281
+ }
3282
+
3283
+ /**
3284
+ * Classify a string against the {@link SchemaFormat} vocabulary.
3285
+ *
3286
+ * @remarks
3287
+ * Total, pure, and deterministic. Fixed precedence, most specific first:
3288
+ * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first
3289
+ * match wins. The `date-time` / `date` / `time` branches require BOTH a
3290
+ * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity
3291
+ * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.
3292
+ * Returns `undefined` when no format matches (including the empty string).
3293
+ *
3294
+ * @param value - The string to classify
3295
+ * @returns The matched {@link SchemaFormat}, or `undefined`
3296
+ *
3297
+ * @example
3298
+ * ```ts
3299
+ * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'
3300
+ * stringToFormat('2024-01-15') // 'date'
3301
+ * stringToFormat('2020-13-45') // undefined — invalid date
3302
+ * stringToFormat('ada@example.com') // 'email'
3303
+ * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset
3304
+ * stringToFormat('10:30:00+02:00') // 'time'
3305
+ * ```
3306
+ */
3307
+ export declare function stringToFormat(value: string): SchemaFormat | undefined;
3308
+
3309
+ /**
3310
+ * Discriminated success branch of a {@link Result}.
3311
+ *
3312
+ * @remarks
3313
+ * Used for operations that can succeed or fail without throwing.
3314
+ */
3315
+ export declare interface Success<T> {
3316
+ readonly success: true;
3317
+ readonly value: T;
3318
+ }
3319
+
3320
+ /**
3321
+ * Build a guard that passes when the base passes AND the projection of the value
3322
+ * satisfies the target guard. Still narrows to `T` (the base type) — the target
3323
+ * check is a validity constraint on a derived view, not a type transformation.
3324
+ *
3325
+ * @remarks
3326
+ * `project` is a plain `(value: T) => U`. Per §14 the returned guard never
3327
+ * throws: a throw from `project` is contained and reported as a non-match.
3328
+ * `target` is itself a Guard (already §14-bound), so it stays outside the
3329
+ * contained region. (Unlike the reference implementation, there is no
3330
+ * "curried projector" branch — a projection that legitimately returns a function
3331
+ * would be double-invoked under that scheme. Compose explicitly if you need it.)
3332
+ *
3333
+ * @example
3334
+ * ```ts
3335
+ * const isBounded = transformOf(
3336
+ * isString,
3337
+ * (s) => s.trim().length,
3338
+ * whereOf(isNumber, (n) => n >= 1 && n <= 50),
3339
+ * )
3340
+ * isBounded('hello') // true
3341
+ * isBounded('') // false
3342
+ * ```
3343
+ */
3344
+ export declare function transformOf<T, U>(base: Guard<T>, project: (value: T) => U, target: Guard<U>): Guard<T>;
3345
+
3346
+ export declare function transformOf<T>(base: Guard<T>, project: (value: T) => unknown, target: (value: unknown) => boolean): Guard<T>;
3347
+
3348
+ /** Map a tuple of element guards to a readonly tuple of their guarded types. */
3349
+ export declare type TupleFromGuards<Ts extends ReadonlyArray<Guard<unknown>>> = Readonly<{
3350
+ [K in keyof Ts]: GuardType<Ts[K]>;
3351
+ }>;
3352
+
3353
+ /**
3354
+ * Build a guard that accepts fixed-arity tuples, testing each index with the
3355
+ * corresponding guard.
3356
+ *
3357
+ * @example
3358
+ * ```ts
3359
+ * const isPair = tupleOf(isString, isNumber)
3360
+ * isPair(['hello', 42]) // true
3361
+ * isPair(['hello']) // false — wrong arity
3362
+ * ```
3363
+ */
3364
+ export declare function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<TupleFromGuards<Gs>>;
3365
+
3366
+ export declare function tupleOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<readonly unknown[]>;
3367
+
3368
+ /**
3369
+ * Unify a list of inferred `JSONSchema` fragments into one schema.
3370
+ *
3371
+ * @remarks
3372
+ * De-duplicates by {@link canonicalStringify}, then applies the one
3373
+ * special-case subsumption inference performs: a bare `{ type: 'integer' }`
3374
+ * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`
3375
+ * (an integer sample is also a valid `number` sample). A single surviving
3376
+ * distinct schema is returned directly; two or more are wrapped as
3377
+ * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
3378
+ * An empty input list returns the empty accept-anything schema `{}`.
3379
+ *
3380
+ * @param schemas - The schemas to unify
3381
+ * @returns The unified schema
3382
+ *
3383
+ * @example
3384
+ * ```ts
3385
+ * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }
3386
+ * unifySchemas([{ type: 'string' }, { type: 'boolean' }])
3387
+ * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }
3388
+ * ```
3389
+ */
3390
+ export declare function unifySchemas(schemas: readonly JSONSchema[]): JSONSchema;
3391
+
3392
+ /**
3393
+ * Build a guard that accepts values matching at least one of the provided
3394
+ * guards — the variadic form of {@link orOf}.
3395
+ *
3396
+ * @example
3397
+ * ```ts
3398
+ * const isStringOrBoolean = unionOf(isString, isBoolean)
3399
+ * ```
3400
+ */
3401
+ export declare function unionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<GuardType<Gs[number]>>;
3402
+
3403
+ export declare function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>;
3404
+
3405
+ /**
3406
+ * A union shape — accepts a value matching any one variant (first match wins).
3407
+ *
3408
+ * @remarks
3409
+ * `mode` selects the emitted JSON Schema keyword: `'anyOf'` (default) or
3410
+ * `'oneOf'`. Runtime behavior is identical.
3411
+ */
3412
+ export declare interface UnionShape<V extends readonly ContractShape[] = readonly ContractShape[]> {
3413
+ readonly type: 'union';
3414
+ readonly variants: V;
3415
+ readonly mode?: 'anyOf' | 'oneOf';
3416
+ readonly description?: string;
3417
+ }
3418
+
3419
+ /**
3420
+ * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
3421
+ *
3422
+ * @param variants - The candidate shapes; the first match wins at runtime
3423
+ * @returns A union shape whose `Infer` is the union of the variants
3424
+ *
3425
+ * @example
3426
+ * ```ts
3427
+ * const id = unionShape(stringShape(), integerShape())
3428
+ * // Infer<typeof id> = string | number
3429
+ * ```
3430
+ */
3431
+ export declare function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
3432
+
3433
+ /** Convert a union type to an intersection type. */
3434
+ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
3435
+
3436
+ /**
3437
+ * Validate that a {@link ContractShape} tree is well-formed — a pure recursive
3438
+ * prepass run before compilation.
3439
+ *
3440
+ * @remarks
3441
+ * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
3442
+ * throws a plain `Error` immediately rather than surfacing as a silently-wrong
3443
+ * guard, parser, schema, or generator later. Checks, recursively:
3444
+ *
3445
+ * - An {@link OptionalShape} is only legal as a direct object-property value —
3446
+ * `optionalShape` wrapping an array item, a union variant, another
3447
+ * optional/nullable's inner shape, `additionalProperties`, or the top-level
3448
+ * shape all throw. An object property IS the one legal placement: its value
3449
+ * is unwrapped to `.inner` before recursing, so `.inner` itself is validated
3450
+ * as a normal (non-optional-wrapping) shape.
3451
+ * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}
3452
+ * needs at least one value and rejects non-finite (`NaN` / `Infinity` /
3453
+ * `-Infinity`) number values.
3454
+ * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
3455
+ * needs `min <= max` when both are set.
3456
+ * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
3457
+ * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
3458
+ * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
3459
+ * continues into array items, object properties (and `additionalProperties`
3460
+ * when it is a shape), union variants, and optional/nullable inner shapes.
3461
+ *
3462
+ * @param shape - The shape to validate
3463
+ * @throws {Error} When the shape is malformed
3464
+ *
3465
+ * @example
3466
+ * ```ts
3467
+ * validateShape(stringShape({ min: 1, max: 10 })) // does not throw
3468
+ * validateShape(stringShape({ min: 10, max: 1 })) // throws
3469
+ * ```
3470
+ */
3471
+ export declare function validateShape(shape: ContractShape): void;
3472
+
3473
+ /**
3474
+ * Infer a `JSONSchema` for one unknown value — the reverse direction of
3475
+ * {@link compileSchema}.
3476
+ *
3477
+ * @remarks
3478
+ * Total: never throws, and is cycle/depth/breadth-bounded (see
3479
+ * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested
3480
+ * objects close to unknown keys (`additionalProperties: false`) by default;
3481
+ * pass `closed: false` to open them. `format` (default `false`) opts a
3482
+ * string/`Date` leaf into the `format` keyword. Structurally-equal inputs
3483
+ * infer byte-identical schemas (object keys and `anyOf` members are sorted).
3484
+ *
3485
+ * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'
3486
+ * }` — is structurally accepted by `schemaToParameters`, but MCP clients
3487
+ * expect an object-shaped `inputSchema`; wrap a non-object payload with
3488
+ * {@link schemaToObject} before advertising it as a tool's parameters.
3489
+ *
3490
+ * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a
3491
+ * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /
3492
+ * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,
3493
+ * fractional) — a hostile or malformed budget can never defeat the depth
3494
+ * guard or corrupt the sampled key/element list.
3495
+ *
3496
+ * @param value - The value to infer a schema from
3497
+ * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds
3498
+ * @returns The inferred `JSONSchema`
3499
+ *
3500
+ * @example
3501
+ * ```ts
3502
+ * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })
3503
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },
3504
+ * // tags: { type: 'array', items: { type: 'string' } } },
3505
+ * // required: ['id', 'name', 'tags'], additionalProperties: false }
3506
+ * ```
3507
+ */
3508
+ export declare function valueToSchema(value: unknown, options?: ValueToSchemaOptions): JSONSchema;
3509
+
3510
+ /**
3511
+ * Options for {@link valueToSchema} / {@link samplesToSchema}.
3512
+ *
3513
+ * @remarks
3514
+ * The reverse direction of {@link compileSchema}: instead of emitting a
3515
+ * `JSONSchema` from a developer-authored `ContractShape`, these bounds tame
3516
+ * inference from an unknown runtime value (or a set of example values), which
3517
+ * — unlike a shape tree — may be arbitrarily deep, wide, or cyclic.
3518
+ *
3519
+ * @remarks
3520
+ * `format` (default `false`) emits a `format` keyword on a string leaf whose
3521
+ * value(s) unanimously match one {@link SchemaFormat} via {@link stringToFormat}
3522
+ * / {@link samplesToFormat}. `enum` (default `false`, multi-sample paths only)
3523
+ * emits an `enum` keyword for a low-cardinality, repeated primitive slot
3524
+ * instead of a bare `type`.
3525
+ */
3526
+ export declare interface ValueToSchemaOptions {
3527
+ readonly maxDepth?: number;
3528
+ readonly maxProperties?: number;
3529
+ readonly closed?: boolean;
3530
+ readonly format?: boolean;
3531
+ readonly enum?: boolean;
3532
+ }
3533
+
3534
+ /**
3535
+ * Refine a base guard with an additional predicate that runs only when the base
3536
+ * passes.
3537
+ *
3538
+ * @remarks
3539
+ * The predicate receives a value already narrowed to `T`. When the predicate is
3540
+ * itself a type guard (`value is U`), the result narrows to `Guard<U>` — it
3541
+ * passes only when the value is genuinely a `U`, so the narrowing is sound. Per
3542
+ * §14 the returned guard never throws: if `predicate` throws, the throw is
3543
+ * contained and the guard reports a non-match.
3544
+ *
3545
+ * @example
3546
+ * ```ts
3547
+ * const isPositive = whereOf(isNumber, (n) => n > 0)
3548
+ * isPositive(5) // true
3549
+ * isPositive(-1) // false
3550
+ *
3551
+ * // A narrowing predicate refines the result type to Guard<5>
3552
+ * const isFive = whereOf(isNumber, (n): n is 5 => n === 5)
3553
+ * ```
3554
+ */
3555
+ export declare function whereOf<T, U extends T>(base: Guard<T>, predicate: (value: T) => value is U): Guard<U>;
3556
+
3557
+ export declare function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T>;
3558
+
3559
+ /** An async function accepting zero arguments and returning a `Promise`. */
3560
+ export declare type ZeroArgAsyncFunction = () => Promise<unknown>;
3561
+
3562
+ /** A function accepting zero arguments and returning `unknown`. */
3563
+ export declare type ZeroArgFunction = () => unknown;
3564
+
3565
+ export { }