/** * Collect one more member into a vocabulary that grows as a walk proceeds. * * @param members - The vocabulary to extend * @param value - The value to admit * * @example * ```ts * const seen = collectMembers([]) * admitMember(seen, 'a') * matchesMember(seen, 'a') // true * ``` */ export declare function admitMember(members: Set, value: unknown): void; /** * Record an object as entered on a traversal's active path. * * @param visited - The active-path set this traversal owns * @param value - The object being entered * * @example * ```ts * admitVisited(active, node) * ``` */ export declare function admitVisited(visited: WeakSet, value: object): void; /** * Combine two guards with logical AND — passes only when both pass. * * @remarks * Use {@link whereOf} when the right side refines an already-narrowed type; use * `andOf` to combine two independent guards. * * @example * ```ts * const isShortString = andOf(isString, isNonEmptyString) * ``` */ export declare function andOf(left: Guard, right: Guard): Guard; export declare function andOf(left: Guard, right: (value: T) => value is U): Guard; export declare function andOf(left: Guard, right: (value: T) => boolean): Guard; export declare function andOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard; /** An async function accepting any arguments and returning a `Promise`. */ export declare type AnyAsyncFunction = (...args: unknown[]) => Promise; /** * Any constructor signature that produces instances of `T`. * * @remarks * Uses `unknown[]` parameters to stay maximally assignable from specific * constructors without resorting to `any`. */ export declare type AnyConstructor = new (...args: unknown[]) => T; /** A function accepting any arguments and returning `unknown`. */ export declare type AnyFunction = (...args: unknown[]) => unknown; /** * Append every element of one array onto another, by index. * * @remarks * The sibling of {@link pathOf}, for the other shape the same defect takes. * `target[target.length] = ...source` and `[summary, ...rest]` both dispatch through * `Array.prototype[Symbol.iterator]`, and a caller-installed iterator that * yields one extra value writes the caller's text into a diagnostic this * package publishes as its own. Both operands here are arrays this package * built, and an indexed read of an own index property dispatches through * nothing. * * @param target - The array to extend in place * @param source - The elements to append, read by index * * @example * ```ts * appendEntries(faults, compileReporter(inner, raw, pathOf(path, key))) * ``` */ export declare function appendEntries(target: T[], source: readonly T[]): void; /** * Build a guard that accepts DENSE arrays whose every element satisfies * `elementGuard`. * * @remarks * Density is part of the contract, not an accident: the guard reads the array * through the shared reflected own-index lens {@link readArrayEntries}, which is * what makes it immune to caller-defined iteration and what `parseArray` reads * too. A SPARSE array is therefore refused outright — `[1, , 3]` fails even when * the element guard accepts `undefined` — because a hole is an absent own * property rather than a present `undefined`, and the two are different facts. * Pass `[1, undefined, 3]` when the middle slot is meant to exist. * * @example * ```ts * const isStringArray = arrayOf(isString) * isStringArray(['a', 'b']) // true * isStringArray(['a', 1]) // false * isStringArray(['a', , 'b']) // false — sparse * ``` */ export declare function arrayOf(elementGuard: Guard): Guard; export declare function arrayOf(elementGuard: (value: unknown) => boolean): Guard; /** * Owned result of reading one array through its reflected own-index lens. * * @remarks * {@link entries} is a frozen native array with actual holes: reading a hole * yields `undefined`, while own membership remains absent. A length-driven * consumer must first require {@link dense} or carry an independent work bound. */ export declare interface ArrayRead { /** Frozen native entries in index order, retaining sparse positions as holes. */ readonly entries: ReadonlyArray; /** Whether every index from zero through length minus one was reflected. */ readonly dense: boolean; } /** An array shape with an element shape and optional length bounds. */ export declare interface ArrayShape { readonly type: 'array'; readonly items: S; readonly min?: number; readonly max?: number; readonly description?: string; } /** * Build an {@link ArrayShape} from an element shape. * * @param items - The element shape * @param options - Optional length bounds and `description` * @returns An array shape * @throws {ContractError} When a present bound is not a non-negative safe integer * * @example * ```ts * const tags = arrayShape(stringShape(), { max: 10 }) * ``` */ export declare function arrayShape(items: S, options?: ArrayShapeOptions): ArrayShape; /** Options for {@link ArrayShape} (via `arrayShape`). */ export declare interface ArrayShapeOptions { readonly min?: number; readonly max?: number; readonly description?: string; } /** * Invoke a callback once and synchronously capture its exact outcome as a * {@link Result}. * * @remarks * The sanctioned never-throw boundary for the guards (AGENTS §14). The * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a * `boolean`. This converts a throwing callback into a `Failure` so the * surrounding guard can treat it as a non-match instead of propagating the * exception, written once and shared rather than copy-pasted as ad-hoc * `try`/`catch`. The return or thrown value is retained exactly and is never * inspected, coerced, cloned, frozen, or mutated. A returned Promise or * thenable is an ordinary successful value; later settlement is outside this * synchronous boundary. {@link isContractError} does not use this boundary and * is not an exception to it: it carries its own `try`/`catch` inside the class * body, because `errors.ts` cannot import this module without inverting the * dependency. The earlier claim here — that it was total BY CONSTRUCTION and had * nothing to contain — was false, and it is what justified deleting the * containment the committed baseline had. A guard whose totality rests on an * argument that nothing inside it can throw is one refactor away from throwing. * * @param callback - The callback to invoke with no arguments * @returns A `Success` carrying the exact return value, or a `Failure` carrying * the exact thrown value as `unknown` * * @example * ```ts * const outcome = attempt(() => predicate(value)) * return outcome.success && outcome.value * ``` */ export declare function attempt(callback: () => T): Result; /** Every fault an audit reports — the parse faults plus undeclared keys. */ export declare type AuditFault = Fault | ExtraFault; /** * A compiled strict-domain diagnostic — the shape of `compileAuditor` bound to * one shape. * * @remarks * The optional `path` is the prefix every fault this call reports is rooted at, * so a nested walk can name where it started. A contract's * {@link ContractInterface.audit} takes only the value, because no contract * consumer injects a root path; a function of this type is assignable to that * property, so one compiled function can serve both surfaces. */ export declare type AuditorFunction = (value: unknown, path?: readonly string[]) => readonly AuditFault[]; /** A boolean shape — accepts only `true` or `false`. */ export declare interface BooleanShape { readonly type: 'boolean'; readonly description?: string; } /** * Build a {@link BooleanShape}. * * @param options - Optional `description` * @returns A boolean shape * * @example * ```ts * const active = booleanShape({ description: 'Whether the record is active' }) * ``` */ export declare function booleanShape(options?: BooleanShapeOptions): BooleanShape; /** Options for {@link BooleanShape} (via `booleanShape`). */ export declare interface BooleanShapeOptions { readonly description?: string; } /** * Build a guard that accepts finite numbers within an inclusive `[min, max]` * range. * * @remarks * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` / * `±Infinity` are rejected before any comparison runs. An absent bound never * constrains that side. Reused for a number's own value AND, applied to a * `.length`, for string and array length refinements — the single source of the * bound logic shared by the compiled guard and parser (compilers.ts). * * @example * ```ts * const inRange = boundsOf(1, 5) * inRange(3) // true * inRange(0) // false — below min * inRange(6) // false — above max * * const atLeastTwo = boundsOf(2) * atLeastTwo(2) // true — unbounded above * ``` */ export declare function boundsOf(min?: number, max?: number): Guard; /** * Build an {@link ObjectShape} from a JSON Schema object node's `properties` / * `required` / `additionalProperties` keywords — the object-specialized branch * of {@link buildShapeFromNode}. * * @remarks * `properties` (when a record) contributes one child shape per own key, capped * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape} * unless it appears as a string entry of `required`. A property whose value is * not itself a record widens to {@link rawShape}. `additionalProperties`: * `false` closes the object; a record value recurses into it (`objectShape` * validates extras against that shape); anything else — `true`, absent, or * malformed — leaves the object OPEN (`true`), matching JSON Schema's own * absent-means-open default and the fact that {@link valueToSchema} / * {@link samplesToSchema} always emit the keyword explicitly, so an absent * value only arises from a hand-written schema. When `properties` has MORE * keys than {@link INFER_BREADTH_LIMIT}, the schema's own * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) — * a dropped key's value could otherwise fail a `false` or record-valued rest * shape it was never checked against — mirroring {@link inferObject}'s * partial-key handling in `inferers.ts`. The accumulator uses a * null-prototype record so a property literally named `__proto__` becomes an * own data key rather than mutating the prototype, mirroring * {@link inferObject} (inferers.ts). * * @param schema - The object schema node * @param depth - Remaining descent budget passed to child properties * @param visited - The ancestor set guarding against cycles — recursion * state owned by the {@link schemaToShape} entry point; passing a shared or * pre-populated `WeakSet` changes cycle-detection behavior and is not * supported usage * @param memo - A per-call `(schema node, remaining depth) → shape` cache — * recursion state owned by the {@link schemaToShape} entry point; passing * a shared or pre-populated `WeakMap` changes caching behavior and is not * supported usage * @param description - The node's already-extracted `description`, if any * @returns The built object shape * * @example * ```ts * buildObjectShape( * { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] }, * INFER_DEPTH_LIMIT, * new WeakSet(), * new WeakMap(), * undefined, * ) * // objectShape({ id: integerShape() }, { additionalProperties: true }) * ``` */ export declare function buildObjectShape(schema: JSONSchema, depth: number, visited: WeakSet, memo: WeakMap>, description: string | undefined): ContractShape; /** * Build one empty {@link SampleMemo} node. * * @remarks * The root a multi-sample walk starts from and the node every further row * prefix is grown into, built from the CAPTURED `WeakMap` and `Map` so a * replaced global cannot decide what a published schema is served from. One * memo belongs to one walk: {@link samplesToSchema} builds it at the door, and * a direct caller of {@link inferSamples} / {@link inferRecordSamples} builds a * fresh one per call. * * @returns An empty memo node with no recorded rows and no recorded schemas * * @example * ```ts * inferRecordSamples([{ id: 1 }], 32, 256, true, false, false, buildSampleMemo()) * ``` */ export declare function buildSampleMemo(): SampleMemo; /** * Build a {@link ContractShape} for one JSON Schema node — the recursive * spine of {@link schemaToShape}, shared with per-child recursion via * {@link schemaNodeToShape}. * * @remarks * Every keyword is read defensively (the node's static `JSONSchema` type is * NOT trusted at runtime — a caller-supplied node may be adversarial), so a * malformed keyword falls through to the next rule instead of throwing. * Precedence, top-down: * * 1. `enum` — an array with at least one string/number/boolean entry (finite * numbers only) becomes a {@link literalShape} over the filtered entries. * Non-primitive / non-finite entries are dropped; an empty result falls * through. * 2. `oneOf` — an array with at least one record entry becomes an * {@link oneOfShape} over the recursively-built variants, provided the * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the * limit, building a subset union would be strictly narrower than the * schema's full union (a value matching only a dropped variant would be * wrongly rejected), so the whole node widens to {@link rawShape} instead * of sampling a subset. * 3. `anyOf` — identically, via {@link unionShape}. * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` — * the matching primitive shape, with length/range bounds derived via * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node * additionally drops its bounds when they describe an EMPTY integer range * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShapeDepth` * rejects — so the result is always a valid shape. * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into * a record-valued `items` (widening to {@link rawShape} otherwise), with * bounds from `minItems` / `maxItems`. * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a * record-valued `properties` — delegates to {@link buildObjectShape}. * 7. Everything else — an empty schema, an unrecognized/absent `type`, or * exhausted depth/breadth — widens to * {@link rawShape}, whose guard accepts every defined value and whose * emitted schema is the same `{}` (plus `description`) the node carried. * This is the exact inverse of `{}`, JSON Schema's accept-anything schema, * and where the inferers themselves bottom out at their own limits. * * `format` and `pattern` are NEVER read into the compiled shape — `format` is * annotation-only and `pattern` compiling an attacker-supplied string into a * `RegExp` is a ReDoS vector. `description`, when a string, carries through to * the produced shape's `description` option. * * @param schema - The schema node to convert * @param depth - Remaining descent budget (0 halts recursion with `rawShape({})`) * @param visited - The ancestor set guarding against cycles — recursion * state owned by the {@link schemaToShape} entry point; passing a shared or * pre-populated `WeakSet` changes cycle-detection behavior and is not * supported usage * @param memo - A per-call `(schema node, remaining depth) → shape` cache * guarding against exponential re-conversion of a * shared-reference schema DAG — recursion state owned by the * {@link schemaToShape} entry point; passing a shared or * pre-populated `WeakMap` changes caching behavior and is not * supported usage * @returns The built shape for `schema` * * @example * ```ts * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap()) * // stringShape({ min: 1 }) * ``` */ export declare function buildShapeFromNode(schema: JSONSchema, depth: number, visited: WeakSet, memo: WeakMap>): ContractShape; /** * Encode one value as a deterministic, key-sorted JSON string — the traversal * spine of {@link canonicalStringify}. * * @remarks * Arrays keep their element order through the shared dense own-index lens; * records sort their own keys before encoding, at every nesting level. Every * other value is encoded by * `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0` * encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes. * * Returns `undefined` for anything JSON cannot encode: `undefined` itself, a * function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A * container carrying such a member is itself un-encodable and returns * `undefined` too, so the result is either a faithful encoding of the WHOLE * value or nothing — a partially-encoded key is never emitted. A hostile * getter or `Proxy` trap is refused through this function's own required-read * boundary, including when this spine is called directly. * * The walk is ITERATIVE over an explicit enter/exit stack and keeps a * walk-local encoding memo, so a container reached through several paths is * encoded ONCE. That memo is sound precisely because a partial answer does not * exist here: any cycle or JSON-inexpressible member abandons the whole call, * so a recorded encoding is the container's complete encoding on every path. * The earlier recursion re-encoded per path, which made thirty ordinary shared * aliases cost `2^30` encodings through the public {@link canonicalStringify} * and {@link unifySchemas} doors. Each container's members are read ONCE, at * the moment it is entered, and the ancestor set is restored on every exit * including the abandoning ones. * * @param value - The value to encode * @param ancestors - Objects on the active traversal path, guarding cycles * @returns The deterministic encoding, or `undefined` when JSON cannot encode * `value` * * @example * ```ts * canonicalizeValue({ b: 1, a: 2 }, new WeakSet()) // '{"a":2,"b":1}' * canonicalizeValue(undefined, new WeakSet()) // undefined * ``` */ export declare function canonicalizeValue(value: unknown, ancestors: WeakSet): string | undefined; /** * Render a value as a deterministic, key-sorted JSON string — or `undefined` * when it has no faithful JSON encoding. * * @remarks * The stable-stringify backing {@link unifySchemas}'s de-duplication and * ordering: unlike `JSON.stringify`, object keys are sorted before encoding * (recursively, at every nesting level), so two structurally-equal * `JSONSchema` fragments built independently always canonicalize to the same * string. Pure host-independent ECMAScript with no environment-specific imports. * * For READABLE input it returns `undefined` — never a partial or invalid * encoding — for every value JSON cannot faithfully encode: * * - `undefined` itself, a function, a symbol, or an array hole (JSON encodes * none of them), at the top level or anywhere inside a container; * - a bigint (`JSON.stringify` throws on one); * - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline * {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic) * reference reached twice through different paths still encodes; * A hostile traversal is categorically different: a throwing own-getter, * hostile `ownKeys` trap, or revoked `Proxy` throws a `structure` * {@link ContractError} through {@link readValue}. A caller can therefore * distinguish "not JSON-encodable" from "could not be read". * * A caller therefore treats `undefined` as "this value has no canonical key", * never as an encoding: see {@link unifySchemas} (an un-keyed member cannot * participate in de-duplication or ordering) and {@link inferPrimitiveEnum} (an * un-keyed member makes the slot enum-ineligible). * * @param value - The value to canonicalize (a `JSONSchema` fragment, or any * nested piece of one) * @returns A deterministic string encoding of `value`, or `undefined` when JSON * cannot encode it * @throws {ContractError} When the value cannot be read * * @example * ```ts * canonicalStringify({ type: 'object', properties: {} }) === * canonicalStringify({ properties: {}, type: 'object' }) // true * canonicalStringify(Number.NaN) // 'null' — JSON.stringify semantics * canonicalStringify(undefined) // undefined * canonicalStringify(cyclicValue) // undefined * ``` */ export declare function canonicalStringify(value: unknown): string | undefined; /** * Classify an already-bounded string against the pattern-only and * calendar-checked {@link SchemaFormat} vocabulary. * * @remarks * The pure leaf behind {@link stringToFormat}'s total boundary: it performs the * pattern dispatch, and the door decides what a failed dispatch answers. Order * is significant — `date-time` is tried before `date`, and both require the * calendar check, so `2020-13-45` matches the pattern and is still refused. * * @param value - The candidate string, already length-bounded * @returns The matched {@link SchemaFormat}, or `undefined` * @throws The exact value thrown by a redirected pattern dispatch * * @example * ```ts * classifyFormat('ada@example.com') // 'email' * ``` */ export declare function classifyFormat(value: string): SchemaFormat | undefined; /** * The maximum number of nodes one JSON snapshot may produce, frozen. * * @remarks * JSON persistence is a TREE, so `cloneJSONValue` / `cloneJSONRecord` * deliberately duplicate a repeated noncyclic alias into distinct equal * branches — `clone.primary !== clone.fallback` is a documented guarantee, not * an accident, and a memo would silently take it away. The price of that * guarantee is that output size is exponential in the number of shared aliases: * an ordinary in-memory graph of twenty-one objects, a few hundred bytes, * produced two million nodes and took seconds, and thirty aliases took hours. * No attacker is needed — shared references are normal data. * * So the cost is BOUNDED rather than paid: the walk counts the nodes it * produces and refuses past this cap with the ordinary cause-free `clone` * refusal, which makes the door's worst case a function of this constant * instead of the caller's input. Size a snapshot against it: a document with * more than this many nodes — counting every array, record, and leaf the * snapshot would contain AFTER alias duplication — is refused rather than * cloned. * * @example * ```ts * CLONE_NODE_LIMIT // 262144 * ``` */ export declare const CLONE_NODE_LIMIT = 262144; /** * Deep-clone an exact JSON object record into an owned frozen snapshot. * * @remarks * Adds a record-root boundary to {@link cloneJSONValue}. The output is a * deeply frozen null-prototype record, and repeated noncyclic aliases are * duplicated as independent JSON tree branches. * * @param value - The unknown record value to validate and snapshot * @returns A deeply cloned and frozen JSON record * @throws {ContractError} When the root is not a record, nested data is inexact, or traversal fails * * @example * ```ts * cloneJSONRecord({ attempt: 1 }) // frozen null-prototype record * ``` */ export declare function cloneJSONRecord(value: unknown): JSONRecord; /** * Deep-clone exact JSON data into an owned frozen snapshot. * * @remarks * Traverses iteratively so deeply nested input cannot exhaust the call stack. * Repeated noncyclic aliases are duplicated because JSON persistence represents * a tree, while a structural back-edge on the active path is rejected as a * cycle. Arrays are rebuilt as standard dense arrays and records as * null-prototype objects; every produced node is frozen after its children are * wired. Array keys must be exactly `length` plus every canonical index. * Writable and configurable index flags are normalized rather than treated as * JSON data, so frozen arrays remain valid. Property descriptors are inspected * without reading values through accessors, and every hostile reflective * operation is contained before a new clone-coded error is exposed. * Each call creates a fresh {@link JSONCloner}; use the class directly when * terminal success or failure identity must be replayed without another read. * * @param value - The unknown value to validate and snapshot * @returns The primitive unchanged, or a deeply cloned and frozen JSON graph * @throws {ContractError} When the value is not exact acyclic JSON data or traversal fails * * @example * ```ts * const source = { settings: { enabled: true } } * const clone = cloneJSONValue(source) * source.settings.enabled = false * clone // { settings: { enabled: true } } * ``` */ export declare function cloneJSONValue(value: unknown): JSONValue; /** * Deep-clone a JSON Schema graph into an owned frozen snapshot. * * @remarks * Walks arrays and records iteratively with a memo, preserving shared * references and closing cyclic edges onto their cloned nodes. Primitive * values and own enumerable string-keyed edges are copied; record nodes use * null prototypes, arrays retain only their intrinsic array prototype, and * every produced object is frozen after its edges are wired. Hostile traversal * throws a clone-coded {@link ContractError}, never a caller-owned raw error. * Each call creates a fresh {@link SchemaCloner}; use the class directly when * terminal success or failure identity must be replayed without another read. * * @param schema - The JSON Schema graph to snapshot * @returns A deeply cloned and frozen JSON Schema graph * @throws {ContractError} When hostile schema traversal prevents ownership * * @example * ```ts * const child = { type: 'string' } * const clone = cloneSchema({ anyOf: [child, child] }) * clone.anyOf?.[0] === clone.anyOf?.[1] // true * ``` */ export declare function cloneSchema(schema: JSONSchema): JSONSchema; /** * Deep-clone a contract shape graph into an owned frozen snapshot. * * @remarks * A fresh public {@link ShapeCloner} preserves shared-child identity while * building the candidate snapshot, owns raw schemas, validates the exact * completed root, applies deferred fidelity, and translates unexpected hostile * failures. Inside the engine, each node's own data discriminant and every * declared field are captured descriptor-first from two agreeing reads, and the * carried population alone supplies its shallow shell, semantic checks, child * scheduling, and later edge wiring. An inherited field is refused through a * non-invoking presence check, and a revealed accessor is refused without * invocation except for the builder's `pattern` contract: two fresh frozen * genuine `RegExp` values with equal source and flags are captured as owned * source/flags semantics. * * Literal and union members retain their own-index descriptor/repeated-read * checks; property entries retain descriptor/first/second agreement plus two * exactly equal ordered key populations; raw schemas delegate to * {@link cloneSchema}. Before return, a fresh {@link ShapeValidator} independently * validates the exact cloned root. Ownership never erases a structural edge or * normalizes an invalid scalar/bound into a plausible declaration: those * inputs throw their coded structure/bound error. Hostile traversal remains * distinct and throws a clone-coded {@link ContractError}. * * @param shape - The contract shape graph to snapshot * @returns A deeply cloned and frozen shape graph * @throws {ContractError} When the declaration cannot be copied faithfully or hostile shape or raw-schema traversal prevents ownership * * @example * ```ts * const child = arrayShape(stringShape()) * const clone = cloneShape(objectShape({ first: child, second: child })) * clone.type === 'object' && clone.properties.first === clone.properties.second // true * ``` */ export declare function cloneShape(shape: StringShape): StringShape; export declare function cloneShape(shape: ContractShape): ContractShape; /** * Build the collector a captured `forEach` sweep appends through. * * @remarks * Extracted rather than written inline for the same reason * {@link compareValues} is: `Reflect.apply` takes its arguments as a LIST, so an * inline collector is a function expression inside an array literal rather than * one passed directly as an argument — a hidden function assignment this * repository forbids wherever it appears. Returned directly from a factory it is * both named and testable. Both sweeps hand the callback `(value, key)`; a `Set` * passes its entry in both positions, so one collector serves both. * * @param target - The pair list to append each swept entry onto * @returns The collector a captured `forEach` invokes per entry * * @example * ```ts * const collected: unknown[][] = [] * new Set(['a']).forEach(collectEntries(collected)) // [['a', 'a']] * ``` */ export declare function collectEntries(target: unknown[][]): (value: unknown, key: unknown) => void; /** * Collect an array's entries into a membership collection this package owns. * * @remarks * THE builder behind every declared vocabulary, and the first half of the answer * to a defect that survived three rounds by moving rather than closing. A guard * deciding membership with `set.has(value)` answers whatever the caller most * recently installed on `Set.prototype`, and answering it instead through the * `has` method of an exported class only moved the writable member one prototype * up: `Vocabulary.prototype.has = () => true` reproduced the whole defect at * nineteen door groups. There is no property lookup here to redirect — * membership is asked of a MODULE BINDING, which the specification makes * immutable to every importer, over operations {@link INTRINSICS} captured while * it evaluated. * * Collection is by INDEX rather than from an iterable on purpose: * `new Set(values)` reads `Symbol.iterator` off the argument and `add` off the * instance, so building from an iterable would reintroduce two replaceable * dispatches to remove one. * * @param values - The members to collect, read by index * @returns A collection no caller holds a reference to * * @example * ```ts * const allowed = collectMembers(['admin', 'guest']) * matchesMember(allowed, 'admin') // true * ``` */ export declare function collectMembers(values: readonly unknown[]): Set; /** * Order two primitive keys or indices ascending. * * @remarks * The comparison {@link sortValues} hands to the captured sort, extracted rather * than written inline. `Reflect.apply` takes its arguments as a LIST, so an * inline comparator is a function expression inside an array literal rather than * one passed directly as an argument — a hidden function assignment, which this * repository forbids wherever it appears because a function that is not a named * declaration is a function no caller can reach and no test can exercise. As a * declaration it is both. The comparison is `<` / `>` on primitives, which * dispatches through nothing: no `valueOf`, no `toString`, and no member a * caller can replace, so the order a published schema is emitted in is decided * by the values and not by the environment. * * @param left - The value ordered first when it compares lower * @param right - The value compared against * @returns `-1`, `1`, or `0` as `left` sorts before, after, or with `right` * * @example * ```ts * compareValues('a', 'b') // -1 * ``` */ export declare function compareValues(left: T, right: T): number; /** * The maximum supported nesting depth of a compiled contract shape, frozen. * * @remarks * {@link validateShapeDepth} rejects the next level * with a depth-coded {@link ContractError} before recursive artifact * compilation begins, so a finite but pathologically deep developer-authored * shape fails predictably instead of reaching the JavaScript call-stack limit. * * @example * ```ts * COMPILE_DEPTH_LIMIT // 512 * ``` */ export declare const COMPILE_DEPTH_LIMIT = 512; /** * The maximum number of nodes a compiled artifact may expand a shape into, * frozen. * * @remarks * A shape graph is a DAG; every compiled artifact is a TREE. A declaration may * therefore be tiny and its schema, guard, parser, reporter, auditor and * generated value enormous: `objectShape({ left: node, right: node })` nested * thirty times is thirty-one authored nodes that expand into more than a * billion emitted ones. Sharing one child is ordinary authoring, not an attack, * and the compilers cannot fold the expansion away without publishing a schema * whose members alias each other. * * So the cost is BOUNDED rather than paid. {@link validateShapeDepth} and * {@link ContractCompiler} preparation both count the nodes the declaration * expands into (one per node, summed over every incoming edge) and refuse past * this cap through {@link refuseExpansion}, with an `expansion`-coded * {@link ContractError}. Ownership is deliberately NOT bounded by it: * {@link cloneShape} and {@link ownShape} preserve shared-child identity, so * they answer a shared-child graph in time proportional to its authored nodes * and keep working above this cap. * * What this cap bounds MOVED when the compilers stopped expanding a DAG. Every * artifact family is now one entry per unique node, so the boundary declaration * above compiles fourteen nodes in about a millisecond rather than sixteen * thousand in 1,342 ms, and the cap is no longer what keeps compilation finite. * What still expands is what a CONSUMER materializes from the artifacts: the * value `generate` builds, and the document a compiled schema serializes to, * are trees of exactly this size. The cap survives as a bound on what a caller * can be handed, not on what the compiler pays. * * @example * ```ts * COMPILE_NODE_LIMIT // 16384 * ``` */ export declare const COMPILE_NODE_LIMIT = 16384; /** * Audit a value against the strict acceptance domain of a {@link ContractShape}. * * @remarks * The diagnostic for the domain {@link compileGuard} and {@link compileSchema} * describe, where {@link compileReporter} diagnoses the wider preimage * {@link compileParser} maps into it. This walk therefore mirrors the guard: * leaf coercions are faults, closed-object extras are faults, and union * acceptance is decided from each variant's strict audit emptiness, so the * soundness invariant * `compileAuditor(shape, v).length === 0 ⟺ compileGuard(shape)(v)` holds * structurally. The shared declaration gate rejects structural and bound-domain * malformations before either artifact is built, so the invariant is only * evaluated for a valid declaration. The invariant relates two * separate calls, so it holds for a value whose reads are stable across calls; * see the read-stability precondition on {@link ContractInterface}. Every * recursive call returns at most {@link FAULT_LIMIT} entries. Hostile property * access raises the shared coded read refusal with the current container path * and shape, so unreadability never masquerades as a type mismatch. * It requests exactly the `auditor` root of a fresh {@link ContractCompiler} * and applies it once; reuse the compiler (or a contract's `audit`) when many * values are audited against one shape. * * @param shape - The shape to audit against * @param value - The value to check * @param path - The path prefix for faults produced at this call * @returns The strict faults found, empty exactly when the compiled guard accepts a stably-read value * * @example * ```ts * const user = objectShape({ name: stringShape() }) * compileAuditor(user, { name: 'Ada', extra: true }) * // [{ reason: 'extra', path: ['extra'] }] * ``` */ export declare function compileAuditor(shape: ContractShape, value: unknown, path?: readonly string[]): readonly AuditFault[]; /** * Compile a {@link ContractShape} into a deterministic seed value. * * @remarks * The same shape and the same `random` source always produce the same value, so * seed data is reproducible. Defaults to a {@link seededRandom} source seeded * from the wall clock when none is supplied. Shape-generation failures throw a * {@link ContractError} with code `'generate'`; {@link drawRandom} failures use * code `'random'` and retain the consuming shape category in context. * Failures include a pattern-constrained `stringShape` whose generated sample * cannot satisfy the pattern, an invalid random sample, and a `rawShape` whose * arbitrary embedded schema cannot be auto-generated. Degenerate empty * literal/union vocabularies fail earlier with the shared gate's `empty` code. * It requests exactly the `generator` root of a fresh * {@link ContractCompiler} and invokes it once, so the declaration is owned and * validated once before any draw. Union candidates are bounded by * {@link GENERATION_ATTEMPT_LIMIT} and accepted only when they satisfy the * union's compiled guard, which is why a declaration containing a union also * builds the compiler's guard plan. * * @param shape - The shape to generate from * @param random - A seeded random source (defaults to a wall-clock seed drawn inside the door's boundary) * @returns A value matching the shape * @throws {ContractError} When the shape or random source cannot produce a valid value * * @example * ```ts * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism) * ``` */ export declare function compileGenerator(shape: S, random?: RandomFunction): Infer; export declare function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown; /** * Compile a {@link ContractShape} into a runtime type guard. * * @remarks * Reuses the combinators for structural and refined shapes, including * {@link literalOf} for SameValueZero literal matching. Compiled object shapes * observe own enumerable string keys through {@link enumerableKeys}, the same * key view their parser, reporter, auditor, and inference use for both open and * closed objects — the view is shared, the verdict on an undeclared key is not * (this guard rejects the object; the parser drops the key). * Like every guard it is total — it never throws (AGENTS §14). It requests * exactly the `guard` root of a fresh {@link ContractCompiler}, which owns the * declaration once through {@link ownShape} and validates that snapshot once, * so an unfrozen caller-owned graph compiles from a snapshot and excessive * nesting, cycles, and excessive expansion are rejected before any guard is * built. * * @param shape - The shape to compile * @returns A guard narrowing to the shape's inferred type * * @example * ```ts * const isUser = compileGuard(objectShape({ name: stringShape() })) * isUser({ name: 'Ada' }) // true * ``` */ export declare function compileGuard(shape: S): Guard>; export declare function compileGuard(shape: ContractShape): Guard; /** * Compile a {@link ContractShape} into an input parser. * * @remarks * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` / * `parseBoolean`) and coerces structurally. An object fails as a * whole on any required-field failure; a union returns a guard-valid value * unchanged, otherwise the first variant that both parses and guards wins. * * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same * combinators {@link compileGuard} uses — `stringOf` for a string's * length/pattern, `boundsOf` for a number's value and an array's length, and * {@link literalOf} for literal membership — so a value that coerces but * violates a bound parses to `undefined`. The result is full parse↔guard * soundness (AGENTS §14): a * non-`undefined` parse always satisfies the contract's `is`, refinements * included — a statement about the OUTPUT, never about the input, which may be * a value `is` rejects. Object presence and extra-key processing read the same * own-enumerable-string key view as the guard, reporter, auditor, and inference * — one key set, deliberately different verdicts: this parser drops an * undeclared key that {@link compileGuard} rejects and {@link compileAuditor} * faults. It requests exactly the `parser` root of a fresh * {@link ContractCompiler}, which owns and validates the declaration once; a * union's variant selection is a guard question, so a declaration containing one * also builds the compiler's guard plan. * * @param shape - The shape to compile * @returns A parser yielding the shape's inferred type or `undefined` * * @example * ```ts * const parseUser = compileParser(objectShape({ name: stringShape() })) * parseUser({ name: 'Ada' }) // { name: 'Ada' } * ``` */ export declare function compileParser(shape: S): Parser>; export declare function compileParser(shape: ContractShape): Parser; /** * Compile a {@link ContractShape} into a structured fault report for a value — * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}. * * @remarks * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` / * `isJSONValue` / …), so the soundness invariant * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined` * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a * coercible value like `'42'` against a `numberShape` reports no fault, the * same leniency `parse` grants, even though the strict guard would reject it). * The invariant relates two separate calls, so it holds for a value whose reads * are stable across calls; see the read-stability precondition on * {@link ContractInterface}. {@link compileAuditor} is the counterpart report * for the strict domain, mirroring {@link compileGuard} the way this one * mirrors {@link compileParser}. * * Faults are collected in stable pre-order (declared key/index order); every * call — object, array, and union alike, including a union's `oneOf` "no * match" / "no consensus" summary fault prepended to its closest variant's * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the * bound holds at every level of nesting, not just the outermost container, on * adversarial input (a huge array, a wide record, a wide union of wide * records). A closed object's extra keys never * fault — `parse` silently drops them, so `explain` mirrors that leniency, and * {@link compileAuditor} is where they do fault; an open object with a * constraining `additionalProperties` shape recurses extras against it instead. * A hostile getter or throwing `Proxy` trap is contained via {@link attempt} * and surfaces as a single top-level type fault, never a throw (AGENTS §14). * It requests exactly the `reporter` root of a fresh {@link ContractCompiler} * and applies it once, so one call owns and validates the declaration once * rather than re-gating every node it descends into. Reuse the compiler (or a * contract's `explain`) when many values are reported against one shape. * * @param shape - The shape to report against * @param value - The value to check * @param path - The path prefix for faults produced at this call (defaults to the root) * @returns The faults found, empty when the value parses successfully * * @example * ```ts * const user = objectShape({ name: stringShape({ min: 1 }) }) * compileReporter(user, { name: '' }) * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '""' }] * compileReporter(user, { name: 'Ada' }) // [] * ``` */ export declare function compileReporter(shape: ContractShape, value: unknown, path?: readonly string[]): readonly Fault[]; /** * Compile a {@link ContractShape} into a JSON Schema document. * * @remarks * Object shapes emit `additionalProperties: false` (unless opened) and list only * required keys in `required`; nullable shapes emit an `anyOf` with `{ type: * 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned * rather than retained by reference. Emission only — it never inspects a * runtime value. It requests exactly the `schema` root of a fresh * {@link ContractCompiler}, so the declaration is owned once and validated once * and no other artifact family is built. Shared declaration identity survives * into the emitted document: two slots holding one authored node hold one * emitted subschema, while structurally equal distinct nodes stay distinct. * * @param shape - The shape to compile * @returns The emitted JSON Schema * * @example * ```ts * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 } * ``` */ export declare function compileSchema(shape: ContractShape): JSONSchema; /** * Build a guard for `Exclude` — accepts values that pass * `base` but not `excluded`. * * @example * ```ts * const isNonEmpty = complementOf(isString, isEmptyString) * isNonEmpty('hi') // true * isNonEmpty('') // false * ``` */ export declare function complementOf(base: Guard, excluded: Guard | ((value: TBase) => value is TExcluded)): Guard>; /** * Run a public door's whole body and publish only this package's error class. * * @remarks * The other half of the answer {@link INTRINSICS} gives, and the half that does * not depend on anyone enumerating anything. Capture removes a named dispatch; * this removes the CONSEQUENCE of every dispatch a door's path still makes, * named or not. Four consecutive rounds fixed the statements they were shown * and were defeated by a statement one line later, because a boundary placed * per statement is only ever as complete as the last sweep. A boundary at the * door composes: whatever the body reaches, and whatever a caller installs * under it, the door publishes a {@link ContractError} or the value it * promised. * * A {@link ContractError} reaching this boundary passes through by identity — * the diagnosis a door spent its whole body computing is the point of the door, * and rewrapping it would demote it to a cause. The mechanism is * {@link isContractError}, which establishes CLASS MEMBERSHIP; it does not and * cannot establish that this package authored the error, and the passthrough is * described by what it tests rather than by what it intends. Anything else is a * host failure the caller arranged, so it is republished under the door's own * name with the exact thrown value retained as `cause`. * * Its population is exactly the public doors that can refuse — every door whose * TSDoc carries `@throws {ContractError}`, and no door whose body cannot throw * at all. A wrapper around a body that only allocates a closure buys nothing * and misreports where the refusals are. * * Use {@link readValue} instead where a single read has its own subject and * deserves its own diagnostic; use this where the subject is the door. * * @param callback - The door body to run * @param door - The public door name used in the diagnostic * @param options - Optional code and structured context for the published refusal * @returns The body's exact return value * @throws {ContractError} The body's own refusal, or a coded translation of a host failure * * @example * ```ts * export function nullShape(options?: NullShapeOptions): NullShape { * return contain(() => buildNullShape(options), 'nullShape') * } * ``` */ export declare function contain(callback: () => T, door: string, options?: ContainOptions): T; /** * Optional diagnostic metadata for a public door's containment boundary. * * @remarks * Deliberately narrower than {@link ReadValueOptions}: a contained door's * subject IS the door, so there is no `subject` to name. The two options types * are separate because a signature that accepts a key it silently ignores tells * the caller a lie the type checker will not catch. */ export declare interface ContainOptions { /** Machine-readable refusal category. */ readonly code?: ContractCode; /** Structured location and domain details retained by the refusal. */ readonly context?: ContractErrorContext; } /** * The registry-global key used to recognize {@link ContractError} values across * package copies. * * @remarks * The descriptor stores the branded value itself. Recognition compares that * identity, so a transparent proxy cannot forward its target's brand as its * own. The registry makes the key discoverable; it is a recognition mechanism, * not an unforgeable provenance marker. */ export declare const CONTRACT_ERROR_BRAND: unique symbol; /** Machine-readable category carried by a {@link ContractError}. */ export declare type ContractCode = /** Identifies a bound contract error. */ 'bound' /** Identifies a range contract error. */ | 'range' /** Identifies an empty-value contract error. */ | 'empty' /** Identifies a valid optional shape used in a forbidden position. */ | 'placement' /** Identifies a corrupt shape node or structural slot. */ | 'structure' /** Identifies a literal contract error. */ | 'literal' /** Identifies a cycle contract error. */ | 'cycle' /** Identifies a pattern contract error. */ | 'pattern' /** Identifies a generation contract error. */ | 'generate' /** Identifies a random-source contract error. */ | 'random' /** Identifies an owned-clone contract error. */ | 'clone' /** Identifies a compilation-depth contract error. */ | 'depth' /** Identifies a shape whose compiled expansion exceeds the emitted-node limit. */ | 'expansion'; /** * Lazy compiler owning one contract shape's six artifacts and their bundle. * * @remarks * The engine every standalone `compile*` function and `createContract` now runs * on. Its reason for existing is that the recursive compilers used to re-own and * re-validate the SUBGRAPH at every node they descended into, so a depth-100 * chain paid a hundred clones of shrinking graphs and a hundred validations — * quadratic work for a linear declaration, measured at 640 ms for one guard and * 1.87 s for one contract. Here ownership runs once, validation runs once over * that owned result, and each unique node and structural edge is indexed once * into children-before-parent order. Every artifact family is then a single * postorder pass whose entries are keyed by node identity, so a shared child is * compiled once however many parents point at it. The same asymmetry exists on * the VALUE side and is answered the same way: `guard`, `auditor` and `reporter` * carry a call-scoped ledger, so a shared object costs one visit per compiled * node rather than one per path through the graph. * * Construction observes nothing at all: no read, no validation, no clone, no * graph-sized allocation, no clock, no draw. The first getter read prepares; the * getters after it replay. A getter builds its own family and no other, except * that `parser`, `reporter` and `generator` build the guard plan when the graph * holds a union, because a union's membership question IS a guard question in * all three. * * One terminal lifecycle covers preparation and every family. A failure settles * the compiler: later getters rethrow that exact error, while an artifact * already handed out keeps working, because each compiled artifact is * self-contained. Reentry — reachable only through a caller accessor the * declaration itself exposes, since a `pattern` getter is the one accessor * ownership invokes — poisons the nested read, the interrupted outer read, and * every later read with one shared cause-free error. * * @typeParam S - The declaration's shape type, which types the published artifacts * * @example * ```ts * const compiler = new ContractCompiler({ type: 'string', min: 1 }) * compiler.guard('Ada') // true * compiler.guard === compiler.guard // true — every getter replays its exact root * ``` */ export declare class ContractCompiler implements ContractCompilerInterface { #private; /** * Retain a shape declaration without observing it. * * @param shape - The live declaration the first getter read will own */ constructor(shape: S); /** * The emitted JSON Schema for the owned declaration. * * @remarks * A deeply frozen graph that preserves shared declaration identity: two * property slots holding the same authored node hold the same emitted * subschema, while structurally equal distinct nodes stay distinct objects. */ get schema(): JSONSchema; /** The compiled strict guard for the owned declaration. */ get guard(): Guard>; /** The compiled coercive parser for the owned declaration. */ get parser(): Parser>; /** The compiled strict-domain diagnostic for the owned declaration. */ get auditor(): AuditorFunction; /** The compiled coercive-domain diagnostic for the owned declaration. */ get reporter(): ReporterFunction; /** The compiled seed-data source for the owned declaration. */ get generator(): SeederFunction>; /** * The frozen six-member bundle of this compiler's artifacts. * * @remarks * Own enumerable keys `schema`, `is`, `parse`, `audit`, `explain`, * `generate`, in that order, each holding the exact value the corresponding * getter publishes. */ get contract(): ContractInterface>; } /** * Lazy owner of one contract shape's six compiled artifacts plus their bundle. * * @remarks * Construction observes nothing. The FIRST getter read owns the declaration * once, validates that owned graph once, and indexes each unique node and * structural edge once into children-before-parent order; every artifact family * is then one postorder pass over that index, so a shared child costs its * authored nodes rather than its paths. A getter builds its own family and no * other, except where an artifact genuinely consumes the compiled guard — * `parser`, `reporter` and `generator` resolve union membership through it, so * they build it too. `contract` requests all six roots in getter order. * * Every getter REPLAYS its exact artifact: reading one twice returns the same * function or graph by identity, and {@link contract}'s six members are those * exact values. One terminal lifecycle covers preparation and every family, so * a failure anywhere settles the compiler permanently — later getters rethrow * that exact error while an artifact already handed out stays usable, because * each one is self-contained. Cross-getter reentry (only reachable through a * caller accessor the declaration exposes) poisons the nested read, the * interrupted outer read, and every later read with one shared cause-free * error. * * @example * ```ts * const compiler = new ContractCompiler(stringShape({ min: 1 })) * compiler.guard('Ada') // true * ``` */ export declare interface ContractCompilerInterface { /** The emitted JSON Schema, deeply frozen and shared-identity preserving. */ readonly schema: JSONSchema; /** The compiled strict guard. */ readonly guard: Guard>; /** The compiled coercive parser. */ readonly parser: Parser>; /** The compiled strict-domain diagnostic. */ readonly auditor: AuditorFunction; /** The compiled coercive-domain diagnostic. */ readonly reporter: ReporterFunction; /** The compiled seed-data source. */ readonly generator: SeederFunction>; /** The frozen six-member bundle whose values are the six artifacts above. */ readonly contract: ContractInterface>; } /** * Error carrying a machine-readable contract category, optional context, and * an exact optional cause. Omitting `cause` omits the own property; explicitly * supplying `cause: undefined` retains an own property with that value. Both * optional options are read as OWN properties, so a construction never consults * the caller-writable prototype chain of the container it was handed. * * @example * ```ts * const error = new ContractError('Minimum exceeds maximum', { * code: 'range', * context: { path: ['properties', 'age'] }, * }) * ``` */ export declare class ContractError extends Error { readonly name = "ContractError"; readonly code: ContractCode; readonly context: ContractErrorContext | undefined; /** * Create a contract error. * * @param message - Human-readable error description * @param options - Machine-readable category, optional context, and optional cause */ constructor(message: string, options: ContractErrorOptions); } /** Optional structured details carried by a {@link ContractError}. */ export declare interface ContractErrorContext { /** Location associated with the error. */ readonly path?: FieldPath; /** Shape label associated with the error. */ readonly shape?: string; /** Numeric or textual limit associated with the error. */ readonly limit?: number | string; /** Received-value description associated with the error. */ readonly received?: string; } /** Construction options for a {@link ContractError}. */ export declare interface ContractErrorOptions { /** Machine-readable error category. */ readonly code: ContractCode; /** Optional structured error details. */ readonly context?: ContractErrorContext; /** Optional originating thrown value. */ readonly cause?: unknown; } /** * A compiled contract — the six lockstep outputs derived from one shape. * * @remarks * Built by `createContract`: `is` narrows, `audit` diagnoses strict rejection, * `parse` coerces (returning the typed value or `undefined`), `schema` is an * owned deeply frozen emitted JSON Schema, `explain` reports the structured * faults behind a failed `parse`, and `generate` produces deterministic seed * data from a {@link RandomFunction} (defaulting to a wall-clock-seeded source * when none is supplied). * * LOCKSTEP means derived from one owned snapshot of the shape, not agreeing on * which values to accept: `is` and `schema` describe the contract's canonical * domain, while `parse` is a map into that domain whose preimage is * deliberately larger (it coerces leaves and drops a closed object's undeclared * keys). `audit` diagnoses the domain; `explain` diagnoses the map. * * READ STABILITY is the precondition on both soundness laws — `audit` against * `is`, `explain` against `parse`. Each law relates two separate calls, and * every call reads the value it is handed, so both hold for a STABLE value: one * whose observable reads do not change between calls. A getter that answers a * declared string on its first read and a number on its second, or a `Proxy` * whose traps change behavior mid-flight, can leave `audit` empty and still * fail `is`; no law spanning two calls can promise otherwise, and no artifact * re-reads a value to close the gap. This is a statement of scope, not a hedge: * for primitives and data-only structures whose entire observable read surface * stays stable across both calls, both laws hold exactly as written. * `Object.freeze` alone does not establish that condition because it is shallow * and does not stabilize accessors. */ export declare interface ContractInterface { readonly schema: JSONSchema; readonly is: Guard; parse(value: unknown): T | undefined; /** * Report every strict fault a value has against this contract. * * @remarks * An empty report means the value is strictly valid. Soundness invariant: * `audit(v).length === 0` if and only if `is(v)`, for a value whose reads are * stable across calls (see the read-stability precondition on * {@link ContractInterface}). It is the report for the stricter of the two * domains, so a coercible leaf and a closed object's undeclared key both * fault here and neither faults in `explain`. * * @param value - The value to check * @returns The faults found, empty when the value is strictly valid */ audit(value: unknown): readonly AuditFault[]; /** * Report every structured parse fault a value has against this contract. * * @remarks * An empty report means the value is valid. Soundness invariant: * `explain(v).length === 0` if and only if `parse(v) !== undefined`, for a * value whose reads are stable across calls (see the read-stability * precondition on {@link ContractInterface}) — explain mirrors `parse`'s * coercion, not the stricter `is`, and `audit` is the report that mirrors * `is`. Faults are listed in stable pre-order (declared key/index order). * * @param value - The value to check * @returns The faults found, empty when the value parses successfully */ explain(value: unknown): readonly Fault[]; generate(random?: RandomFunction): T; } /** * A contract shape — a declarative description of a value, built with the shape * builders and compiled into a guard, a parser, a JSON Schema, and a generator. * * @remarks * A discriminated union keyed on `type`. Shapes nest (an `ArrayShape` holds an * element shape, an `ObjectShape` a map of them). {@link validateShapeDepth} * enforces an acyclic graph within {@link COMPILE_DEPTH_LIMIT}. */ export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape; /** * Build the length faults an array has against an {@link ArrayShape}. * * @remarks * Takes the LENGTH rather than the array, because both doors have already read * their entries through {@link readArrayEntries} and must report the length that * read observed rather than re-asking the caller's value for it. `received` is * that count rendered through the captured `String`, matching the other length * diagnostics in the package. Order is `min`, then `max`. It refuses an * unreadable shape through the same boundary and for the same reason * {@link createStringFaults} does. * * @param shape - The array shape whose bounds are checked * @param length - The entry count the door already observed * @param path - The path every produced fault is rooted at * @returns A fresh array of faults, empty when the length satisfies both bounds * @throws {ContractError} When the shape's bound fields cannot be read * * @example * ```ts * createArrayFaults({ type: 'array', items: { type: 'string' }, min: 2 }, 1, []) * // [{ reason: 'constraint', path: [], expected: 'array', constraint: 'min', limit: 2, received: '1' }] * ``` */ export declare function createArrayFaults(shape: ArrayShape, length: number, path: readonly string[]): readonly Fault[]; /** * Compile a {@link ContractShape} into a {@link ContractInterface} — the six * lockstep outputs from one declaration, lockstep meaning derived from one * owned snapshot rather than accepting the same values. * * @remarks * Creates ONE {@link ContractCompiler} and returns that compiler's exact * `contract` bundle. One ownership population governs the whole contract: the * declaration is owned once through {@link ownShape}, that owned graph is * validated once, and the six artifacts are compiled from it. There is no * discarded pre-ownership pass over the caller's declaration and no second * snapshot — ownership already refuses a malformed structural slot, scalar * field, or bound rather than normalizing it, so a second walk of the caller's * live source only added a population that could disagree with the one the * artifacts actually use. * All six artifacts are precompiled, so `audit`, `explain` and `generate` no * longer re-walk and re-gate the declaration on every call the way they used * to; `contract.audit` and `compileAuditor` are the same compiled function * reached two ways. * * @param shape - The shape to compile * @returns A contract bundling `schema` / `is` / `parse` / `audit` / `explain` / `generate` * * @example * ```ts * const user = createContract(objectShape({ name: stringShape(), age: integerShape() })) * user.is({ name: 'Ada', age: 36 }) // true * user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 } * user.schema // { type: 'object', properties: { … }, … } * ``` */ export declare function createContract(shape: S): ContractInterface>; export declare function createContract(shape: ContractShape): ContractInterface; /** * Build the refinement faults a number value has against a {@link NumberShape}. * * @remarks * The numeric sibling of {@link createStringFaults}, shared by the same two * doors for the same reason. `expected` is the shape's own kind — `'integer'` * when `integer: true`, otherwise `'number'` — so a caller reading the report * sees the declaration's vocabulary rather than the value's. Order is * `integer`, then `min`, then `max`. It refuses an unreadable shape through the * same boundary and for the same reason {@link createStringFaults} does. * * @param shape - The number shape whose refinements are checked * @param value - The already-obtained number to check * @param path - The path every produced fault is rooted at * @returns A fresh array of faults, empty when the value satisfies every refinement * @throws {ContractError} When the shape's refinement fields cannot be read * * @example * ```ts * createNumberFaults({ type: 'number', integer: true }, 1.5, []) * // [{ reason: 'constraint', path: [], expected: 'integer', constraint: 'integer', received: '1.5' }] * ``` */ export declare function createNumberFaults(shape: NumberShape, value: number, path: readonly string[]): readonly Fault[]; /** * Build the refinement faults a string value has against a {@link StringShape}. * * @remarks * The single source of the string refinement report, shared by * `compileReporter` and `compileAuditor`. The two doors differ only in how they * OBTAIN the string — the reporter coerces through `parseString`, the auditor * demands a primitive string — and agreed on every constraint afterwards by * carrying two copies of the same twenty-one lines, which is one edit away from * two contracts. Faults come out in declaration order — `min`, then `max`, then * `pattern` — because a report is read top to bottom and its order is public. * * The pattern is applied through an OWNED stateless rebuild * ({@link readPattern}) and asked through {@link matchesPattern}, so a caller's * `lastIndex` never moves and no caller-writable member decides whether the * value matched. * * The whole body reads the caller's SHAPE, so it runs through the same * {@link readValue} boundary {@link shapeToKind} uses and refuses an * out-of-domain declaration with the same diagnostic. The compiled doors gate a * non-`RegExp` `pattern` and a non-finite bound long before this helper sees * them, so the package's own path never arrives here off-domain — but the door * is PUBLISHED, and a shape a `StringShape` annotation merely vouched for * (parsed out of a document, say) reaches it unchecked. Publishing the host's * own `TypeError` from such a shape would falsify the promise this module makes * for every one of its doors. * * @param shape - The string shape whose refinements are checked * @param value - The already-obtained string to check * @param path - The path every produced fault is rooted at * @returns A fresh array of faults, empty when the value satisfies every refinement * @throws {ContractError} When the shape's refinement fields cannot be read * * @example * ```ts * createStringFaults({ type: 'string', min: 3 }, 'ab', []) * // [{ reason: 'constraint', path: [], expected: 'string', constraint: 'min', limit: 3, received: '"ab"' }] * ``` */ export declare function createStringFaults(shape: StringShape, value: string, path: readonly string[]): readonly Fault[]; /** * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`). * * @remarks * Total and pure. Either keyword is used only when it is a non-negative * safe integer (`Number.isSafeInteger` + `>= 0`); a malformed value (a string, * a negative number, `NaN`, `Infinity`, a fraction, or an unsafe integer) is * dropped as if absent. When both bounds are present and `min` exceeds `max`, * the PAIR is dropped entirely (an unbounded shape is always a legal widening * of a contradictory schema). * * @param min - The raw `minLength` / `minItems` keyword value * @param max - The raw `maxLength` / `maxItems` keyword value * @returns The derived `min` / `max` pair, either possibly `undefined` * * @example * ```ts * deriveLengthBounds(1, 10) // { min: 1, max: 10 } * deriveLengthBounds(10, 1) // {} — contradictory, dropped * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped * ``` */ export declare function deriveLengthBounds(min: unknown, max: unknown): { readonly min?: number; readonly max?: number; }; /** * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema * range keywords (`minimum`/`maximum`). * * @remarks * Total and pure. Either keyword is used only when it is a finite number * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when * both bounds are present and `min` exceeds `max`, the PAIR is dropped * entirely, the same contradiction rule {@link deriveLengthBounds} applies. * * @param min - The raw `minimum` keyword value * @param max - The raw `maximum` keyword value * @returns The derived `min` / `max` pair, either possibly `undefined` * * @example * ```ts * deriveRangeBounds(0, 120) // { min: 0, max: 120 } * deriveRangeBounds(5, 1) // {} — contradictory, dropped * ``` */ export declare function deriveRangeBounds(min: unknown, max: unknown): { readonly min?: number; readonly max?: number; }; /** * Draw and validate one generator random sample. * * @param random - The caller-supplied random source * @param shape - The shape category consuming the sample * @returns A finite sample in `[0, 1)` * @throws {ContractError} When the source throws or returns outside `[0, 1)`; * a thrown value is retained exactly as the cause * * @example * ```ts * drawRandom(() => 0.5, 'number') // 0.5 * ``` */ export declare function drawRandom(random: RandomFunction, shape: string): number; /** * Encode one non-container value the way JSON encodes it, or `undefined` when * JSON cannot encode it at all. * * @remarks * The leaf half of {@link canonicalizeValue}: `JSON.stringify` returns * `undefined` (never a string) for `undefined`, a function, and a symbol — * exactly the values with no JSON encoding — and THROWS on a bigint, which is * refused before the call rather than through it. A `Date` and any other * non-record object encode through the same captured `JSON.stringify`, so a * `toJSON` member keeps its ordinary meaning. * * @param value - The non-container value to encode * @returns The JSON encoding, or `undefined` when JSON cannot encode `value` * * @example * ```ts * encodeLeaf(Number.NaN) // 'null' * encodeLeaf(undefined) // undefined * ``` */ export declare function encodeLeaf(value: unknown): string | undefined; /** * Snapshot an object's own enumerable string keys through a total boundary. * * @remarks * This is the package-wide runtime property view used by compiled object * guards, parsers, reporters, schema inference, and owned schema cloning. It * matches the object-key view serialized by `JSON.stringify`: inherited, * symbol, and non-enumerable properties are excluded. A hostile Proxy trap * returns `undefined` rather than escaping. * * @param value - The object whose keys to snapshot * @returns A frozen owned key list, or `undefined` when enumeration throws * * @example * ```ts * enumerableKeys({ visible: 1 }) // ['visible'] * ``` */ export declare function enumerableKeys(value: object): readonly string[] | undefined; /** * Count the enumerable own-symbol keys on a value. * * @remarks * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose * descriptor is `enumerable` are counted, and each descriptor is read through * the captured observation so no accessor runs. It answers exactly the * `JSON.stringify`-invisible half of a record's own-symbol population, for a * consumer that needs that count directly. It does NOT back `isEmptyObject` / * `isNonEmptyObject` — those ask the complete own-key question `recordOf` asks, * because an enumerable-only count made their `never` narrowing unsound for an * own non-enumerable key. * * @param value - The object to inspect * @returns The number of enumerable own-symbol keys * * @example * ```ts * const flag = Symbol('flag') * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1 * enumerableSymbolCount({}) // 0 * ``` */ export declare function enumerableSymbolCount(value: object): number; /** * Build a guard from a native `enum` or any object whose values are strings or * numbers. * @param enumeration - The readable enumeration whose values the guard accepts * @returns A guard accepting one enumeration value * @throws {ContractError} When the enumeration cannot be read * * @example * ```ts * enum Direction { Up = 'up', Down = 'down' } * const isDirection = enumOf(Direction) * isDirection('up') // true * isDirection('left') // false * ``` */ export declare function enumOf>(enumeration: E): Guard; /** A key present on a value that its closed object shape does not declare. */ export declare interface ExtraFault { readonly reason: 'extra'; readonly path: FieldPath; } /** * Discriminated failure branch of a {@link Result}. * * @remarks * Carries the error value when an operation does not succeed. */ export declare interface Failure { readonly success: false; readonly error: E; } /** * A single structured parse-failure diagnostic — one entry of an * {@link ContractInterface.explain} report. * * @remarks * A discriminated union on `reason`: * - `'type'` — the value could not coerce to `expected` at all. * - `'missing'` — a required object property was absent. * - `'constraint'` — the value coerced to `expected` but violated one * refinement (`min` / `max` / `pattern` / `integer`); `limit` carries the * violated bound/pattern when applicable. * - `'variant'` — an `anyOf`-mode union matched no variant; `variants` is the * variant count, followed (in the report) by the closest variant's own faults. * - `'oneOf'` — a `oneOf`-mode union matched zero or two-or-more variants; * `matched` is the raw match count. */ export declare type Fault = { readonly reason: 'type'; readonly path: FieldPath; readonly expected: FaultKind; readonly received: string; } | { readonly reason: 'missing'; readonly path: FieldPath; readonly expected: FaultKind; } | { readonly reason: 'constraint'; readonly path: FieldPath; readonly expected: FaultKind; readonly constraint: FaultConstraint; readonly limit?: number | string; readonly received: string; } | { readonly reason: 'variant'; readonly path: FieldPath; readonly variants: number; } | { readonly reason: 'oneOf'; readonly path: FieldPath; readonly matched: number; }; /** * The maximum number of {@link Fault} / {@link AuditFault} entries a single * `explain` or `audit` report ever returns, frozen. * * @remarks * Bounds BOTH reports against adversarial input (a giant array, a wide record) * — `compileReporter` and `compileAuditor` each collect faults in stable * pre-order and stop once this cap is reached, and every recursive call slices * to it, so the report size (and the work to build it) stays finite and * deterministic at every nesting level regardless of the input's size. Size a * diagnostic surface off this constant and it bounds `audit` exactly as it * bounds `explain`. */ export declare const FAULT_LIMIT = 64; /** The refinement a {@link Fault} of reason `'constraint'` violates. */ export declare type FaultConstraint = 'min' | 'max' | 'pattern' | 'integer'; /** The kind of value a {@link Fault} expected — the shape-projected counterpart of a `ContractShape`'s `type`. */ export declare type FaultKind = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'literal' | 'array' | 'object' | 'union' | 'json'; /** * A field path into a record: a single key, or an ordered list of keys to * descend through nested objects. * * @remarks * A single `string` is ONE key — it is never split on `.`, so keys that contain * dots stay safe. Use a `readonly string[]` to descend into nested objects. */ export declare type FieldPath = string | readonly string[]; /** * The maximum string length {@link stringToFormat} attempts to classify, * frozen. * * @remarks * Bounds per-string format-detection work: a value longer than this returns * `undefined` immediately, before any pattern match runs. 128 sits * comfortably above the longest real format token — an RFC 3339 date-time * with fractional seconds and a UTC offset — so no legitimate classification * changes; only pathologically long strings (a multi-megabyte payload passed * as a candidate email/URI) are skipped. */ export declare const FORMAT_MAX_LENGTH = 128; /** * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats * (`uuid` / `email` / `uri`), frozen as data. * * @remarks * The ISO-8601 date/time formats are NOT listed here — they additionally * require an attempt-guarded `Date` validity check, so their pattern lives * inline in `stringToFormat` rather than as reusable standalone data. */ export declare const FORMAT_PATTERNS: Readonly>; /** Resolve a {@link GuardsShape} to a readonly object type of its guarded property types. */ export declare type FromGuards = Readonly<{ [K in keyof G]: GuardType; }>; /** * The maximum number of candidate-generation attempts for a constrained * generated value, frozen. * * @remarks * Provides one deterministic work bound for generators that must retry a * candidate against a contract constraint. * * @example * ```ts * GENERATION_ATTEMPT_LIMIT // 32 * ``` */ export declare const GENERATION_ATTEMPT_LIMIT = 32; /** A runtime type guard: returns `true` when `value` satisfies `T` and narrows it. */ export declare type Guard = (value: unknown) => value is T; /** * The maximum active recursion or JSON container depth for runtime guards, * frozen. * * @remarks * Bounds explicitly recursive guards before the JavaScript call stack becomes * the limiting mechanism. It also caps array/plain-record containers on each * active path inspected by {@link matchesJSONDepth}: noncontainers are depth * zero, an empty container is depth one, 512 containers pass, and the 513th * fails. Active cycle edges do not add a level. * * @example * ```ts * GUARD_DEPTH_LIMIT // 512 * ``` */ export declare const GUARD_DEPTH_LIMIT = 512; /** * A mapping of string keys to guards. * * @remarks * The shape parameter for the `recordOf`, `pickOf`, and `omitOf` combinators. */ export declare type GuardsShape = Readonly>>; /** Extract the guarded type `T` from a `Guard`. */ export declare type GuardType = G extends Guard ? T : never; /** * Invoke a predicate through the sanctioned never-throw boundary. * * @param callback - The predicate to invoke with no arguments * @returns `true` only when the callback returns the boolean value `true` * * @example * ```ts * holds(() => value instanceof Widget) // false when inspection throws * ``` */ export declare function holds(callback: () => boolean): boolean; /** * Infer the static TypeScript type a {@link ContractShape} describes. * * @remarks * Structural and recursive: optional object fields surface as optional * properties, nullable wrappers add `| null`, and a literal tuple becomes a * string/number/boolean-literal union. * * The first, non-distributive branch bails out to `unknown` when `S` is the * full widened {@link ContractShape} union. Five members of that union recurse * back into the whole union through their defaulted generics, so inferring the * full union is a fixed point that can never shrink — the compiler would fan * out until it aborts with TS2589. Bailing out lazily short-circuits that * fixed point (the untaken branch is never instantiated) while every narrow * shape and every partial union still flows through the exact chain below. * * The `ObjectShape` branch's `additionalProperties` guard (`[A] extends * [boolean | ContractShape]`) is likewise wrapped in a tuple to stay * non-distributive: a naked `A extends boolean | ContractShape` distributes * over a union `A`, fanning a wide `additionalProperties` type into one * {@link InferObject} instantiation per union member instead of one * instantiation over the whole union — the same TS2589 risk under repeated * nesting. {@link InferIndex} and {@link InferOpenIndex} apply the identical * tuple guard to their own `A` parameter for the same reason. */ export declare type Infer = [ContractShape] extends [S] ? unknown : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends { readonly type: 'literal'; readonly values: infer V; } ? V extends ReadonlyArray ? L : never : S extends { readonly type: 'array'; readonly items: infer I; } ? I extends ContractShape ? ReadonlyArray> : never : S extends ObjectShape ? P extends Readonly> ? [A] extends [boolean | ContractShape] ? InferObject : never : never : S extends { readonly type: 'union'; readonly variants: infer V; } ? V extends readonly ContractShape[] ? InferUnion : never : S extends { readonly type: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer | undefined : never : S extends { readonly type: 'nullable'; readonly inner: infer I; } ? I extends ContractShape ? Infer | null : never : S extends JSONShape ? JSONValue : unknown; /** * The default maximum number of object properties / array elements * {@link valueToSchema} samples per container, frozen. * * @remarks * Bounds the work (and the emitted schema's size) against a wide record or a * huge array — properties/elements beyond this cap are never inspected. * Overridable per call via {@link ValueToSchemaOptions.maxProperties}. */ export declare const INFER_BREADTH_LIMIT = 256; /** * The maximum object/array nesting depth {@link valueToSchema} walks, frozen. * * @remarks * Bounds inference against adversarial or cyclic runtime input — once the * remaining depth budget reaches zero, inference stops descending and emits * the empty accept-anything schema `{}` for that branch instead of recursing * further. LOWERABLE per call via {@link ValueToSchemaOptions.maxDepth}; a * higher value is held here. * * A ceiling rather than a default, because the walk recurses: what a deeper * walk spends is the JavaScript call stack rather than this budget, and that * stack is not a fixed quantity. The survivable depth measured on one host rose * across repeated calls within a single process as the engine optimized, and * fell to roughly this number under a reduced stack size. Any larger constant * therefore has a host where it fails, which is why none is published. */ export declare const INFER_DEPTH_LIMIT = 32; /** * The default maximum number of distinct values a multi-sample slot may hold * before enum inference gives up and falls back to a bare `type`, frozen. * * @remarks * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples} * will emit — a slot with distinct-value count at or above this limit is * treated as unbounded (an ID column, not a category) and never gets an * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum} * (which gates whether enum inference runs at all). */ export declare const INFER_ENUM_LIMIT = 12; /** * Infer a `JSONSchema` array fragment from an array's sampled elements. * * @remarks * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the * first `breadth` elements are classified via {@link inferValue} (one less * depth) and unified with {@link unifySchemas}: a single distinct element * schema becomes `items` directly; multiple distinct schemas become * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of * `value` both yield the empty schema `{}` instead of descending. A SPARSE * array (holes, e.g. `[1, , 3]`) has no JSON expression and widens to the * accept-anything `{}`, the same treatment `NaN`, a function, a symbol, a * `Map` and a `Set` receive — it is not read as a list of present `undefined` * leaves, because the array schema that reading produced was rejected by its * own compiled guard, which is the one direction the round-trip law forbids. * Invalid direct depth and breadth budgets use {@link sanitizeBudget} with the * package defaults, matching the higher-level inference boundaries. * * ALL reads of `value` — including its `length` — happen inside * {@link attempt}, then cross {@link readValue}: a hostile `length` getter, * throwing own-getter element, or hostile element access raises the shared * coded refusal instead of returning the empty-array schema. A genuinely * empty sampled/classified list still returns `{ type: 'array' }` with no * `items`. A same-object re-inference at the same remaining `depth` is served * from `memo` instead of recomputing (guards a shared-reference DAG against * exponential blowup). * * @param value - The array to infer from * @param depth - Remaining descent budget; invalid values use the package default * @param breadth - Maximum elements sampled; invalid values use the package default * @param closed - Threaded through to nested object elements * @param format - Threaded through to nested string/`Date` elements * @param visited - The ancestor set guarding against cycles * @param memo - A per-call `(object, remaining depth) → schema` cache guarding * against exponential re-inference of a shared-reference DAG * @returns The inferred array schema * @throws {ContractError} When the array cannot be read * * @example * ```ts * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap()) * // { type: 'array', items: { type: 'number' } } * ``` */ export declare function inferArray(value: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet, memo: WeakMap>): JSONSchema; /** * The index-signature contribution of a pure record shape's `additionalProperties` * — the `recordShape` case, where `properties` is empty. * * @remarks * `false` (closed) contributes `unknown`, which collapses away in an * intersection — a closed object's {@link Infer} is unaffected. `true` (open, * unconstrained) contributes an `unknown`-valued index signature. A * {@link ContractShape} (open, constrained) contributes an index signature * typed to that shape's own `Infer` — sound here because there are no fixed * properties for the index to collide with. * * @remarks * The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay * non-distributive, matching {@link Infer}'s own object-branch guard — see * that type's remarks for why a naked `extends` here would fan a wide `A` * into a union of `InferIndex` instantiations instead of one. */ export declare type InferIndex = [A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: Infer; } : unknown; /** {@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. */ export declare type InferMutable = { -readonly [K in keyof Infer]: Infer[K]; }; /** * {@link Infer} of an object shape's `properties` — the required keys, plus the * `optional`-wrapped keys as optional members, plus the index-signature * contribution of `additionalProperties` (see {@link InferIndex}). * * @remarks * The `[keyof P] extends [never]` split is hoisted to the front (rather than * folded into the intersection's second operand) so a pure record shape * (`P` empty) short-circuits straight to {@link InferIndex} without ever * building the `Readonly<{} & {}>` intersection shell — the clean * `Readonly>` {@link InferIndex} already returns. A closed * empty object (`P` empty, `A` `false`/absent) still resolves through * {@link InferIndex}'s own `[A] extends [false]` branch to * `Readonly>`, preserving the empty-closed-object result. * A shape with fixed properties always routes through {@link InferOpenIndex}. */ export declare type InferObject

>, A extends boolean | ContractShape = false> = [keyof P] extends [never] ? [A] extends [false] ? Readonly> : InferIndex : Readonly<{ [K in keyof P as P[K] extends { readonly type: 'optional'; } ? never : K]: Infer; } & { [K in keyof P as P[K] extends { readonly type: 'optional'; } ? K : never]?: P[K] extends { readonly type: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer : never : never; }> & InferOpenIndex; /** * Infer a `JSONSchema` object fragment from a plain record's sampled * properties. * * @remarks * Own enumerable string keys via {@link enumerableKeys}, sorted * lexicographically for deterministic output, capped at `breadth`. This is the * same property view compiled object guards, parsers, and reporters use. Each * property value is read through {@link attempt} and {@link readValue}; a * hostile getter raises the shared coded refusal. A readable property whose * value is `undefined` is DROPPED * — JSON encodes no such property (`JSON.stringify({ a: undefined })` is * `'{}'`), so it contributes neither a `properties` entry nor a `required` * entry. Every other present key is required (single-value mode). * * Emits `additionalProperties: false` when `closed`, `true` otherwise — * mirroring {@link compileSchema}'s object-emission convention — EXCEPT when * the sampled key list no longer describes every key `value` actually carries, * which happens two ways: the own-key list exceeds `breadth` (truncation), or * a key was dropped for holding `undefined`. Either way `additionalProperties` * is forced to `true` regardless of `closed`, because a CLOSED schema built * from an incomplete key list would reject the very object it was inferred * from (`recordOf` rejects any own key the shape does not declare). * * Depth exhaustion or a cyclic re-encounter of `value` both yield `{}`. A * same-object re-inference at the same remaining `depth` is served from `memo` * instead of recomputing (guards a shared-reference DAG against exponential * blowup). * * @param value - The record to infer from * @param depth - Remaining descent budget * @param breadth - The maximum number of properties sampled * @param closed - Whether the emitted schema closes to unknown keys * @param format - Threaded through to nested string/`Date` properties * @param visited - The ancestor set guarding against cycles * @param memo - A per-call `(object, remaining depth) → schema` cache guarding * against exponential re-inference of a shared-reference DAG * @returns The inferred object schema * @throws {ContractError} When the record cannot be read * * @example * ```ts * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap()) * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'], * // additionalProperties: false } * ``` */ export declare function inferObject(value: Record, depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet, memo: WeakMap>): JSONSchema; /** * The index-signature contribution of a MIXED object shape's * `additionalProperties` — one with both fixed `properties` and an open tail. * * @remarks * A typed index (`{ readonly [k: string]: Infer }`) collapses any * differently-typed fixed property to `never` on intersection and makes the * object type unconstructable — TypeScript rejects assigning any property * whose type differs from the index value type. So when `A` is a * {@link ContractShape} here, the index is deliberately widened to * `{ readonly [k: string]: unknown }`: the static type stops over-claiming the * extra-key type while the runtime guard still validates extras against `A`. * `false` / `true` behave exactly as {@link InferIndex}. * * @remarks * The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay * non-distributive, matching {@link Infer}'s own object-branch guard and * {@link InferIndex}'s tail — see {@link Infer}'s remarks for why a naked * `extends` here would fan a wide `A` into a union of instantiations. */ export declare type InferOpenIndex = [A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: unknown; } : unknown; /** * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated * primitive slot — the multi-sample-only counterpart to * {@link stringToFormat} ({@link valueToSchema} never emits `enum`). * * @remarks * Fires only when ALL of: every value is the same primitive kind (all string * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed * slot never qualifies, and a slot containing `NaN` / `±Infinity` never * qualifies either, since {@link canonicalStringify} collapses `NaN` to * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2 * values are given; the distinct-by-{@link canonicalStringify} count is LESS * than the value count (repetition required — separates a categorical column * from an ID column); and the distinct count is at most `limit`. The emitted * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s * `literalShape` emission. Members are sorted by canonical key for * deterministic output. * * A member {@link canonicalStringify} cannot key has no identity to * de-duplicate against, so the whole slot is enum-INELIGIBLE and returns * `undefined` — widening to the caller's bare `type` rather than emitting an * `enum` that might silently omit a value. (A string or finite number always * canonicalizes, so this only guards the total contract.) * * @param values - The collected slot values * @param limit - The maximum distinct-value count before giving up * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible * * @example * ```ts * inferPrimitiveEnum(['active', 'inactive', 'active'], 12) * // { enum: ['active', 'inactive'] } * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition * ``` */ export declare function inferPrimitiveEnum(values: readonly unknown[], limit: number): JSONSchema | undefined; /** * Infer a `JSONSchema` object fragment from a set of plain-record samples * (e.g. database rows) — the record-specialized branch of * {@link samplesToSchema}. * * @remarks * `properties` is the union of every sample's own keys (sorted, capped at * `breadth`); a key is `required` only when present (and non-`undefined`) in * EVERY sample. Each key's schema is inferred over the collected values for * that key via {@link inferSamples} itself (one less depth), so a * property that is itself an array/object of varying shape across rows is * unified the same way the top level is, and the same `format` / `enum` * gating applies per key. Unlike {@link inferObject}/ * {@link inferArray}, this path carries no `visited` `WeakSet` — a value * shared by reference across multiple sample rows is legitimate (not a * cycle back to an ancestor), so termination on cyclic row data relies on * the decrementing `depth` budget and the shared {@link SampleMemo}. * * `additionalProperties` is forced to `true` regardless of `closed` when the * key union exceeds `breadth`, or a readable row carries a key as an own * property holding `undefined`. A hostile getter or failed KEY walk throws the * shared coded refusal instead of dropping a key or widening the whole slot. * * The memo is keyed by the slot's ORDERED row identities, not by a single row. * Keying only the one-row slot left every MULTI-row slot — the shape this door * exists for — re-inferring a shared child once per path: two rows sharing one * `{ a: child, b: child }` detail cost `2^depth` inferences, the identical * denial of service the one-row memo was added to remove, through the same * public door. * * @param samples - The plain-record samples * @param depth - Remaining descent budget * @param breadth - The maximum number of properties sampled * @param closed - Whether the emitted schema closes to unknown keys * @param format - Whether a unanimous string column gains a `format` keyword * @param enumOn - Whether a low-cardinality column may emit `enum` * @param memo - The walk's {@link SampleMemo}, shared with * {@link inferSamples}; build one with {@link buildSampleMemo} * @returns The inferred object schema * @throws {ContractError} When a sample row or the memo cannot be read * * @example * ```ts * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false, buildSampleMemo()) * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } }, * // required: ['id'], additionalProperties: false } * ``` */ export declare function inferRecordSamples(samples: ReadonlyArray>, depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean, memo: SampleMemo): JSONSchema; /** * Infer a `JSONSchema` for a collected slot of sample values — the shared * non-record recursion step behind {@link samplesToSchema} (top level) and * {@link inferRecordSamples} (per collected property). * * @remarks * When every value is itself a plain record, delegates to * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality, * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins * outright (ENUM > FORMAT > bare string). Failing that, each value is * classified independently via {@link inferValue} with `format` FORCED OFF * (the multi-sample seam: nested formats never compound into an `anyOf`) and * unified with {@link unifySchemas}; only when that unified result is exactly * `{ type: 'string' }` and the outer `format` flag is on does * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`. * * @param samples - The collected slot values * @param depth - Remaining descent budget * @param breadth - The maximum number of properties/elements sampled per nested container * @param closed - Whether nested objects close to unknown keys * @param format - Whether a unanimous string slot gains a `format` keyword * @param enumOn - Whether low-cardinality primitive slots may emit `enum` * @param memo - The walk's {@link SampleMemo}, shared with * {@link inferRecordSamples} so a row list reached through * several slots is inferred once; build one with * {@link buildSampleMemo} * @returns The inferred schema for the slot * @throws {ContractError} When the samples or the memo cannot be read * * @example * ```ts * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false, buildSampleMemo()) * // { type: 'string', format: 'date' } * ``` */ export declare function inferSamples(samples: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean, memo: SampleMemo): JSONSchema; /** {@link Infer} of a union shape's `variants` — the union of each variant's inferred type. */ export declare type InferUnion = V extends ReadonlyArray ? (U extends ContractShape ? Infer : never) : never; /** * Infer a `JSONSchema` fragment for one runtime value — the recursive spine * shared by {@link valueToSchema} and, per collected property/element, by * {@link inferArray} / {@link inferObject}. * * @remarks * Terminates on cyclic readable input via `visited`; failed traversal is * refused by the containing public reader. Leaf * classification order: `null`, boolean, integer (`Number.isInteger` * semantics — `-0` counts), finite non-integer number, string (gaining a * `format` keyword when `format` is on and {@link stringToFormat} matches), * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`, * plus `format: 'date-time'` when `format` is on); everything else — a * NON-FINITE number (`NaN` / `±Infinity`), a function, a symbol, a bigint, * `undefined`, and other non-plain objects such as `Map` / `Set` — is the * empty accept-anything schema `{}`. * * A non-finite number bottoms out with the other JSON-inexpressible values on * purpose: JSON carries no `NaN` / `±Infinity` (`JSON.stringify(Number.NaN)` * is `'null'`), so `{ type: 'number' }` would ASSERT something a JSON Schema * validator rejects — and the shape {@link schemaToShape} builds from it would * reject the very sample it was inferred from. `{}` is the truthful * description, and it inverts to an accept-anything shape, keeping * `compileGuard(schemaToShape(valueToSchema(v)))(v)` true. * * @param value - The value to classify * @param depth - Remaining descent budget (0 halts recursion with `{}`) * @param breadth - The per-container sampling cap passed through to children * @param closed - Whether descended objects emit `additionalProperties: false` * @param format - Whether a string/`Date` leaf gains a `format` keyword * @param visited - The ancestor set guarding against cycles * @param memo - A per-call `(object, remaining depth) → schema` cache guarding * against exponential re-inference of a shared-reference DAG * @returns The inferred schema fragment for `value` * @throws {ContractError} When a traversed container cannot be read * * @example * ```ts * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' } * ``` */ export declare function inferValue(value: unknown, depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet, memo: WeakMap>): JSONSchema; /** * Build a guard that accepts instances of the provided constructor. * * @remarks * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first, * so passing an arrow function does not silently produce a broken guard. * * @example * ```ts * const isDateValue = instanceOf(Date) * isDateValue(new Date()) // true * isDateValue({}) // false * ``` */ export declare function instanceOf object>(ctor: C): Guard>; /** * Build an integer {@link NumberShape} — forces `integer: true`. * * @remarks * The emitted JSON Schema uses `"type": "integer"` and the guard rejects * fractional numbers. * * @param options - Optional bounds and `description` (no `integer` key) * @returns An integer number shape * @throws {ContractError} When a present bound is not finite */ export declare function integerShape(options?: Omit): NumberShape; /** Intersection of the types guarded by a tuple of guards — backs `intersectionOf`. */ export declare type IntersectionFromGuards>> = UnionToIntersection>; /** * Build a guard that accepts values matching ALL of the provided guards — the * variadic form of {@link andOf}. * * @example * ```ts * const isNonEmpty = intersectionOf(isString, isNonEmptyString) * ``` */ export declare function intersectionOf>>(...guards: Gs): Guard>; export declare function intersectionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard; /** * Every host operation this package dispatches through, captured while this * module evaluates. * * @remarks * THE answer to a defect class that mutated four times before anyone stated it * as a class. A caller can replace a global constructor, a static, a prototype * member, or a symbol-keyed hook, and each replacement can fail in two ways: it * can THROW, which a boundary contains, or it can LIE, which no boundary can * see. `Object.freeze = (value) => value` is the second kind and it is the * worse one: every cloner succeeds, publishes a mutable graph, and the caller * cannot tell that the package's central guarantee evaporated. * * Containment cannot close that, because there is nothing to contain — only * capture can, and only capture taken while this module evaluates. A module's * initializers run at import, so a reference read here is whatever was * installed at the moment THIS module evaluated, and reading it later, at the * call site, is reading whatever the caller most recently installed. "Before any * caller code runs" is the tempting phrasing and it is false in exactly the case * the limit below names, so it is not used. * * The limit that follows, stated as a limit rather than as a guarantee: capture * is only as early as this package's own evaluation. A consumer module that * evaluates BEFORE `@orkestrel/contract` — ESM evaluates imports in source * order — chooses what this table captures, and no mechanism inside the package * can reach code that ran before the package existed. That precondition is * outside this package's control, and an adversary who holds it can replace the * package wholesale rather than bother with the table, so it is named here * instead of defended. * * Membership rule, stated so a reviewer can apply it and a new call site knows * where to go: **every host operation this package dispatches by name whose * result a published answer depends on.** That admits statics, constructors and * namespaces, and — this is the part the earlier wording got wrong by writing * the rule from the rows instead of the rows from the rule — it admits a * PROTOTYPE member on the same terms, including an ACCESSOR's getter, * dispatched onto the package's own receiver through {@link INTRINSICS.apply}. * A round that read `Object.getOwnPropertyDescriptor(RegExp.prototype, 'source')` * per call had captured nothing: capture is decided by WHEN the reference is * taken, not by which reflective spelling takes it. * * Collection membership was previously excluded on the grounds that it needs a * data structure rather than one operation, and the exclusion was answered with * an exported class whose `has` method every consumer could rewrite — which * reproduced the whole defect one prototype higher. The rule has no exception * for it: `Set.prototype.has` / `.add` / `.forEach`, * `Map.prototype.has` / `.forEach`, and * `WeakSet.prototype.has` / `.add` / `.delete` are ordinary rows here, dispatched * onto collections this package built and no caller holds, and every membership * and visitation answer in the package is asked through the module-scope * functions {@link matchesMember} / {@link admitMember} / * {@link matchesVisited} / {@link admitVisited} / {@link omitVisited}. A module * binding is not a property, so there is no member on that path to replace. * * The walk-collection exclusion the earlier wording carried — "a redirect * corrupts it inside a boundary and the door refuses, which is loud" — was * false in the direction the corpus itself installs. `WeakSet.prototype.has` * answering `false` does not make a cyclic clone refuse; it removes the * termination bound, and a door that never returns is the one failure no * boundary can report. Visitation state is captured here for that reason. * * @example * ```ts * INTRINSICS.freeze(snapshot) // the genuine Object.freeze, whatever the caller installed * ``` */ export declare const INTRINSICS: Readonly<{ /** `Object.freeze` — the operation the ownership guarantee is made of. */ freeze: { (f: T): T; (o: T): Readonly; (o: T): Readonly; }; /** `Object.isFrozen` — the independent check that the guarantee actually held. */ frozen: (o: any) => boolean; /** `Object.keys` — the own enumerable string-key population of a snapshot. */ keys: { (o: object): string[]; (o: {}): string[]; }; /** `Object.values` — the own enumerable value population of a snapshot. */ values: { (o: { [s: string]: T; } | ArrayLike): T[]; (o: {}): any[]; }; /** `Object.hasOwn` — own presence, so no read leaves a container for its prototype. */ own: (o: object, v: PropertyKey) => boolean; /** `Object.is` — `SameValue`, so a `NaN` or signed-zero comparison stays exact. */ same: (value1: any, value2: any) => boolean; /** `Object.create` — the null-prototype and prototype-pinned accumulators. */ create: { (o: object | null): any; (o: object | null, properties: PropertyDescriptorMap & ThisType): any; }; /** `Object.getOwnPropertyDescriptor` — value observation that runs no accessor. */ describe: (o: any, p: PropertyKey) => PropertyDescriptor | undefined; /** `Object.defineProperty` — exact placement of an own data property. */ define: (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T; /** `Object.getPrototypeOf` — the record-brand observation. */ prototype: (o: any) => any; /** `Object.getOwnPropertySymbols` — the own-symbol population. */ symbols: (o: any) => symbol[]; /** `Object.prototype` — the realm-local plain-record prototype identity. */ base: Object; /** `Reflect.get` — a proxy-visible read that reports the trap's exact answer. */ read: typeof Reflect.get; /** `Reflect.set` — a proxy-visible write. */ write: typeof Reflect.set; /** `Reflect.ownKeys` — the complete own-key population, strings and symbols. */ members: typeof Reflect.ownKeys; /** `Reflect.has` — a proxy-visible presence observation. */ present: typeof Reflect.has; /** `Reflect.getOwnPropertyDescriptor` — the reflective descriptor observation. */ reveal: typeof Reflect.getOwnPropertyDescriptor; /** `Reflect.defineProperty` — placement that answers instead of throwing. */ declare: typeof Reflect.defineProperty; /** `Reflect.getPrototypeOf` — the reflective prototype observation. */ parent: typeof Reflect.getPrototypeOf; /** `Reflect.apply` — dispatch of a captured method onto its receiver. */ apply: typeof Reflect.apply; /** `Reflect.construct` — construction with an explicit new target. */ construct: typeof Reflect.construct; /** `Number.isFinite` — the finite-bound test every numeric shape refuses on. */ finite: (number: unknown) => boolean; /** `Number.isInteger` — the integer-budget test the inference caps refuse on. */ integer: (number: unknown) => boolean; /** `Number.isSafeInteger` — the safe-integer test every length bound refuses on. */ safe: (number: unknown) => boolean; /** `Number.isNaN` — the calendar-validity test for a parsed instant. */ nan: (number: unknown) => boolean; /** `Array.isArray` — array identity across realms. */ array: (arg: any) => arg is any[]; /** `JSON.stringify` — the escaping used by previews and canonical text. */ stringify: { (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string; (value: any, replacer?: (number | string)[] | null, space?: string | number): string; }; /** `JSON.parse` — document decoding. */ decode: (text: string, reviver?: (this: any, key: string, value: any) => any) => any; /** `Math.floor` — index and quantity flooring. */ floor: (x: number) => number; /** `Math.ceil` — index and quantity ceiling. */ ceil: (x: number) => number; /** `Math.max` — bound selection. */ max: (...values: number[]) => number; /** `Math.min` — bound selection. */ min: (...values: number[]) => number; /** `Math.imul` — the seeded generator's mixing step. */ imul: (x: number, y: number) => number; /** `String` — primitive text coercion. */ text: StringConstructor; /** `Number` — primitive numeric coercion. */ numeric: NumberConstructor; /** `RegExp` — pattern construction from captured source and flags. */ pattern: RegExpConstructor; /** * `RegExp.prototype.exec` — THE pattern membership answer, dispatched through * `apply`. * * @remarks * `test` is deliberately absent. `RegExp.prototype.test` is spec-defined in * terms of `RegExpExec`, which re-reads `exec` OFF THE RECEIVER and calls it * when it is callable, so capturing `test` and dispatching it still asks * whatever the caller installed on `RegExp.prototype.exec`. Only * `RegExp.prototype.exec` itself is `RegExpBuiltinExec`, which reads the * pattern's internal slots and no member at all. A capture that still routes * through the replaced member is not a capture. */ captures: (string: string) => RegExpExecArray | null; /** The `RegExp.prototype.source` getter — the pattern text a published schema embeds, dispatched through `apply`. */ expression: (() => any) | undefined; /** The `RegExp.prototype.flags` getter — the flag text an owned pattern is rebuilt from, dispatched through `apply`. */ modifiers: (() => any) | undefined; /** `Array` — array construction. */ list: ArrayConstructor; /** `Array.prototype.sort` — the deterministic ordering every published schema is emitted in, dispatched through `apply`. */ order: (compareFn?: ((a: any, b: any) => number) | undefined) => any[]; /** `Map` — keyed working state. */ map: MapConstructor; /** `Map.prototype.get` — a memo read whose answer a published graph embeds, dispatched through `apply`. */ fetch: (key: any) => any; /** `Map.prototype.set` — a memo write a published graph is later assembled from, dispatched through `apply`. */ store: (key: any, value: any) => Map; /** `Map.prototype.has` — a memo presence answer that decides whether a node is captured, dispatched through `apply`. */ keyed: (key: any) => boolean; /** `Map.prototype.forEach` — the only full view of a caller's `Map` that runs no iterator, dispatched through `apply`. */ pairs: (callbackfn: (value: any, key: any, map: Map) => void, thisArg?: any) => void; /** `Set` — membership working state. */ set: SetConstructor; /** `Set.prototype.has` — THE membership answer every published verdict rests on, dispatched through `apply`. */ member: (value: any) => boolean; /** `Set.prototype.add` — collection of one more member, dispatched through `apply`. */ admit: (value: any) => Set; /** `Set.prototype.forEach` — the only full view of a caller's `Set` that runs no iterator, dispatched through `apply`. */ sweep: (callbackfn: (value: any, value2: any, set: Set) => void, thisArg?: any) => void; /** `WeakMap` — object-keyed working state. */ weakMap: WeakMapConstructor; /** `WeakMap.prototype.get` — an object-keyed memo read a published graph embeds, dispatched through `apply`. */ recall: (key: WeakKey) => any; /** `WeakMap.prototype.set` — an object-keyed memo write, dispatched through `apply`. */ retain: (key: WeakKey, value: any) => WeakMap; /** `WeakSet` — object-membership working state. */ weakSet: WeakSetConstructor; /** `WeakSet.prototype.has` — the visitation answer every traversal's termination rests on, dispatched through `apply`. */ tracked: (value: WeakKey) => boolean; /** `WeakSet.prototype.add` — entry onto the active path, dispatched through `apply`. */ track: (value: WeakKey) => WeakSet; /** `WeakSet.prototype.delete` — exit from the active path, dispatched through `apply`. */ untrack: (value: WeakKey) => boolean; /** `Error` — the internal marker an engine throws into its own contained walk. */ error: ErrorConstructor; /** `Date` — calendar validation of an ISO instant. */ date: DateConstructor; /** `Date.prototype.getTime` — the calendar verdict a published `format` rests on, dispatched through `apply`. */ instant: () => number; /** `Date.now` — the wall-clock reading a default generator seed is drawn from. */ now: () => number; }>; /** Determine whether a value is an array. * * @example * ```ts * isArray([1, 2]) // true * isArray('12') // false * ``` */ export declare function isArray(value: unknown): value is readonly T[]; /** Determine whether a value is an `ArrayBuffer`. * * @example * ```ts * isArrayBuffer(new ArrayBuffer(8)) // true * isArrayBuffer([]) // false * ``` */ export declare function isArrayBuffer(value: unknown): value is ArrayBuffer; /** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`). * * @example * ```ts * isArrayBufferView(new Uint8Array(4)) // true * isArrayBufferView([1, 2, 3, 4]) // false * ``` */ export declare function isArrayBufferView(value: unknown): value is ArrayBufferView; /** * Determine whether a value is a native `async function`. * * @remarks * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is * unreliable across realms. The `?.` keeps the guard total (§14): a function * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`. * * @example * ```ts * isAsyncFunction(async () => {}) // true * isAsyncFunction(() => {}) // false * ``` */ export declare function isAsyncFunction(value: unknown): value is AnyAsyncFunction; /** Determine whether a value is an async generator function (`async function*`). * * @example * ```ts * isAsyncGeneratorFunction(async function* () {}) // true * isAsyncGeneratorFunction(function* () {}) // false * ``` */ export declare function isAsyncGeneratorFunction(value: unknown): value is (...args: unknown[]) => AsyncGenerator; /** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`). * * @example * ```ts * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true * isAsyncIterable([1, 2]) // false * ``` */ export declare function isAsyncIterable(value: unknown): value is AsyncIterable; /** Determine whether a value is a bigint. * * @example * ```ts * isBigInt(1n) // true * isBigInt(1) // false * ``` */ export declare function isBigInt(value: unknown): value is bigint; /** * Determine whether a value is a `BigInt64Array`. * * @remarks * Guards the global existence of `BigInt64Array` first — safe in environments * that pre-date the BigInt typed-array additions. * * @example * ```ts * isBigInt64Array(new BigInt64Array(2)) // true * isBigInt64Array(new Float64Array(2)) // false * ``` */ export declare function isBigInt64Array(value: unknown): value is BigInt64Array; /** * Determine whether a value is a `BigUint64Array`. * * @remarks * Guards the global existence of `BigUint64Array` first — safe in environments * that pre-date the BigInt typed-array additions. * * @example * ```ts * isBigUint64Array(new BigUint64Array(2)) // true * isBigUint64Array(new BigInt64Array(2)) // false * ``` */ export declare function isBigUint64Array(value: unknown): value is BigUint64Array; /** Determine whether a value is a boolean. * * @example * ```ts * isBoolean(true) // true * isBoolean(1) // false * ``` */ export declare function isBoolean(value: unknown): value is boolean; /** * Determine whether a value is a depth-bounded JSON record. * * @remarks * Requires the existing plain-record root invariant before applying * {@link isBoundedJSONValue}. Arrays therefore remain valid bounded JSON * values but never bounded JSON records. * * @param value - The value to inspect * @returns `true` when the value is a plain-record-rooted bounded JSON value * * @example * ```ts * isBoundedJSONRecord({ value: 1 }) // true * isBoundedJSONRecord([1]) // false * ``` */ export declare function isBoundedJSONRecord(value: unknown): value is JSONRecord; /** * Determine whether a value is JSON-valid within the fixed container-depth limit. * * @remarks * Runs the total depth predicate before the existing JSON guard. These are * sequential observations of caller-owned input, not an atomic snapshot. * * @param value - The value to inspect * @returns `true` when the value is both depth-bounded and a valid {@link JSONValue} * * @example * ```ts * isBoundedJSONValue({ nested: [1] }) // true * isBoundedJSONValue(new Date()) // false * ``` */ export declare function isBoundedJSONValue(value: unknown): value is JSONValue; /** * Determine whether a value can be used as a `new`-target constructor. * * @remarks * Probes with `Reflect.construct(String, [], value)`: a real constructor * succeeds, while arrow functions, plain functions, and non-functions throw * and yield `false`. Never throws. Backs the `instanceOf` combinator. * * @example * ```ts * isConstructor(class X {}) // true * isConstructor(() => {}) // false * ``` */ export declare function isConstructor(value: unknown): value is AnyConstructor; /** * Checks whether an unknown value is a {@link ContractError}. * * @remarks * Recognition combines a global own-property brand with the native `Error` * base, a subclass prototype, the fixed name, and a declared contract code. * The brand stores the error itself and recognition requires that exact * identity. A transparent proxy is therefore refused because its forwarded * descriptor still stores the target, not the proxy. * The brand is recognized across duplicate installations and ESM/CommonJS * module copies at 0.0.13 or later. A copy earlier than 0.0.13 stamps no brand, * so an error it throws stays outside the type, and so does a plain or * property-only lookalike. * * @param value - The value to inspect * @returns True only for a `ContractError` instance; false otherwise * * @example * ```ts * isContractError(new ContractError('Invalid shape', { code: 'placement' })) // true * isContractError(new Error('Invalid shape')) // false * ``` */ export declare function isContractError(value: unknown): value is ContractError; /** Determine whether a value is a `DataView`. * * @example * ```ts * isDataView(new DataView(new ArrayBuffer(8))) // true * isDataView(new ArrayBuffer(8)) // false * ``` */ export declare function isDataView(value: unknown): value is DataView; /** Determine whether a value is a `Date`. * * @example * ```ts * isDate(new Date()) // true * isDate('2024-01-01') // false * ``` */ export declare function isDate(value: unknown): value is Date; /** Determine whether a value is defined (neither `null` nor `undefined`). * * @example * ```ts * isDefined('hi') // true * isDefined(null) // false * isDefined(undefined) // false * ``` */ export declare function isDefined(value: T | null | undefined): value is T; /** Determine whether a value is an empty array. * * @example * ```ts * isEmptyArray([]) // true * isEmptyArray([1]) // false * ``` */ export declare function isEmptyArray(value: unknown): value is readonly []; /** Determine whether a value is an empty `Map`. * * @example * ```ts * isEmptyMap(new Map()) // true * isEmptyMap(new Map([['a', 1]])) // false * ``` */ export declare function isEmptyMap(value: unknown): value is ReadonlyMap; /** Determine whether a value is an empty plain object — no OWN keys at all, of any * kind: string or symbol, enumerable or not. * * @remarks * The own-key population is the one `recordOf` inspects (`Reflect.ownKeys`), and * it has to be: this guard narrows to `Record`, so * counting only ENUMERABLE keys made the narrowing unsound — a record carrying * an own non-enumerable `hidden: 1` answered `true` here while `recordOf({})` * saw the key and rejected the same value, and the enumerable-symbol and * non-enumerable-string cases were treated differently for no stated reason. * * @example * ```ts * isEmptyObject({}) // true * isEmptyObject({ a: 1 }) // false * isEmptyObject(Object.defineProperty({}, 'hidden', { value: 1 })) // false * ``` */ export declare function isEmptyObject(value: unknown): value is Record; /** Determine whether a value is an empty `Set`. * * @example * ```ts * isEmptySet(new Set()) // true * isEmptySet(new Set([1])) // false * ``` */ export declare function isEmptySet(value: unknown): value is ReadonlySet; /** Determine whether a value is the empty string `''`. * * @example * ```ts * isEmptyString('') // true * isEmptyString('a') // false * ``` */ export declare function isEmptyString(value: unknown): value is ''; /** Determine whether a value is an `Error`. * * @example * ```ts * isError(new Error('boom')) // true * isError('boom') // false * ``` */ export declare function isError(value: unknown): value is Error; /** Determine whether a value is exactly `false`. * * @example * ```ts * isFalse(false) // true * isFalse(true) // false * ``` */ export declare function isFalse(value: unknown): value is false; /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). * * @example * ```ts * isFiniteNumber(42) // true * isFiniteNumber(Number.NaN) // false * isFiniteNumber(Infinity) // false * ``` */ export declare function isFiniteNumber(value: unknown): value is number; /** Determine whether a value is a `Float32Array`. * * @example * ```ts * isFloat32Array(new Float32Array(2)) // true * isFloat32Array(new Float64Array(2)) // false * ``` */ export declare function isFloat32Array(value: unknown): value is Float32Array; /** Determine whether a value is a `Float64Array`. * * @example * ```ts * isFloat64Array(new Float64Array(2)) // true * isFloat64Array(new Float32Array(2)) // false * ``` */ export declare function isFloat64Array(value: unknown): value is Float64Array; /** Determine whether a value is callable. * * @example * ```ts * isFunction(() => {}) // true * isFunction({}) // false * ``` */ export declare function isFunction(value: unknown): value is AnyFunction; /** Determine whether a value is a generator function (`function*`). * * @example * ```ts * isGeneratorFunction(function* () {}) // true * isGeneratorFunction(() => {}) // false * ``` */ export declare function isGeneratorFunction(value: unknown): value is (...args: unknown[]) => Generator; /** * Determine whether a value is an instance of a constructor, contained against * a throwing `instanceof` check. * * @remarks * The low-level total helper every `instanceof`-based guard in this file (and * the `instanceOf` combinator) routes through. A bare `value instanceof X` is * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This * wraps the check in {@link holds} (see ./helpers.js) so any such throw * yields `false` instead of escaping. * * @param value - The value to test * @param ctor - The constructor to test against * @returns `true` when `value instanceof ctor`, `false` on a non-match or a * contained throw * * @example * ```ts * isInstance(new Date(), Date) // true * isInstance({}, Date) // false * ``` */ export declare function isInstance(value: unknown, ctor: C): value is InstanceType>; /** Determine whether a value is an `Int16Array`. * * @example * ```ts * isInt16Array(new Int16Array(2)) // true * isInt16Array(new Int8Array(2)) // false * ``` */ export declare function isInt16Array(value: unknown): value is Int16Array; /** Determine whether a value is an `Int32Array`. * * @example * ```ts * isInt32Array(new Int32Array(2)) // true * isInt32Array(new Int16Array(2)) // false * ``` */ export declare function isInt32Array(value: unknown): value is Int32Array; /** Determine whether a value is an `Int8Array`. * * @example * ```ts * isInt8Array(new Int8Array(2)) // true * isInt8Array(new Uint8Array(2)) // false * ``` */ export declare function isInt8Array(value: unknown): value is Int8Array; /** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers). * * @example * ```ts * isInteger(3) // true * isInteger(3.5) // false * ``` */ export declare function isInteger(value: unknown): value is number; /** * Determine whether a value implements the iterable protocol (`Symbol.iterator`). * * @remarks * Strings are explicitly included: a string has a callable `Symbol.iterator` * but is not an object, so the generic object path alone would miss it. * * @example * ```ts * isIterable([1, 2]) // true * isIterable('abc') // true * isIterable({ a: 1 }) // false * ``` */ export declare function isIterable(value: unknown): value is Iterable; /** * Determine whether a value is a primitive JSON value. * * @remarks * The flat leaf of any JSON document: `null`, a string, a **finite** number, or * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`. * * The recursive {@link isJSONValue} guard is shipped and stays total with * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`. * * @param value - The value to test * @returns `true` when `value` is `null`, a string, a finite number, or a boolean * * @example * ```ts * isJSONPrimitive(null) // true * isJSONPrimitive('hi') // true * isJSONPrimitive(42) // true * isJSONPrimitive(Number.NaN) // false — not representable in JSON * isJSONPrimitive({}) // false * ``` */ export declare function isJSONPrimitive(value: unknown): value is JSONPrimitive; /** * Determine whether a value is a cycle-safe JSON value. * * @remarks * Total guard: never throws, returns `false` for cycles, functions, `Date` * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records * are walked with an ancestor set so recursive input fails instead of hanging. * The whole walk runs inside `holds` (AGENTS §14): a hostile getter on a * record property, or a revoked `Proxy` anywhere in the structure, is caught * and yields `false` instead of escaping as a thrown error. * * @param value - The value to test * @returns `true` when the value has a JSON representation * * @example * ```ts * isJSONValue({ nested: [1, 'x', null] }) // true * isJSONValue(Number.NaN) // false * ``` */ export declare function isJSONValue(value: unknown): value is JSONValue; /** * Determine whether a value belongs to the string, number, or boolean literal domain. * * @remarks * Every JavaScript number belongs to this structural domain, including `NaN`, * `±Infinity`, and signed zero. Declaration and schema policies apply finiteness * separately where their contracts require it. * * @param value - The value to inspect * @returns `true` for a string, number, or boolean * * @example * ```ts * isLiteralValue(Number.NaN) // true * isLiteralValue(null) // false * ``` */ export declare function isLiteralValue(value: unknown): value is LiteralValue; /** Determine whether a value is a `Map`. * * @example * ```ts * isMap(new Map()) // true * isMap({}) // false * ``` */ export declare function isMap(value: unknown): value is ReadonlyMap; /** Determine whether a value is a non-empty array (at least one element). * * @example * ```ts * isNonEmptyArray([1]) // true * isNonEmptyArray([]) // false * ``` */ export declare function isNonEmptyArray(value: unknown): value is readonly [T, ...T[]]; /** Determine whether a value is a non-empty `Map` (at least one entry). * * @example * ```ts * isNonEmptyMap(new Map([['a', 1]])) // true * isNonEmptyMap(new Map()) // false * ``` */ export declare function isNonEmptyMap(value: unknown): value is ReadonlyMap; /** Determine whether a value is a non-empty plain object — at least one own key of * any kind: string or symbol, enumerable or not. * * @remarks * The exact negation of {@link isEmptyObject} over the same own-key population; * see there for why enumerability is not part of the rule. * * @example * ```ts * isNonEmptyObject({ a: 1 }) // true * isNonEmptyObject({}) // false * ``` */ export declare function isNonEmptyObject(value: unknown): value is Record; /** Determine whether a value is a non-empty `Set` (at least one element). * * @example * ```ts * isNonEmptySet(new Set([1])) // true * isNonEmptySet(new Set()) // false * ``` */ export declare function isNonEmptySet(value: unknown): value is ReadonlySet; /** Determine whether a value is a non-empty string (at least one character). * * @example * ```ts * isNonEmptyString('a') // true * isNonEmptyString('') // false * ``` */ export declare function isNonEmptyString(value: unknown): value is string; /** * Determine whether a value is a non-negative finite primitive integer. * * @remarks * Composes {@link isNonNegativeNumber} with {@link isInteger}. Representable * unsafe integers remain integers; safe-integer policy is a separate domain. * * @param value - The value to inspect * @returns `true` for non-negative integers other than `-0` * * @example * ```ts * isNonNegativeInteger(3) // true * isNonNegativeInteger(3.5) // false * ``` */ export declare function isNonNegativeInteger(value: unknown): value is number; /** * Determine whether a value is a finite primitive number at or above positive zero. * * @remarks * Positive fractions pass. Negative zero is rejected explicitly, and no * coercion or property access is performed for non-number inputs. * * @param value - The value to inspect * @returns `true` for finite primitive numbers greater than or equal to zero, except `-0` * * @example * ```ts * isNonNegativeNumber(0.5) // true * isNonNegativeNumber(-0) // false * ``` */ export declare function isNonNegativeNumber(value: unknown): value is number; /** Determine whether a value is `null`. * * @example * ```ts * isNull(null) // true * isNull(undefined) // false * ``` */ export declare function isNull(value: unknown): value is null; /** Determine whether a value is a boolean or `null`. * * @example * ```ts * isNullableBoolean(true) // true * isNullableBoolean(null) // true * isNullableBoolean(1) // false * ``` */ export declare function isNullableBoolean(value: unknown): value is boolean | null; /** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`). * * @example * ```ts * isNullableNumber(42) // true * isNullableNumber(null) // true * isNullableNumber('hi') // false * ``` */ export declare function isNullableNumber(value: unknown): value is number | null; /** Determine whether a value is a string or `null`. * * @example * ```ts * isNullableString('hi') // true * isNullableString(null) // true * isNullableString(42) // false * ``` */ export declare function isNullableString(value: unknown): value is string | null; /** * Determine whether a value is a number. * * @remarks * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them. * * @example * ```ts * isNumber(42) // true * isNumber(Number.NaN) // true — NaN is still a number * isNumber('42') // false * ``` */ export declare function isNumber(value: unknown): value is number; /** * Determine whether a value is a non-null object. * * @remarks * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use * {@link isRecord} when you need a plain-record check. * * @example * ```ts * isObject({}) // true * isObject([]) // true * isObject(null) // false * ``` */ export declare function isObject(value: unknown): value is object; /** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable). * * @example * ```ts * isPromise(Promise.resolve()) // true * isPromise({ then() {} }) // false * ``` */ export declare function isPromise(value: unknown): value is Promise; /** * Determine whether a value is promise-like — an object exposing callable * `then`, `catch`, and `finally` methods. * * @remarks * Accepts any object with all three methods, not only native `Promise` * instances. Use {@link isPromise} when you specifically need `instanceof Promise`. * * @example * ```ts * isPromiseLike(Promise.resolve()) // true * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true * isPromiseLike({ then() {} }) // false * ``` */ export declare function isPromiseLike(value: unknown): value is Promise | (PromiseLike & { catch: unknown; finally: unknown; }); /** * Determine whether a value is a plain record (object literal or null-prototype), * not an array or class instance. * * @remarks * The total form of the shared {@link matchesRecordBrand} rule, and the only * one a guard may use: the whole brand runs inside `holds` (AGENTS §14) so a * revoked `Proxy` or a hostile `getPrototypeOf` trap answers `false` instead of * escaping as a thrown error. Use instead of {@link isObject} to distinguish a * plain `{}` / `Object.create(null)` — or a plain object from another realm, * whose prototype is that realm's `Object.prototype` — from arrays, `Date`, * `Map`, and class instances, including a class whose prototype a caller * reparented to `null`. * * @example * ```ts * isRecord({ a: 1 }) // true * isRecord(Object.create(null)) // true * isRecord([]) // false * isRecord(new Date()) // false * ``` */ export declare function isRecord(value: unknown): value is Record; /** Determine whether a value is a `RegExp`. * * @example * ```ts * isRegExp(/a/) // true * isRegExp('a') // false * ``` */ export declare function isRegExp(value: unknown): value is RegExp; /** Determine whether a value is a `Set`. * * @example * ```ts * isSet(new Set()) // true * isSet([]) // false * ``` */ export declare function isSet(value: unknown): value is ReadonlySet; /** * Determine whether a value is a `SharedArrayBuffer`. * * @remarks * Guards the global existence of `SharedArrayBuffer` first — safe where it is * absent or disabled (e.g. a context that is not cross-origin isolated). * * @example * ```ts * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true * isSharedArrayBuffer(new ArrayBuffer(8)) // false * ``` */ export declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer; /** Determine whether a value is a string. * * @example * ```ts * isString('hi') // true * isString(42) // false * ``` */ export declare function isString(value: unknown): value is string; /** Determine whether a value is a symbol. * * @example * ```ts * isSymbol(Symbol('x')) // true * isSymbol('x') // false * ``` */ export declare function isSymbol(value: unknown): value is symbol; /** Determine whether a value is exactly `true`. * * @example * ```ts * isTrue(true) // true * isTrue(false) // false * ``` */ export declare function isTrue(value: unknown): value is true; /** Determine whether a value is a `Uint16Array`. * * @example * ```ts * isUint16Array(new Uint16Array(2)) // true * isUint16Array(new Int16Array(2)) // false * ``` */ export declare function isUint16Array(value: unknown): value is Uint16Array; /** Determine whether a value is a `Uint32Array`. * * @example * ```ts * isUint32Array(new Uint32Array(2)) // true * isUint32Array(new Int32Array(2)) // false * ``` */ export declare function isUint32Array(value: unknown): value is Uint32Array; /** Determine whether a value is a `Uint8Array`. * * @example * ```ts * isUint8Array(new Uint8Array(2)) // true * isUint8Array(new Int8Array(2)) // false * ``` */ export declare function isUint8Array(value: unknown): value is Uint8Array; /** Determine whether a value is a `Uint8ClampedArray`. * * @example * ```ts * isUint8ClampedArray(new Uint8ClampedArray(2)) // true * isUint8ClampedArray(new Uint8Array(2)) // false * ``` */ export declare function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray; /** Determine whether a value is `undefined`. * * @example * ```ts * isUndefined(undefined) // true * isUndefined(null) // false * ``` */ export declare function isUndefined(value: unknown): value is undefined; /** * Determine whether a supported ISO-8601 date or date-time is valid. * * @remarks * Accepts exactly `YYYY-MM-DD`, or `YYYY-MM-DDTHH:MM:SS` with optional * fractional seconds followed by `Z` or a numeric offset. Inside the * {@link attempt} boundary, captured components receive explicit Gregorian * month/leap/day and clock validation before `Date#getTime` performs the final * offset/instant refusal. Backs {@link stringToFormat}'s `date`, `date-time`, * and prefixed `time` validation. * * @param value - The candidate ISO-8601 string * @returns `true` when `value` parses to a real instant * * @example * ```ts * isValidISOInstant('2024-02-29') // true * isValidISOInstant('2024-01-01T24:00Z') // false — incomplete normalized clock * ``` */ export declare function isValidISOInstant(value: string): boolean; /** Determine whether a value is a `WeakMap`. * * @example * ```ts * isWeakMap(new WeakMap()) // true * isWeakMap({}) // false * ``` */ export declare function isWeakMap(value: unknown): value is WeakMap; /** Determine whether a value is a `WeakSet`. * * @example * ```ts * isWeakSet(new WeakSet()) // true * isWeakSet({}) // false * ``` */ export declare function isWeakSet(value: unknown): value is WeakSet; /** Determine whether a value is a function that declares zero parameters (`Function.length === 0`). * * @example * ```ts * isZeroArg(() => {}) // true * isZeroArg((a) => a) // false * ``` */ export declare function isZeroArg(value: unknown): value is ZeroArgFunction; /** Determine whether a value is a zero-argument async function. * * @example * ```ts * isZeroArgAsync(async () => {}) // true * isZeroArgAsync(async (a) => a) // false * ``` */ export declare function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction; /** Determine whether a value is a zero-argument async generator function. * * @example * ```ts * isZeroArgAsyncGenerator(async function* () {}) // true * isZeroArgAsyncGenerator(async function* (a) {}) // false * ``` */ export declare function isZeroArgAsyncGenerator(value: unknown): value is () => AsyncGenerator; /** Determine whether a value is a zero-argument generator function. * * @example * ```ts * isZeroArgGenerator(function* () {}) // true * isZeroArgGenerator(function* (a) {}) // false * ``` */ export declare function isZeroArgGenerator(value: unknown): value is () => Generator; /** * The seven standard JSON Schema `type` names, frozen. * * @remarks * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose * it with the shipped primitives instead of reaching for a bespoke guard: * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)` * is the parser. * * @example * ```ts * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@orkestrel/contract' * * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined * ``` */ export declare const JSON_SCHEMA_TYPES: readonly JSONSchemaType[]; /** * Stateful owner of one exact JSON snapshot operation. * * @remarks * Construction retains the source without observing it. The first * {@link clone} call performs one iterative descriptor walk and settles * permanently. Success replays the exact frozen root; failure rethrows the * exact class-owned error. Nonredirectable terminal failure releases partial * traversal working state while retaining the source and exact error. Reentry * poisons the active operation and every later call with one shared cause-free * error. * * @param value - The unknown value to retain for cloning * * @example * ```ts * const source = { settings: { enabled: true } } * const cloner = new JSONCloner(source) * const clone = cloner.clone() * source.settings.enabled = false * cloner.clone() === clone // true * ``` */ export declare class JSONCloner implements JSONClonerInterface { #private; constructor(value: unknown); /** * Clone the retained source into exact, deeply frozen JSON data. * * @returns The settled JSON snapshot * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered */ clone(): JSONValue; } /** * Stateful owner of one exact JSON snapshot operation. * * @remarks * Construction retains the source without observing it. The first * {@link clone} call settles once; later calls replay the exact same frozen * value or exact same owned {@link ContractError}. Terminal failure releases * partial traversal working state while retaining the source and exact error. */ export declare interface JSONClonerInterface { /** * Clone the retained source into exact, deeply frozen JSON data. * * @returns The settled JSON snapshot * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered */ clone(): JSONValue; } /** * A primitive JSON value — the flat leaf of any JSON document. * * @remarks * The recursive {@link JSONValue} tree type is shipped for consumers that need a * reusable JSON metadata contract. {@link JSONRecord} supplies the record-root * contract needed by persistence and metadata consumers; a dedicated * `JSONArray` alias remains unnecessary because `readonly JSONValue[]` already * expresses that branch directly. */ export declare type JSONPrimitive = string | number | boolean | null; /** * A readonly string-keyed JSON object record. * * @remarks * Runtime ownership through * {@link import('./cloners.js').cloneJSONRecord} normalizes records to a frozen * null-prototype object after exact descriptor validation. * * @example * ```ts * const metadata: JSONRecord = { attempt: 1, labels: ['ready'] } * ``` */ export declare type JSONRecord = { readonly [key: string]: JSONValue; }; /** * A JSON Schema fragment — the supported keyword vocabulary the contract * compiler emits and {@link RawShape} validates before embedding. * * @remarks * Intentionally lean (not the full ~50-keyword vocabulary): it carries only the * keywords {@link Infer}-driven `compileSchema` produces, plus `format` — * emitted by the {@link stringToFormat} / {@link samplesToFormat} inference * heuristics (`valueToSchema` / `samplesToSchema`), never by `compileSchema`. * Recursive via `items` / `properties` / `additionalProperties` / `anyOf` / * `oneOf`. {@link createContract} owns and validates developer-authored shape * graphs; cycles and nesting past {@link COMPILE_DEPTH_LIMIT} fail with a coded * {@link ContractError} before artifact compilation. */ export declare interface JSONSchema { readonly type?: JSONSchemaType; readonly description?: string; readonly enum?: readonly LiteralValue[]; readonly minLength?: number; readonly maxLength?: number; readonly pattern?: string; readonly format?: string; readonly minimum?: number; readonly maximum?: number; readonly minItems?: number; readonly maxItems?: number; readonly items?: JSONSchema; readonly properties?: Readonly>; readonly required?: readonly string[]; readonly additionalProperties?: boolean | JSONSchema; readonly anyOf?: readonly JSONSchema[]; readonly oneOf?: readonly JSONSchema[]; } /** The seven standard JSON Schema `type` names. */ export declare type JSONSchemaType = 'null' | 'boolean' | 'object' | 'array' | 'number' | 'integer' | 'string'; /** * A JSON passthrough shape — accepts any JSON value. * * @remarks * The compiled guard is a sound {@link isJSONValue} check (rejecting cycles, * functions, `NaN`, and `±Infinity`); the parser gates through that guard; the * schema is the empty schema `{}` (matches any JSON instance); the generator * emits a small deterministic {@link JSONValue}. Unlike {@link RawShape}, whose * guard accepts every defined value, this shape validates that a value is real JSON. */ export declare interface JSONShape { readonly type: 'json'; readonly description?: string; } /** * Build a {@link JSONShape}. * * @remarks * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary * schema fragment and accepts every defined value at runtime, while `jsonShape` * validates that a value is real JSON (via {@link isJSONValue}). Its emitted * schema is the empty accept-anything `{}`, so here the schema claims MORE than * the compiled guard accepts — `NaN`, a `Map`, and a class instance all satisfy * `{}` and all fail `isJSONValue`. * * @param options - Optional `description` * @returns A JSON passthrough shape * * @example * ```ts * const payload = jsonShape({ description: 'Arbitrary JSON payload' }) * ``` */ export declare function jsonShape(options?: JSONShapeOptions): JSONShape; /** Options for {@link JSONShape} (via `jsonShape`). */ export declare interface JSONShapeOptions { readonly description?: string; } /** * A recursive JSON value — primitives, arrays, and object records. * * @remarks * The static type admits any `number` because TypeScript cannot express * finiteness. The {@link isJSONValue} guard rejects `NaN` and `±Infinity` since * they have no JSON representation. * * @example * ```ts * const value: JSONValue = { nested: [1, 'x', null] } * ``` */ export declare type JSONValue = JSONPrimitive | readonly JSONValue[] | JSONRecord; /** * Build a guard that accepts values that are own keys of the provided object. * * @remarks * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys * (`toString`, `constructor`, …) are rejected. An own property that shadows a * prototype name is accepted. * * @example * ```ts * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const * const isColorKey = keyOf(COLORS) * isColorKey('red') // true * isColorKey('purple') // false * isColorKey('toString') // false — inherited, not an own key * ``` */ export declare function keyOf>>(value: O): Guard; /** * Defer guard creation until first use by calling `thunk()` on every * invocation. * * @remarks * `thunk` is called on every guard call, not cached — this lets it close over a * binding assigned *after* `lazyOf` is called, the primary use case for * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard * it resolves to) is contained and reported as a non-match. * * Each lazy guard tracks its active invocation depth. An invocation that would * exceed {@link GUARD_DEPTH_LIMIT} returns `false` before resolving `thunk`; the * counter always unwinds after the contained call, so one deep or cyclic input * cannot poison later guard calls. * * @example * ```ts * type Tree = { value: number; children: Tree[] } * let isTree: Guard * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) }) * ``` */ export declare function lazyOf(thunk: () => Guard): Guard; /** * Take at most `limit` leading elements of an array, by index. * * @remarks * `Array.prototype.slice` is a caller-writable member on every path that bounds * a published report, so a substitute decides how much of a diagnostic the * caller sees. Returns the input untouched when it already fits, so a bounded * report allocates nothing in the ordinary case. * * @param entries - The entries to bound * @param limit - The maximum number of leading entries to retain * @returns The input when it already fits, otherwise a fresh bounded copy * * @example * ```ts * limitEntries(faults, FAULT_LIMIT) * ``` */ export declare function limitEntries(entries: readonly T[], limit: number): readonly T[]; /** * Build a guard that accepts a provided literal primitive using SameValueZero * comparison. * * @remarks * Signed zero compares equal, while `NaN` compares equal to `NaN`. Two call * forms, one meaning: list the literals inline, or hand in one array of them. * The array form exists for a vocabulary that is machine-generated rather than * hand-written — a `literalShape` built from an untrusted schema's `enum`, say * — where spreading a list of tens of thousands of entries would exhaust the * engine's argument limit. `compileGuard` / `compileParser` / `compileReporter` * take the array form for exactly that reason. * * @param literals - The permitted literal primitives, listed inline or as one array * @returns A guard narrowing to the provided literal union * * @example * ```ts * const isRole = literalOf('admin', 'member', 'guest') * isRole('admin') // true * isRole('owner') // false * * const isSameRole = literalOf(['admin', 'member', 'guest']) // the same guard, from an array * ``` */ export declare function literalOf(literals: Literals): Guard; export declare function literalOf(...literals: Literals): Guard; /** A literal shape — accepts exactly one of a fixed set of primitive values. */ export declare interface LiteralShape { readonly type: 'literal'; readonly values: T; readonly description?: string; } /** * Build a literal shape from a fixed set of primitive values. * * @param values - The permitted literals * @param options - Optional `description` * @returns A literal shape whose `Infer` is the union of `values` * * @example * ```ts * const role = literalShape(['admin', 'member', 'guest']) * // Infer = 'admin' | 'member' | 'guest' * * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' }) * ``` */ export declare function literalShape(values: T, options?: LiteralShapeOptions): LiteralShape>; /** Options for {@link LiteralShape} (via `literalShape`). */ export declare interface LiteralShapeOptions { readonly description?: string; } /** A string, number, or boolean literal value. */ export declare type LiteralValue = string | number | boolean; /** * Build a guard that accepts `Map` instances where every key satisfies * `keyGuard` and every value satisfies `valueGuard`. * * @example * ```ts * const isStringNumberMap = mapOf(isString, isNumber) * isStringNumberMap(new Map([['a', 1]])) // true * isStringNumberMap(new Map([[1, 'a']])) // false * ``` */ export declare function mapOf(keyGuard: Guard, valueGuard: Guard): Guard>; export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard>; /** * Determine whether a readable value stays within the fixed JSON container-depth limit. * * @remarks * Counts array and plain-record containers on each active root-to-value path. * Primitive and readable non-record objects are leaves, active cycles add no * level, and shared aliases are answered from the shallowest depth at which * the alias already fit. Arrays are traversed through their reflected * own-index population, so sparse work is proportional to populated entries * rather than advertised length. Every observable operation is contained; * hostile or contradictory reads return `false`. * * The walk carries a settled-depth memo beside its active-path set: a * container that fit at depth `d` also fits at any depth `<= d`, because every * path below it is then shallower than the one already measured. Without it a * node reachable by `k` distinct paths was re-walked `k` times, so an ORDINARY * record graph with thirty shared aliases — thirty-one nodes — cost `2^30` * visits through a public guard. * * @param value - The value whose readable container depth to inspect * @returns `true` when no active path exceeds {@link GUARD_DEPTH_LIMIT} * * @example * ```ts * matchesJSONDepth({ nested: [1] }) // true * ``` */ export declare function matchesJSONDepth(value: unknown): boolean; /** * Match an unknown value against the recursive JSON value structure. * * @remarks * The caller-owned ancestor set tracks only the active traversal path, so * cycles fail while shared references across sibling branches remain valid. * The set belongs to one traversal from one entry point; passing a shared or * pre-populated set is unsupported. Arrays descend through the shared dense * own-index lens and plain records descend by values; class instances and * non-finite numbers are rejected. * * The walk is ITERATIVE, over an explicit enter/exit stack, exactly as * {@link matchesJSONDepth} already was. It used to recurse, and that made the * verdict a function of the REMAINING CALL STACK rather than of the value: the * same readable 4,000-deep document answered `true` at a root call site and * `false` a few frames down, and `parseJSONValue` republished the resulting * `RangeError` as `value could not be read` for a value every read of which * succeeded. A cap enforced by the JavaScript stack is not a cap. This walk * carries no depth cap of its own — `isJSONValue` is deliberately the unbounded * deep gate and {@link matchesJSONDepth} / `isBoundedJSONValue` are the bounded * pair beside it — so the answer now depends only on the value, at every depth * and from every call site. * * Beside the ancestor set the walk keeps a walk-local PROVED set, so a node * whose whole subtree already matched is not re-walked when a second path * reaches it. Removing the recursion alone left the work exponential in shared * aliases: thirty aliases — thirty-one ordinary records — cost `2^30` visits * through `isJSONValue`, `parseJSONValue`, `canonicalStringify` and every * `jsonShape` contract. * * @param entry - The value to inspect * @param ancestors - Objects on the active traversal path * @returns `true` when the value is a cycle-free JSON value * * @example * ```ts * matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true * matchesJSONValue(Number.NaN, new WeakSet()) // false * ``` */ export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet): entry is JSONValue; /** * Determine whether a value is a member of a collected vocabulary, by * SameValueZero. * * @param members - The vocabulary to ask, built by {@link collectMembers} * @param value - The value to test for membership * @returns `true` only when the value was collected * * @example * ```ts * matchesMember(collectMembers([Number.NaN]), Number.NaN) // true — SameValueZero * ``` */ export declare function matchesMember(members: ReadonlySet, value: unknown): boolean; /** * Determine whether a string is in the language of a pattern this package owns. * * @remarks * The pattern-membership answer, asked exactly as {@link matchesMember} asks the * literal one, and asked through `exec` rather than `test` on purpose: * `RegExp.prototype.test` is spec-defined in terms of `RegExpExec`, which * re-reads `exec` off the receiver, so even a CAPTURED `test` still answers * whatever the caller installed. Replacing either member decided what `matchOf`, * `stringOf`, `contract.is`, `contract.parse`, `audit`, `explain` and the format * inferers published — a wrong yes for a non-member and a wrong no for a member, * silently. * * @param pattern - The owned pattern to apply * @param value - The string to test * @returns `true` only when the pattern genuinely matches * * @example * ```ts * matchesPattern(/^[0-9a-f]+$/, '1a2f') // true * ``` */ export declare function matchesPattern(pattern: RegExp, value: string): boolean; /** * Determine whether a value carries the plain-record brand, raising a hostile * prototype observation instead of answering it. * * @remarks * THE single record-brand rule: a plain record is a non-array object whose * prototype is `null`, or is a realm's `Object.prototype`. Realm-agnosticism is * why the second arm cannot simply compare against this realm's * `Object.prototype` — a plain object from another `vm.Context`, iframe, or * worker inherits from THAT realm's `Object.prototype`, which is a different * object. The earlier rule accepted any prototype that itself had a `null` * prototype, which every realm's `Object.prototype` satisfies — and so does a * class prototype a caller reparented to `null`, which is how a class instance * laundered through every ownership door. A foreign `Object.prototype` is * therefore identified by the own members ECMAScript requires every realm to * put on it (`constructor`, `hasOwnProperty`, `isPrototypeOf`, * `propertyIsEnumerable`, `toLocaleString`, `toString`, `valueOf`), each read * through its own DESCRIPTOR so no accessor on a hostile prototype ever runs. * Each must be an own DATA property whose value is a FUNCTION — true of every * conformant realm, so the requirement costs a genuine foreign record nothing, * and it refuses the cheapest forgery (stamping the seven names with * `undefined`) for free. * * That is a structural test, not a provenance one, and the residual is stated * as exactly what it is: a FUNCTION-VALUED forgery passes, and this realm's own * `Object.prototype` supplies the seven functions to stamp, so the price is a * few lines rather than nothing. Reparenting a class prototype to `null` and * stamping the seven names with real functions passes; so does leaving the * class untouched and putting a `Proxy` in prototype position that reports * `null` as its own prototype and answers those seven descriptor reads with * functions. In both cases the value is a live class instance whose methods are * still reachable on it. A further own-key SUBSET rule buys even less: it * refuses a forgery that left methods on its prototype and accepts the same * class with those methods moved onto the instance, where they are * indistinguishable from a plain record's function * properties — so it raises the forgery's price and narrows the realm-agnostic * arm this rule exists to keep open. What the pass buys is acceptance at * brand-governed doors and nothing after it: every ownership engine publishes a * frozen plain record built only from captured data, so no class instance, * class behavior, or forged prototype survives into a snapshot. * * `Object.create()` is refused, and NOT because it is * structurally identical to a reparented class instance — it is not, since a * class prototype always owns `constructor` and a bare `Object.create(null)` * owns nothing. It is refused as policy: no realm produces that chain for a * plain object, no consumer of it has been named, and a caller erases the * difference by deleting `constructor`. * * This is the diagnosing form, deliberately NOT total: a revoked `Proxy` or a * hostile `getPrototypeOf` trap throws out of it, so an ownership engine can * report an unreadable value as a failed read with the exact cause rather than * as a well-formed structural refusal. {@link isRecord} is the total form for * every guard consumer and contains that throw as `false`. * * @param value - The value whose record brand to inspect * @returns `true` only when the value is a plain record * @throws The exact value thrown by a hostile brand observation * * @example * ```ts * matchesRecordBrand({}) // true * matchesRecordBrand(Object.create(null)) // true * matchesRecordBrand(new Date()) // false * ``` */ export declare function matchesRecordBrand(value: unknown): boolean; /** * Determine whether an object is already on a traversal's active path. * * @remarks * The visitation half, and the one an earlier ruling wrongly excused as safe * because "a redirect corrupts it inside a boundary and the door refuses, which * is loud". It is not loud in the direction that matters: * `WeakSet.prototype.has` answering `false` does not make a cyclic clone refuse, * it removes the door's termination bound, and a door that never returns is the * one failure a containment boundary cannot report. Every walk's termination * therefore rests on a captured operation rather than on a caller-writable one. * * @param visited - The active-path set this traversal owns * @param value - The object to test * @returns `true` only when the object is already on the active path * * @example * ```ts * const active = new WeakSet() * admitVisited(active, node) * matchesVisited(active, node) // true * ``` */ export declare function matchesVisited(visited: WeakSet, value: object): boolean; /** * Build a guard that accepts strings matching a regular expression. * * @remarks * Clones the pattern for the guard and strips the stateful `g` / `y` flags, so * repeated checks are stable and never change the caller's `lastIndex`. * * @param pattern - The regular expression to own and apply * @returns A stateless string guard * * @example * ```ts * const isHex = matchOf(/^[0-9a-f]+$/) * isHex('1a2f') // true * isHex('xyz') // false * ``` */ export declare function matchOf(pattern: RegExp): Guard; /** * Negate a guard or predicate — passes when `guard` returns `false`. * * @remarks * Typed as `Guard` because `Exclude` is not useful; use * {@link complementOf} when you need the narrowed `Exclude`. * * @example * ```ts * const isNotNull = notOf(isNull) * ``` */ export declare function notOf(guard: (value: unknown) => boolean): Guard; /** * Extend a guard to also allow `null`. * * @example * ```ts * const isNullableString = nullableOf(isString) * isNullableString('hi') // true * isNullableString(null) // true * isNullableString(42) // false * ``` */ export declare function nullableOf(guard: Guard): Guard; /** A nullable wrapper — the inner shape may be `null`. */ export declare interface NullableShape { readonly type: 'nullable'; readonly inner: S; } /** * Wrap a shape so it may be `null`. * * @param inner - The wrapped shape * @returns A nullable shape * * @example * ```ts * const bio = nullableShape(stringShape()) * // Infer = string | null * ``` */ export declare function nullableShape(inner: S): NullableShape; /** A null shape — accepts only `null`. */ export declare interface NullShape { readonly type: 'null'; readonly description?: string; } /** * Build a {@link NullShape}. * * @param options - Optional `description` * @returns A null shape * * @example * ```ts * const empty = nullShape() * ``` */ export declare function nullShape(options?: NullShapeOptions): NullShape; /** Options for {@link NullShape} (via `nullShape`). */ export declare interface NullShapeOptions { readonly description?: string; } /** A numeric shape with optional bounds; `integer` restricts to whole numbers. */ export declare interface NumberShape { readonly type: 'number'; readonly min?: number; readonly max?: number; readonly integer?: boolean; readonly description?: string; } /** * Build a numeric {@link NumberShape}. * * @param options - Optional bounds (`min` / `max`), `integer`, and `description` * @returns A number shape * @throws {ContractError} When a present bound is not finite * * @example * ```ts * const age = numberShape({ min: 0, max: 120 }) * ``` */ export declare function numberShape(options?: NumberShapeOptions): NumberShape; /** Options for {@link NumberShape} (via `numberShape` / `integerShape`). */ export declare interface NumberShapeOptions { readonly min?: number; readonly max?: number; readonly integer?: boolean; readonly description?: string; } export declare function objectOf(shape: S): Guard>; export declare function objectOf>(shape: S, optional: K): Guard>; export declare function objectOf(shape: S, optional: true): Guard[P]; }>>; /** * An object shape — a map of property names to child shapes. * * @remarks * A property whose shape is an {@link OptionalShape} may be absent; all others * are required. `additionalProperties` controls unknown keys, and each compiled * artifact acts on that setting in its own way. Closed (`undefined` / `false`): * the compiled guard rejects the object, the compiled auditor reports one * `'extra'` fault at the offending key, and the emitted schema sets * `additionalProperties: false` — while the compiled parser drops the key and * the compiled reporter stays silent, mirroring that parser. `true` accepts * unknown keys as-is, and a `ContractShape` validates them, in every artifact. */ export declare interface ObjectShape

> = Readonly>, A extends boolean | ContractShape = boolean | ContractShape> { readonly type: 'object'; readonly properties: P; readonly additionalProperties?: A; readonly description?: string; } /** * Build an {@link ObjectShape} from a property map. * * @remarks * Wrap any property in {@link optionalShape} to allow its absence. By default * the compiled guard rejects unknown keys; pass `additionalProperties` to open * the object. * * @param properties - Map of property names to child shapes * @param options - Optional `additionalProperties` and `description` * @returns An object shape * * @example * ```ts * const user = objectShape({ * name: stringShape({ min: 1 }), * age: integerShape({ min: 0, max: 120 }), * bio: optionalShape(stringShape()), * }) * ``` */ export declare function objectShape

>, const A extends boolean | ContractShape = false>(properties: P, options?: ObjectShapeOptions): ObjectShape; /** Options for {@link ObjectShape} (via `objectShape`). */ export declare interface ObjectShapeOptions { readonly additionalProperties?: A; readonly description?: string; } /** * Build a new guard shape by removing the listed keys — the structural * equivalent of `Omit`. Produces a shape for {@link recordOf}, not a guard. * * @example * ```ts * const full = { name: isString, age: isNumber, role: isString } * const isPublic = recordOf(omitOf(full, ['role'])) * isPublic({ name: 'Ada', age: 36 }) // true * ``` */ export declare function omitOf>(shape: S, keys: K): Omit; /** * Record an object as exited from a traversal's active path. * * @param visited - The active-path set this traversal owns * @param value - The object being exited * * @example * ```ts * omitVisited(active, node) * ``` */ export declare function omitVisited(visited: WeakSet, value: object): void; /** * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema. * * @remarks * Unlike {@link unionShape} (`anyOf` — at least one variant matches), * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match: * * - **Guard**: accepts the value only when exactly one variant's guard * accepts it. A value matching two-or-more variants — which would violate * the emitted `oneOf` schema — is rejected, even though it would pass * {@link unionShape}'s guard. * - **Parser**: judged on the RAW input's guard matches only, with NO * coercion fallback for an ambiguous input. When exactly one variant's * guard accepts the raw value, that variant's parser runs. Zero matches or * two-or-more matches both parse to `undefined` — a value ambiguous * between variants has no well-defined coercion target. * * Prefer {@link unionShape} when a value may legitimately satisfy more than * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer * `oneOfShape` when overlap between variants indicates malformed input that * must be rejected. * * @param variants - The candidate shapes * @returns A union shape with `mode: 'oneOf'` * * @example * ```ts * const id = oneOfShape(numberShape(), integerShape()) * // 3 fails — matches both numberShape and integerShape * // 3.5 passes — matches numberShape only * ``` */ export declare function oneOfShape(...variants: V): UnionShape>; /** * Like {@link FromGuards}, but every key listed in `K` becomes a true optional * member (`?`) rather than a required key widened with `| undefined`. * * @remarks * A key present in `K` may be omitted entirely; if present, its value must * still satisfy the key's guard — a present key holding `undefined` is not * accepted. * * @typeParam S - The full guard shape * @typeParam K - Tuple of keys to make optional */ export declare type OptionalFromGuards> = Readonly<{ [P in Exclude]: FromGuards[P]; } & { [P in Extract]?: FromGuards[P]; }>; /** * Extend a guard to also allow `undefined` — the optional counterpart of * {@link nullableOf}. * * @example * ```ts * const isOptionalString = optionalOf(isString) * isOptionalString('hi') // true * isOptionalString(undefined) // true * isOptionalString(null) // false * ``` */ export declare function optionalOf(guard: Guard): Guard; /** An optional wrapper — the inner shape may be absent (`undefined`). */ export declare interface OptionalShape { readonly type: 'optional'; readonly inner: S; } /** * Wrap a shape so it may be absent (`undefined`). * * @remarks * As an {@link objectShape} property, the field becomes a true optional property * in the inferred type. * * @param inner - The wrapped shape * @returns An optional shape */ export declare function optionalShape(inner: S): OptionalShape; /** * Combine two guards with logical OR — passes when at least one passes. For more * than two variants prefer {@link unionOf}. * * @example * ```ts * const isStringOrNumber = orOf(isString, isNumber) * ``` */ export declare function orOf(left: Guard, right: Guard): Guard; export declare function orOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard; /** * Take ownership of a contract shape node as an independent {@link cloneShape} * snapshot of its graph. * * @remarks * Every successful return is a deeply frozen caller-independent graph, and * "frozen" here means frozen by the `Object.freeze` this package captured while * it loaded, not by whatever `Object.freeze` names when the call is made. The * distinction is the whole guarantee: under `Object.freeze = (value) => value` * this door used to SUCCEED and publish a mutable graph, with no throw and no * signal a caller could read. A frozen caller root receives no identity * exception: shallow freezing cannot establish ownership of nested collections, * child nodes, raw schemas, or `RegExp` internal state, and the fidelity clone * has already paid the traversal cost needed to prove and carry those values. * * @param shape - The contract shape to own * @returns A deeply cloned frozen snapshot * * @example * ```ts * const authored = stringShape() * ownShape(authored) === authored // false * ``` */ export declare function ownShape(shape: ContractShape): ContractShape; /** * Parse an unknown value to an array — the input reference, never cloned — * optionally guarding every element. * * @remarks * Without a `guard`, element types are NOT verified; let `T` default to * `unknown` rather than asserting a specific element type. * * @param value - The value to parse * @param guard - Optional element guard * @returns The array, or `undefined` * * @example * ```ts * parseArray([1, 2]) // [1, 2] * parseArray([1, 'x'], isNumber) // undefined * ``` */ export declare function parseArray(value: unknown, guard?: Guard): readonly T[] | undefined; /** * Read and parse an array field from a record by key or nested key path, * optionally guarding elements. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @param guard - Optional element guard * @returns An array, or `undefined` * * @example * ```ts * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2] * parseArrayField({}, 'tags') // undefined * ``` */ export declare function parseArrayField(record: Record, path: FieldPath, guard?: Guard): readonly T[] | undefined; /** * Parse an unknown value to a boolean. * * @remarks * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` / * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything * else → `undefined`. * * @param value - The value to parse * @returns A boolean, or `undefined` * * @example * ```ts * parseBoolean(true) // true * parseBoolean('1') // true * parseBoolean('nope') // undefined * ``` */ export declare function parseBoolean(value: unknown): boolean | undefined; /** * Read and parse a boolean field from a record by key or nested key path. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns A boolean, or `undefined` * * @example * ```ts * parseBooleanField({ on: 'true' }, 'on') // true * parseBooleanField({}, 'on') // undefined * ``` */ export declare function parseBooleanField(record: Record, path: FieldPath): boolean | undefined; /** * Parse an unknown value as one of the allowed literal primitives. * * @remarks * Pairs with {@link literalOf} — both match by SameValueZero, so the * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive * (string, number, or boolean), not only strings. Matching is identity, never * cross-type coercion: `parseEnum('1', [1])` stays `undefined`. The allowed * values are captured through their dense own-index view and copied into an * owned `Set`; caller-defined iteration is ignored and unreadability returns * `undefined` rather than escaping. * * @param value - The value to parse * @param allowed - The permitted literal values * @returns The input when it matches an allowed literal by SameValueZero, or `undefined` * * @example * ```ts * parseEnum('b', ['a', 'b', 'c']) // 'b' * parseEnum('z', ['a', 'b', 'c']) // undefined * ``` */ export declare function parseEnum(value: unknown, allowed: readonly T[]): T | undefined; export declare function parseEnum(value: unknown, allowed: readonly LiteralValue[]): LiteralValue | undefined; /** * Read and parse an enum field from a record by key or nested key path. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @param allowed - The permitted literal values * @returns The matched literal, or `undefined` */ export declare function parseEnumField(record: Record, path: FieldPath, allowed: readonly T[]): T | undefined; /** * Parse an unknown value to a finite integer. * * @remarks * Accepts whatever {@link parseNumber} accepts, then requires the result to have * no fractional part. `3.14` / `'3.14'` → `undefined`. * * @param value - The value to parse * @returns A finite integer, or `undefined` * * @example * ```ts * parseInteger(42) // 42 * parseInteger(3.14) // undefined * ``` */ export declare function parseInteger(value: unknown): number | undefined; /** * Read and parse a finite-integer field from a record by key or nested key path. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns A finite integer, or `undefined` */ export declare function parseIntegerField(record: Record, path: FieldPath): number | undefined; /** * Parse a JSON string, returning `undefined` instead of throwing. * * @remarks * The safe boundary for untrusted JSON text: a malformed string yields * `undefined`, never an exception. Returns `unknown` — a successful parse proves * nothing about shape, so narrow the result with a guard (or use * {@link parseJSONAs}). A large document is not walked here; parsing is shallow * and lazy validation is the caller's to compose. * * @param value - The JSON string to parse * @returns The parsed value, or `undefined` when `value` is not valid JSON */ export declare function parseJSON(value: string): unknown; /** * Parse a JSON string and validate the result against a guard. * * @remarks * The lazy, safe path from an untrusted string to a typed `T`: parse, then check * the parsed value with the guard you bring — typically one composed from the * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is * validated, so a large document is never walked in full unless the guard does. * * @param value - The JSON string to parse * @param guard - The guard for the expected shape * @returns The parsed value when it satisfies `guard`, otherwise `undefined` * * @example * ```ts * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) }) * parseJSONAs('{"host":"localhost","tags":["a"]}', isConfig) // { host: 'localhost', tags: ['a'] } * parseJSONAs('{"host":"localhost"}', isConfig) // undefined — guard fails * parseJSONAs('not json', isConfig) // undefined — never throws * ``` */ export declare function parseJSONAs(value: string, guard: Guard): T | undefined; /** * Parse an unknown value to a cycle-safe JSON value — the input reference, * never cloned. * * @remarks * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it * walks the entire tree via {@link isJSONValue} rather than checking only the * top-level shape. That walk is cycle-safe. A readable non-JSON structure, * including a cycle, returns `undefined`; a failed property read throws a * `structure` {@link ContractError}, keeping unreadability distinct from an * honest invalid result. * * @param value - The value to parse * @returns The value, or `undefined` when it is not a valid JSON value * @throws {ContractError} When the JSON tree cannot be read * * @example * ```ts * parseJSONValue({ a: 1 }) // { a: 1 } * parseJSONValue(Number.NaN) // undefined * ``` */ export declare function parseJSONValue(value: unknown): JSONValue | undefined; /** * Read and parse a JSON-value field from a record by key or nested key path. * * @remarks * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that * function's remarks for why this differs from the shallow * {@link parseRecordField} / {@link parseArrayField}. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns The value, or `undefined` * * @example * ```ts * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 } * parseJSONValueField({}, 'data') // undefined * ``` */ export declare function parseJSONValueField(record: Record, path: FieldPath): JSONValue | undefined; /** * Parse an unknown value to `null`. * * @remarks * A successful parse returns `null` itself — distinct from the `undefined` * failure sentinel every other parser in this file uses. Only `null` passes; * every other value (including `undefined`) → `undefined`. * * @param value - The value to parse * @returns `null` on a successful parse, or `undefined` * * @example * ```ts * parseNull(null) // null * parseNull(undefined) // undefined * ``` */ export declare function parseNull(value: unknown): null | undefined; /** * Read and parse a `null` field from a record by key or nested key path. * * @remarks * A successful parse returns `null` itself — distinct from the `undefined` * failure sentinel, which also covers a missing field. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns `null` on a successful parse, or `undefined` * * @example * ```ts * parseNullField({ value: null }, 'value') // null * parseNullField({}, 'value') // undefined * ``` */ export declare function parseNullField(record: Record, path: FieldPath): null | undefined; /** * Parse an unknown value to a finite number. * * @remarks * A finite number is returned unchanged; a non-blank numeric string is parsed * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every * other type → `undefined`. * * @param value - The value to parse * @returns A finite number, or `undefined` * * @example * ```ts * parseNumber(42) // 42 * parseNumber('42') // 42 * parseNumber('abc') // undefined * ``` */ export declare function parseNumber(value: unknown): number | undefined; /** * Read and parse a finite-number field from a record by key or nested key path. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns A finite number, or `undefined` * * @example * ```ts * parseNumberField({ age: '42' }, 'age') // 42 * parseNumberField({}, 'age') // undefined * ``` */ export declare function parseNumberField(record: Record, path: FieldPath): number | undefined; /** * A parser: coerces an unknown value to `T`, or returns `undefined`. * * @remarks * The runtime parallel of {@link Guard}. A parser pairs soundly with the guard * for its output type: a guard-valid input is returned unchanged, and every * non-`undefined` output satisfies that guard. */ export declare type Parser = (value: unknown) => T | undefined; /** * Parse an unknown value to a plain record — the input reference, never cloned. * * @param value - The value to parse * @returns The record, or `undefined` * @throws {ContractError} When an object value cannot be read */ export declare function parseRecord(value: unknown): Record | undefined; /** * Read and parse a nested record field from a record by key or nested key path. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns A plain record, or `undefined` */ export declare function parseRecordField(record: Record, path: FieldPath): Record | undefined; /** * Parse an unknown value to a string. * * @remarks * A string is returned unchanged; a finite number is coerced to its decimal * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`. * * @param value - The value to parse * @returns A string, or `undefined` * * @example * ```ts * parseString('hi') // 'hi' * parseString(42) // '42' * parseString(true) // undefined * ``` */ export declare function parseString(value: unknown): string | undefined; /** * Read and parse a string field from a record by key or nested key path. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns A string, or `undefined` */ export declare function parseStringField(record: Record, path: FieldPath): string | undefined; /** * Build a diagnostic path from an existing path and further segments, without * dispatching through array iteration. * * @remarks * `[...path, key]` reads well and dispatches through * `Array.prototype[Symbol.iterator]`, a member every caller can write — and the * damaging installation is not a thrower but a LIAR. An iterator yielding one * extra value before the array's real contents turns a refusal this package * authored into `path: ['INJECTED', 'properties', 'INJECTED']`, so the caller * writes their own text into a diagnostic this package published. An indexed * walk reads only own index properties of an array this package owns, and a * rest parameter collects its arguments without an iterator either, so nothing * on the path is caller-reachable. * * @param path - The path segments accumulated so far * @param segments - Further segments to append in order; an absent segment is * omitted, so an optional level needs no branch at the call site * @returns A fresh path carrying every existing segment and each new one * * @example * ```ts * pathOf(['properties'], 'age') // ['properties', 'age'] * pathOf(path) // an owned copy * ``` */ export declare function pathOf(path: readonly string[], ...segments: ReadonlyArray): readonly string[]; /** * Build a new guard shape by keeping only the listed keys — the structural * equivalent of `Pick`. Produces a shape for {@link recordOf}, not a guard. * * @example * ```ts * const full = { name: isString, age: isNumber, role: isString } * const isName = recordOf(pickOf(full, ['name'])) * isName({ name: 'Ada' }) // true * ``` */ export declare function pickOf>(shape: S, keys: K): Pick; /** * Pin every own member of a class prototype as a non-configurable member — * non-writable too when it is a data property — and verify the pin took. * * @remarks * The other half of the structural answer. Membership answers moved off class * methods entirely, but a class this package EXPORTS still has methods its own * modules dispatch through — `cloneShape` reaches `ShapeCloner.prototype.clone`, * and one assignment there made `compileSchema` publish whatever the caller * chose while `compileSchema` itself was never touched. That is the same defect * as a replaced host member with the package's own name on it, so every exported * class pins its prototype while it is DEFINED. * * The qualification that phrase used to carry — "before any importer's code can * run" — was FALSE, in exactly the case {@link INTRINSICS} already states and * does not defend: ESM evaluates imports in source order, so a module that * evaluates before this package has already run. What is true is narrower and is * what the pin buys: no code that runs AFTER this class is defined can replace a * member on its prototype. * * Placement goes through the captured `Reflect.defineProperty`, which ANSWERS * instead of throwing, and the answer is then corroborated by reading the * descriptor back. Installing is not reading: a pin that silently did not happen * is indistinguishable from one that did until something asks, so this asks. The * residual is named rather than denied: an adversary who also answers the * verifying descriptor read defeats this, and that adversary already chose what * {@link INTRINSICS} captured. * * @param prototype - The class prototype to pin * @param owner - The class name used in the refusal * @throws {ContractError} When a member cannot be pinned or the pin cannot be verified * * @example * ```ts * class Widget { static { pinMembers(Widget.prototype, 'Widget') } } * ``` */ export declare function pinMembers(prototype: object, owner: string): void; /** * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s * `received` field. * * @remarks * A primitive renders as printable text: a string retains its quoted JSON * representation, while a narrowed symbol renders through intrinsic `String` * and receives the same escaping without outer quotes. One bounded indexed * encoder appends only complete escaped code-point tokens within * {@link PREVIEW_LIMIT}; clipping therefore never retrieves the mutable string * iterator or splits an escape/surrogate pair before its trailing `…`, and * enormous primitive text is not fully traversed. A number / boolean / bigint * renders via `String`; `null` and `undefined` render as their own name. An * array renders as `'array'`. Every other host — a plain object, a function, a * class instance, a `Map` — is NEVER traversed or stringified; it renders as * its bare `typeof` tag (`'object'` / `'function'`). * * @param value - The value to preview * @returns A short descriptive string, always safe to embed in a diagnostic * * @example * ```ts * preview('hi') // '"hi"' * preview(42) // '42' * preview(null) // 'null' * preview({ a: 1 }) // 'object' * preview([1, 2, 3]) // 'array' * ``` */ export declare function preview(value: unknown): string; /** * The maximum character length of a {@link preview}-rendered string, frozen. * * @remarks * A previewed string longer than this is clipped with a trailing `…` so a * {@link Fault}'s `received` field never embeds an unbounded amount of * untrusted text. */ export declare const PREVIEW_LIMIT = 64; /** A deterministic random source returning a value in `[0, 1)`. */ export declare type RandomFunction = () => number; /** * A validated raw JSON Schema passthrough — embeds a supported schema fragment directly. * * @remarks * For values the shape DSL can't express. The fragment is checked recursively * against the lean {@link JSONSchema} vocabulary before it is accepted or * emitted; unsupported keywords and malformed keyword values throw a coded * {@link ContractError}. This is structural and keyword-domain validation, * not a full JSON Schema solver: it does not resolve cross-keyword * contradictions, `required`/`properties` membership, keyword/type coherence, * `enum`/`type` compatibility, or a closed `format` vocabulary. The compiled guard accepts every * top-level value except `undefined`, which is reserved as the parser failure * sentinel. Wrap the shape with {@link OptionalShape} to admit absence. Defined * values pass through unchanged, and the schema is emitted structurally * verbatim as an owned deeply frozen copy. */ export declare interface RawShape { readonly type: 'raw'; readonly schema: JSONSchema; } /** * Build a {@link RawShape} from a supported JSON Schema fragment. * * @remarks * For values the shape DSL can't express. The fragment is recursively checked * against the lean {@link JSONSchema} vocabulary before ownership is taken; * malformed or unsupported keywords throw a coded {@link ContractError}. The * compiled guard accepts every * DEFINED value — `undefined` alone fails, because it is the parser's failure * sentinel; wrap the shape in {@link optionalShape} to admit absence. The * parser passes a defined value through unchanged, and the fragment is * deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so * `rawShape(fragment).schema !== fragment` and later edits to the caller's * fragment cannot reach the shape. `compileSchema` re-emits that snapshot * structurally verbatim, so here the schema claims LESS than the compiled guard * accepts — `rawShape({ type: 'string' })` emits `{ type: 'string' }` and its * guard still accepts `42`, the mirror of {@link jsonShape}'s looseness. * `compileGenerator` throws, since an arbitrary embedded schema has no * auto-generatable sample. * * @param schema - The JSON Schema fragment to embed * @returns A raw shape owning a frozen copy of the fragment * * @example * ```ts * const custom = rawShape({ type: 'string', format: 'uuid' }) * ``` */ export declare function rawShape(schema: JSONSchema): RawShape; /** * Snapshot an array through its reflected own-index population. * * @remarks * Reads `length` once and one reflected own-key population, then corroborates * and reads only those reflected canonical indices in ascending order. The * frozen native snapshot retains actual holes: reading one yields `undefined`, * while own membership remains absent. Its work is proportional to the * reflected population, so a length-driven consumer must require `dense` or * carry an independent bound. Caller-defined iteration is ignored. A * descriptor-only index omitted from reflection is deliberately outside this * lens and remains a hole. Failure retains the exact thrown value when length, * reflection, membership, or indexed value observation throws; a non-native * length or view disagreement is also failure. `4294967295` is metadata rather * than an array index. * * @param value - The array whose reflected indexed entries to read * @returns A successful frozen entry snapshot with its dense fact, or a * failure carrying the exact thrown value as `unknown` * * @example * ```ts * readArrayEntries([1, 2]) // { success: true, value: { entries: [1, 2], dense: true } } * ``` */ export declare function readArrayEntries(value: readonly T[]): Result>; /** * Snapshot a guard shape and its optional-key mode for a shape combinator. * * @remarks * A null-prototype record plus its own key list is used instead of a `Map`. * The declared-key population decides the guard's answer, and * `Map.prototype.has`, `Map.prototype.get`, and map iteration are three * caller-writable members on that path. An own data key read by index * dispatches through nothing. * * @param shape - The guard shape whose own string declarations to snapshot * @param optional - The optional-key list, `true` for every key, or `undefined` * @param reader - The public combinator name used in read refusals * @returns The owned guards and names plus the collected optional-key membership * @throws {ContractError} When the shape or optional-key list cannot be read * * @example * ```ts * readGuardShape({ id: isString }, undefined, 'recordOf') * ``` */ export declare function readGuardShape(shape: GuardsShape, optional: readonly string[] | true | undefined, reader: string): Readonly<{ readonly guards: Readonly | undefined>>; readonly names: readonly string[]; readonly optional: ReadonlySet; readonly vocabulary: ReadonlySet; }>; /** * Snapshot the genuine entries of a caller's `Map` without running an iterator. * * @remarks * The `Map` half of {@link readSetEntries}, with one further replaceable * dispatch removed: destructuring `for (const [key, value] of map)` reads * `Map.prototype[Symbol.iterator]` AND `Array.prototype[Symbol.iterator]` for * every pair, so a substituting iterator could rename a key or replace a value * while every downstream structural check still passed. Each pair is read * positionally from a list this package built. * * @param value - The map whose genuine entries to snapshot * @returns A frozen `[key, value]` pair snapshot, or a failure carrying the exact thrown value * * @example * ```ts * readMapEntries(new Map([['a', 1]])) // { success: true, value: [['a', 1]] } * ``` */ export declare function readMapEntries(value: ReadonlyMap): Result>; /** * Validate and snapshot a shape-builder options record through every reflective * operation the builder relies on. * * @remarks * Primitive inputs are rejected before reflection so ordinary caller mistakes * retain the reader's precise plain-record diagnostic. For an object, every * consumed key is read exactly once, checked for presence, and inspected for an * own descriptor while the container is enumerated once. Every successfully * read non-`undefined` consumed value enters the fresh own-enumerable snapshot, * including an inherited or non-enumerable option. A hostile host is reported * uniformly as an unreadable options record, while a readable array or class * instance retains the plain-record diagnostic. * * @param source - The optional builder options value * @param keys - Every option key consumed by that builder * @param builder - The builder name used in diagnostics * @param shape - The shape category used in structured error context * @returns An owned options snapshot, or `undefined` when options are absent * @throws {ContractError} When the value is not a plain record or reflection fails * * @example * ```ts * const options = readOptions(source, ['min', 'max'], 'numberShape', 'number') * ``` */ export declare function readOptions(source: T | undefined, keys: ReadonlyArray, builder: string, shape: string): T | undefined; /** * Rebuild a caller's regular expression as a stateless pattern this package * owns. * * @remarks * Strips the stateful `g` / `y` flags so repeated checks are stable and the * caller's `lastIndex` never moves. The strip is an INDEXED character filter * rather than `String.prototype.replaceAll`, which is itself a caller-writable * member: a substitute answering `'i'` made `matchOf(/^abc$/)` accept `'ABC'` — * the package building a case-insensitive pattern the developer never wrote. * * @param pattern - The caller's regular expression * @returns An owned, stateless equivalent * @throws The exact value thrown when the pattern's source or flags cannot be read * * @example * ```ts * readPattern(/^a+$/gy) // /^a+$/ * ``` */ export declare function readPattern(pattern: RegExp): RegExp; /** * Read a regular expression's flag text through the captured accessor. * * @param pattern - The candidate regular expression to read * @returns The pattern's flag text, or `undefined` when it cannot be read as a string * @throws The exact value the captured accessor throws for a receiver that is not a pattern * * @example * ```ts * readPatternFlags(/^a+$/giu) // 'giu' * ``` */ export declare function readPatternFlags(pattern: unknown): string | undefined; /** * Read a regular expression's source text through the captured accessor. * * @remarks * `RegExp.prototype.source` is an ACCESSOR on a shared prototype, so replacing * its getter changes what every pattern in the realm reports — not only the * caller's own. A getter answering `'.*'` made `compileSchema` publish * `pattern: ".*"` inside a frozen schema and made `isRegExp('x')` answer `true`. * Reading the descriptor per call, as an earlier round did, captures nothing: * capture is decided by WHEN the reference is taken. * * @param pattern - The candidate regular expression to read * @returns The pattern's source text, or `undefined` when it cannot be read as a string * @throws The exact value the captured accessor throws for a receiver that is not a pattern * * @example * ```ts * readPatternSource(/^a+$/) // '^a+$' * ``` */ export declare function readPatternSource(pattern: unknown): string | undefined; /** * Check that a value really is a {@link SampleMemo} before a walk stores a * published schema in it. * * @remarks * The memo is the one argument position on `inferSamples` / * `inferRecordSamples` that reaches a `WeakMap` and a `Map` the caller * supplied, and both doors are reachable untyped from JavaScript. Without this * check a wrong value there failed inside the traversal and was published as * `samples could not be read` — a true refusal naming the wrong argument, the * defect class those doors were already corrected for twice. It refuses under * the memo's own name and its own path instead. * * @param memo - The candidate memo * @param reader - The door name the refusal is published under * @returns The same memo when it carries a real `rows` `WeakMap` and `schemas` `Map` * @throws {ContractError} When the memo is not a `SampleMemo` * * @example * ```ts * readSampleMemo(buildSampleMemo(), 'inferSamples') // the same memo * ``` */ export declare function readSampleMemo(memo: SampleMemo, reader: string): SampleMemo; /** * Snapshot the genuine contents of a caller's `Set` without running an iterator. * * @remarks * `Set.prototype[Symbol.iterator]` is a caller-writable member, and every other * view of the same collection disagrees with a replaced one: an iterator that * silently skips the non-string in `new Set(['a', 42])` made `setOf(isString)` * answer `true` while `forEach` and `size` still reported the real contents. The * sibling `arrayOf` already read its caller's collection through captured * reflection, so the exclusion was not even self-consistent within one file. * `forEach` is the only complete view of `[[SetData]]` that runs no iterator, so * it is dispatched here from the captured table. * * @param value - The set whose genuine entries to snapshot * @returns A frozen entry snapshot, or a failure carrying the exact thrown value * * @example * ```ts * readSetEntries(new Set(['a', 42])) // { success: true, value: ['a', 42] } * ``` */ export declare function readSetEntries(value: ReadonlySet): Result; /** * Read a value through the shared containment boundary or refuse it with the * contract module's uniform read diagnostic. * * @remarks * Unlike {@link attempt}, this is not an optional-result boundary: a caller * has committed to reading the supplied value, so a failed read cannot be * represented as absence or another permissive answer. Every reader using * this helper throws with the same `: could not be read` * message shape and retains the exact thrown value as its cause. Required * structural readers use the defaults; pattern readers supply `pattern` for * both the subject and code. * * @param callback - The read operation to perform * @param reader - The public reader name used in the diagnostic * @param options - Optional subject, code, and structured context * @returns The successfully read value * @throws {ContractError} When the read operation fails * * @example * ```ts * readValue(() => source.value, 'parseRecord') * ``` */ export declare function readValue(callback: () => T, reader: string, options?: ReadValueOptions): T; /** Optional diagnostic metadata for a required read. */ export declare interface ReadValueOptions { /** Argument/domain noun used in the refusal message. */ readonly subject?: string; /** Machine-readable refusal category. */ readonly code?: ContractCode; /** Structured location and domain details retained by the refusal. */ readonly context?: ContractErrorContext; } export declare function recordOf(shape: S): Guard>; export declare function recordOf>(shape: S, optional: K): Guard>; export declare function recordOf(shape: S, optional: true): Guard[P]; }>>; /** * Build an open {@link ObjectShape} with no fixed properties — a dictionary. * * @remarks * Every value is validated against `values`; keys are unconstrained. Equivalent * to `objectShape({}, { additionalProperties: values })`. * * @param values - The shape every value must match * @param options - Optional `description` * @returns An open object shape * @throws {ContractError} When `values` is absent at runtime * * @example * ```ts * const bindings = recordShape(numberShape()) // ~ Record * ``` */ export declare function recordShape(values: S, options?: RecordShapeOptions): ObjectShape, S>; /** Options for record shapes (via `recordShape`). */ export declare interface RecordShapeOptions { readonly description?: string; } /** * Refuse a validated declaration whose compiled expansion exceeds * {@link COMPILE_NODE_LIMIT}. * * @remarks * The compilers' emitted-node bound, written once because two boundaries apply * it over a {@link ShapeValidatorInterface.expansion} count: the eager * {@link validateShapeDepth} function and the lazy {@link ContractCompiler} * preparation. The refusal keeps `validateShapeDepth`'s name because that gate * OWNS the rule and its exact diagnostic is public API — the same reason * `ShapeCloner` publishes the gate's depth wording rather than inventing a * second vocabulary for one rule. Two constructions of one refusal are two * messages waiting to drift apart. * * @param expansion - The node count one successful validation measured * @returns Nothing when the count is within the limit * @throws {ContractError} When the count exceeds {@link COMPILE_NODE_LIMIT} * * @example * ```ts * const validator = new ShapeValidator(shape) * validator.validate() * refuseExpansion(validator.expansion) * ``` */ export declare function refuseExpansion(expansion: number): void; /** * A compiled coercive-domain diagnostic — the shape of `compileReporter` bound * to one shape. * * @remarks * The counterpart of {@link AuditorFunction} for the wider preimage `parse` * maps into the domain, with the same optional root-path prefix and the same * assignability to {@link ContractInterface.explain}. */ export declare type ReporterFunction = (value: unknown, path?: readonly string[]) => readonly Fault[]; /** * Resolve a (possibly nested) field value from a record by a key or key path. * * @remarks * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a * string array descends left-to-right through own properties of nested objects. * The root must satisfy {@link isRecord}; inherited properties are never fields. * Intermediates may be objects or arrays indexed by string. Returns `undefined` * the moment a segment is missing or lands on a non-object, so the lookup is * total — even against a hostile getter or Proxy trap that throws on read, * contained via {@link attempt} so the throw never escapes. * * @param record - The source record * @param path - A property key, or a key path descending into nested objects * @returns The resolved value, or `undefined` * * @example * ```ts * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada' * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key) * resolveField({ a: 1 }, ['a', 'b']) // undefined * ``` */ export declare function resolveField(record: Readonly>, path: FieldPath): unknown; /** * Discriminated union for operations that can succeed or fail without throwing. * * @remarks * The failure channel defaults to `unknown`. Operations with a guaranteed * domain error name that error type explicitly. */ export declare type Result = Success | Failure; /** * Record one node's answer at one remaining-depth allowance in a shared memo. * * @remarks * A depth-bounded walk answers the same node differently depending on how much * allowance was left when it arrived, so each node keeps a `Map` of answers * inside one `WeakMap`. Written inline, the get-or-create ferried that map out * of the branch that built it through a `let`, three times over in * `inferArray`, `inferObject` and `schemaNodeToShape`. Written once it is one * statement per caller, and the captured `WeakMap`/`Map` members stay the only * ones all three dispatch through — a substituted `WeakMap.prototype.get` that * answered a decoy map would otherwise decide what a later call replays. * * @param memo - The per-node depth memo this walk owns * @param node - The source node the answer was computed for * @param depth - The remaining-depth allowance the answer was computed under * @param answer - The answer to record for that node at that allowance * * @example * ```ts * const memo = new WeakMap>() * retainDepth(memo, node, 8, 'answer') * memo.get(node)?.get(8) // 'answer' * ``` */ export declare function retainDepth(memo: WeakMap>, node: object, depth: number, answer: T): void; /** * The per-walk memo {@link inferSamples} and {@link inferRecordSamples} share, * keyed by the ORDERED identities of the rows a slot collected. * * @remarks * `rows` is one step of a prefix chain: following the slot's rows in order * lands on the node that owns that exact row list, so two slots collecting the * same rows in the same order share one entry and two slots collecting * different rows never do. `schemas` holds that row list's already-inferred * results, keyed by EVERY budget and flag the emitted schema depends on * (remaining depth, breadth, `closed`, `format`, `enum`) — so the memo can * only ever return the schema a fresh call would have produced, and two * ordinary calls that differ in one flag cannot be served each other's answer. * * Build one with {@link buildSampleMemo} and give it to ONE walk. It is * traversal state, not a cache to keep: nothing is invalidated when a sample * row is later mutated. * * @example * ```ts * const memo = buildSampleMemo() * inferSamples([{ id: 1 }], 32, 256, true, false, false, memo) * ``` */ export declare interface SampleMemo { readonly rows: WeakMap; readonly schemas: Map; } /** * Classify a list of sample values against the {@link SchemaFormat} * vocabulary, requiring unanimity. * * @remarks * A format is returned ONLY IF every value is a string AND every one maps to * the SAME {@link stringToFormat} result (including all mapping to * `undefined`, which itself returns `undefined` here). A single disagreeing * value, a non-string value, or an empty list all yield `undefined` — the * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples}) * relies on this unanimity so a slot with mixed string shapes emits a bare * `{ type: 'string' }` rather than an `anyOf` of formats. * * @param values - The sample values to classify * @returns The unanimous {@link SchemaFormat}, or `undefined` * * @example * ```ts * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date' * samplesToFormat(['2024-01-01', 'not a date']) // undefined * samplesToFormat([]) // undefined * ``` */ export declare function samplesToFormat(values: readonly unknown[]): SchemaFormat | undefined; /** * Infer a `JSONSchema` from a set of example values — the multi-example * counterpart of {@link valueToSchema} (e.g. inferring one schema from * several database rows). * * @remarks * An empty `samples` array infers the empty accept-anything schema `{}`. * When every sample is a plain record, properties/required are unified * per-key across all samples (see {@link inferRecordSamples}) — a key * required iff present and non-`undefined` in every sample. Otherwise the * slot is inferred via {@link inferSamples} (independent {@link valueToSchema} * per sample, unified with {@link unifySchemas} — the same de-duplication and * `anyOf` ordering {@link inferArray} applies to element schemas). `format` * and `enum` (both default `false`) opt a low-cardinality/unanimous-format * slot into the corresponding keyword — see {@link inferSamples} for the * precedence and the multi-sample format-disabling seam. `maxDepth` / * `maxProperties` are resolved exactly as {@link valueToSchema} resolves them — * breadth through {@link sanitizeBudget}, depth through {@link sanitizeDepth}, * which also caps at {@link INFER_DEPTH_LIMIT}; see there for why. * * @param samples - The example values to infer a schema from * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds * @returns The inferred `JSONSchema` * @throws {ContractError} When the samples or options cannot be read * * @example * ```ts * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }]) * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } }, * // required: ['id'], additionalProperties: false } * samplesToSchema([]) // {} * ``` */ export declare function samplesToSchema(samples: readonly unknown[], options?: ValueToSchemaOptions): JSONSchema; /** * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to * a finite non-negative integer, selecting a valid fallback for anything else. * * @remarks * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard * (`NaN <= 0` is `false`, so recursion never halts), and a negative * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key * instead of capping the list (a fractional value has a similarly undefined * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)` * is `false` — since an unbounded budget is exactly the adversarial case the * caps exist to prevent. A valid candidate passes through unchanged without * inspecting the fallback. When the candidate is invalid, the fallback must * satisfy the same finite non-negative-integer contract or this boundary * refuses it with a coded error instead of returning an invalid budget. * * @param value - The candidate budget value * @param fallback - The default to select when `value` is not a finite * non-negative integer * @returns A finite non-negative integer budget * @throws {ContractError} When the selected fallback is not a finite * non-negative integer * * @example * ```ts * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4 * ``` */ export declare function sanitizeBudget(value: number | undefined, fallback: number): number; /** * Resolve a caller's depth budget to one the traversal can actually survive. * * @remarks * {@link sanitizeBudget} decides the SHAPE of a budget and deliberately lets any * finite non-negative integer through, because it must never read a fallback a * hostile caller supplied. That left the depth axis unbounded from above, and * depth is the axis that recurses: `1e9` is a valid integer, so the walk descended * until the call STACK failed, at a depth that varied between runs, and the * refusal surfaced as an unreadable value rather than as the exhaustion the guard * promises. Breadth needs no such ceiling — its loop is already bounded by the * entries actually present. * * So {@link INFER_DEPTH_LIMIT} is the ceiling as well as the default, and * `maxDepth` narrows the walk rather than widening it. One bound, and the same * answer on every host. * * @param value - The candidate depth budget * @returns A finite non-negative integer no greater than `INFER_DEPTH_LIMIT` * * @example * ```ts * sanitizeDepth(4) // 4 * sanitizeDepth(1e9) // 32 * ``` */ export declare function sanitizeDepth(value: number | undefined): number; /** * Stateful owner of one JSON Schema snapshot operation. * * @remarks * Construction retains the source without observing it. The first * {@link clone} call performs one iterative identity-memoized walk and settles * permanently. Success replays the exact frozen root; failure rethrows the * exact class-owned error. Nonredirectable terminal settlement releases * populated traversal state before publishing that result, while retaining * the source and exact result afterward. Reentry poisons the active operation * and every later call with one shared cause-free error. * * @param schema - The JSON Schema graph to retain for cloning * * @example * ```ts * const child = { type: 'string' } * const cloner = new SchemaCloner({ anyOf: [child, child] }) * const clone = cloner.clone() * clone.anyOf?.[0] === clone.anyOf?.[1] // true * cloner.clone() === clone // true * ``` */ export declare class SchemaCloner implements SchemaClonerInterface { #private; constructor(schema: JSONSchema); /** * Clone the retained schema into an identity-preserving frozen graph. * * @returns The settled JSON Schema snapshot * @throws {ContractError} When traversal is unreadable or cloning is reentered */ clone(): JSONSchema; } /** * Stateful owner of one JSON Schema snapshot operation. * * @remarks * Construction retains the schema without observing it. The first * {@link clone} call settles once; later calls replay the exact same frozen * schema or exact same owned {@link ContractError}. Nonredirectable terminal * settlement releases populated traversal state before publishing that exact * result, while retaining the source and result afterward. */ export declare interface SchemaClonerInterface { /** * Clone the retained schema into a deeply frozen identity-preserving graph. * * @returns The settled JSON Schema snapshot * @throws {ContractError} When traversal is unreadable or cloning is reentered */ clone(): JSONSchema; } /** * The closed set of string formats {@link stringToFormat} recognizes. * * @remarks * Lowercase spec literals, matching the JSON Schema `format` vocabulary for * the subset the inferers detect: `'date-time'` / `'date'` / `'time'` are * ISO-8601 (validity-checked via `Date`, not pattern-only), `'uuid'` matches * RFC-4122 hex layout, `'email'` and `'uri'` are pragmatic (not full-spec) * shape checks. See {@link FORMAT_PATTERNS}. */ export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'email' | 'uri'; /** * Convert one JSON Schema node into a {@link ContractShape} — the recursion * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for * every child (`items`, `properties` values, `additionalProperties`, * `oneOf` / `anyOf` variants). * * @remarks * Guards depth exhaustion, a readable non-record node (the node's static * `JSONSchema` type is not trusted at runtime), and a cyclic re-encounter of * `schema` — all three widen to {@link rawShape}. The * ancestor set is added to and removed from around the WHOLE subtree * conversion (not permanently), so a DAG-shaped schema reached twice via two * different, non-cyclic paths does not false-positive as a cycle. The * subtree conversion itself runs through {@link readValue}, so a hostile * throwing getter/Proxy anywhere in `schema` raises a coded read refusal * instead of degrading to an accept-anything shape. A same-node re-conversion at * the same remaining `depth` is served from `memo` (guards a * shared-reference schema DAG against exponential blowup), mirroring * {@link inferObject} / {@link inferArray} (inferers.ts). * * @param schema - The schema node to convert * @param depth - Remaining descent budget * @param visited - The ancestor set guarding against cycles — recursion * state owned by the {@link schemaToShape} entry point; passing a shared or * pre-populated `WeakSet` changes cycle-detection behavior and is not * supported usage * @param memo - A per-call `(schema node, remaining depth) → shape` cache — * recursion state owned by the {@link schemaToShape} entry point; passing * a shared or pre-populated `WeakMap` changes caching behavior and is not * supported usage * @returns The built shape for `schema`, or {@link rawShape} for readable widening cases * @throws {ContractError} When schema traversal fails * * @example * ```ts * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap()) * // booleanShape() * ``` */ export declare function schemaNodeToShape(schema: JSONSchema, depth: number, visited: WeakSet, memo: WeakMap>): ContractShape; /** * Wrap a non-object `JSONSchema` root in a single-property object schema, so * an inferred primitive/array/union schema can flow into {@link schemaToParameters} * as an MCP-compatible `inputSchema`. * * @remarks * Deterministic for readable input. `schema.type === 'object'` passes through * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only * schema with no `type`, or the empty `{}`) is wrapped as a single required * `value` property: `{ type: 'object', properties: { value: schema }, * required: ['value'], additionalProperties: false }`. Composition: * `schemaToParameters(schemaToObject(valueToSchema(payload)))`. * * @param schema - The schema to wrap * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema * @throws {ContractError} When the schema root cannot be read * * @example * ```ts * schemaToObject({ type: 'string' }) * // { type: 'object', properties: { value: { type: 'string' } }, * // required: ['value'], additionalProperties: false } * schemaToObject({ type: 'object', properties: {} }) // unchanged * ``` */ export declare function schemaToObject(schema: JSONSchema): JSONSchema; /** * Narrow a compiled {@link JSONSchema} down to the open `Readonly>` shape * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never * an assertion (AGENTS §14). * * @remarks * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a * tool advertises its `parameters` as an open record. The two are structurally compatible but not * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site. * * @param schema - The compiled JSON Schema (a contract's `schema`) * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record * @throws {ContractError} When the schema cannot be read * * @example * ```ts * import { createContract, schemaToParameters } from '@orkestrel/contract' * * const contract = createContract(shape) * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises * ``` */ export declare function schemaToParameters(schema: JSONSchema): Readonly> | undefined; /** * Convert a runtime `JSONSchema` value into a validating {@link ContractShape} * — the inverse of {@link compileSchema}. Unlike direct {@link rawShape} * construction, which rejects malformed supported-vocabulary keywords, this * conversion is total and widens an inexpressible input to a valid raw `{}`. * * @remarks * Readable malformed, cyclic, or deeply nested schema nodes widen to * {@link rawShape}; a failed traversal raises the shared coded refusal because * an unreadable value is not a schema. `createContract(schemaToShape(x))` * therefore remains safe for every readable `x`. See * {@link buildShapeFromNode} for the exact per-keyword precedence. * * `format` and `pattern` are NEVER asserted by the compiled shape — `format` * is annotation-only (per the JSON Schema spec, it never narrows validation * on its own) and compiling an attacker-controlled `pattern` string into a * `RegExp` is a ReDoS vector; both keywords are read only far enough to be * ignored. Any node the walk cannot express — an empty `{}`, an * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a * cyclic re-encounter — widens to {@link rawShape} (accept any defined * value), never narrows. * * ROUND TRIP: for every readable `v`, * `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` — including * values no JSON Schema keyword describes (`NaN`, `±Infinity`, a `Map`, a * `Set`, a class instance, a function, a symbol, a bigint, and readable cyclic * hosts), which infer `{}` and widen back to an accept-anything * {@link rawShape}. An unreadable host is refused by {@link valueToSchema} * before this law produces a schema; direct hostile input to * {@link schemaToShape} receives the same coded refusal. * Widening is the only source of looseness. The law has three explicit host * limits: * * - **Absence.** `undefined` is not a value: no compiled guard accepts it * (`rawShape` reserves it as the parser failure sentinel). So `undefined` * itself, an array element holding it, and an array HOLE (`arrayOf` requires * every index to be an own property, the same rule `isJSONValue` applies) * all fall outside the law. An OBJECT property holding `undefined` does not: * `valueToSchema` drops the key and opens the object, so the source object * is still accepted. * - **`Date` serialization.** A `Date` infers the schema of its JSON form * (`{ type: 'string' }`, plus `format: 'date-time'` when `format` is on), so * the law applies to `date.toISOString()` rather than the runtime instance. * - **Stateful access.** A getter whose result changes between inference and * guard evaluation can invalidate the sampled fact. Likewise, an array that * overrides iteration behavior can present different elements to the two * phases. The law applies only while the sampled host's observable own * enumerable string properties and array iteration remain stable. * * A widened node cannot be auto-generated: `rawShape` embeds an arbitrary * schema fragment, so `createContract(schemaToShape(x)).generate()` throws * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain` * stay total. * * @param schema - The JSON Schema value to convert * @returns The built {@link ContractShape} * @throws {ContractError} When schema traversal fails * * @example * ```ts * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }]) * const contract = createContract(schemaToShape(schema)) * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' } * contract.parse({ id: 'nope' }) // undefined * ``` */ export declare function schemaToShape(schema: JSONSchema): ContractShape; /** * Build a deterministic pseudo-random source seeded from a single number. * * @remarks * A mulberry32 generator — the same seed always yields the same sequence, so * generated seed data is reproducible across runs. Used as the default random * source for {@link compileGenerator}, seeded from the wall clock so casual * callers still get varied output without passing a source themselves. * * @param seed - The seed for the sequence * @returns A {@link RandomFunction} returning values in `[0, 1)` * * @example * ```ts * const random = seededRandom(42) * random() // always the same first value for seed 42 * ``` */ export declare function seededRandom(seed: number): RandomFunction; /** * A compiled seed-data source — the shape of `compileGenerator` bound to one * shape. * * @remarks * An absent `random` selects the invocation's own wall-clock-seeded source, so * a generator retains no randomness between calls. * * @remarks * Named for the SEED DATA it produces rather than for the `generator` getter it * serves, which is the one place this package's three compiled-diagnostic types * break their own symmetry with {@link AuditorFunction} and * {@link ReporterFunction}. `GeneratorFunction` is already taken twice over: it * is a realm global (the constructor every `function*` reports), and it is the * exact string {@link isGeneratorFunction} compares against. Publishing a type * of that name beside that guard would put two contradictory meanings of one * word in one barrel, where `isGeneratorFunction(contract.generate)` answers * `false` for a value the types call a `GeneratorFunction`. */ export declare type SeederFunction = (random?: RandomFunction) => T; /** * Select the report of the variant that came closest to matching. * * @remarks * The union summary both diagnostic doors append their closest variant's faults * to. "Closest" is the SHORTEST report, and an earlier variant wins a tie, so a * union's diagnostic follows declaration order rather than whichever variant a * later comparison happened to visit. The winning report is returned BY * IDENTITY, never copied, so the summary carries the exact fault objects the * variant produced. No report at all — a union whose every variant slot was * unreadable — yields a frozen empty collection rather than `undefined`, so the * caller appends nothing instead of branching. * * The scan is an indexed read of arrays this package built, so neither the * choice of variant nor the length comparison dispatches through a member a * caller can replace. * * @param reports - One report per variant, in declaration order * @returns The first shortest report, or a frozen empty collection when there are none * * @example * ```ts * selectClosestFaults([[fault, fault], [fault]]) // the second report * selectClosestFaults([]) // [] * ``` */ export declare function selectClosestFaults(reports: ReadonlyArray): readonly T[]; /** * Build a guard that accepts `Set` instances whose every element satisfies * `elementGuard`. * * @example * ```ts * const isStringSet = setOf(isString) * isStringSet(new Set(['a', 'b'])) // true * isStringSet(new Set(['a', 1])) // false * ``` */ export declare function setOf(elementGuard: Guard): Guard>; export declare function setOf(elementGuard: (value: unknown) => boolean): Guard>; /** * Stateful owner of one contract-shape snapshot operation. * * @remarks * Construction retains the source without observing it. The first * {@link clone} call captures and validates one owned graph and settles * permanently. Success replays the exact frozen root; failure rethrows the * exact class-owned or directly adopted error. Nonredirectable settlement * releases populated traversal state before publishing that result. Reentry * poisons the active operation and every later call with one shared cause-free * error. * * @param shape - The contract-shape graph to retain for cloning * * @example * ```ts * const cloner = new ShapeCloner({ type: 'string', min: 1 }) * const clone = cloner.clone() * cloner.clone() === clone // true * ``` */ export declare class ShapeCloner implements ShapeClonerInterface { #private; constructor(shape: ContractShape); /** * Clone the retained declaration into an owned, validated frozen graph. * * @returns The settled contract-shape snapshot * @throws {ContractError} When the declaration is malformed, unreadable, cyclic, too deep, or cloning is reentered */ clone(): ContractShape; } export declare interface ShapeClonerInterface { /** * Clone the retained shape into a deeply frozen identity-preserving graph. * * @returns The settled contract-shape snapshot * @throws {ContractError} When the declaration is malformed, unreadable, cyclic, too deep, or cloning is reentered */ clone(): ContractShape; } /** * Stateful owner of one contract-shape snapshot operation. * * @remarks * Construction retains the shape without observing it. The first * {@link clone} call settles once; later calls replay the exact same frozen * shape or exact same owned {@link ContractError}. Nonredirectable terminal * settlement releases populated traversal state before publishing that exact * result, while retaining the source and result afterward. * Reentry permanently poisons the active operation with one shared error. */ /** * One captured property of an object shape, held as an ordered entry rather * than as a `Map` pair. * * @remarks * The published property population of a cloned object shape is decided by * walking these entries. A `Map` would be the natural carrier and the wrong * one: iterating it dispatches through `Map.prototype[Symbol.iterator]` and * destructuring each pair through `Array.prototype[Symbol.iterator]`, both * caller-writable, and an arity-preserving substitution there renames a * property inside a snapshot the package publishes as exact. */ export declare interface ShapeProperty { /** The own enumerable key the property was captured under. */ readonly key: string; /** The captured child shape, absent when the declaration held no shape. */ readonly child: ContractShape | undefined; } /** * Project a {@link ContractShape} to the {@link FaultKind} it describes. * * @remarks * A structural mapping used by {@link compileReporter} to fill a `Fault`'s * `expected` field and by {@link compileAuditor} to fill an `AuditFault`'s: * most shapes map to their own `type` (`numberShape` maps to * `'integer'` when `integer: true`, else `'number'`); `optionalShape` / * `nullableShape` project through to their inner shape's kind, and `rawShape` * (an arbitrary embedded schema with no fixed kind) projects to `'json'`. * * A hand-authored node carrying an unrecognized discriminant is REFUSED rather * than answered out of type. The switch used to fall off its end and return * `undefined` for such a node, which made the declared non-optional * {@link FaultKind} return type a lie at a public export; every other door in * this module refuses out-of-domain input, so this one does too. * * @param shape - The shape to project * @returns The shape's {@link FaultKind} * @throws {ContractError} When the node carries no recognized shape discriminant * * @example * ```ts * shapeToKind(stringShape()) // 'string' * shapeToKind(integerShape()) // 'integer' * shapeToKind(optionalShape(nullShape())) // 'null' * ``` */ export declare function shapeToKind(shape: ContractShape): FaultKind; /** * A reusable live validator for one retained contract-shape source. * * @remarks * Construction performs no source observation. Every non-overlapping * {@link validate} call starts a fresh pass over the source's current state. * Reentry poisons the active pass with one shared cause-free structure error; * cleanup always restores an idle validator for the next independent call. * * @example * ```ts * const validator = new ShapeValidator({ type: 'string', min: 1 }) * validator.validate() * ``` */ export declare class ShapeValidator implements ShapeValidatorInterface { #private; /** * Retain a shape source without observing it. * * @param shape - The live shape source validated by each call */ constructor(shape: ContractShape); /** * The number of nodes the last successful {@link validate} found the source * expands into. * * @remarks * One per node per INCOMING EDGE, summed bottom-up — the size of the tree a * compiler would build from this DAG, which a node count of the declaration * itself does not describe. `0` before the first successful pass and after a * failed one, because a failed pass has no expansion to report. */ get expansion(): number; /** * Validate the retained source's current declaration. * * @remarks * The whole traversal is contained, and a failure this class did not author * is translated into `validateShapeDepth: shape reflection failed` carrying * the exact thrown value. Containment is what makes that claim hold for * dispatch nobody enumerated — including the recognition of an authored error, * which is why that recognition is no longer answerable by any member a caller * can write. The sentence this replaces asserted the same conclusion from the * absence of reachable dispatch, and the absence was not established. * * @returns Nothing when the declaration is valid * @throws {ContractError} When the declaration is malformed, cyclic, too deep, unreadable, or reentered */ validate(): void; } /** * Validates one retained contract-shape source on demand. * * @remarks * Construction does not observe the source. Every {@link validate} call is an * independent live validation pass over its current state. */ export declare interface ShapeValidatorInterface { /** * The number of nodes the last successful {@link validate} found the retained * declaration expands into, counting one per node per incoming edge — the * size of the TREE every compiled artifact would build from this DAG. `0` * before the first successful pass and after a failed one. */ readonly expansion: number; /** * Validate the retained shape declaration. * * @returns Nothing when the declaration is valid * @throws {ContractError} When the declaration is malformed, cyclic, or too deep */ validate(): void; } /** * Order primitive keys or indices deterministically, on an owned copy, through * the captured sort. * * @remarks * Every schema this package emits is ordered so the same input produces the * same bytes, and `Array.prototype.sort` is a caller-writable member on every * one of those paths: a substitute that empties its receiver made * `valueToSchema({ b: 1, a: 2 })` publish `{"type":"object","additionalProperties":false}` * — a successful answer with the caller's properties silently gone. The copy is * taken first so a caller-owned array is never reordered in place, and the order * is decided by {@link compareValues}, whose `<` / `>` comparison dispatches * through nothing. * * @param values - The keys or indices to order * @returns A fresh array in ascending order * * @example * ```ts * sortValues(['b', 'a']) // ['a', 'b'] * ``` */ export declare function sortValues(values: readonly T[]): readonly T[]; /** * Build a guard that accepts strings satisfying optional length and pattern * refinements — `min` / `max` length and a `pattern`. * * @remarks * Composes {@link isString} with {@link boundsOf} on the string's `.length` and * an owned stateless pattern (the same refinement {@link matchOf} performs). * When all three options are absent it returns the bare {@link isString} guard * (the unconstrained fast path), so an unrefined string leaf pays no wrapping * cost. The single source of the string refinement shared by the compiled guard * and parser (compilers.ts). * * @param options - Optional length bounds and regular expression refinement * @returns A string guard enforcing the requested refinements * @throws {ContractError} When the options cannot be read * * @example * ```ts * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ }) * isSlug('hello-world') // true * isSlug('') // false — below min * isSlug('Hello') // false — pattern miss * * stringOf() // identical to isString * ``` */ export declare function stringOf(options?: { min?: number; max?: number; pattern?: RegExp; }): Guard; /** A string shape with optional length and pattern constraints. */ export declare interface StringShape { readonly type: 'string'; readonly min?: number; readonly max?: number; /** * An unflagged pattern constraint; use inline pattern constructs for flag-like behavior. * Builders and cloners expose an owned fresh frozen zero-state copy per read. */ readonly pattern?: RegExp; readonly description?: string; } /** * Build a string {@link StringShape}. * * @remarks * A supplied pattern is captured by source and flags. The shape exposes a fresh * frozen zero-state `RegExp` on every `pattern` read, so neither the caller's * original nor a value read from the shape can drift later compiled artifacts. * * @param options - Optional length (`min` / `max`), `pattern`, and `description` * @returns A string shape * @throws {ContractError} When a present bound is invalid, `pattern` is not a `RegExp`, or `pattern` has flags * * @example * ```ts * const name = stringShape({ min: 1, max: 80, description: 'Display name' }) * ``` */ export declare function stringShape(options?: StringShapeOptions): StringShape; /** Options for {@link StringShape} (via `stringShape`). */ export declare interface StringShapeOptions { readonly min?: number; readonly max?: number; readonly pattern?: RegExp; readonly description?: string; } /** * Classify a string against the {@link SchemaFormat} vocabulary. * * @remarks * Total, pure, and deterministic. Fixed precedence, most specific first: * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first * match wins. The `date-time` / `date` / `time` branches require BOTH a * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected. * Returns `undefined` when no format matches (including the empty string). * * @param value - The string to classify * @returns The matched {@link SchemaFormat}, or `undefined` * * @example * ```ts * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid' * stringToFormat('2024-01-15') // 'date' * stringToFormat('2020-13-45') // undefined — invalid date * stringToFormat('ada@example.com') // 'email' * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset * stringToFormat('10:30:00+02:00') // 'time' * ``` */ export declare function stringToFormat(value: string): SchemaFormat | undefined; /** * Discriminated success branch of a {@link Result}. * * @remarks * Used for operations that can succeed or fail without throwing. */ export declare interface Success { readonly success: true; readonly value: T; } /** * Build a guard that passes when the base passes AND the projection of the value * satisfies the target guard. Still narrows to `T` (the base type) — the target * check is a validity constraint on a derived view, not a type transformation. * * @remarks * `project` is a plain `(value: T) => U`. Per §14 the returned guard never * throws: a throw from `project` or `target` is contained and reported as a * non-match. (Unlike the reference implementation, there is no * "curried projector" branch — a projection that legitimately returns a function * would be double-invoked under that scheme. Compose explicitly if you need it.) * * @example * ```ts * const isBounded = transformOf( * isString, * (s) => s.trim().length, * whereOf(isNumber, (n) => n >= 1 && n <= 50), * ) * isBounded('hello') // true * isBounded('') // false * ``` */ export declare function transformOf(base: Guard, project: (value: T) => U, target: Guard): Guard; export declare function transformOf(base: Guard, project: (value: T) => unknown, target: (value: unknown) => boolean): Guard; /** Map a tuple of element guards to a readonly tuple of their guarded types. */ export declare type TupleFromGuards>> = Readonly<{ [K in keyof Ts]: GuardType; }>; /** * Build a guard that accepts fixed-arity DENSE tuples, testing each index with * the corresponding guard. * * @example * ```ts * const isPair = tupleOf(isString, isNumber) * isPair(['hello', 42]) // true * isPair(['hello']) // false — wrong arity * isPair([, 42]) // false — sparse; see arrayOf for the dense lens * ``` */ export declare function tupleOf>>(...guards: Gs): Guard>; export declare function tupleOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard; /** * Unify a list of inferred `JSONSchema` fragments into one schema. * * @remarks * De-duplicates by {@link canonicalStringify}, then applies the one * special-case subsumption inference performs: a bare `{ type: 'integer' }` * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }` * (an integer sample is also a valid `number` sample). A single surviving * distinct schema is returned directly; two or more are wrapped as * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output. * An empty input list returns the empty accept-anything schema `{}`. * * Every captured member must first be a non-null object record. This runtime * requirement is realm-agnostic and admits ordinary and null-prototype schema * records while refusing primitives and callables before canonicalization. * * A readable member {@link canonicalStringify} cannot key — a cyclic or * otherwise JSON-inexpressible fragment, which only a direct caller can supply * since the inferers always build plain encodable fragments — has NO * de-duplication key, so it can participate in neither de-duplication nor the * canonical-key ordering. It is KEPT (dropping a variant would narrow the * union, and unification only ever widens), appended in input order after the * sorted keyed members. A failed member read propagates the canonicalizer's * coded refusal instead of participating in the union. * * @param schemas - The schemas to unify * @returns The unified schema * * @example * ```ts * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' } * unifySchemas([{ type: 'string' }, { type: 'boolean' }]) * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] } * ``` */ export declare function unifySchemas(schemas: readonly JSONSchema[]): JSONSchema; /** * Build a guard that accepts values matching at least one of the provided * guards — the variadic form of {@link orOf}. * * @example * ```ts * const isStringOrBoolean = unionOf(isString, isBoolean) * ``` */ export declare function unionOf>>(...guards: Gs): Guard>; export declare function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard; /** * A union shape — accepts a value matching any one variant (first match wins). * * @remarks * `mode` selects the emitted JSON Schema keyword and runtime matching rule: * `'anyOf'` (default) accepts the first matching variant, while `'oneOf'` * requires exactly one variant to match. */ export declare interface UnionShape { readonly type: 'union'; readonly variants: V; readonly mode?: 'anyOf' | 'oneOf'; readonly description?: string; } /** * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema). * * @param variants - The candidate shapes; the first match wins at runtime * @returns A union shape whose `Infer` is the union of the variants * * @example * ```ts * const id = unionShape(stringShape(), integerShape()) * // Infer = string | number * ``` */ export declare function unionShape(...variants: V): UnionShape>; /** Convert a union type to an intersection type. */ export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; /** * Gate recursive compiler work on shape structure, depth, and cycles. * * @remarks * Constructs a fresh {@link ShapeValidator} and eagerly validates the graph. * The validator walks iteratively with explicit stack space and observes each * unique node exactly ONCE per call, so a shared-child DAG costs its AUTHORED * nodes and edges rather than its paths. Every incoming edge is still inspected: * where an `optional` node is legal depends on the slot it arrived through, and * depth is measured over the captured graph afterwards rather than by walking * each path. * * This is also where the compilers' expansion bound lives. Every compiled * artifact is a tree, so a DAG's cost is the size of the tree it expands into — * `objectShape({ left: node, right: node })` nested thirty times is thirty-one * authored nodes and more than a billion emitted ones. The validator counts * that expansion and {@link refuseExpansion} refuses past * {@link COMPILE_NODE_LIMIT} with an `expansion`-coded {@link ContractError}, so * every standalone compiler and {@link createContract} answer a shared-child * declaration in bounded time instead of not answering. {@link cloneShape} / * {@link ownShape} are deliberately NOT bounded by it: they preserve * shared-child identity, so ownership of the same declaration stays * proportional to its authored nodes. * Every structural child slot must contain a shape node before it can enter the * walk; every scalar field must hold its declared runtime domain before a * compiler can use it; and a missing child, corrupt container, inherited * discriminant, or unrecognized node reports `structure`. This is the SOLE * eager well-formedness pass — there is no second prepass and no alias for it: * it enforces every bound domain and range used by the artifacts, including * non-empty literal/union vocabularies, finite literal numbers, integer-range * satisfiability, unflagged string patterns, optional-shape placement, and the * recursively supported raw-schema vocabulary where every present property or * dense union member is a record. * Active ancestors are tracked so shared children remain legal. Every * standalone compiler reaches this same validation once, over its owned * snapshot, through {@link ContractCompiler} preparation. * Failures have deterministic precedence independent of traversal order: depth, * then structure, then cycle, then field and vocabulary policy. * * @param shape - The shape graph to gate * @returns Nothing; successful return means recursive compilation is structurally safe, depth-safe, and bounded in emitted nodes * @throws {ContractError} When a node or structural slot is corrupt, a bound or vocabulary is outside its declared domain, the graph is cyclic, it exceeds the compilation depth limit, or it expands past the compilation node limit * * @example * ```ts * validateShapeDepth(stringShape({ min: 1 })) // returns; the declaration is compilable * ``` */ export declare function validateShapeDepth(shape: ContractShape): void; /** * Infer a `JSONSchema` for one unknown value — the reverse direction of * {@link compileSchema}. * * @remarks * Cycle/depth/breadth-bounded (see {@link inferValue} / {@link inferArray} / * {@link inferObject}). A failed traversal throws a `structure` * {@link ContractError}; it never becomes `{}` or another permissive schema. Nested * objects close to unknown keys (`additionalProperties: false`) by default; * pass `closed: false` to open them. `format` (default `false`) opts a * string/`Date` leaf into the `format` keyword. Structurally-equal inputs * infer byte-identical schemas (object keys and `anyOf` members are sorted). * * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string' * }` — is structurally accepted by `schemaToParameters`, but MCP clients * expect an object-shaped `inputSchema`; wrap a non-object payload with * {@link schemaToObject} before advertising it as a tool's parameters. * * `maxProperties` is sanitized via {@link sanitizeBudget} to a finite * non-negative integer, falling back to {@link INFER_BREADTH_LIMIT} for anything * else (`NaN`, `Infinity`, negative, fractional), so a malformed breadth cannot * corrupt the sampled key/element list. * * `maxDepth` goes through {@link sanitizeDepth}, which does the same and then caps * at {@link INFER_DEPTH_LIMIT}, so the option NARROWS the walk and cannot widen * it. The cap is what makes the depth guard unbreakable: depth is the recursing * axis, and a large-but-valid budget used to descend until the call STACK failed * rather than until the guard said stop. * * @param value - The value to infer a schema from * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds * @returns The inferred `JSONSchema` * @throws {ContractError} When the value or options cannot be read * * @example * ```ts * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] }) * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' }, * // tags: { type: 'array', items: { type: 'string' } } }, * // required: ['id', 'name', 'tags'], additionalProperties: false } * ``` */ export declare function valueToSchema(value: unknown, options?: ValueToSchemaOptions): JSONSchema; /** * Options for {@link valueToSchema} / {@link samplesToSchema}. * * @remarks * The reverse direction of {@link compileSchema}: instead of emitting a * `JSONSchema` from a developer-authored `ContractShape`, these bounds tame * inference from an unknown runtime value (or a set of example values), which * — unlike a shape tree — may be arbitrarily deep, wide, or cyclic. * * @remarks * `format` (default `false`) emits a `format` keyword on a string leaf whose * value(s) unanimously match one {@link SchemaFormat} via {@link stringToFormat} * / {@link samplesToFormat}. `enum` (default `false`, multi-sample paths only) * emits an `enum` keyword for a low-cardinality, repeated primitive slot * instead of a bare `type`. */ export declare interface ValueToSchemaOptions { readonly maxDepth?: number; readonly maxProperties?: number; readonly closed?: boolean; readonly format?: boolean; readonly enum?: boolean; } /** * Refine a base guard with an additional predicate that runs only when the base * passes. * * @remarks * The predicate receives a value already narrowed to `T`. When the predicate is * itself a type guard (`value is U`), the result narrows to `Guard` — it * passes only when the value is genuinely a `U`, so the narrowing is sound. Per * §14 the returned guard never throws: if `predicate` throws, the throw is * contained and the guard reports a non-match. * * @example * ```ts * const isPositive = whereOf(isNumber, (n) => n > 0) * isPositive(5) // true * isPositive(-1) // false * * // A narrowing predicate refines the result type to Guard<5> * const isFive = whereOf(isNumber, (n): n is 5 => n === 5) * ``` */ export declare function whereOf(base: Guard, predicate: (value: T) => value is U): Guard; export declare function whereOf(base: Guard, predicate: (value: T) => boolean): Guard; /** An async function accepting zero arguments and returning a `Promise`. */ export declare type ZeroArgAsyncFunction = () => Promise; /** A function accepting zero arguments and returning `unknown`. */ export declare type ZeroArgFunction = () => unknown; export { }