@orkestrel/contract 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -5
- package/dist/src/core/index.cjs +1870 -611
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +696 -143
- package/dist/src/core/index.d.ts +696 -143
- package/dist/src/core/index.js +1855 -611
- package/dist/src/core/index.js.map +1 -1
- package/package.json +14 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/combinators.ts","../../../src/core/parsers.ts","../../../src/core/compilers.ts","../../../src/core/inferers.ts","../../../src/core/shapers.ts"],"sourcesContent":["import type { JSONSchemaType } from './types.js'\n\n// JSON-related constants. Kept as plain frozen data so the shipped combinators\n// and parsers operate on them directly — there is deliberately no bespoke\n// JSON-Schema guard (AGENTS §14 — the deep recursive validators stay out by\n// design).\n\n/**\n * The seven standard JSON Schema `type` names, frozen.\n *\n * @remarks\n * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose\n * it with the shipped primitives instead of reaching for a bespoke guard:\n * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and\n * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`\n * is the parser.\n *\n * @example\n * ```ts\n * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'\n *\n * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>\n * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined\n * ```\n */\nexport const JSON_SCHEMA_TYPES: readonly JSONSchemaType[] = Object.freeze([\n\t'null',\n\t'boolean',\n\t'object',\n\t'array',\n\t'number',\n\t'integer',\n\t'string',\n])\n\n// Reporting-surface bounds (`compileReporter` / `ContractInterface.explain`).\n\n/**\n * The maximum number of {@link Fault} entries a single `explain` report ever\n * returns, frozen.\n *\n * @remarks\n * Bounds the report against adversarial input (a giant array, a wide record) —\n * `compileReporter` collects faults in stable pre-order and stops once this cap\n * is reached, so the report size (and the work to build it) stays finite and\n * deterministic regardless of the input's size.\n */\nexport const FAULT_LIMIT = 64\n\n/**\n * The maximum character length of a {@link preview}-rendered string, frozen.\n *\n * @remarks\n * A previewed string longer than this is clipped with a trailing `…` so a\n * {@link Fault}'s `received` field never embeds an unbounded amount of\n * untrusted text.\n */\nexport const PREVIEW_LIMIT = 64\n\n// Value-to-schema inference bounds (`valueToSchema` / `samplesToSchema`).\n\n/**\n * The default maximum object/array nesting depth {@link valueToSchema} walks,\n * frozen.\n *\n * @remarks\n * Bounds inference against adversarial or cyclic runtime input — once the\n * remaining depth budget reaches zero, inference stops descending and emits\n * the empty accept-anything schema `{}` for that branch instead of recursing\n * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.\n */\nexport const INFER_DEPTH_LIMIT = 32\n\n/**\n * The default maximum number of object properties / array elements\n * {@link valueToSchema} samples per container, frozen.\n *\n * @remarks\n * Bounds the work (and the emitted schema's size) against a wide record or a\n * huge array — properties/elements beyond this cap are never inspected.\n * Overridable per call via {@link ValueToSchemaOptions.maxProperties}.\n */\nexport const INFER_BREADTH_LIMIT = 256\n\n/**\n * The default maximum number of distinct values a multi-sample slot may hold\n * before enum inference gives up and falls back to a bare `type`, frozen.\n *\n * @remarks\n * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}\n * will emit — a slot with distinct-value count at or above this limit is\n * treated as unbounded (an ID column, not a category) and never gets an\n * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}\n * (which gates whether enum inference runs at all).\n */\nexport const INFER_ENUM_LIMIT = 12\n\n/**\n * The maximum string length {@link stringToFormat} attempts to classify,\n * frozen.\n *\n * @remarks\n * Bounds per-string format-detection work: a value longer than this returns\n * `undefined` immediately, before any pattern match runs. 128 sits\n * comfortably above the longest real format token — an RFC 3339 date-time\n * with fractional seconds and a UTC offset — so no legitimate classification\n * changes; only pathologically long strings (a multi-megabyte payload passed\n * as a candidate email/URI) are skipped.\n */\nexport const FORMAT_MAX_LENGTH = 128\n\n/**\n * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats\n * (`uuid` / `email` / `uri`), frozen as data.\n *\n * @remarks\n * The ISO-8601 date/time formats are NOT listed here — they additionally\n * require an attempt-guarded `Date` validity check, so their pattern lives\n * inline in `stringToFormat` rather than as reusable standalone data.\n */\nexport const FORMAT_PATTERNS: Readonly<Record<'uuid' | 'email' | 'uri', RegExp>> = Object.freeze({\n\tuuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n\temail: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n\turi: /^[a-z][a-z0-9+.-]*:\\/\\//i,\n})\n","import type {\n\tAnyAsyncFunction,\n\tAnyConstructor,\n\tAnyFunction,\n\tJSONPrimitive,\n\tJSONValue,\n\tZeroArgAsyncFunction,\n\tZeroArgFunction,\n} from './types.js'\nimport { attempt, enumerableSymbolCount } from './helpers.js'\n\n// AGENTS §14: guards are total functions — a guard NEVER throws. Adversarial\n// input (hostile getters, exotic objects, cycles) returns `false`, never an\n// error. Guards built from a single `typeof` / strict-equality test are\n// immediately total — no probe of the value's internals can throw. Every\n// OTHER guard here probes the value in some way — a property read through\n// `Reflect.get`, a structural walk (`isPromiseLike`, `isIterable`,\n// `isAsyncIterable`, `isJSONValue`, `isRecord`), an `instanceof` check (which\n// invokes the target's `[Symbol.hasInstance]` / triggers a `getPrototypeOf`\n// trap), or an own-key enumeration (`isEmptyObject` / `isNonEmptyObject`) —\n// so a hostile getter, a revoked `Proxy`, or an exotic trap can throw\n// mid-probe. Totality is NOT automatic for these: each contains its\n// probe/walk in `attempt` (see ./helpers.js) and returns `false` on a caught\n// throw. Every `instanceof`-based guard in this file routes through the\n// shared {@link isInstance} helper, which is the one place that containment\n// lives for that family.\n\n// === Primitive guards\n\n/** Determine whether a value is `null`.\n *\n * @example\n * ```ts\n * isNull(null) // true\n * isNull(undefined) // false\n * ```\n */\nexport function isNull(value: unknown): value is null {\n\treturn value === null\n}\n\n/** Determine whether a value is `undefined`.\n *\n * @example\n * ```ts\n * isUndefined(undefined) // true\n * isUndefined(null) // false\n * ```\n */\nexport function isUndefined(value: unknown): value is undefined {\n\treturn value === undefined\n}\n\n/** Determine whether a value is defined (neither `null` nor `undefined`).\n *\n * @example\n * ```ts\n * isDefined('hi') // true\n * isDefined(null) // false\n * isDefined(undefined) // false\n * ```\n */\nexport function isDefined<T>(value: T | null | undefined): value is T {\n\treturn value !== null && value !== undefined\n}\n\n/** Determine whether a value is a string.\n *\n * @example\n * ```ts\n * isString('hi') // true\n * isString(42) // false\n * ```\n */\nexport function isString(value: unknown): value is string {\n\treturn typeof value === 'string'\n}\n\n/**\n * Determine whether a value is a number.\n *\n * @remarks\n * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.\n *\n * @example\n * ```ts\n * isNumber(42) // true\n * isNumber(Number.NaN) // true — NaN is still a number\n * isNumber('42') // false\n * ```\n */\nexport function isNumber(value: unknown): value is number {\n\treturn typeof value === 'number'\n}\n\n/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).\n *\n * @example\n * ```ts\n * isFiniteNumber(42) // true\n * isFiniteNumber(Number.NaN) // false\n * isFiniteNumber(Infinity) // false\n * ```\n */\nexport function isFiniteNumber(value: unknown): value is number {\n\treturn typeof value === 'number' && Number.isFinite(value)\n}\n\n/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).\n *\n * @example\n * ```ts\n * isInteger(3) // true\n * isInteger(3.5) // false\n * ```\n */\nexport function isInteger(value: unknown): value is number {\n\treturn Number.isInteger(value)\n}\n\n/** Determine whether a value is a boolean.\n *\n * @example\n * ```ts\n * isBoolean(true) // true\n * isBoolean(1) // false\n * ```\n */\nexport function isBoolean(value: unknown): value is boolean {\n\treturn typeof value === 'boolean'\n}\n\n/** Determine whether a value is exactly `true`.\n *\n * @example\n * ```ts\n * isTrue(true) // true\n * isTrue(false) // false\n * ```\n */\nexport function isTrue(value: unknown): value is true {\n\treturn value === true\n}\n\n/** Determine whether a value is exactly `false`.\n *\n * @example\n * ```ts\n * isFalse(false) // true\n * isFalse(true) // false\n * ```\n */\nexport function isFalse(value: unknown): value is false {\n\treturn value === false\n}\n\n/** Determine whether a value is a bigint.\n *\n * @example\n * ```ts\n * isBigInt(1n) // true\n * isBigInt(1) // false\n * ```\n */\nexport function isBigInt(value: unknown): value is bigint {\n\treturn typeof value === 'bigint'\n}\n\n/** Determine whether a value is a symbol.\n *\n * @example\n * ```ts\n * isSymbol(Symbol('x')) // true\n * isSymbol('x') // false\n * ```\n */\nexport function isSymbol(value: unknown): value is symbol {\n\treturn typeof value === 'symbol'\n}\n\n/** Determine whether a value is callable.\n *\n * @example\n * ```ts\n * isFunction(() => {}) // true\n * isFunction({}) // false\n * ```\n */\nexport function isFunction(value: unknown): value is AnyFunction {\n\treturn typeof value === 'function'\n}\n\n/** Determine whether a value is a string or `null`.\n *\n * @example\n * ```ts\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function isNullableString(value: unknown): value is string | null {\n\treturn value === null || isString(value)\n}\n\n/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).\n *\n * @example\n * ```ts\n * isNullableNumber(42) // true\n * isNullableNumber(null) // true\n * isNullableNumber('hi') // false\n * ```\n */\nexport function isNullableNumber(value: unknown): value is number | null {\n\treturn value === null || isNumber(value)\n}\n\n/** Determine whether a value is a boolean or `null`.\n *\n * @example\n * ```ts\n * isNullableBoolean(true) // true\n * isNullableBoolean(null) // true\n * isNullableBoolean(1) // false\n * ```\n */\nexport function isNullableBoolean(value: unknown): value is boolean | null {\n\treturn value === null || isBoolean(value)\n}\n\n// === Built-in guards\n//\n// The `instanceof`-based guard families below (Date/RegExp/Error/Promise,\n// Map/Set/WeakMap/WeakSet, the typed-array guards) are same-realm checks:\n// `instanceof` compares against the constructor's prototype in the CURRENT\n// realm, so a value built by another realm (a different `vm.Context`, iframe,\n// or worker global) fails even when it is structurally identical. This is a\n// known, accepted limitation — cross-realm identity would require duck-typing\n// every built-in, which trades soundness for portability.\n\n/**\n * Determine whether a value is an instance of a constructor, contained against\n * a throwing `instanceof` check.\n *\n * @remarks\n * The low-level total helper every `instanceof`-based guard in this file (and\n * the `instanceOf` combinator) routes through. A bare `value instanceof X` is\n * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a\n * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when\n * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This\n * wraps the check in {@link attempt} (see ./helpers.js) so any such throw\n * yields `false` instead of escaping.\n *\n * @param value - The value to test\n * @param ctor - The constructor to test against\n * @returns `true` when `value instanceof ctor`, `false` on a non-match or a\n * contained throw\n *\n * @example\n * ```ts\n * isInstance(new Date(), Date) // true\n * isInstance({}, Date) // false\n * ```\n */\nexport function isInstance<C>(\n\tvalue: unknown,\n\tctor: C,\n): value is InstanceType<C & AnyConstructor<object>> {\n\t// `ctor` is narrowed to a function through `isFunction` before the `instanceof`\n\t// check — an unconstrained generic RHS loses TS's built-in instanceof leniency\n\t// once nested inside another generic call (the `attempt` callback), so the\n\t// narrowing keeps this call legal without a constraint that would reject\n\t// combinators.ts's `instanceOf`, which validates `ctor` separately.\n\tconst target: unknown = ctor\n\tconst outcome = attempt(() => isFunction(target) && value instanceof target)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a `Date`.\n *\n * @example\n * ```ts\n * isDate(new Date()) // true\n * isDate('2024-01-01') // false\n * ```\n */\nexport function isDate(value: unknown): value is Date {\n\treturn isInstance(value, Date)\n}\n\n/** Determine whether a value is a `RegExp`.\n *\n * @example\n * ```ts\n * isRegExp(/a/) // true\n * isRegExp('a') // false\n * ```\n */\nexport function isRegExp(value: unknown): value is RegExp {\n\treturn isInstance(value, RegExp)\n}\n\n/** Determine whether a value is an `Error`.\n *\n * @example\n * ```ts\n * isError(new Error('boom')) // true\n * isError('boom') // false\n * ```\n */\nexport function isError(value: unknown): value is Error {\n\treturn isInstance(value, Error)\n}\n\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve()) // true\n * isPromise({ then() {} }) // false\n * ```\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n\treturn isInstance(value, Promise)\n}\n\n/**\n * Determine whether a value is promise-like — an object exposing callable\n * `then`, `catch`, and `finally` methods.\n *\n * @remarks\n * Accepts any object with all three methods, not only native `Promise`\n * instances. Use {@link isPromise} when you specifically need `instanceof Promise`.\n *\n * @example\n * ```ts\n * isPromiseLike(Promise.resolve()) // true\n * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true\n * isPromiseLike({ then() {} }) // false\n * ```\n */\nexport function isPromiseLike<T = unknown>(\n\tvalue: unknown,\n): value is Promise<T> | (PromiseLike<T> & { catch: unknown; finally: unknown }) {\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => {\n\t\tconst thenValue = Reflect.get(value, 'then')\n\t\tconst catchValue = Reflect.get(value, 'catch')\n\t\tconst finallyValue = Reflect.get(value, 'finally')\n\t\treturn isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue)\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is an `ArrayBuffer`.\n *\n * @example\n * ```ts\n * isArrayBuffer(new ArrayBuffer(8)) // true\n * isArrayBuffer([]) // false\n * ```\n */\nexport function isArrayBuffer(value: unknown): value is ArrayBuffer {\n\treturn isInstance(value, ArrayBuffer)\n}\n\n/**\n * Determine whether a value is a `SharedArrayBuffer`.\n *\n * @remarks\n * Guards the global existence of `SharedArrayBuffer` first — safe where it is\n * absent or disabled (e.g. a context that is not cross-origin isolated).\n *\n * @example\n * ```ts\n * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true\n * isSharedArrayBuffer(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n\treturn typeof SharedArrayBuffer !== 'undefined' && isInstance(value, SharedArrayBuffer)\n}\n\n// === Protocol guards\n\n/**\n * Determine whether a value implements the iterable protocol (`Symbol.iterator`).\n *\n * @remarks\n * Strings are explicitly included: a string has a callable `Symbol.iterator`\n * but is not an object, so the generic object path alone would miss it.\n *\n * @example\n * ```ts\n * isIterable([1, 2]) // true\n * isIterable('abc') // true\n * isIterable({ a: 1 }) // false\n * ```\n */\nexport function isIterable<T = unknown>(value: unknown): value is Iterable<T> {\n\tif (isString(value)) {\n\t\treturn true\n\t}\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)))\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).\n *\n * @example\n * ```ts\n * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true\n * isAsyncIterable([1, 2]) // false\n * ```\n */\nexport function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T> {\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)))\n\treturn outcome.success && outcome.value\n}\n\n// === Object & collection guards\n\n/**\n * Determine whether a value is a non-null object.\n *\n * @remarks\n * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use\n * {@link isRecord} when you need a plain-record check.\n *\n * @example\n * ```ts\n * isObject({}) // true\n * isObject([]) // true\n * isObject(null) // false\n * ```\n */\nexport function isObject(value: unknown): value is object {\n\treturn typeof value === 'object' && value !== null\n}\n\n/**\n * Determine whether a value is a plain record (object literal or null-prototype),\n * not an array or class instance.\n *\n * @remarks\n * Use instead of {@link isObject} to distinguish a plain `{}` /\n * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain\n * test is realm-agnostic: rather than comparing against the current realm's\n * `Object.prototype` (which a plain object from another `vm.Context`, iframe,\n * or worker would fail), it accepts any value whose prototype is `null`, OR\n * whose prototype's own prototype is `null` — the shape every plain object\n * has in every realm, since `Object.prototype` itself always sits one step\n * above `null`. Arrays and class instances are still rejected: an array's\n * prototype chain runs through `Array.prototype` before `null`, and a class\n * instance's runs through the class's own prototype. The whole body runs\n * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile\n * `getPrototypeOf` trap cannot escape as a thrown error.\n *\n * @example\n * ```ts\n * isRecord({ a: 1 }) // true\n * isRecord(Object.create(null)) // true\n * isRecord([]) // false\n * isRecord(new Date()) // false\n * ```\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\tconst outcome = attempt(() => {\n\t\tif (!isObject(value) || isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\treturn prototype === null || Object.getPrototypeOf(prototype) === null\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a `Map`.\n *\n * @example\n * ```ts\n * isMap(new Map()) // true\n * isMap({}) // false\n * ```\n */\nexport function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V> {\n\treturn isInstance(value, Map)\n}\n\n/** Determine whether a value is a `Set`.\n *\n * @example\n * ```ts\n * isSet(new Set()) // true\n * isSet([]) // false\n * ```\n */\nexport function isSet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isInstance(value, Set)\n}\n\n/** Determine whether a value is a `WeakMap`.\n *\n * @example\n * ```ts\n * isWeakMap(new WeakMap()) // true\n * isWeakMap({}) // false\n * ```\n */\nexport function isWeakMap(value: unknown): value is WeakMap<object, unknown> {\n\treturn isInstance(value, WeakMap)\n}\n\n/** Determine whether a value is a `WeakSet`.\n *\n * @example\n * ```ts\n * isWeakSet(new WeakSet()) // true\n * isWeakSet({}) // false\n * ```\n */\nexport function isWeakSet(value: unknown): value is WeakSet<object> {\n\treturn isInstance(value, WeakSet)\n}\n\n// === Array & typed-array guards\n\n/** Determine whether a value is an array.\n *\n * @example\n * ```ts\n * isArray([1, 2]) // true\n * isArray('12') // false\n * ```\n */\nexport function isArray<T = unknown>(value: unknown): value is readonly T[] {\n\treturn Array.isArray(value)\n}\n\n/** Determine whether a value is a `DataView`.\n *\n * @example\n * ```ts\n * isDataView(new DataView(new ArrayBuffer(8))) // true\n * isDataView(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isDataView(value: unknown): value is DataView<ArrayBufferLike> {\n\treturn isInstance(value, DataView)\n}\n\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).\n *\n * @example\n * ```ts\n * isArrayBufferView(new Uint8Array(4)) // true\n * isArrayBufferView([1, 2, 3, 4]) // false\n * ```\n */\nexport function isArrayBufferView(value: unknown): value is ArrayBufferView {\n\treturn ArrayBuffer.isView(value)\n}\n\n/** Determine whether a value is an `Int8Array`.\n *\n * @example\n * ```ts\n * isInt8Array(new Int8Array(2)) // true\n * isInt8Array(new Uint8Array(2)) // false\n * ```\n */\nexport function isInt8Array(value: unknown): value is Int8Array {\n\treturn isInstance(value, Int8Array)\n}\n\n/** Determine whether a value is a `Uint8Array`.\n *\n * @example\n * ```ts\n * isUint8Array(new Uint8Array(2)) // true\n * isUint8Array(new Int8Array(2)) // false\n * ```\n */\nexport function isUint8Array(value: unknown): value is Uint8Array {\n\treturn isInstance(value, Uint8Array)\n}\n\n/** Determine whether a value is a `Uint8ClampedArray`.\n *\n * @example\n * ```ts\n * isUint8ClampedArray(new Uint8ClampedArray(2)) // true\n * isUint8ClampedArray(new Uint8Array(2)) // false\n * ```\n */\nexport function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray {\n\treturn isInstance(value, Uint8ClampedArray)\n}\n\n/** Determine whether a value is an `Int16Array`.\n *\n * @example\n * ```ts\n * isInt16Array(new Int16Array(2)) // true\n * isInt16Array(new Int8Array(2)) // false\n * ```\n */\nexport function isInt16Array(value: unknown): value is Int16Array {\n\treturn isInstance(value, Int16Array)\n}\n\n/** Determine whether a value is a `Uint16Array`.\n *\n * @example\n * ```ts\n * isUint16Array(new Uint16Array(2)) // true\n * isUint16Array(new Int16Array(2)) // false\n * ```\n */\nexport function isUint16Array(value: unknown): value is Uint16Array {\n\treturn isInstance(value, Uint16Array)\n}\n\n/** Determine whether a value is an `Int32Array`.\n *\n * @example\n * ```ts\n * isInt32Array(new Int32Array(2)) // true\n * isInt32Array(new Int16Array(2)) // false\n * ```\n */\nexport function isInt32Array(value: unknown): value is Int32Array {\n\treturn isInstance(value, Int32Array)\n}\n\n/** Determine whether a value is a `Uint32Array`.\n *\n * @example\n * ```ts\n * isUint32Array(new Uint32Array(2)) // true\n * isUint32Array(new Int32Array(2)) // false\n * ```\n */\nexport function isUint32Array(value: unknown): value is Uint32Array {\n\treturn isInstance(value, Uint32Array)\n}\n\n/** Determine whether a value is a `Float32Array`.\n *\n * @example\n * ```ts\n * isFloat32Array(new Float32Array(2)) // true\n * isFloat32Array(new Float64Array(2)) // false\n * ```\n */\nexport function isFloat32Array(value: unknown): value is Float32Array {\n\treturn isInstance(value, Float32Array)\n}\n\n/** Determine whether a value is a `Float64Array`.\n *\n * @example\n * ```ts\n * isFloat64Array(new Float64Array(2)) // true\n * isFloat64Array(new Float32Array(2)) // false\n * ```\n */\nexport function isFloat64Array(value: unknown): value is Float64Array {\n\treturn isInstance(value, Float64Array)\n}\n\n/**\n * Determine whether a value is a `BigInt64Array`.\n *\n * @remarks\n * Guards the global existence of `BigInt64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigInt64Array(new BigInt64Array(2)) // true\n * isBigInt64Array(new Float64Array(2)) // false\n * ```\n */\nexport function isBigInt64Array(value: unknown): value is BigInt64Array {\n\treturn typeof BigInt64Array !== 'undefined' && isInstance(value, BigInt64Array)\n}\n\n/**\n * Determine whether a value is a `BigUint64Array`.\n *\n * @remarks\n * Guards the global existence of `BigUint64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigUint64Array(new BigUint64Array(2)) // true\n * isBigUint64Array(new BigInt64Array(2)) // false\n * ```\n */\nexport function isBigUint64Array(value: unknown): value is BigUint64Array {\n\treturn typeof BigUint64Array !== 'undefined' && isInstance(value, BigUint64Array)\n}\n\n// === Emptiness guards\n\n/** Determine whether a value is the empty string `''`.\n *\n * @example\n * ```ts\n * isEmptyString('') // true\n * isEmptyString('a') // false\n * ```\n */\nexport function isEmptyString(value: unknown): value is '' {\n\treturn isString(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty array.\n *\n * @example\n * ```ts\n * isEmptyArray([]) // true\n * isEmptyArray([1]) // false\n * ```\n */\nexport function isEmptyArray(value: unknown): value is readonly [] {\n\treturn isArray(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).\n *\n * @example\n * ```ts\n * isEmptyObject({}) // true\n * isEmptyObject({ a: 1 }) // false\n * ```\n */\nexport function isEmptyObject(value: unknown): value is Record<string | symbol, never> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\t// Object.keys / getOwnPropertySymbols read the object's own-key list, which\n\t// an `ownKeys` Proxy trap can throw from — contained via `attempt` (AGENTS §14).\n\tconst outcome = attempt(\n\t\t() => Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0,\n\t)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is an empty `Map`.\n *\n * @example\n * ```ts\n * isEmptyMap(new Map()) // true\n * isEmptyMap(new Map([['a', 1]])) // false\n * ```\n */\nexport function isEmptyMap(value: unknown): value is ReadonlyMap<never, never> {\n\treturn isMap(value) && value.size === 0\n}\n\n/** Determine whether a value is an empty `Set`.\n *\n * @example\n * ```ts\n * isEmptySet(new Set()) // true\n * isEmptySet(new Set([1])) // false\n * ```\n */\nexport function isEmptySet(value: unknown): value is ReadonlySet<never> {\n\treturn isSet(value) && value.size === 0\n}\n\n/** Determine whether a value is a non-empty string (at least one character).\n *\n * @example\n * ```ts\n * isNonEmptyString('a') // true\n * isNonEmptyString('') // false\n * ```\n */\nexport function isNonEmptyString(value: unknown): value is string {\n\treturn isString(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty array (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptyArray([1]) // true\n * isNonEmptyArray([]) // false\n * ```\n */\nexport function isNonEmptyArray<T = unknown>(value: unknown): value is readonly [T, ...T[]] {\n\treturn isArray(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).\n *\n * @example\n * ```ts\n * isNonEmptyObject({ a: 1 }) // true\n * isNonEmptyObject({}) // false\n * ```\n */\nexport function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\t// Same containment as isEmptyObject — an `ownKeys` Proxy trap can throw.\n\tconst outcome = attempt(() => Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a non-empty `Map` (at least one entry).\n *\n * @example\n * ```ts\n * isNonEmptyMap(new Map([['a', 1]])) // true\n * isNonEmptyMap(new Map()) // false\n * ```\n */\nexport function isNonEmptyMap<K = unknown, V = unknown>(\n\tvalue: unknown,\n): value is ReadonlyMap<K, V> {\n\treturn isMap(value) && value.size > 0\n}\n\n/** Determine whether a value is a non-empty `Set` (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptySet(new Set([1])) // true\n * isNonEmptySet(new Set()) // false\n * ```\n */\nexport function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isSet(value) && value.size > 0\n}\n\n// === Function guards\n\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).\n *\n * @example\n * ```ts\n * isZeroArg(() => {}) // true\n * isZeroArg((a) => a) // false\n * ```\n */\nexport function isZeroArg(value: unknown): value is ZeroArgFunction {\n\treturn isFunction(value) && value.length === 0\n}\n\n/**\n * Determine whether a value is a native `async function`.\n *\n * @remarks\n * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is\n * unreliable across realms. The `?.` keeps the guard total (§14): a function\n * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.\n *\n * @example\n * ```ts\n * isAsyncFunction(async () => {}) // true\n * isAsyncFunction(() => {}) // false\n * ```\n */\nexport function isAsyncFunction(value: unknown): value is AnyAsyncFunction {\n\treturn isFunction(value) && value.constructor?.name === 'AsyncFunction'\n}\n\n/** Determine whether a value is a generator function (`function*`).\n *\n * @example\n * ```ts\n * isGeneratorFunction(function* () {}) // true\n * isGeneratorFunction(() => {}) // false\n * ```\n */\nexport function isGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => Generator<unknown, unknown, unknown> {\n\treturn isFunction(value) && value.constructor?.name === 'GeneratorFunction'\n}\n\n/** Determine whether a value is an async generator function (`async function*`).\n *\n * @example\n * ```ts\n * isAsyncGeneratorFunction(async function* () {}) // true\n * isAsyncGeneratorFunction(function* () {}) // false\n * ```\n */\nexport function isAsyncGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isFunction(value) && value.constructor?.name === 'AsyncGeneratorFunction'\n}\n\n/** Determine whether a value is a zero-argument async function.\n *\n * @example\n * ```ts\n * isZeroArgAsync(async () => {}) // true\n * isZeroArgAsync(async (a) => a) // false\n * ```\n */\nexport function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction {\n\treturn isZeroArg(value) && isAsyncFunction(value)\n}\n\n/** Determine whether a value is a zero-argument generator function.\n *\n * @example\n * ```ts\n * isZeroArgGenerator(function* () {}) // true\n * isZeroArgGenerator(function* (a) {}) // false\n * ```\n */\nexport function isZeroArgGenerator(\n\tvalue: unknown,\n): value is () => Generator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isGeneratorFunction(value)\n}\n\n/** Determine whether a value is a zero-argument async generator function.\n *\n * @example\n * ```ts\n * isZeroArgAsyncGenerator(async function* () {}) // true\n * isZeroArgAsyncGenerator(async function* (a) {}) // false\n * ```\n */\nexport function isZeroArgAsyncGenerator(\n\tvalue: unknown,\n): value is () => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isAsyncGeneratorFunction(value)\n}\n\n/**\n * Determine whether a value can be used as a `new`-target constructor.\n *\n * @remarks\n * Probes with `Reflect.construct(String, [], value)`: a real constructor\n * succeeds, while arrow functions, plain functions, and non-functions throw\n * and yield `false`. Never throws. Backs the `instanceOf` combinator.\n *\n * @example\n * ```ts\n * isConstructor(class X {}) // true\n * isConstructor(() => {}) // false\n * ```\n */\nexport function isConstructor(value: unknown): value is AnyConstructor<object> {\n\tif (!isFunction(value)) {\n\t\treturn false\n\t}\n\ttry {\n\t\tReflect.construct(String, [], value)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n// === JSON\n\n/**\n * Determine whether a value is a cycle-safe JSON value.\n *\n * @remarks\n * Total guard: never throws, returns `false` for cycles, functions, `Date`\n * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records\n * are walked with an ancestor set so recursive input fails instead of hanging.\n * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a\n * record property, or a revoked `Proxy` anywhere in the structure, is caught\n * and yields `false` instead of escaping as a thrown error.\n *\n * @param value - The value to test\n * @returns `true` when the value has a JSON representation\n *\n * @example\n * ```ts\n * isJSONValue({ nested: [1, 'x', null] }) // true\n * isJSONValue(Number.NaN) // false\n * ```\n */\nexport function isJSONValue(value: unknown): value is JSONValue {\n\tconst ancestors = new WeakSet<object>()\n\tconst check = (entry: unknown): entry is JSONValue => {\n\t\tif (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (ancestors.has(entry)) return false\n\t\t\tancestors.add(entry)\n\t\t\tconst valid = entry.every(check)\n\t\t\tancestors.delete(entry)\n\t\t\treturn valid\n\t\t}\n\t\tif (!isRecord(entry)) return false\n\t\tif (ancestors.has(entry)) return false\n\t\tancestors.add(entry)\n\t\tconst valid = Object.values(entry).every(check)\n\t\tancestors.delete(entry)\n\t\treturn valid\n\t}\n\tconst outcome = attempt(() => check(value))\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Determine whether a value is a primitive JSON value.\n *\n * @remarks\n * The flat leaf of any JSON document: `null`, a string, a **finite** number, or\n * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON\n * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.\n *\n * The recursive {@link isJSONValue} guard is shipped and stays total with\n * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and\n * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with\n * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.\n *\n * @param value - The value to test\n * @returns `true` when `value` is `null`, a string, a finite number, or a boolean\n *\n * @example\n * ```ts\n * isJSONPrimitive(null) // true\n * isJSONPrimitive('hi') // true\n * isJSONPrimitive(42) // true\n * isJSONPrimitive(Number.NaN) // false — not representable in JSON\n * isJSONPrimitive({}) // false\n * ```\n */\nexport function isJSONPrimitive(value: unknown): value is JSONPrimitive {\n\treturn isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value)\n}\n","import type {\n\tContractShape,\n\tFaultKind,\n\tFieldPath,\n\tJSONSchema,\n\tRandomFunction,\n\tResult,\n} from './types.js'\nimport { PREVIEW_LIMIT } from './constants.js'\nimport {\n\tisBigInt,\n\tisBoolean,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisString,\n\tisSymbol,\n} from './validators.js'\n\n// === Result helpers\n\n/**\n * Invoke a callback and capture its outcome as a {@link Result}, never letting\n * a throw escape.\n *\n * @remarks\n * The single sanctioned never-throw boundary for the guards (AGENTS §14). The\n * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied\n * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a\n * `boolean`. This converts a throwing callback into a `Failure` so the\n * surrounding guard can treat it as a non-match instead of propagating the\n * exception, written once and shared rather than copy-pasted as ad-hoc\n * `try`/`catch`.\n *\n * @param callback - The callback to invoke with no arguments\n * @returns A `Success` carrying the return value, or a `Failure` carrying the\n * thrown reason normalised to an `Error`\n *\n * @example\n * ```ts\n * const outcome = attempt(() => predicate(value))\n * return outcome.success && outcome.value\n * ```\n */\nexport function attempt<T>(callback: () => T): Result<T> {\n\ttry {\n\t\treturn { success: true, value: callback() }\n\t} catch (reason) {\n\t\tif (reason instanceof Error) {\n\t\t\treturn { success: false, error: reason }\n\t\t}\n\t\t// A thrown non-Error value's own `toString` may itself throw (a hostile\n\t\t// object) — contain that conversion too so normalization never escapes.\n\t\tlet message = 'Unknown thrown value'\n\t\ttry {\n\t\t\tmessage = String(reason)\n\t\t} catch {\n\t\t\t// keep the fallback message\n\t\t}\n\t\treturn { success: false, error: new Error(message) }\n\t}\n}\n\n// === Record-field access\n\n/**\n * Resolve a (possibly nested) field value from a record by a key or key path.\n *\n * @remarks\n * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a\n * string array descends left-to-right through nested objects. Intermediates may\n * be any object — records, class instances, or arrays indexed by string. Returns\n * `undefined` the moment a segment is missing or lands on a non-object, so the\n * lookup is total — even against a hostile getter or Proxy trap that throws on\n * read, contained via {@link attempt} so the throw never escapes.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The resolved value, or `undefined`\n *\n * @example\n * ```ts\n * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'\n * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)\n * resolveField({ a: 1 }, ['a', 'b']) // undefined\n * ```\n */\nexport function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown {\n\tconst keys = isString(path) ? [path] : path\n\tlet current: unknown = record\n\tfor (const key of keys) {\n\t\tif (!isObject(current)) return undefined\n\t\tconst container = current\n\t\tconst outcome = attempt(() => Reflect.get(container, key))\n\t\tif (!outcome.success) return undefined\n\t\tcurrent = outcome.value\n\t}\n\treturn current\n}\n\n// === Random\n\n/**\n * Build a deterministic pseudo-random source seeded from a single number.\n *\n * @remarks\n * A mulberry32 generator — the same seed always yields the same sequence, so\n * generated seed data is reproducible across runs. Used as the default random\n * source for {@link compileGenerator}, seeded from the wall clock so casual\n * callers still get varied output without passing a source themselves.\n *\n * @param seed - The seed for the sequence\n * @returns A {@link RandomFunction} returning values in `[0, 1)`\n *\n * @example\n * ```ts\n * const random = seededRandom(42)\n * random() // always the same first value for seed 42\n * ```\n */\nexport function seededRandom(seed: number): RandomFunction {\n\tlet state = seed >>> 0\n\treturn () => {\n\t\tstate = (state + 0x6d2b79f5) >>> 0\n\t\tlet t = state\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1)\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296\n\t}\n}\n\n/**\n * Count the enumerable own-symbol keys on a value.\n *\n * @remarks\n * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose\n * descriptor is `enumerable` are counted. Backs the object-emptiness guards\n * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an\n * enumerable symbol is not mistaken for empty.\n *\n * @param value - The object to inspect\n * @returns The number of enumerable own-symbol keys\n *\n * @example\n * ```ts\n * const flag = Symbol('flag')\n * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1\n * enumerableSymbolCount({}) // 0\n * ```\n */\nexport function enumerableSymbolCount(value: object): number {\n\tlet count = 0\n\tfor (const symbol of Object.getOwnPropertySymbols(value)) {\n\t\tif (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) {\n\t\t\tcount += 1\n\t\t}\n\t}\n\treturn count\n}\n\n/**\n * Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape\n * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never\n * an assertion (AGENTS §14).\n *\n * @remarks\n * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a\n * tool advertises its `parameters` as an open record. The two are structurally compatible but not\n * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema\n * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's\n * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open\n * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.\n *\n * @param schema - The compiled JSON Schema (a contract's `schema`)\n * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record\n *\n * @example\n * ```ts\n * import { createContract, schemaToParameters } from '@src/core'\n *\n * const contract = createContract(shape)\n * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises\n * ```\n */\nexport function schemaToParameters(\n\tschema: JSONSchema,\n): Readonly<Record<string, unknown>> | undefined {\n\treturn isRecord(schema) ? schema : undefined\n}\n\n/**\n * Wrap a non-object `JSONSchema` root in a single-property object schema, so\n * an inferred primitive/array/union schema can flow into {@link schemaToParameters}\n * as an MCP-compatible `inputSchema`.\n *\n * @remarks\n * Total and deterministic. `schema.type === 'object'` passes through\n * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only\n * schema with no `type`, or the empty `{}`) is wrapped as a single required\n * `value` property: `{ type: 'object', properties: { value: schema },\n * required: ['value'], additionalProperties: false }`. Composition:\n * `schemaToParameters(schemaToObject(valueToSchema(payload)))`.\n *\n * @param schema - The schema to wrap\n * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema\n *\n * @example\n * ```ts\n * schemaToObject({ type: 'string' })\n * // { type: 'object', properties: { value: { type: 'string' } },\n * // required: ['value'], additionalProperties: false }\n * schemaToObject({ type: 'object', properties: {} }) // unchanged\n * ```\n */\nexport function schemaToObject(schema: JSONSchema): JSONSchema {\n\tif (schema.type === 'object') return schema\n\treturn {\n\t\ttype: 'object',\n\t\tproperties: { value: schema },\n\t\trequired: ['value'],\n\t\tadditionalProperties: false,\n\t}\n}\n\n// === Inference option sanitization\n\n/**\n * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to\n * a finite non-negative integer, falling back to a default for anything else.\n *\n * @remarks\n * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or\n * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard\n * (`NaN <= 0` is `false`, so recursion never halts), and a negative\n * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key\n * instead of capping the list (a fractional value has a similarly undefined\n * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`\n * is `false` — since an unbounded budget is exactly the adversarial case the\n * caps exist to prevent. A valid finite non-negative integer passes through\n * unchanged.\n *\n * @param value - The candidate budget value\n * @param fallback - The default to use when `value` is not a finite\n * non-negative integer\n * @returns A finite non-negative integer budget\n *\n * @example\n * ```ts\n * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT\n * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT\n * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4\n * ```\n */\nexport function sanitizeBudget(value: number | undefined, fallback: number): number {\n\treturn typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : fallback\n}\n\n// === Reporting\n\n/**\n * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s\n * `received` field.\n *\n * @remarks\n * A primitive renders as its literal: a string is `JSON.stringify`-escaped and\n * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when\n * clipped); a number / boolean / bigint / symbol renders via `String`; `null`\n * and `undefined` render as their own name. Everything else — a plain object,\n * an array, a function, a class instance, a `Map` — is NEVER traversed or\n * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),\n * so a hostile or enormous structure can never blow up the preview.\n *\n * @param value - The value to preview\n * @returns A short descriptive string, always safe to embed in a diagnostic\n *\n * @example\n * ```ts\n * preview('hi') // '\"hi\"'\n * preview(42) // '42'\n * preview(null) // 'null'\n * preview({ a: 1 }) // 'object'\n * preview([1, 2, 3]) // 'object'\n * ```\n */\nexport function preview(value: unknown): string {\n\tif (value === null) return 'null'\n\tif (value === undefined) return 'undefined'\n\tif (isString(value)) {\n\t\tconst text = JSON.stringify(value)\n\t\treturn text.length > PREVIEW_LIMIT ? `${text.slice(0, PREVIEW_LIMIT)}…` : text\n\t}\n\tif (isNumber(value) || isBoolean(value)) return String(value)\n\tif (isBigInt(value)) return `${value}n`\n\tif (isSymbol(value)) return value.toString()\n\treturn typeof value\n}\n\n/**\n * Project a {@link ContractShape} to the {@link FaultKind} it describes.\n *\n * @remarks\n * A structural mapping used by {@link compileReporter} to fill a `Fault`'s\n * `expected` field: most shapes map to their own `type` (`numberShape` maps to\n * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /\n * `nullableShape` project through to their inner shape's kind, and `rawShape`\n * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.\n *\n * @param shape - The shape to project\n * @returns The shape's {@link FaultKind}\n *\n * @example\n * ```ts\n * shapeToKind(stringShape()) // 'string'\n * shapeToKind(integerShape()) // 'integer'\n * shapeToKind(optionalShape(nullShape())) // 'null'\n * ```\n */\nexport function shapeToKind(shape: ContractShape): FaultKind {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn shape.integer === true ? 'integer' : 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'null':\n\t\t\treturn 'null'\n\t\tcase 'literal':\n\t\t\treturn 'literal'\n\t\tcase 'array':\n\t\t\treturn 'array'\n\t\tcase 'object':\n\t\t\treturn 'object'\n\t\tcase 'union':\n\t\t\treturn 'union'\n\t\tcase 'json':\n\t\t\treturn 'json'\n\t\tcase 'optional':\n\t\t\treturn shapeToKind(shape.inner)\n\t\tcase 'nullable':\n\t\t\treturn shapeToKind(shape.inner)\n\t\tcase 'raw':\n\t\t\treturn 'json'\n\t}\n}\n","import type {\n\tFromGuards,\n\tGuard,\n\tGuardsShape,\n\tGuardType,\n\tIntersectionFromGuards,\n\tOptionalFromGuards,\n\tTupleFromGuards,\n} from './types.js'\nimport {\n\tisArray,\n\tisConstructor,\n\tisFiniteNumber,\n\tisInstance,\n\tisIterable,\n\tisMap,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisSet,\n\tisString,\n\tisSymbol,\n} from './validators.js'\nimport { attempt } from './helpers.js'\n\n// Every combinator returns a `Guard<T>` — a total function (AGENTS §14). The\n// three combinators that invoke a caller-supplied callback inside the guard\n// body (`whereOf`, `lazyOf`, `transformOf`) contain any throw via `attempt`, so\n// the produced guard reports a non-match instead of propagating. The container\n// combinators (`arrayOf`, `tupleOf`, `setOf`, `mapOf`, `iterableOf`, `recordOf`)\n// likewise wrap their element/entry/key-read walk in `attempt` after the cheap\n// structural check — a hostile Proxy trap, a throwing getter, a throwing\n// iterator, or a throwing caller-supplied predicate yields a non-match, never a\n// propagated throw.\n\n/**\n * Build a guard that accepts arrays whose every element satisfies `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringArray = arrayOf(isString)\n * isStringArray(['a', 'b']) // true\n * isStringArray(['a', 1]) // false\n * ```\n */\nexport function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] => {\n\t\tif (!isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => value.every(elementGuard))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts fixed-arity tuples, testing each index with the\n * corresponding guard.\n *\n * @example\n * ```ts\n * const isPair = tupleOf(isString, isNumber)\n * isPair(['hello', 42]) // true\n * isPair(['hello']) // false — wrong arity\n * ```\n */\nexport function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<TupleFromGuards<Gs>>\nexport function tupleOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]>\nexport function tupleOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] => {\n\t\tif (!isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// Arity comparison reads `.length`, which — like the element reads below —\n\t\t// can hit a hostile Proxy trap, so it stays inside the contained region too.\n\t\tconst outcome = attempt(() => {\n\t\t\tif (value.length !== guards.length) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let index = 0; index < guards.length; index += 1) {\n\t\t\t\tconst guard = guards[index]\n\t\t\t\tif (!guard?.(value[index])) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts values identical (via `Object.is`) to one of the\n * provided literal primitives.\n *\n * @example\n * ```ts\n * const isRole = literalOf('admin', 'member', 'guest')\n * isRole('admin') // true\n * isRole('owner') // false\n * ```\n */\nexport function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(\n\t...literals: Literals\n): Guard<Literals[number]> {\n\treturn (value: unknown): value is Literals[number] =>\n\t\tliterals.some((literal) => Object.is(literal, value))\n}\n\n/**\n * Build a guard that accepts instances of the provided constructor.\n *\n * @remarks\n * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,\n * so passing an arrow function does not silently produce a broken guard.\n *\n * @example\n * ```ts\n * const isDateValue = instanceOf(Date)\n * isDateValue(new Date()) // true\n * isDateValue({}) // false\n * ```\n */\nexport function instanceOf<C extends abstract new (...args: never) => object>(\n\tctor: C,\n): Guard<InstanceType<C>> {\n\treturn (value: unknown): value is InstanceType<C> =>\n\t\tisConstructor(ctor) && isObject(value) && isInstance(value, ctor)\n}\n\n/**\n * Build a guard from a native `enum` or any object whose values are strings or\n * numbers.\n *\n * @example\n * ```ts\n * enum Direction { Up = 'up', Down = 'down' }\n * const isDirection = enumOf(Direction)\n * isDirection('up') // true\n * isDirection('left') // false\n * ```\n */\nexport function enumOf<const E extends Record<string, string | number>>(\n\tenumeration: E,\n): Guard<E[keyof E]> {\n\tconst values = new Set(Object.values(enumeration))\n\treturn (value: unknown): value is E[keyof E] =>\n\t\t(isString(value) || isNumber(value)) && values.has(value)\n}\n\n/**\n * Build a guard that accepts `Set` instances whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringSet = setOf(isString)\n * isStringSet(new Set(['a', 'b'])) // true\n * isStringSet(new Set(['a', 1])) // false\n * ```\n */\nexport function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>> {\n\treturn (value: unknown): value is ReadonlySet<unknown> => {\n\t\tif (!isSet(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts `Map` instances where every key satisfies\n * `keyGuard` and every value satisfies `valueGuard`.\n *\n * @example\n * ```ts\n * const isStringNumberMap = mapOf(isString, isNumber)\n * isStringNumberMap(new Map([['a', 1]])) // true\n * isStringNumberMap(new Map([[1, 'a']])) // false\n * ```\n */\nexport function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<ReadonlyMap<K, V>>\nexport function mapOf(\n\tkeyPredicate: (value: unknown) => boolean,\n\tvaluePredicate: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>>\nexport function mapOf(\n\tkeyGuard: (value: unknown) => boolean,\n\tvalueGuard: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>> {\n\treturn (value: unknown): value is ReadonlyMap<unknown, unknown> => {\n\t\tif (!isMap(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const [key, entryValue] of value) {\n\t\t\t\tif (!keyGuard(key) || !valueGuard(entryValue)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\nexport function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>\nexport function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\toptional: K,\n): Guard<OptionalFromGuards<S, K>>\nexport function recordOf<S extends GuardsShape>(\n\tshape: S,\n\toptional: true,\n): Guard<Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>>\n\n/**\n * Build a guard that accepts plain records matching a guard shape.\n *\n * @remarks\n * Three calling modes depending on the `optional` argument:\n * - **No `optional`** — all shape keys required; extra keys rejected.\n * - **`optional: K[]`** — the listed keys are optional; all others required.\n * - **`optional: true`** — every shape key is optional.\n *\n * Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by\n * an inherited prototype member (`toString`, `constructor`, …) counts as absent.\n * A non-object / `null` / array input returns `false` rather than throwing. The\n * extra-key check only inspects `Object.keys` (string keys), so an extra\n * enumerable SYMBOL key is never rejected — intentional, for JSON fidelity, and\n * matches the compiled guard.\n *\n * @example\n * ```ts\n * const isUser = recordOf({ name: isString, age: isNumber })\n * isUser({ name: 'Ada', age: 36 }) // true\n * isUser({ name: 'Ada' }) // false — age missing\n *\n * const isPartial = recordOf({ name: isString, age: isNumber }, ['age'])\n * isPartial({ name: 'Ada' }) // true\n * ```\n */\nexport function recordOf<\n\tS extends GuardsShape,\n\tK extends ReadonlyArray<keyof S & string> | true | undefined,\n>(\n\tshape: S,\n\toptional?: K,\n): Guard<\n\tK extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S>\n> {\n\tconst allowed = new Set<string>()\n\tfor (const key in shape) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tallowed.add(key)\n\t\t}\n\t}\n\tconst optionalSet = new Set<string>(\n\t\toptional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : [],\n\t)\n\n\treturn (\n\t\tvalue: unknown,\n\t): value is K extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S> => {\n\t\tif (!isRecord(value)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\tif (!allowed.has(key)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const key in shape) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst present = Object.hasOwn(value, key)\n\t\t\t\tif (!optionalSet.has(key) && !present) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif (present) {\n\t\t\t\t\tconst guard = shape[key]\n\t\t\t\t\tif (!guard(value[key])) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts any iterable whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isNumberIterable = iterableOf(isNumber)\n * isNumberIterable([1, 2, 3]) // true\n * isNumberIterable(new Set([1, 2])) // true\n * isNumberIterable([1, 'two']) // false\n * ```\n */\nexport function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>\nexport function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>\nexport function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>> {\n\treturn (value: unknown): value is Iterable<unknown> => {\n\t\tif (!isIterable(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts values that are own keys of the provided object.\n *\n * @remarks\n * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys\n * (`toString`, `constructor`, …) are rejected. An own property that shadows a\n * prototype name is accepted.\n *\n * @example\n * ```ts\n * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const\n * const isColorKey = keyOf(COLORS)\n * isColorKey('red') // true\n * isColorKey('purple') // false\n * isColorKey('toString') // false — inherited, not an own key\n * ```\n */\nexport function keyOf<const O extends Readonly<Record<PropertyKey, unknown>>>(\n\tvalue: O,\n): Guard<keyof O> {\n\treturn (entry: unknown): entry is keyof O =>\n\t\t(isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry)\n}\n\n/**\n * Build a new guard shape by keeping only the listed keys — the structural\n * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isName = recordOf(pickOf(full, ['name']))\n * isName({ name: 'Ada' }) // true\n * ```\n */\nexport function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Pick<S, K[number]> {\n\t// Honest typing: the accumulator IS the picked-shape type, so every write is\n\t// checked against `S[P]` — no `as` / `!` / `asserts`. The seed is a genuine\n\t// null-prototype empty object, filled before any read.\n\tconst result: { [P in K[number]]: S[P] } = Object.create(null)\n\tfor (const key of keys) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Build a new guard shape by removing the listed keys — the structural\n * equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isPublic = recordOf(omitOf(full, ['role']))\n * isPublic({ name: 'Ada', age: 36 }) // true\n * ```\n */\nexport function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Omit<S, K[number]> {\n\tconst skipped = new Set<PropertyKey>()\n\tfor (const key of keys) {\n\t\tskipped.add(key)\n\t}\n\t// Sound over-approximation: only kept keys are written, so the value\n\t// structurally satisfies `Omit<S, K[number]>`. Same honest typing as\n\t// `pickOf` — no `as` / `!` / `asserts`.\n\tconst result: { [P in keyof S]: S[P] } = Object.create(null)\n\tfor (const key in shape) {\n\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!skipped.has(key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Combine two guards with logical AND — passes only when both pass.\n *\n * @remarks\n * Use {@link whereOf} when the right side refines an already-narrowed type; use\n * `andOf` to combine two independent guards.\n *\n * @example\n * ```ts\n * const isShortString = andOf(isString, isNonEmptyString)\n * ```\n */\nexport function andOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A & B>\nexport function andOf<T, U extends T>(left: Guard<T>, right: (value: T) => value is U): Guard<U>\nexport function andOf<T>(left: Guard<T>, right: (value: T) => boolean): Guard<T>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => left(value) && right(value)\n}\n\n/**\n * Combine two guards with logical OR — passes when at least one passes. For more\n * than two variants prefer {@link unionOf}.\n *\n * @example\n * ```ts\n * const isStringOrNumber = orOf(isString, isNumber)\n * ```\n */\nexport function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => left(value) || right(value)\n}\n\n/**\n * Negate a guard or predicate — passes when `guard` returns `false`.\n *\n * @remarks\n * Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use\n * {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.\n *\n * @example\n * ```ts\n * const isNotNull = notOf(isNull)\n * ```\n */\nexport function notOf(guard: (value: unknown) => boolean): Guard<unknown> {\n\treturn (value: unknown): value is unknown => !guard(value)\n}\n\n/**\n * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass\n * `base` but not `excluded`.\n *\n * @example\n * ```ts\n * const isNonEmpty = complementOf(isString, isEmptyString)\n * isNonEmpty('hi') // true\n * isNonEmpty('') // false\n * ```\n */\nexport function complementOf<TBase, TExcluded extends TBase>(\n\tbase: Guard<TBase>,\n\texcluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded),\n): Guard<Exclude<TBase, TExcluded>> {\n\treturn (value: unknown): value is Exclude<TBase, TExcluded> => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\treturn !excluded(value)\n\t}\n}\n\n/**\n * Build a guard that accepts values matching at least one of the provided\n * guards — the variadic form of {@link orOf}.\n *\n * @example\n * ```ts\n * const isStringOrBoolean = unionOf(isString, isBoolean)\n * ```\n */\nexport function unionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<GuardType<Gs[number]>>\nexport function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>\nexport function unionOf(...guards: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown> {\n\treturn (value: unknown): value is unknown => guards.some((guard) => guard(value))\n}\n\n/**\n * Build a guard that accepts values matching ALL of the provided guards — the\n * variadic form of {@link andOf}.\n *\n * @example\n * ```ts\n * const isNonEmpty = intersectionOf(isString, isNonEmptyString)\n * ```\n */\nexport function intersectionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<IntersectionFromGuards<Gs>>\nexport function intersectionOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown>\nexport function intersectionOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => guards.every((guard) => guard(value))\n}\n\n/**\n * Refine a base guard with an additional predicate that runs only when the base\n * passes.\n *\n * @remarks\n * The predicate receives a value already narrowed to `T`. When the predicate is\n * itself a type guard (`value is U`), the result narrows to `Guard<U>` — it\n * passes only when the value is genuinely a `U`, so the narrowing is sound. Per\n * §14 the returned guard never throws: if `predicate` throws, the throw is\n * contained and the guard reports a non-match.\n *\n * @example\n * ```ts\n * const isPositive = whereOf(isNumber, (n) => n > 0)\n * isPositive(5) // true\n * isPositive(-1) // false\n *\n * // A narrowing predicate refines the result type to Guard<5>\n * const isFive = whereOf(isNumber, (n): n is 5 => n === 5)\n * ```\n */\nexport function whereOf<T, U extends T>(\n\tbase: Guard<T>,\n\tpredicate: (value: T) => value is U,\n): Guard<U>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// `predicate` is user-supplied with no never-throw contract; §14 forbids\n\t\t// the guard from propagating its throw.\n\t\tconst outcome = attempt(() => predicate(value))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Defer guard creation until first use by calling `thunk()` on every\n * invocation.\n *\n * @remarks\n * `thunk` is called on every guard call, not cached — this lets it close over a\n * binding assigned *after* `lazyOf` is called, the primary use case for\n * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard\n * it resolves to) is contained and reported as a non-match.\n *\n * A recursive guard built this way has no cycle/depth detection: a cyclic or\n * pathologically deep input is stack-bounded — the overflow is contained and the\n * guard returns `false` rather than throwing, but it is not validated correctly\n * past that bound.\n *\n * @example\n * ```ts\n * type Tree = { value: number; children: Tree[] }\n * let isTree: Guard<Tree>\n * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })\n * ```\n */\nexport function lazyOf<T>(thunk: () => Guard<T>): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\t// `thunk` and the guard it returns are user-supplied; §14 forbids\n\t\t// propagating either throw.\n\t\tconst outcome = attempt(() => thunk()(value))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that passes when the base passes AND the projection of the value\n * satisfies the target guard. Still narrows to `T` (the base type) — the target\n * check is a validity constraint on a derived view, not a type transformation.\n *\n * @remarks\n * `project` is a plain `(value: T) => U`. Per §14 the returned guard never\n * throws: a throw from `project` is contained and reported as a non-match.\n * `target` is itself a Guard (already §14-bound), so it stays outside the\n * contained region. (Unlike the reference implementation, there is no\n * \"curried projector\" branch — a projection that legitimately returns a function\n * would be double-invoked under that scheme. Compose explicitly if you need it.)\n *\n * @example\n * ```ts\n * const isBounded = transformOf(\n * isString,\n * (s) => s.trim().length,\n * whereOf(isNumber, (n) => n >= 1 && n <= 50),\n * )\n * isBounded('hello') // true\n * isBounded('') // false\n * ```\n */\nexport function transformOf<T, U>(\n\tbase: Guard<T>,\n\tproject: (value: T) => U,\n\ttarget: Guard<U>,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// `project` is user-supplied with no never-throw contract; §14 forbids the\n\t\t// guard from propagating its throw.\n\t\tconst outcome = attempt(() => project(value))\n\t\treturn outcome.success && target(outcome.value)\n\t}\n}\n\n/**\n * Build a guard that accepts finite numbers within an inclusive `[min, max]`\n * range.\n *\n * @remarks\n * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /\n * `±Infinity` are rejected before any comparison runs. An absent bound never\n * constrains that side. Reused for a number's own value AND, applied to a\n * `.length`, for string and array length refinements — the single source of the\n * bound logic shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const inRange = boundsOf(1, 5)\n * inRange(3) // true\n * inRange(0) // false — below min\n * inRange(6) // false — above max\n *\n * const atLeastTwo = boundsOf(2)\n * atLeastTwo(2) // true — unbounded above\n * ```\n */\nexport function boundsOf(min?: number, max?: number): Guard<number> {\n\treturn whereOf(\n\t\tisFiniteNumber,\n\t\t(value) => (min === undefined || value >= min) && (max === undefined || value <= max),\n\t)\n}\n\n/**\n * Build a guard that accepts strings matching a regular expression.\n *\n * @example\n * ```ts\n * const isHex = matchOf(/^[0-9a-f]+$/)\n * isHex('1a2f') // true\n * isHex('xyz') // false\n * ```\n */\nexport function matchOf(pattern: RegExp): Guard<string> {\n\treturn whereOf(isString, (value) => pattern.test(value))\n}\n\n/**\n * Build a guard that accepts strings satisfying optional length and pattern\n * refinements — `min` / `max` length and a `pattern`.\n *\n * @remarks\n * Composes {@link isString} with {@link boundsOf} on the string's `.length` and\n * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns\n * the bare {@link isString} guard (the unconstrained fast path), so an\n * unrefined string leaf pays no wrapping cost. The single source of the string\n * refinement shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })\n * isSlug('hello-world') // true\n * isSlug('') // false — below min\n * isSlug('Hello') // false — pattern miss\n *\n * stringOf() // identical to isString\n * ```\n */\nexport function stringOf(options?: {\n\tmin?: number\n\tmax?: number\n\tpattern?: RegExp\n}): Guard<string> {\n\tconst min = options?.min\n\tconst max = options?.max\n\tconst pattern = options?.pattern\n\tif (min === undefined && max === undefined && pattern === undefined) {\n\t\treturn isString\n\t}\n\tconst withinLength = boundsOf(min, max)\n\treturn whereOf(\n\t\tisString,\n\t\t(value) => withinLength(value.length) && (pattern === undefined || pattern.test(value)),\n\t)\n}\n\n/**\n * Extend a guard to also allow `null`.\n *\n * @example\n * ```ts\n * const isNullableString = nullableOf(isString)\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function nullableOf<T>(guard: Guard<T>): Guard<T | null> {\n\treturn (value: unknown): value is T | null => value === null || guard(value)\n}\n\n/**\n * Extend a guard to also allow `undefined` — the optional counterpart of\n * {@link nullableOf}.\n *\n * @example\n * ```ts\n * const isOptionalString = optionalOf(isString)\n * isOptionalString('hi') // true\n * isOptionalString(undefined) // true\n * isOptionalString(null) // false\n * ```\n */\nexport function optionalOf<T>(guard: Guard<T>): Guard<T | undefined> {\n\treturn (value: unknown): value is T | undefined => value === undefined || guard(value)\n}\n","import type { Guard, JSONValue } from './types.js'\nimport type { FieldPath } from './types.js'\nimport { isArray, isFiniteNumber, isJSONValue, isNull, isRecord, isString } from './validators.js'\nimport { resolveField } from './helpers.js'\n\n// AGENTS §14: a parser answers \"give me a `T` or nothing\" — it returns the\n// typed value or `undefined`, and it never throws. Each leaf parser here forms a\n// SOUND pair with the guard for its output TYPE: a guard-valid input is returned\n// UNCHANGED (by identity, never rejected), and every non-`undefined` output\n// satisfies that type guard. The pairings (verified in parsers.test.ts):\n//\n// parseString ↔ isString parseRecord ↔ isRecord\n// parseNumber ↔ isFiniteNumber parseArray ↔ arrayOf(guard) / isArray\n// parseInteger ↔ isInteger parseEnum ↔ literalOf(...allowed)\n// parseBoolean ↔ isBoolean parseNull ↔ isNull\n// parseJSONValue ↔ isJSONValue\n//\n// Coercion of NON-valid inputs (e.g. numeric strings → numbers) is a bonus on\n// top of soundness, not a violation of it — clause A only constrains inputs the\n// guard already accepts.\n//\n// These leaf parsers are deliberately TYPE-only: they know nothing about a\n// shape's `min` / `max` / `pattern` refinements. Those refinements are enforced\n// one layer up, by the compiled parser (compilers.ts `compileParser`), which\n// re-applies the shared refinement combinators (`stringOf` / `boundsOf`,\n// combinators.ts) after coercion — the same source the compiled guard uses. So `createContract(...).parse` IS sound against the FULL\n// guard (refinements included); the split keeps each leaf parser small while the\n// compiler composes the full soundness.\n//\n// Coercion policy — which types cross into which:\n// - number <-> string is BIDIRECTIONAL by design: parseNumber accepts a\n// numeric string ('42' -> 42) and parseString accepts a finite number,\n// stringifying it (42 -> '42'). Use isString / isFiniteNumber directly\n// (never the parser) when you need STRICT type rejection with no coercion.\n// - boolean is a coercion SINK, never a source: parseBoolean accepts\n// 'true'/'false'/'1'/'0' and 1/0 and coerces them TO a boolean, but\n// parseNumber and parseString both reject booleans outright — a boolean\n// never coerces INTO a number or string. This is intentional asymmetry:\n// '1' meaning \"the number one\" and '1' meaning \"true\" are genuinely\n// different domains, so only the boolean parser treats the numeric/string\n// forms as booleans.\n\n// === Primitive parsers\n\n/**\n * Parse an unknown value to a string.\n *\n * @remarks\n * A string is returned unchanged; a finite number is coerced to its decimal\n * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A string, or `undefined`\n *\n * @example\n * ```ts\n * parseString('hi') // 'hi'\n * parseString(42) // '42'\n * parseString(true) // undefined\n * ```\n */\nexport function parseString(value: unknown): string | undefined {\n\tif (isString(value)) return value\n\tif (isFiniteNumber(value)) return String(value)\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite number.\n *\n * @remarks\n * A finite number is returned unchanged; a non-blank numeric string is parsed\n * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every\n * other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumber(42) // 42\n * parseNumber('42') // 42\n * parseNumber('abc') // undefined\n * ```\n */\nexport function parseNumber(value: unknown): number | undefined {\n\tif (typeof value === 'number') {\n\t\treturn Number.isFinite(value) ? value : undefined\n\t}\n\tif (isString(value)) {\n\t\tif (value.trim() === '') return undefined\n\t\tconst parsed = Number(value)\n\t\treturn Number.isFinite(parsed) ? parsed : undefined\n\t}\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite integer.\n *\n * @remarks\n * Accepts whatever {@link parseNumber} accepts, then requires the result to have\n * no fractional part. `3.14` / `'3.14'` → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite integer, or `undefined`\n *\n * @example\n * ```ts\n * parseInteger(42) // 42\n * parseInteger(3.14) // undefined\n * ```\n */\nexport function parseInteger(value: unknown): number | undefined {\n\tconst parsed = parseNumber(value)\n\tif (parsed === undefined) return undefined\n\treturn Number.isInteger(parsed) ? parsed : undefined\n}\n\n/**\n * Parse an unknown value to a boolean.\n *\n * @remarks\n * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /\n * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything\n * else → `undefined`.\n *\n * @param value - The value to parse\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBoolean(true) // true\n * parseBoolean('1') // true\n * parseBoolean('nope') // undefined\n * ```\n */\nexport function parseBoolean(value: unknown): boolean | undefined {\n\tif (typeof value === 'boolean') return value\n\tif (value === 'true' || value === '1' || value === 1) return true\n\tif (value === 'false' || value === '0' || value === 0) return false\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to `null`.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel every other parser in this file uses. Only `null` passes;\n * every other value (including `undefined`) → `undefined`.\n *\n * @param value - The value to parse\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNull(null) // null\n * parseNull(undefined) // undefined\n * ```\n */\nexport function parseNull(value: unknown): null | undefined {\n\treturn isNull(value) ? value : undefined\n}\n\n// === Structural parsers\n\n/**\n * Parse an unknown value to a plain record — the input reference, never cloned.\n *\n * @param value - The value to parse\n * @returns The record, or `undefined`\n */\nexport function parseRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined\n}\n\n/**\n * Parse an unknown value to an array — the input reference, never cloned —\n * optionally guarding every element.\n *\n * @remarks\n * Without a `guard`, element types are NOT verified; let `T` default to\n * `unknown` rather than asserting a specific element type.\n *\n * @param value - The value to parse\n * @param guard - Optional element guard\n * @returns The array, or `undefined`\n *\n * @example\n * ```ts\n * parseArray([1, 2]) // [1, 2]\n * parseArray([1, 'x'], isNumber) // undefined\n * ```\n */\nexport function parseArray<T = unknown>(\n\tvalue: unknown,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\tif (!isArray<T>(value)) return undefined\n\tif (guard !== undefined && !value.every(guard)) return undefined\n\treturn value\n}\n\n/**\n * Parse an unknown value to a cycle-safe JSON value — the input reference,\n * never cloned.\n *\n * @remarks\n * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it\n * walks the entire tree via {@link isJSONValue} rather than checking only the\n * top-level shape. That walk is cycle-safe and total (never throws) because\n * `isJSONValue` runs its own probe inside a guard, so an adversarial\n * structure (a cycle, a hostile getter) yields `undefined` instead of hanging\n * or throwing.\n *\n * @param value - The value to parse\n * @returns The value, or `undefined` when it is not a valid JSON value\n *\n * @example\n * ```ts\n * parseJSONValue({ a: 1 }) // { a: 1 }\n * parseJSONValue(Number.NaN) // undefined\n * ```\n */\nexport function parseJSONValue(value: unknown): JSONValue | undefined {\n\treturn isJSONValue(value) ? value : undefined\n}\n\n// === Enum parser\n\n/**\n * Parse an unknown value as one of the allowed literal primitives.\n *\n * @remarks\n * Pairs with {@link literalOf} — both match by `Object.is`, so the\n * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive\n * (string, number, or boolean), not only strings. Matching is identity, never\n * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.\n *\n * @param value - The value to parse\n * @param allowed - The permitted literal values\n * @returns The matched literal (by identity), or `undefined`\n *\n * @example\n * ```ts\n * parseEnum('b', ['a', 'b', 'c']) // 'b'\n * parseEnum('z', ['a', 'b', 'c']) // undefined\n * ```\n */\nexport function parseEnum<const T extends string | number | boolean>(\n\tvalue: unknown,\n\tallowed: readonly T[],\n): T | undefined {\n\tfor (const option of allowed) {\n\t\tif (Object.is(value, option)) return option\n\t}\n\treturn undefined\n}\n\n// === Record-field parsers\n\n/**\n * Read and parse a string field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A string, or `undefined`\n */\nexport function parseStringField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): string | undefined {\n\treturn parseString(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-number field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumberField({ age: '42' }, 'age') // 42\n * parseNumberField({}, 'age') // undefined\n * ```\n */\nexport function parseNumberField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseNumber(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-integer field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite integer, or `undefined`\n */\nexport function parseIntegerField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseInteger(resolveField(record, path))\n}\n\n/**\n * Read and parse a boolean field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBooleanField({ on: 'true' }, 'on') // true\n * parseBooleanField({}, 'on') // undefined\n * ```\n */\nexport function parseBooleanField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): boolean | undefined {\n\treturn parseBoolean(resolveField(record, path))\n}\n\n/**\n * Read and parse a `null` field from a record by key or nested key path.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel, which also covers a missing field.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNullField({ value: null }, 'value') // null\n * parseNullField({}, 'value') // undefined\n * ```\n */\nexport function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined {\n\treturn parseNull(resolveField(record, path))\n}\n\n/**\n * Read and parse a nested record field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A plain record, or `undefined`\n */\nexport function parseRecordField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): Record<string, unknown> | undefined {\n\treturn parseRecord(resolveField(record, path))\n}\n\n/**\n * Read and parse an array field from a record by key or nested key path,\n * optionally guarding elements.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param guard - Optional element guard\n * @returns An array, or `undefined`\n *\n * @example\n * ```ts\n * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]\n * parseArrayField({}, 'tags') // undefined\n * ```\n */\nexport function parseArrayField<T = unknown>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\treturn parseArray(resolveField(record, path), guard)\n}\n\n/**\n * Read and parse an enum field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param allowed - The permitted literal values\n * @returns The matched literal, or `undefined`\n */\nexport function parseEnumField<const T extends string | number | boolean>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tallowed: readonly T[],\n): T | undefined {\n\treturn parseEnum(resolveField(record, path), allowed)\n}\n\n/**\n * Read and parse a JSON-value field from a record by key or nested key path.\n *\n * @remarks\n * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that\n * function's remarks for why this differs from the shallow\n * {@link parseRecordField} / {@link parseArrayField}.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The value, or `undefined`\n *\n * @example\n * ```ts\n * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }\n * parseJSONValueField({}, 'data') // undefined\n * ```\n */\nexport function parseJSONValueField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): JSONValue | undefined {\n\treturn parseJSONValue(resolveField(record, path))\n}\n\n// === JSON\n\n/**\n * Parse a JSON string, returning `undefined` instead of throwing.\n *\n * @remarks\n * The safe boundary for untrusted JSON text: a malformed string yields\n * `undefined`, never an exception. Returns `unknown` — a successful parse proves\n * nothing about shape, so narrow the result with a guard (or use\n * {@link parseJSONAs}). A large document is not walked here; parsing is shallow\n * and lazy validation is the caller's to compose.\n *\n * @param value - The JSON string to parse\n * @returns The parsed value, or `undefined` when `value` is not valid JSON\n */\nexport function parseJSON(value: string): unknown {\n\ttry {\n\t\treturn JSON.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Parse a JSON string and validate the result against a guard.\n *\n * @remarks\n * The lazy, safe path from an untrusted string to a typed `T`: parse, then check\n * the parsed value with the guard you bring — typically one composed from the\n * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is\n * validated, so a large document is never walked in full unless the guard does.\n *\n * @param value - The JSON string to parse\n * @param guard - The guard for the expected shape\n * @returns The parsed value when it satisfies `guard`, otherwise `undefined`\n *\n * @example\n * ```ts\n * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })\n * parseJSONAs('{\"host\":\"localhost\",\"tags\":[\"a\"]}', isConfig) // { host: 'localhost', tags: ['a'] }\n * parseJSONAs('{\"host\":\"localhost\"}', isConfig) // undefined — guard fails\n * parseJSONAs('not json', isConfig) // undefined — never throws\n * ```\n */\nexport function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined {\n\tconst parsed = parseJSON(value)\n\tif (parsed === undefined) return undefined\n\treturn guard(parsed) ? parsed : undefined\n}\n","import type {\n\tContractInterface,\n\tContractShape,\n\tFault,\n\tFaultKind,\n\tGuard,\n\tInfer,\n\tJSONSchema,\n\tParser,\n\tRandomFunction,\n} from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisInteger,\n\tisJSONValue,\n\tisNull,\n\tisRecord,\n\tisString,\n\tisUndefined,\n} from './validators.js'\nimport { attempt, preview, seededRandom, shapeToKind } from './helpers.js'\nimport { FAULT_LIMIT } from './constants.js'\nimport {\n\tarrayOf,\n\tboundsOf,\n\tintersectionOf,\n\tliteralOf,\n\tnullableOf,\n\torOf,\n\trecordOf,\n\tstringOf,\n\tunionOf,\n\twhereOf,\n} from './combinators.js'\nimport { parseBoolean, parseInteger, parseNumber, parseRecord, parseString } from './parsers.js'\n\n// The compilers walk a finite, developer-authored shape tree (never cyclic) and\n// recurse on themselves — branches are kept inline and public per AGENTS §5,\n// never hidden behind private helpers. `compileGuard` / `compileParser` reuse the\n// existing combinators and parsers rather than re-implementing them.\n\n// === Validation\n\n/**\n * Validate that a {@link ContractShape} tree is well-formed — a pure recursive\n * prepass run before compilation.\n *\n * @remarks\n * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this\n * throws a plain `Error` immediately rather than surfacing as a silently-wrong\n * guard, parser, schema, or generator later. Checks, recursively:\n *\n * - An {@link OptionalShape} is only legal as a direct object-property value —\n * `optionalShape` wrapping an array item, a union variant, another\n * optional/nullable's inner shape, `additionalProperties`, or the top-level\n * shape all throw. An object property IS the one legal placement: its value\n * is unwrapped to `.inner` before recursing, so `.inner` itself is validated\n * as a normal (non-optional-wrapping) shape.\n * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}\n * needs at least one value and rejects non-finite (`NaN` / `Infinity` /\n * `-Infinity`) number values.\n * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}\n * needs `min <= max` when both are set.\n * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer\n * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.\n * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion\n * continues into array items, object properties (and `additionalProperties`\n * when it is a shape), union variants, and optional/nullable inner shapes.\n *\n * @param shape - The shape to validate\n * @throws {Error} When the shape is malformed\n *\n * @example\n * ```ts\n * validateShape(stringShape({ min: 1, max: 10 })) // does not throw\n * validateShape(stringShape({ min: 10, max: 1 })) // throws\n * ```\n */\nexport function validateShape(shape: ContractShape): void {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: a string shape has min greater than max')\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase 'number': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: a number shape has min greater than max')\n\t\t\t}\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY)\n\t\t\t\tconst hi = Math.floor(shape.max ?? Number.POSITIVE_INFINITY)\n\t\t\t\tif (lo > hi) {\n\t\t\t\t\tthrow new Error('validateShape: an integer number shape has an empty integer range')\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase 'boolean':\n\t\tcase 'null':\n\t\tcase 'json':\n\t\tcase 'raw':\n\t\t\treturn\n\t\tcase 'literal':\n\t\t\tif (shape.values.length === 0) {\n\t\t\t\tthrow new Error('validateShape: a literal shape needs at least one value')\n\t\t\t}\n\t\t\tfor (const value of shape.values) {\n\t\t\t\tif (typeof value === 'number' && !Number.isFinite(value)) {\n\t\t\t\t\tthrow new Error('validateShape: a literal shape may not contain non-finite number values')\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\tcase 'array': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: an array shape has min greater than max')\n\t\t\t}\n\t\t\tvalidateShape(shape.items)\n\t\t\treturn\n\t\t}\n\t\tcase 'object': {\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tvalidateShape(child.type === 'optional' ? child.inner : child)\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) validateShape(extra)\n\t\t\treturn\n\t\t}\n\t\tcase 'union':\n\t\t\tif (shape.variants.length === 0) {\n\t\t\t\tthrow new Error('validateShape: a union shape needs at least one variant')\n\t\t\t}\n\t\t\tfor (const variant of shape.variants) validateShape(variant)\n\t\t\treturn\n\t\tcase 'optional':\n\t\t\tthrow new Error(\n\t\t\t\t'validateShape: an optional shape may only appear as a direct object-property value',\n\t\t\t)\n\t\tcase 'nullable':\n\t\t\tvalidateShape(shape.inner)\n\t\t\treturn\n\t}\n}\n\n// === Schema\n\n/**\n * Compile a {@link ContractShape} into a JSON Schema document.\n *\n * @remarks\n * Object shapes emit `additionalProperties: false` (unless opened) and list only\n * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:\n * 'null' }`. Emission only — it never inspects a runtime value.\n *\n * @param shape - The shape to compile\n * @returns The emitted JSON Schema\n *\n * @example\n * ```ts\n * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }\n * ```\n */\nexport function compileSchema(shape: ContractShape): JSONSchema {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\treturn {\n\t\t\t\ttype: 'string',\n\t\t\t\t...(shape.min !== undefined ? { minLength: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maxLength: shape.max } : {}),\n\t\t\t\t...(shape.pattern !== undefined ? { pattern: shape.pattern.source } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'number':\n\t\t\treturn {\n\t\t\t\ttype: shape.integer === true ? 'integer' : 'number',\n\t\t\t\t...(shape.min !== undefined ? { minimum: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maximum: shape.max } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'boolean':\n\t\t\treturn {\n\t\t\t\ttype: 'boolean',\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'null':\n\t\t\treturn {\n\t\t\t\ttype: 'null',\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'json':\n\t\t\treturn {\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'literal':\n\t\t\treturn {\n\t\t\t\tenum: [...shape.values],\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'array':\n\t\t\treturn {\n\t\t\t\ttype: 'array',\n\t\t\t\titems: compileSchema(shape.items),\n\t\t\t\t...(shape.min !== undefined ? { minItems: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maxItems: shape.max } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'object': {\n\t\t\tconst properties: Record<string, JSONSchema> = {}\n\t\t\tconst required: string[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tproperties[key] = compileSchema(child)\n\t\t\t\tif (child.type !== 'optional') required.push(key)\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tconst additionalProperties: boolean | JSONSchema =\n\t\t\t\textra === true\n\t\t\t\t\t? true\n\t\t\t\t\t: extra !== undefined && extra !== false\n\t\t\t\t\t\t? compileSchema(extra)\n\t\t\t\t\t\t: false\n\t\t\treturn {\n\t\t\t\ttype: 'object',\n\t\t\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t\t\t...(required.length > 0 ? { required } : {}),\n\t\t\t\tadditionalProperties,\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\t}\n\t\tcase 'union':\n\t\t\treturn {\n\t\t\t\t...(shape.mode === 'oneOf'\n\t\t\t\t\t? { oneOf: shape.variants.map((variant) => compileSchema(variant)) }\n\t\t\t\t\t: { anyOf: shape.variants.map((variant) => compileSchema(variant)) }),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileSchema(shape.inner)\n\t\tcase 'nullable':\n\t\t\treturn { anyOf: [compileSchema(shape.inner), { type: 'null' }] }\n\t\tcase 'raw':\n\t\t\treturn shape.schema\n\t}\n}\n\n// === Guard\n\n/**\n * Compile a {@link ContractShape} into a runtime type guard.\n *\n * @remarks\n * Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,\n * `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,\n * and `whereOf` for constraint refinement. Like every guard it is total — it\n * never throws (AGENTS §14).\n *\n * @param shape - The shape to compile\n * @returns A guard narrowing to the shape's inferred type\n *\n * @example\n * ```ts\n * const isUser = compileGuard(objectShape({ name: stringShape() }))\n * isUser({ name: 'Ada' }) // true\n * ```\n */\nexport function compileGuard<S extends ContractShape>(shape: S): Guard<Infer<S>>\nexport function compileGuard(shape: ContractShape): Guard<unknown>\nexport function compileGuard(shape: ContractShape): Guard<unknown> {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\t// `stringOf` returns bare `isString` when unrefined, else composes the\n\t\t\t// length-bounds + pattern refinement — the same guard the parser re-applies.\n\t\t\treturn stringOf({ min: shape.min, max: shape.max, pattern: shape.pattern })\n\t\tcase 'number': {\n\t\t\tconst base = shape.integer === true ? isInteger : isFiniteNumber\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\t// `boundsOf` already refines `isFiniteNumber`; intersect with `isInteger`\n\t\t\t// when the leaf is an integer so both the integrality and the bounds hold.\n\t\t\treturn shape.integer === true\n\t\t\t\t? intersectionOf(isInteger, boundsOf(shape.min, shape.max))\n\t\t\t\t: boundsOf(shape.min, shape.max)\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn isBoolean\n\t\tcase 'null':\n\t\t\treturn isNull\n\t\tcase 'json':\n\t\t\treturn isJSONValue\n\t\tcase 'literal':\n\t\t\treturn literalOf(...shape.values)\n\t\tcase 'array': {\n\t\t\tconst base = arrayOf(compileGuard(shape.items))\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max)\n\t\t\treturn whereOf(base, (value) => withinLength(value.length))\n\t\t}\n\t\tcase 'object': {\n\t\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t\t// prototype — the same pattern `pickOf` uses (combinators.ts).\n\t\t\tconst map: Record<string, Guard<unknown>> = Object.create(null)\n\t\t\tconst optionalKeys: string[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional') {\n\t\t\t\t\tmap[key] = compileGuard(child.inner)\n\t\t\t\t\toptionalKeys.push(key)\n\t\t\t\t} else {\n\t\t\t\t\tmap[key] = compileGuard<ContractShape>(child)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\t// Closed object → the exact, optional-key-aware `recordOf`.\n\t\t\tif (extra === undefined || extra === false) {\n\t\t\t\treturn optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map)\n\t\t\t}\n\t\t\t// Open object → validate known keys, then accept (`true`) or guard extras.\n\t\t\tconst additional = extra === true ? undefined : compileGuard(extra)\n\t\t\tconst required = Object.keys(map).filter((key) => !optionalKeys.includes(key))\n\t\t\treturn (value: unknown): value is unknown => {\n\t\t\t\tif (!isRecord(value)) return false\n\t\t\t\tfor (const key of required) {\n\t\t\t\t\tif (!Object.hasOwn(value, key)) return false\n\t\t\t\t}\n\t\t\t\t// Contain the whole key-enumeration + value-read walk — a hostile\n\t\t\t\t// getter on `value` must yield `false`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\t\t\tconst guard = Object.hasOwn(map, key) ? map[key] : undefined\n\t\t\t\t\t\tif (guard !== undefined) {\n\t\t\t\t\t\t\tif (!guard(value[key])) return false\n\t\t\t\t\t\t} else if (additional !== undefined && !additional(value[key])) {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\treturn outcome.success && outcome.value\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst guards = shape.variants.map((variant) => compileGuard(variant))\n\t\t\t// A `oneOf`-mode union matches the emitted JSON Schema `oneOf` keyword —\n\t\t\t// EXACTLY one variant must guard-accept the value, not \"at least one\"\n\t\t\t// (unionOf's anyOf semantics). A value matching two-or-more variants is\n\t\t\t// rejected, since it would violate the compiled schema.\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\treturn (value: unknown): value is unknown =>\n\t\t\t\t\tguards.filter((guard) => guard(value)).length === 1\n\t\t\t}\n\t\t\treturn unionOf(...guards)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn orOf(isUndefined, compileGuard(shape.inner))\n\t\tcase 'nullable':\n\t\t\treturn nullableOf(compileGuard(shape.inner))\n\t\tcase 'raw':\n\t\t\t// The tautological always-true guard for `raw` — accepts anything, so `_value` is\n\t\t\t// genuinely unused (the `_` suppresses the unused-arg lint; AGENTS §4.8).\n\t\t\treturn (_value: unknown): _value is unknown => true\n\t}\n}\n\n// === Parser\n\n/**\n * Compile a {@link ContractShape} into an input parser.\n *\n * @remarks\n * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /\n * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a\n * whole on any required-field failure; a union returns a guard-valid value\n * unchanged, otherwise the first variant that both parses and guards wins.\n *\n * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same\n * combinators `compileGuard` uses — `stringOf` for a string's length/pattern and\n * `boundsOf` for a number's value and an array's length — so a value that coerces\n * but violates a bound parses to `undefined`. The result is full parse↔guard\n * soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's\n * `is`, refinements included.\n *\n * @param shape - The shape to compile\n * @returns A parser yielding the shape's inferred type or `undefined`\n *\n * @example\n * ```ts\n * const parseUser = compileParser(objectShape({ name: stringShape() }))\n * parseUser({ name: 'Ada' }) // { name: 'Ada' }\n * ```\n */\nexport function compileParser<S extends ContractShape>(shape: S): Parser<Infer<S>>\nexport function compileParser(shape: ContractShape): Parser<unknown>\nexport function compileParser(shape: ContractShape): Parser<unknown> {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tif (shape.min === undefined && shape.max === undefined && shape.pattern === undefined) {\n\t\t\t\treturn parseString\n\t\t\t}\n\t\t\t// Coerce by type, then re-apply the SAME refinement the guard enforces (the\n\t\t\t// identical `stringOf`) — a value that parses but violates a bound or the\n\t\t\t// pattern fails the parse (returns `undefined`).\n\t\t\tconst guard = stringOf({ min: shape.min, max: shape.max, pattern: shape.pattern })\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = parseString(value)\n\t\t\t\treturn parsed !== undefined && guard(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst base = shape.integer === true ? parseInteger : parseNumber\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\t// The same bound check the guard applies (integrality is already enforced by\n\t\t\t// `parseInteger`, so only the bounds need re-checking after coercion).\n\t\t\tconst within = boundsOf(shape.min, shape.max)\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = base(value)\n\t\t\t\treturn parsed !== undefined && within(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean\n\t\tcase 'null':\n\t\t\treturn (value) => (value === null ? null : undefined)\n\t\tcase 'json':\n\t\t\treturn (value) => (isJSONValue(value) ? value : undefined)\n\t\t// The literal parser trims a matching string but never numeric-coerces —\n\t\t// `'42'` never parses to the literal `42`; only an exact (post-trim) match\n\t\t// of one of `shape.values` succeeds. This is an intended leniency, not a\n\t\t// soundness gap: a coerced value is always re-checked against `allowed`.\n\t\tcase 'literal': {\n\t\t\tconst allowed = new Set<unknown>(shape.values)\n\t\t\treturn (value) => {\n\t\t\t\tif (allowed.has(value)) return value\n\t\t\t\tif (isString(value)) {\n\t\t\t\t\tconst trimmed = value.trim()\n\t\t\t\t\tif (allowed.has(trimmed)) return trimmed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst item = compileParser(shape.items)\n\t\t\tconst unbounded = shape.min === undefined && shape.max === undefined\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max)\n\t\t\treturn (value) => {\n\t\t\t\tif (!isArray(value)) return undefined\n\t\t\t\tconst result: unknown[] = []\n\t\t\t\tfor (const entry of value) {\n\t\t\t\t\tconst parsed = item(entry)\n\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\tresult.push(parsed)\n\t\t\t\t}\n\t\t\t\t// Enforce the SAME length bounds the guard does (coercion never changes\n\t\t\t\t// length, so this is checked once on the assembled result).\n\t\t\t\treturn unbounded || withinLength(result.length) ? result : undefined\n\t\t\t}\n\t\t}\n\t\t// A closed object (no `additionalProperties`) silently drops unknown keys\n\t\t// present on the input rather than failing the parse — an intended\n\t\t// coercion leniency (the compiled guard still rejects them; this only\n\t\t// matters for guard-invalid inputs handed to `parse`).\n\t\tcase 'object': {\n\t\t\tconst entries: { key: string; parse: Parser<unknown>; optional: boolean }[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\tentries.push({ key, parse: compileParser(optional ? child.inner : child), optional })\n\t\t\t}\n\t\t\tconst known = new Set(entries.map((entry) => entry.key))\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tconst additional =\n\t\t\t\textra === undefined || extra === false || extra === true ? undefined : compileParser(extra)\n\t\t\tconst open = extra === true || additional !== undefined\n\t\t\treturn (value) => {\n\t\t\t\tconst record = parseRecord(value)\n\t\t\t\tif (record === undefined) return undefined\n\t\t\t\t// Contain the whole record walk — a hostile getter on `record` must\n\t\t\t\t// yield `undefined`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\t// Honest typing: a null-prototype accumulator so an input own key\n\t\t\t\t\t// literally named '__proto__' lands as an own data key instead of\n\t\t\t\t\t// mutating the prototype (same pattern as `pickOf`).\n\t\t\t\t\tconst result: Record<string, unknown> = Object.create(null)\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst raw = record[entry.key]\n\t\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\t\tif (entry.optional) continue\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst parsed = entry.parse(raw)\n\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\tresult[entry.key] = parsed\n\t\t\t\t\t}\n\t\t\t\t\tif (open) {\n\t\t\t\t\t\tfor (const key of Object.keys(record)) {\n\t\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\t\tif (additional === undefined) {\n\t\t\t\t\t\t\t\tresult[key] = record[key]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst parsed = additional(record[key])\n\t\t\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\t\t\tresult[key] = parsed\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn result\n\t\t\t\t})\n\t\t\t\treturn outcome.success ? outcome.value : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst variants = shape.variants.map((variant) => ({\n\t\t\t\tparse: compileParser(variant),\n\t\t\t\tguard: compileGuard(variant),\n\t\t\t}))\n\t\t\t// `oneOf` exactly-one semantics (documented on `oneOfShape`): judged on\n\t\t\t// the RAW input's guard matches only — no coercion fallback. Exactly one\n\t\t\t// variant's guard must accept the raw value; that variant's parser then\n\t\t\t// runs (its parse must equal the already guard-valid input by clause A).\n\t\t\t// Zero matches (no variant fits) or two-or-more matches (ambiguous —\n\t\t\t// which variant the value belongs to isn't well-defined) both fail the\n\t\t\t// parse, deliberately simpler than attempting a coercion-then-recheck\n\t\t\t// resolution for ambiguous input.\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\treturn (value) => {\n\t\t\t\t\tconst matches = variants.filter((variant) => variant.guard(value))\n\t\t\t\t\tconst [only] = matches\n\t\t\t\t\treturn matches.length === 1 && only !== undefined ? only.parse(value) : undefined\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (value) => {\n\t\t\t\t// Identity pass first (AGENTS §14 clause A): a value already valid\n\t\t\t\t// against ANY variant's guard is returned unchanged, so an earlier\n\t\t\t\t// variant's coercion never overwrites a guard-valid input.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tif (variant.guard(value)) return value\n\t\t\t\t}\n\t\t\t\t// Coercion pass: no variant matched as-is, so parse-then-guard,\n\t\t\t\t// first variant that both parses and guards wins.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst parsed = variant.parse(value)\n\t\t\t\t\tif (parsed !== undefined && variant.guard(parsed)) return parsed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'optional': {\n\t\t\tconst inner = compileParser(shape.inner)\n\t\t\treturn (value) => (value === undefined ? undefined : inner(value))\n\t\t}\n\t\tcase 'nullable': {\n\t\t\tconst inner = compileParser(shape.inner)\n\t\t\treturn (value) => (value === null ? null : inner(value))\n\t\t}\n\t\tcase 'raw':\n\t\t\treturn (value) => value\n\t}\n}\n\n// === Generator\n\n/**\n * Compile a {@link ContractShape} into a deterministic seed value.\n *\n * @remarks\n * The same shape and the same `random` source always produce the same value, so\n * seed data is reproducible. Defaults to a {@link seededRandom} source seeded\n * from the wall clock when none is supplied. Throws on a degenerate empty\n * `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose\n * generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded\n * schema is arbitrary and cannot be auto-generated) — a programmer error that\n * cannot generate a value (AGENTS §12). `createContract` runs\n * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /\n * bounded shape is normally caught there; these throws remain here as defense\n * for standalone `compileGenerator` use.\n *\n * @param shape - The shape to generate from\n * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)\n * @returns A value matching the shape\n *\n * @example\n * ```ts\n * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)\n * ```\n */\nexport function compileGenerator<S extends ContractShape>(\n\tshape: S,\n\trandom?: RandomFunction,\n): Infer<S>\nexport function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown\nexport function compileGenerator(\n\tshape: ContractShape,\n\trandom: RandomFunction = seededRandom(Date.now()),\n): unknown {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tconst min = shape.min ?? 0\n\t\t\tconst max = shape.max ?? Math.max(min, 12)\n\t\t\tconst length = Math.max(min, Math.min(max, 8))\n\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n\t\t\tlet value = ''\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tvalue += alphabet[Math.floor(random() * alphabet.length)]\n\t\t\t}\n\t\t\tif (shape.pattern !== undefined && !shape.pattern.test(value)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way',\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst min = shape.min ?? 0\n\t\t\tconst max = shape.max ?? 100\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(min)\n\t\t\t\tconst hi = Math.floor(max)\n\t\t\t\treturn Math.floor(random() * (hi - lo + 1)) + lo\n\t\t\t}\n\t\t\treturn random() * (max - min) + min\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn random() >= 0.5\n\t\tcase 'null':\n\t\t\treturn null\n\t\tcase 'json': {\n\t\t\tconst pick = Math.floor(random() * 5)\n\t\t\tif (pick === 0) return null\n\t\t\tif (pick === 1) return random() >= 0.5\n\t\t\tif (pick === 2) return Math.floor(random() * 1000)\n\t\t\tif (pick === 3) {\n\t\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\t\t\t\tlet value = ''\n\t\t\t\tfor (let index = 0; index < 6; index += 1) {\n\t\t\t\t\tvalue += alphabet[Math.floor(random() * alphabet.length)]\n\t\t\t\t}\n\t\t\t\treturn value\n\t\t\t}\n\t\t\treturn { value: Math.floor(random() * 1000) }\n\t\t}\n\t\tcase 'literal': {\n\t\t\tif (shape.values.length === 0) {\n\t\t\t\tthrow new Error('compileGenerator: a literal shape needs at least one value')\n\t\t\t}\n\t\t\treturn shape.values[Math.floor(random() * shape.values.length)]\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst lo = shape.min ?? Math.min(1, shape.max ?? 1)\n\t\t\tconst hi = shape.max ?? Math.max(lo, 3)\n\t\t\tconst length = Math.floor(random() * (hi - lo + 1)) + lo\n\t\t\tconst result: unknown[] = []\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tresult.push(compileGenerator(shape.items, random))\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'object': {\n\t\t\tconst result: Record<string, unknown> = {}\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional' && random() < 0.3) continue\n\t\t\t\tresult[key] = compileGenerator(child, random)\n\t\t\t}\n\t\t\t// An open object (additionalProperties is a shape, not a boolean) also\n\t\t\t// generates synthetic extra entries so the shape does not trivially\n\t\t\t// generate as `{}` — skip any collision with a declared property name.\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\tconst count = 1 + Math.floor(random() * 2)\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst key = `key${index}`\n\t\t\t\t\tif (Object.hasOwn(result, key)) continue\n\t\t\t\t\tresult[key] = compileGenerator(extra, random)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'union': {\n\t\t\tif (shape.variants.length === 0) {\n\t\t\t\tthrow new Error('compileGenerator: a union shape needs at least one variant')\n\t\t\t}\n\t\t\treturn compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileGenerator(shape.inner, random)\n\t\tcase 'nullable':\n\t\t\treturn random() < 0.2 ? null : compileGenerator(shape.inner, random)\n\t\tcase 'raw':\n\t\t\tthrow new Error(\n\t\t\t\t'compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way',\n\t\t\t)\n\t}\n}\n\n// === Reporter\n\n/**\n * Compile a {@link ContractShape} into a structured fault report for a value —\n * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.\n *\n * @remarks\n * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards\n * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /\n * `isJSONValue` / …), so the soundness invariant\n * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`\n * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a\n * coercible value like `'42'` against a `numberShape` reports no fault, the\n * same leniency `parse` grants, even though the strict guard would reject it).\n *\n * Faults are collected in stable pre-order (declared key/index order); every\n * call — object, array, and union alike, including a union's `oneOf` \"no\n * match\" / \"no consensus\" summary fault prepended to its closest variant's\n * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the\n * bound holds at every level of nesting, not just the outermost container, on\n * adversarial input (a huge array, a wide record, a wide union of wide\n * records). A closed object's extra keys never\n * fault — `parse` silently drops them, so `explain` mirrors that leniency; an\n * open object with a constraining `additionalProperties` shape recurses extras\n * against it instead. A hostile getter or throwing `Proxy` trap is contained\n * via {@link attempt} and surfaces as a single top-level type fault, never a\n * throw (AGENTS §14).\n *\n * @param shape - The shape to report against\n * @param value - The value to check\n * @param path - The path prefix for faults produced at this call (defaults to the root)\n * @returns The faults found, empty when the value parses successfully\n *\n * @example\n * ```ts\n * const user = objectShape({ name: stringShape({ min: 1 }) })\n * compileReporter(user, { name: '' })\n * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '\"\"' }]\n * compileReporter(user, { name: 'Ada' }) // []\n * ```\n */\nexport function compileReporter(\n\tshape: ContractShape,\n\tvalue: unknown,\n\tpath: string[] = [],\n): readonly Fault[] {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tconst parsed = parseString(value)\n\t\t\tif (parsed === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'string', received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tif (shape.min !== undefined && parsed.length < shape.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: shape.min,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.max !== undefined && parsed.length > shape.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: shape.max,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.pattern !== undefined && !shape.pattern.test(parsed)) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'pattern',\n\t\t\t\t\tlimit: shape.pattern.source,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst kind: FaultKind = shape.integer === true ? 'integer' : 'number'\n\t\t\tconst parsed = parseNumber(value)\n\t\t\tif (parsed === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: kind, received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tif (shape.integer === true && !Number.isInteger(parsed)) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'integer',\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.min !== undefined && parsed < shape.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: shape.min,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.max !== undefined && parsed > shape.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: shape.max,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean(value) === undefined\n\t\t\t\t? [{ reason: 'type', path, expected: 'boolean', received: preview(value) }]\n\t\t\t\t: []\n\t\tcase 'null':\n\t\t\treturn value === null\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'null', received: preview(value) }]\n\t\tcase 'json':\n\t\t\treturn isJSONValue(value)\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'json', received: preview(value) }]\n\t\tcase 'literal': {\n\t\t\tconst allowed = new Set<unknown>(shape.values)\n\t\t\tconst matched = allowed.has(value) || (isString(value) && allowed.has(value.trim()))\n\t\t\treturn matched\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'literal', received: preview(value) }]\n\t\t}\n\t\tcase 'array': {\n\t\t\tif (!isArray(value)) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'array', received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tconst outcome = attempt(() => {\n\t\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\tfaults.push(...compileReporter(shape.items, value[index], [...path, String(index)]))\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!outcome.success) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'array', received: preview(value) }]\n\t\t\t}\n\t\t\tif (shape.min !== undefined && value.length < shape.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'array',\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: shape.min,\n\t\t\t\t\treceived: String(value.length),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.max !== undefined && value.length > shape.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'array',\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: shape.max,\n\t\t\t\t\treceived: String(value.length),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults.length > FAULT_LIMIT ? faults.slice(0, FAULT_LIMIT) : faults\n\t\t}\n\t\tcase 'object': {\n\t\t\tif (!isRecord(value)) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\tconst record = value\n\t\t\tconst faults: Fault[] = []\n\t\t\tconst known = new Set<string>()\n\t\t\tconst outcome = attempt(() => {\n\t\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\tconst child = shape.properties[key]\n\t\t\t\t\tif (child === undefined) continue\n\t\t\t\t\tknown.add(key)\n\t\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\t\tconst inner = optional ? child.inner : child\n\t\t\t\t\t// Mirror the parser's presence gate exactly (compileParser,\n\t\t\t\t\t// object branch, ~line 492): a property is \"absent\" when its\n\t\t\t\t\t// VALUE is `undefined`, not when the key itself is missing\n\t\t\t\t\t// (`Object.hasOwn`) — a present key with an explicit `undefined`\n\t\t\t\t\t// value is treated identically to a missing one, so `explain`\n\t\t\t\t\t// never faults (or recurses into the inner reporter) where\n\t\t\t\t\t// `parse` silently skips it.\n\t\t\t\t\tconst raw = record[key]\n\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\tif (!optional) {\n\t\t\t\t\t\t\tfaults.push({ reason: 'missing', path: [...path, key], expected: shapeToKind(inner) })\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfaults.push(...compileReporter(inner, raw, [...path, key]))\n\t\t\t\t}\n\t\t\t\tconst extra = shape.additionalProperties\n\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\t\tfor (const key of Object.keys(record)) {\n\t\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\tfaults.push(...compileReporter(extra, record[key], [...path, key]))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!outcome.success) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\treturn faults.length > FAULT_LIMIT ? faults.slice(0, FAULT_LIMIT) : faults\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst perVariant = shape.variants.map((variant) => compileReporter(variant, value, path))\n\t\t\tlet bestIndex = 0\n\t\t\tfor (let index = 1; index < perVariant.length; index += 1) {\n\t\t\t\tconst current = perVariant[index]\n\t\t\t\tconst best = perVariant[bestIndex]\n\t\t\t\tif (current !== undefined && best !== undefined && current.length < best.length) {\n\t\t\t\t\tbestIndex = index\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst closest = perVariant[bestIndex] ?? []\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\tlet matched = 0\n\t\t\t\tfor (const variant of shape.variants) {\n\t\t\t\t\tif (compileGuard(variant)(value)) matched += 1\n\t\t\t\t}\n\t\t\t\tif (matched === 1) return []\n\t\t\t\tif (matched === 0) {\n\t\t\t\t\tconst summary: Fault = { reason: 'oneOf', path, matched: 0 }\n\t\t\t\t\treturn [summary, ...closest].slice(0, FAULT_LIMIT)\n\t\t\t\t}\n\t\t\t\treturn [{ reason: 'oneOf', path, matched }]\n\t\t\t}\n\t\t\tconst anyMatch = perVariant.some((variantFaults) => variantFaults.length === 0)\n\t\t\tif (anyMatch) return []\n\t\t\tconst summary: Fault = { reason: 'variant', path, variants: shape.variants.length }\n\t\t\treturn [summary, ...closest].slice(0, FAULT_LIMIT)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn value === undefined ? [] : compileReporter(shape.inner, value, path)\n\t\tcase 'nullable':\n\t\t\treturn value === null ? [] : compileReporter(shape.inner, value, path)\n\t\tcase 'raw':\n\t\t\treturn []\n\t}\n}\n\n// === Contract\n\n/**\n * Compile a {@link ContractShape} into a {@link ContractInterface} — the four\n * lockstep outputs from one declaration.\n *\n * @remarks\n * Runs {@link validateShape} first — a malformed shape throws immediately\n * rather than compiling into a silently-wrong contract (AGENTS §12). Then\n * precompiles the schema, guard, and parser once; `generate` walks the shape\n * per call with the supplied random source, and `explain` compiles the\n * diagnostic report via {@link compileReporter} at zero added compile-time cost\n * (it re-walks the shape per call, exactly like `generate`).\n *\n * @param shape - The shape to compile\n * @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`\n *\n * @example\n * ```ts\n * const user = createContract(objectShape({ name: stringShape(), age: integerShape() }))\n * user.is({ name: 'Ada', age: 36 }) // true\n * user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 }\n * user.schema // { type: 'object', properties: { … }, … }\n * ```\n */\nexport function createContract<S extends ContractShape>(shape: S): ContractInterface<Infer<S>>\nexport function createContract(shape: ContractShape): ContractInterface<unknown>\nexport function createContract(shape: ContractShape): ContractInterface<unknown> {\n\tvalidateShape(shape)\n\tconst schema = compileSchema(shape)\n\tconst guard = compileGuard(shape)\n\tconst parser = compileParser(shape)\n\treturn {\n\t\tschema,\n\t\tis: guard,\n\t\tparse(value: unknown): unknown {\n\t\t\treturn parser(value)\n\t\t},\n\t\texplain(value: unknown): readonly Fault[] {\n\t\t\treturn compileReporter(shape, value)\n\t\t},\n\t\tgenerate(random?: RandomFunction): unknown {\n\t\t\treturn compileGenerator(shape, random)\n\t\t},\n\t}\n}\n","import type { JSONSchema, SchemaFormat, ValueToSchemaOptions } from './types.js'\nimport {\n\tFORMAT_MAX_LENGTH,\n\tFORMAT_PATTERNS,\n\tINFER_BREADTH_LIMIT,\n\tINFER_DEPTH_LIMIT,\n\tINFER_ENUM_LIMIT,\n} from './constants.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisDate,\n\tisFiniteNumber,\n\tisInteger,\n\tisNull,\n\tisNumber,\n\tisRecord,\n\tisString,\n} from './validators.js'\nimport { attempt, sanitizeBudget } from './helpers.js'\n\n// The inferers walk an UNKNOWN, possibly adversarial runtime value (or a set\n// of example values) and emit a JSONSchema — the reverse direction of\n// compileSchema (compilers.ts), which walks a finite, developer-authored\n// ContractShape tree. Recursion here is runtime-only and bounded on three\n// axes: a WeakSet of ancestor objects/arrays (cycle safety), a decrementing\n// depth budget (INFER_DEPTH_LIMIT default), and a per-container sampling cap\n// (INFER_BREADTH_LIMIT default) — every branch stays total, per AGENTS §14.\n\n// === Canonicalization\n\n/**\n * Render a value as a deterministic, key-sorted JSON string.\n *\n * @remarks\n * The stable-stringify backing {@link unifySchemas}'s de-duplication and\n * ordering: unlike `JSON.stringify`, object keys are sorted before encoding\n * (recursively, at every nesting level), so two structurally-equal\n * `JSONSchema` fragments built independently always canonicalize to the same\n * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.\n *\n * @param value - The value to canonicalize (a `JSONSchema` fragment, or any\n * nested piece of one)\n * @returns A deterministic string encoding of `value`\n *\n * @example\n * ```ts\n * canonicalStringify({ type: 'object', properties: {} }) ===\n * \tcanonicalStringify({ properties: {}, type: 'object' }) // true\n * ```\n */\nexport function canonicalStringify(value: unknown): string {\n\tif (isArray(value)) {\n\t\treturn `[${value.map((entry) => canonicalStringify(entry)).join(',')}]`\n\t}\n\tif (isRecord(value)) {\n\t\tconst keys = Object.keys(value).sort()\n\t\tconst parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalStringify(value[key])}`)\n\t\treturn `{${parts.join(',')}}`\n\t}\n\treturn JSON.stringify(value)\n}\n\n/**\n * Unify a list of inferred `JSONSchema` fragments into one schema.\n *\n * @remarks\n * De-duplicates by {@link canonicalStringify}, then applies the one\n * special-case subsumption inference performs: a bare `{ type: 'integer' }`\n * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`\n * (an integer sample is also a valid `number` sample). A single surviving\n * distinct schema is returned directly; two or more are wrapped as\n * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.\n * An empty input list returns the empty accept-anything schema `{}`.\n *\n * @param schemas - The schemas to unify\n * @returns The unified schema\n *\n * @example\n * ```ts\n * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }\n * unifySchemas([{ type: 'string' }, { type: 'boolean' }])\n * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }\n * ```\n */\nexport function unifySchemas(schemas: readonly JSONSchema[]): JSONSchema {\n\tif (schemas.length === 0) return {}\n\tconst seen = new Map<string, JSONSchema>()\n\tfor (const schema of schemas) {\n\t\tconst key = canonicalStringify(schema)\n\t\tif (!seen.has(key)) seen.set(key, schema)\n\t}\n\tconst integerKey = canonicalStringify({ type: 'integer' })\n\tconst numberKey = canonicalStringify({ type: 'number' })\n\tif (seen.has(integerKey) && seen.has(numberKey)) {\n\t\tseen.delete(integerKey)\n\t}\n\tconst distinct = [...seen.entries()]\n\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n\t\t.map(([, schema]) => schema)\n\tif (distinct.length <= 1) {\n\t\tconst [only] = distinct\n\t\treturn only ?? {}\n\t}\n\treturn { anyOf: distinct }\n}\n\n// === Format inference\n\n/**\n * Determine whether an ISO-8601-shaped string parses to a valid instant.\n *\n * @remarks\n * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never\n * throws on a string input, but a value like `2020-13-45` parses to an\n * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation\n * step behind {@link stringToFormat}'s `date` / `date-time` / `time`\n * branches, which pattern-match the shape first and confirm validity here.\n *\n * @param value - The candidate ISO-8601 string\n * @returns `true` when `value` parses to a real instant\n *\n * @example\n * ```ts\n * isValidISOInstant('2020-01-01') // true\n * isValidISOInstant('2020-13-45') // false\n * ```\n */\nexport function isValidISOInstant(value: string): boolean {\n\tconst outcome = attempt(() => {\n\t\tconst date = new Date(value)\n\t\treturn !Number.isNaN(date.getTime())\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Classify a string against the {@link SchemaFormat} vocabulary.\n *\n * @remarks\n * Total, pure, and deterministic. Fixed precedence, most specific first:\n * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first\n * match wins. The `date-time` / `date` / `time` branches require BOTH a\n * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity\n * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.\n * Returns `undefined` when no format matches (including the empty string).\n *\n * @param value - The string to classify\n * @returns The matched {@link SchemaFormat}, or `undefined`\n *\n * @example\n * ```ts\n * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'\n * stringToFormat('2024-01-15') // 'date'\n * stringToFormat('2020-13-45') // undefined — invalid date\n * stringToFormat('ada@example.com') // 'email'\n * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset\n * stringToFormat('10:30:00+02:00') // 'time'\n * ```\n */\nexport function stringToFormat(value: string): SchemaFormat | undefined {\n\tif (value.length > FORMAT_MAX_LENGTH) return undefined\n\tif (FORMAT_PATTERNS.uuid.test(value)) return 'uuid'\n\tif (\n\t\t/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n\t\tisValidISOInstant(value)\n\t) {\n\t\treturn 'date-time'\n\t}\n\tif (/^\\d{4}-\\d{2}-\\d{2}$/.test(value) && isValidISOInstant(value)) {\n\t\treturn 'date'\n\t}\n\tif (\n\t\t/^\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n\t\tisValidISOInstant(`1970-01-01T${value}`)\n\t) {\n\t\treturn 'time'\n\t}\n\tif (FORMAT_PATTERNS.email.test(value)) return 'email'\n\tif (FORMAT_PATTERNS.uri.test(value)) return 'uri'\n\treturn undefined\n}\n\n/**\n * Classify a list of sample values against the {@link SchemaFormat}\n * vocabulary, requiring unanimity.\n *\n * @remarks\n * A format is returned ONLY IF every value is a string AND every one maps to\n * the SAME {@link stringToFormat} result (including all mapping to\n * `undefined`, which itself returns `undefined` here). A single disagreeing\n * value, a non-string value, or an empty list all yield `undefined` — the\n * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})\n * relies on this unanimity so a slot with mixed string shapes emits a bare\n * `{ type: 'string' }` rather than an `anyOf` of formats.\n *\n * @param values - The sample values to classify\n * @returns The unanimous {@link SchemaFormat}, or `undefined`\n *\n * @example\n * ```ts\n * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'\n * samplesToFormat(['2024-01-01', 'not a date']) // undefined\n * samplesToFormat([]) // undefined\n * ```\n */\nexport function samplesToFormat(values: readonly unknown[]): SchemaFormat | undefined {\n\tif (values.length === 0 || !values.every((value) => isString(value))) return undefined\n\tconst formats = values.map((value) => stringToFormat(value))\n\tconst [first, ...rest] = formats\n\tif (first === undefined) return undefined\n\treturn rest.every((format) => format === first) ? first : undefined\n}\n\n// === Enum inference\n\n/**\n * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated\n * primitive slot — the multi-sample-only counterpart to\n * {@link stringToFormat} ({@link valueToSchema} never emits `enum`).\n *\n * @remarks\n * Fires only when ALL of: every value is the same primitive kind (all string\n * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed\n * slot never qualifies, and a slot containing `NaN` / `±Infinity` never\n * qualifies either, since {@link canonicalStringify} collapses `NaN` to\n * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2\n * values are given; the distinct-by-{@link canonicalStringify} count is LESS\n * than the value count (repetition required — separates a categorical column\n * from an ID column); and the distinct count is at most `limit`. The emitted\n * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s\n * `literalShape` emission. Members are sorted by canonical key for\n * deterministic output.\n *\n * @param values - The collected slot values\n * @param limit - The maximum distinct-value count before giving up\n * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible\n *\n * @example\n * ```ts\n * inferPrimitiveEnum(['active', 'inactive', 'active'], 12)\n * // { enum: ['active', 'inactive'] }\n * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition\n * ```\n */\nexport function inferPrimitiveEnum(\n\tvalues: readonly unknown[],\n\tlimit: number,\n): JSONSchema | undefined {\n\tif (values.length < 2) return undefined\n\tconst allString = values.every((value) => isString(value))\n\tconst allNumber = !allString && values.every((value) => isFiniteNumber(value))\n\tif (!allString && !allNumber) return undefined\n\tconst distinct = new Map<string, string | number>()\n\tfor (const value of values) {\n\t\tif (isString(value) || isFiniteNumber(value)) distinct.set(canonicalStringify(value), value)\n\t}\n\tif (distinct.size >= values.length || distinct.size > limit) return undefined\n\tconst sorted = [...distinct.entries()].sort(([left], [right]) =>\n\t\tleft < right ? -1 : left > right ? 1 : 0,\n\t)\n\treturn { enum: sorted.map(([, value]) => value) }\n}\n\n// === Single-value inference\n\n/**\n * Infer a `JSONSchema` fragment for one runtime value — the recursive spine\n * shared by {@link valueToSchema} and, per collected property/element, by\n * {@link inferArray} / {@link inferObject}.\n *\n * @remarks\n * Total: never throws, and terminates on cyclic input via `visited`. Leaf\n * classification order: `null`, boolean, integer (`Number.isInteger`\n * semantics — `-0` counts), finite non-integer number, non-finite number\n * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a\n * `format` keyword when `format` is on and {@link stringToFormat} matches),\n * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,\n * plus `format: 'date-time'` when `format` is on); everything else\n * (function, symbol, bigint, `undefined`, and other non-plain objects such as\n * `Map` / `Set`) is the empty accept-anything schema `{}`.\n *\n * @param value - The value to classify\n * @param depth - Remaining descent budget (0 halts recursion with `{}`)\n * @param breadth - The per-container sampling cap passed through to children\n * @param closed - Whether descended objects emit `additionalProperties: false`\n * @param format - Whether a string/`Date` leaf gains a `format` keyword\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred schema fragment for `value`\n *\n * @example\n * ```ts\n * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }\n * ```\n */\nexport function inferValue(\n\tvalue: unknown,\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (isNull(value)) return { type: 'null' }\n\tif (isBoolean(value)) return { type: 'boolean' }\n\tif (isInteger(value)) return { type: 'integer' }\n\tif (isFiniteNumber(value)) return { type: 'number' }\n\tif (isNumber(value)) return { type: 'number' }\n\tif (isString(value)) {\n\t\tif (format) {\n\t\t\tconst detected = stringToFormat(value)\n\t\t\tif (detected) return { type: 'string', format: detected }\n\t\t}\n\t\treturn { type: 'string' }\n\t}\n\tif (isArray(value)) return inferArray(value, depth, breadth, closed, format, visited, memo)\n\tif (isRecord(value)) return inferObject(value, depth, breadth, closed, format, visited, memo)\n\tif (isDate(value)) return format ? { type: 'string', format: 'date-time' } : { type: 'string' }\n\treturn {}\n}\n\n/**\n * Infer a `JSONSchema` array fragment from an array's sampled elements.\n *\n * @remarks\n * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the\n * first `breadth` elements are classified via {@link inferValue} (one less\n * depth) and unified with {@link unifySchemas}: a single distinct element\n * schema becomes `items` directly; multiple distinct schemas become\n * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of\n * `value` both yield the empty schema `{}` instead of descending. A sparse\n * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before\n * sampling so every slot — including a hole — is visited as an explicit\n * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left\n * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.\n *\n * ALL reads of `value` — including its `length` — happen inside\n * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose\n * `get` trap throws) is exactly as contained as a throwing own-getter element\n * or a Proxy-over-array element access, and cannot escape as a thrown error.\n * On failure — or when the sampled/classified list ends up empty — this\n * returns `{ type: 'array' }` (no `items`), since `value` is still known to\n * be an array, mirroring the empty-array emission. A same-object\n * re-inference at the same remaining `depth` is served from `memo` instead\n * of recomputing (guards a shared-reference DAG against exponential blowup).\n *\n * @param value - The array to infer from\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of elements sampled\n * @param closed - Threaded through to nested object elements\n * @param format - Threaded through to nested string/`Date` elements\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred array schema\n *\n * @example\n * ```ts\n * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())\n * // { type: 'array', items: { type: 'number' } }\n * ```\n */\nexport function inferArray(\n\tvalue: readonly unknown[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (!(depth > 0) || visited.has(value)) return {}\n\t// At a node reached through a cycle at the SAME remaining depth via two\n\t// different paths, the memo may serve the first traversal's already\n\t// cycle-truncated fragment (`{}`) to the second path instead of a fully\n\t// re-descended schema — a sound, deterministic over-approximation, never\n\t// a false-reject (a schema too permissive, never too strict).\n\tconst cached = memo.get(value)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(value)\n\tconst outcome = attempt(() => {\n\t\tconst sampled = Array.from(value.slice(0, breadth))\n\t\treturn sampled.map((entry) =>\n\t\t\tinferValue(entry, depth - 1, breadth, closed, format, visited, memo),\n\t\t)\n\t})\n\tvisited.delete(value)\n\tconst schema: JSONSchema =\n\t\toutcome.success && outcome.value.length > 0\n\t\t\t? { type: 'array', items: unifySchemas(outcome.value) }\n\t\t\t: { type: 'array' }\n\tlet depths = memo.get(value)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(value, depths)\n\t}\n\tdepths.set(depth, schema)\n\treturn schema\n}\n\n/**\n * Infer a `JSONSchema` object fragment from a plain record's sampled\n * properties.\n *\n * @remarks\n * Own enumerable string keys via `Object.keys`, sorted lexicographically for\n * deterministic output, capped at `breadth`. Each property value is read\n * through {@link attempt} so a hostile getter cannot escape as a thrown\n * error; a property whose value is `undefined` (hostile-getter failure\n * included) is treated as ABSENT — it contributes neither a `properties`\n * entry nor a `required` entry. Every other present key is required (single-\n * value mode). Emits `additionalProperties: false` when `closed`, `true`\n * otherwise — mirroring {@link compileSchema}'s object-emission convention —\n * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means\n * the sampled schema no longer describes every property `value` actually\n * carries, so `additionalProperties` is forced to `true` regardless of\n * `closed` (a closed schema built from a truncated sample would otherwise\n * reject the very object it was inferred from). Depth exhaustion or a cyclic\n * re-encounter of `value` both yield `{}`. A same-object re-inference at the\n * same remaining `depth` is served from `memo` instead of recomputing\n * (guards a shared-reference DAG against exponential blowup).\n *\n * @param value - The record to infer from\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties sampled\n * @param closed - Whether the emitted schema closes to unknown keys\n * @param format - Threaded through to nested string/`Date` properties\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred object schema\n *\n * @example\n * ```ts\n * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())\n * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],\n * // additionalProperties: false }\n * ```\n */\nexport function inferObject(\n\tvalue: Record<string, unknown>,\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (!(depth > 0) || visited.has(value)) return {}\n\tconst cached = memo.get(value)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(value)\n\t// Contain the whole key-enumeration + value-read walk — a hostile ownKeys\n\t// trap or property getter on `value` must yield {} for this object, never\n\t// throw (AGENTS §14) — mirroring compileGuard's object branch\n\t// (compilers.ts).\n\tconst outcome = attempt(() => {\n\t\tconst allKeys = Object.keys(value).sort()\n\t\tconst keys = allKeys.slice(0, breadth)\n\t\tconst truncated = allKeys.length > breadth\n\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t// prototype — the same pattern compileGuard / compileParser use\n\t\t// (compilers.ts).\n\t\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\t\tconst required: string[] = []\n\t\tfor (const key of keys) {\n\t\t\tconst propertyValue = value[key]\n\t\t\tif (propertyValue === undefined) continue\n\t\t\tproperties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo)\n\t\t\trequired.push(key)\n\t\t}\n\t\treturn { properties, required, truncated }\n\t})\n\tvisited.delete(value)\n\tif (!outcome.success) return {}\n\tconst { properties, required, truncated } = outcome.value\n\tconst schema: JSONSchema = {\n\t\ttype: 'object',\n\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t...(required.length > 0 ? { required } : {}),\n\t\tadditionalProperties: truncated ? true : !closed,\n\t}\n\tlet depths = memo.get(value)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(value, depths)\n\t}\n\tdepths.set(depth, schema)\n\treturn schema\n}\n\n/**\n * Infer a `JSONSchema` for one unknown value — the reverse direction of\n * {@link compileSchema}.\n *\n * @remarks\n * Total: never throws, and is cycle/depth/breadth-bounded (see\n * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested\n * objects close to unknown keys (`additionalProperties: false`) by default;\n * pass `closed: false` to open them. `format` (default `false`) opts a\n * string/`Date` leaf into the `format` keyword. Structurally-equal inputs\n * infer byte-identical schemas (object keys and `anyOf` members are sorted).\n *\n * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'\n * }` — is structurally accepted by `schemaToParameters`, but MCP clients\n * expect an object-shaped `inputSchema`; wrap a non-object payload with\n * {@link schemaToObject} before advertising it as a tool's parameters.\n *\n * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a\n * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /\n * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,\n * fractional) — a hostile or malformed budget can never defeat the depth\n * guard or corrupt the sampled key/element list.\n *\n * @param value - The value to infer a schema from\n * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds\n * @returns The inferred `JSONSchema`\n *\n * @example\n * ```ts\n * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },\n * // tags: { type: 'array', items: { type: 'string' } } },\n * // required: ['id', 'name', 'tags'], additionalProperties: false }\n * ```\n */\nexport function valueToSchema(value: unknown, options?: ValueToSchemaOptions): JSONSchema {\n\tconst maxDepth = sanitizeBudget(options?.maxDepth, INFER_DEPTH_LIMIT)\n\tconst maxProperties = sanitizeBudget(options?.maxProperties, INFER_BREADTH_LIMIT)\n\tconst closed = options?.closed ?? true\n\tconst format = options?.format ?? false\n\treturn inferValue(value, maxDepth, maxProperties, closed, format, new WeakSet(), new WeakMap())\n}\n\n// === Multi-sample inference\n\n/**\n * Infer a `JSONSchema` for a collected slot of sample values — the shared\n * non-record recursion step behind {@link samplesToSchema} (top level) and\n * {@link inferRecordSamples} (per collected property).\n *\n * @remarks\n * When every value is itself a plain record, delegates to\n * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when\n * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,\n * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins\n * outright (ENUM > FORMAT > bare string). Failing that, each value is\n * classified independently via {@link inferValue} with `format` FORCED OFF\n * (the multi-sample seam: nested formats never compound into an `anyOf`) and\n * unified with {@link unifySchemas}; only when that unified result is exactly\n * `{ type: 'string' }` and the outer `format` flag is on does\n * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.\n *\n * @param samples - The collected slot values\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties/elements sampled per nested container\n * @param closed - Whether nested objects close to unknown keys\n * @param format - Whether a unanimous string slot gains a `format` keyword\n * @param enumOn - Whether low-cardinality primitive slots may emit `enum`\n * @returns The inferred schema for the slot\n *\n * @example\n * ```ts\n * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)\n * // { type: 'string', format: 'date' }\n * ```\n */\nexport function inferSamples(\n\tsamples: readonly unknown[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tenumOn: boolean,\n): JSONSchema {\n\tif (samples.length === 0) return {}\n\tif (samples.every((sample) => isRecord(sample))) {\n\t\treturn inferRecordSamples(samples, depth, breadth, closed, format, enumOn)\n\t}\n\tif (enumOn) {\n\t\tconst enumSchema = inferPrimitiveEnum(samples, INFER_ENUM_LIMIT)\n\t\tif (enumSchema) return enumSchema\n\t}\n\tconst schemas = samples.map((sample) =>\n\t\tinferValue(sample, depth, breadth, closed, false, new WeakSet(), new WeakMap()),\n\t)\n\tconst unified = unifySchemas(schemas)\n\tif (format && unified.type === 'string' && Object.keys(unified).length === 1) {\n\t\tconst detected = samplesToFormat(samples)\n\t\tif (detected) return { type: 'string', format: detected }\n\t}\n\treturn unified\n}\n\n/**\n * Infer a `JSONSchema` object fragment from a set of plain-record samples\n * (e.g. database rows) — the record-specialized branch of\n * {@link samplesToSchema}.\n *\n * @remarks\n * `properties` is the union of every sample's own keys (sorted, capped at\n * `breadth`); a key is `required` only when present (and non-`undefined`) in\n * EVERY sample. Each key's schema is inferred over the collected values for\n * that key via {@link inferSamples} itself (one less depth), so a\n * property that is itself an array/object of varying shape across rows is\n * unified the same way the top level is, and the same `format` / `enum`\n * gating applies per key. Unlike {@link inferObject}/\n * {@link inferArray}, this path carries no `visited` `WeakSet` — a value\n * shared by reference across multiple sample rows is legitimate (not a\n * cycle back to an ancestor), so termination on cyclic row data relies on\n * the decrementing `depth` budget alone. When the union of sample keys\n * exceeds `breadth`, the key list is truncated and `additionalProperties` is\n * forced to `true` regardless of `closed` — the same truncation-opens-the-\n * schema rule {@link inferObject} applies, so a closed schema built from a\n * truncated key union never rejects the very rows it was inferred from. A\n * hostile getter on ONE sample row drops that key for ALL rows (the whole\n * per-key value collection is a single {@link attempt}-contained walk) —\n * this is a deliberate all-or-nothing scope, not a per-row partial failure.\n *\n * @param samples - The plain-record samples\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties sampled\n * @param closed - Whether the emitted schema closes to unknown keys\n * @param format - Whether a unanimous string column gains a `format` keyword\n * @param enumOn - Whether a low-cardinality column may emit `enum`\n * @returns The inferred object schema\n *\n * @example\n * ```ts\n * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },\n * // required: ['id'], additionalProperties: false }\n * ```\n */\nexport function inferRecordSamples(\n\tsamples: readonly Record<string, unknown>[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tenumOn: boolean,\n): JSONSchema {\n\tif (!(depth > 0)) return {}\n\t// Contain the whole key-enumeration walk — a hostile ownKeys trap on any\n\t// sample must yield an empty key set for this branch, never throw\n\t// (AGENTS §14).\n\tconst keysOutcome = attempt(() => {\n\t\tconst keySet = new Set<string>()\n\t\tfor (const sample of samples) {\n\t\t\tfor (const key of Object.keys(sample)) keySet.add(key)\n\t\t}\n\t\tconst allKeys = [...keySet].sort()\n\t\treturn { keys: allKeys.slice(0, breadth), truncated: allKeys.length > breadth }\n\t})\n\tconst keys = keysOutcome.success ? keysOutcome.value.keys : []\n\tconst truncated = keysOutcome.success && keysOutcome.value.truncated\n\t// Honest typing: a null-prototype accumulator so a key literally named\n\t// '__proto__' becomes an own data key instead of mutating the prototype —\n\t// the same pattern compileGuard / compileParser use (compilers.ts).\n\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\tconst required: string[] = []\n\t// Bounded by depth alone: unlike inferObject/inferArray, this record-\n\t// sample path carries no `visited` WeakSet. A shared reference across\n\t// sample rows is legitimate data (not a cycle back to an ancestor), so\n\t// the decrementing depth budget is the sole termination guarantee here.\n\tfor (const key of keys) {\n\t\t// Contain the per-sample value read — a hostile getter on any sample\n\t\t// must yield an empty value list for this key, never throw\n\t\t// (AGENTS §14).\n\t\tconst valuesOutcome = attempt(() => {\n\t\t\tconst values: unknown[] = []\n\t\t\tfor (const sample of samples) {\n\t\t\t\tconst propertyValue = sample[key]\n\t\t\t\tif (propertyValue !== undefined) values.push(propertyValue)\n\t\t\t}\n\t\t\treturn values\n\t\t})\n\t\tconst values = valuesOutcome.success ? valuesOutcome.value : []\n\t\tif (values.length > 0) {\n\t\t\tproperties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn)\n\t\t}\n\t\tif (values.length === samples.length) required.push(key)\n\t}\n\treturn {\n\t\ttype: 'object',\n\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t...(required.length > 0 ? { required } : {}),\n\t\tadditionalProperties: truncated ? true : !closed,\n\t}\n}\n\n/**\n * Infer a `JSONSchema` from a set of example values — the multi-example\n * counterpart of {@link valueToSchema} (e.g. inferring one schema from\n * several database rows).\n *\n * @remarks\n * An empty `samples` array infers the empty accept-anything schema `{}`.\n * When every sample is a plain record, properties/required are unified\n * per-key across all samples (see {@link inferRecordSamples}) — a key\n * required iff present and non-`undefined` in every sample. Otherwise the\n * slot is inferred via {@link inferSamples} (independent {@link valueToSchema}\n * per sample, unified with {@link unifySchemas} — the same de-duplication and\n * `anyOf` ordering {@link inferArray} applies to element schemas). `format`\n * and `enum` (both default `false`) opt a low-cardinality/unanimous-format\n * slot into the corresponding keyword — see {@link inferSamples} for the\n * precedence and the multi-sample format-disabling seam. `maxDepth` /\n * `maxProperties` are sanitized via {@link sanitizeBudget} the same way\n * {@link valueToSchema} sanitizes them — see there for why.\n *\n * @param samples - The example values to infer a schema from\n * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds\n * @returns The inferred `JSONSchema`\n *\n * @example\n * ```ts\n * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },\n * // required: ['id'], additionalProperties: false }\n * samplesToSchema([]) // {}\n * ```\n */\nexport function samplesToSchema(\n\tsamples: readonly unknown[],\n\toptions?: ValueToSchemaOptions,\n): JSONSchema {\n\tconst maxDepth = sanitizeBudget(options?.maxDepth, INFER_DEPTH_LIMIT)\n\tconst maxProperties = sanitizeBudget(options?.maxProperties, INFER_BREADTH_LIMIT)\n\tconst closed = options?.closed ?? true\n\tconst format = options?.format ?? false\n\tconst enumOn = options?.enum ?? false\n\treturn inferSamples(samples, maxDepth, maxProperties, closed, format, enumOn)\n}\n","import type {\n\tArrayShape,\n\tArrayShapeOptions,\n\tBooleanShape,\n\tBooleanShapeOptions,\n\tContractShape,\n\tJSONSchema,\n\tJSONShape,\n\tJSONShapeOptions,\n\tLiteralShape,\n\tLiteralShapeOptions,\n\tNullableShape,\n\tNullShape,\n\tNullShapeOptions,\n\tNumberShape,\n\tNumberShapeOptions,\n\tObjectShape,\n\tObjectShapeOptions,\n\tOptionalShape,\n\tRawShape,\n\tRecordShapeOptions,\n\tStringShape,\n\tStringShapeOptions,\n\tUnionShape,\n} from './types.js'\nimport { INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT } from './constants.js'\nimport { attempt } from './helpers.js'\nimport { isArray, isBoolean, isFiniteNumber, isInteger, isRecord, isString } from './validators.js'\n\n// The builders return the parameterized types.ts interfaces (e.g. `ArrayShape<S>`,\n// `ObjectShape<P>`), never inline object literals — the generic parameter keeps\n// `Infer<typeof shape>` exact while the return type still enforces conformance to\n// the shared shape interface.\n\n// Shape builders — pure constructors for the `ContractShape` union. Each returns\n// a plain descriptor; the compilers (compilers.ts) turn it into a guard, parser,\n// schema, and generator. The precise return types (e.g. literal tuples, generic\n// `items` / `properties`) are preserved so `Infer<typeof shape>` stays exact.\n\n// === Primitives\n\n/**\n * Build a string {@link StringShape}.\n *\n * @param options - Optional length (`min` / `max`), `pattern`, and `description`\n * @returns A string shape\n *\n * @example\n * ```ts\n * const name = stringShape({ min: 1, max: 80, description: 'Display name' })\n * ```\n */\nexport function stringShape(options?: StringShapeOptions): StringShape {\n\treturn {\n\t\ttype: 'string',\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tpattern: options?.pattern,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a numeric {@link NumberShape}.\n *\n * @param options - Optional bounds (`min` / `max`), `integer`, and `description`\n * @returns A number shape\n *\n * @example\n * ```ts\n * const age = numberShape({ min: 0, max: 120 })\n * ```\n */\nexport function numberShape(options?: NumberShapeOptions): NumberShape {\n\treturn {\n\t\ttype: 'number',\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tinteger: options?.integer,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an integer {@link NumberShape} — forces `integer: true`.\n *\n * @remarks\n * The emitted JSON Schema uses `\"type\": \"integer\"` and the guard rejects\n * fractional numbers.\n *\n * @param options - Optional bounds and `description` (no `integer` key)\n * @returns An integer number shape\n */\nexport function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape {\n\treturn {\n\t\ttype: 'number',\n\t\tinteger: true,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a {@link BooleanShape}.\n *\n * @param options - Optional `description`\n * @returns A boolean shape\n *\n * @example\n * ```ts\n * const active = booleanShape({ description: 'Whether the record is active' })\n * ```\n */\nexport function booleanShape(options?: BooleanShapeOptions): BooleanShape {\n\treturn {\n\t\ttype: 'boolean',\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a {@link NullShape}.\n *\n * @param options - Optional `description`\n * @returns A null shape\n *\n * @example\n * ```ts\n * const empty = nullShape()\n * ```\n */\nexport function nullShape(options?: NullShapeOptions): NullShape {\n\treturn { type: 'null', description: options?.description }\n}\n\n/**\n * Build a literal shape from a fixed set of primitive values.\n *\n * @param values - The permitted literals\n * @param options - Optional `description`\n * @returns A literal shape whose `Infer` is the union of `values`\n *\n * @example\n * ```ts\n * const role = literalShape(['admin', 'member', 'guest'])\n * // Infer<typeof role> = 'admin' | 'member' | 'guest'\n *\n * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })\n * ```\n */\nexport function literalShape<const T extends readonly (string | number | boolean)[]>(\n\tvalues: T,\n\toptions?: LiteralShapeOptions,\n): LiteralShape<T> {\n\treturn { type: 'literal', values, description: options?.description }\n}\n\n// === Collections\n\n/**\n * Build an {@link ArrayShape} from an element shape.\n *\n * @param items - The element shape\n * @param options - Optional length bounds and `description`\n * @returns An array shape\n *\n * @example\n * ```ts\n * const tags = arrayShape(stringShape(), { max: 10 })\n * ```\n */\nexport function arrayShape<S extends ContractShape>(\n\titems: S,\n\toptions?: ArrayShapeOptions,\n): ArrayShape<S> {\n\treturn {\n\t\ttype: 'array',\n\t\titems,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an {@link ObjectShape} from a property map.\n *\n * @remarks\n * Wrap any property in {@link optionalShape} to allow its absence. By default\n * the compiled guard rejects unknown keys; pass `additionalProperties` to open\n * the object.\n *\n * @param properties - Map of property names to child shapes\n * @param options - Optional `additionalProperties` and `description`\n * @returns An object shape\n *\n * @example\n * ```ts\n * const user = objectShape({\n * \tname: stringShape({ min: 1 }),\n * \tage: integerShape({ min: 0, max: 120 }),\n * \tbio: optionalShape(stringShape()),\n * })\n * ```\n */\nexport function objectShape<\n\tP extends Readonly<Record<string, ContractShape>>,\n\tconst A extends boolean | ContractShape = false,\n>(properties: P, options?: ObjectShapeOptions<A>): ObjectShape<P, A> {\n\treturn {\n\t\ttype: 'object',\n\t\tproperties,\n\t\tadditionalProperties: options?.additionalProperties,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an open {@link ObjectShape} with no fixed properties — a dictionary.\n *\n * @remarks\n * Every value is validated against `values`; keys are unconstrained. Equivalent\n * to `objectShape({}, { additionalProperties: values })`.\n *\n * @param values - The shape every value must match\n * @param options - Optional `description`\n * @returns An open object shape\n *\n * @example\n * ```ts\n * const bindings = recordShape(numberShape()) // ~ Record<string, number>\n * ```\n */\nexport function recordShape<S extends ContractShape>(\n\tvalues: S,\n\toptions?: RecordShapeOptions,\n): ObjectShape<Record<never, never>, S> {\n\treturn {\n\t\ttype: 'object',\n\t\tproperties: {},\n\t\tadditionalProperties: values,\n\t\tdescription: options?.description,\n\t}\n}\n\n// === Composition\n\n/**\n * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).\n *\n * @param variants - The candidate shapes; the first match wins at runtime\n * @returns A union shape whose `Infer` is the union of the variants\n *\n * @example\n * ```ts\n * const id = unionShape(stringShape(), integerShape())\n * // Infer<typeof id> = string | number\n * ```\n */\nexport function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V> {\n\treturn { type: 'union', variants }\n}\n\n/**\n * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.\n *\n * @remarks\n * Unlike {@link unionShape} (`anyOf` — at least one variant matches),\n * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:\n *\n * - **Guard**: accepts the value only when exactly one variant's guard\n * accepts it. A value matching two-or-more variants — which would violate\n * the emitted `oneOf` schema — is rejected, even though it would pass\n * {@link unionShape}'s guard.\n * - **Parser**: judged on the RAW input's guard matches only, with NO\n * coercion fallback for an ambiguous input. When exactly one variant's\n * guard accepts the raw value, that variant's parser runs. Zero matches or\n * two-or-more matches both parse to `undefined` — a value ambiguous\n * between variants has no well-defined coercion target.\n *\n * Prefer {@link unionShape} when a value may legitimately satisfy more than\n * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer\n * `oneOfShape` when overlap between variants indicates malformed input that\n * must be rejected.\n *\n * @param variants - The candidate shapes\n * @returns A union shape with `mode: 'oneOf'`\n *\n * @example\n * ```ts\n * const id = oneOfShape(numberShape(), integerShape())\n * // 3 fails — matches both numberShape and integerShape\n * // 3.5 passes — matches numberShape only\n * ```\n */\nexport function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V> {\n\treturn { type: 'union', variants, mode: 'oneOf' }\n}\n\n/**\n * Wrap a shape so it may be absent (`undefined`).\n *\n * @remarks\n * As an {@link objectShape} property, the field becomes a true optional property\n * in the inferred type.\n *\n * @param inner - The wrapped shape\n * @returns An optional shape\n */\nexport function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S> {\n\treturn { type: 'optional', inner }\n}\n\n/**\n * Wrap a shape so it may be `null`.\n *\n * @param inner - The wrapped shape\n * @returns A nullable shape\n *\n * @example\n * ```ts\n * const bio = nullableShape(stringShape())\n * // Infer<typeof bio> = string | null\n * ```\n */\nexport function nullableShape<S extends ContractShape>(inner: S): NullableShape<S> {\n\treturn { type: 'nullable', inner }\n}\n\n// === Escape hatch\n\n/**\n * Build a {@link JSONShape}.\n *\n * @remarks\n * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary\n * schema fragment and accepts anything at runtime, while `jsonShape` validates\n * that a value is real JSON (via {@link isJSONValue}).\n *\n * @param options - Optional `description`\n * @returns A JSON passthrough shape\n *\n * @example\n * ```ts\n * const payload = jsonShape({ description: 'Arbitrary JSON payload' })\n * ```\n */\nexport function jsonShape(options?: JSONShapeOptions): JSONShape {\n\treturn { type: 'json', description: options?.description }\n}\n\n/**\n * Build a {@link RawShape} from a JSON Schema fragment.\n *\n * @remarks\n * For values the shape DSL can't express. The compiled guard accepts any value;\n * the parser passes it through; the schema is emitted verbatim.\n *\n * @param schema - The JSON Schema fragment to embed\n * @returns A raw shape\n *\n * @example\n * ```ts\n * const custom = rawShape({ type: 'string', format: 'uuid' })\n * ```\n */\nexport function rawShape(schema: JSONSchema): RawShape {\n\treturn { type: 'raw', schema }\n}\n\n// === Schema inversion\n\n// schemaToShape walks an UNKNOWN, possibly adversarial runtime JSONSchema value\n// (a hand-written schema, or one produced by valueToSchema / samplesToSchema)\n// and emits a validating ContractShape — the reverse direction of\n// compileSchema (compilers.ts), which walks a finite, developer-authored\n// ContractShape tree and emits a JSONSchema. Recursion here is runtime-only\n// and bounded on three axes, mirroring the inferers: a WeakSet of ancestor\n// schema nodes (cycle safety), a decrementing depth budget (INFER_DEPTH_LIMIT\n// default), and a per-container sampling cap (INFER_BREADTH_LIMIT) on\n// properties/oneOf/anyOf entries — every branch stays total, per AGENTS §14.\n// Every keyword read is type-guarded: a malformed keyword is IGNORED, falling\n// through to the next rule, never thrown. `format` and `pattern` are NEVER\n// asserted — `format` is annotation-only, and compiling an attacker-supplied\n// `pattern` into a `RegExp` is a ReDoS vector — so neither keyword narrows the\n// compiled guard; the returned shape is always one `validateShape` accepts.\n\n/**\n * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON\n * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).\n *\n * @remarks\n * Total and pure. Either keyword is used only when it is a non-negative\n * integer (`isInteger` + `>= 0`); a malformed value (a string, a negative\n * number, `NaN`, `Infinity`, a fraction) is dropped as if absent. When both\n * bounds are present and `min` exceeds `max`, the PAIR is dropped entirely\n * (an unbounded shape is always a legal widening of a contradictory schema).\n *\n * @param min - The raw `minLength` / `minItems` keyword value\n * @param max - The raw `maxLength` / `maxItems` keyword value\n * @returns The derived `min` / `max` pair, either possibly `undefined`\n *\n * @example\n * ```ts\n * deriveLengthBounds(1, 10) // { min: 1, max: 10 }\n * deriveLengthBounds(10, 1) // {} — contradictory, dropped\n * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped\n * ```\n */\nexport function deriveLengthBounds(\n\tmin: unknown,\n\tmax: unknown,\n): { readonly min?: number; readonly max?: number } {\n\tconst lo = isInteger(min) && min >= 0 ? min : undefined\n\tconst hi = isInteger(max) && max >= 0 ? max : undefined\n\tif (lo !== undefined && hi !== undefined && lo > hi) return {}\n\treturn { min: lo, max: hi }\n}\n\n/**\n * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema\n * range keywords (`minimum`/`maximum`).\n *\n * @remarks\n * Total and pure. Either keyword is used only when it is a finite number\n * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when\n * both bounds are present and `min` exceeds `max`, the PAIR is dropped\n * entirely, the same contradiction rule {@link deriveLengthBounds} applies.\n *\n * @param min - The raw `minimum` keyword value\n * @param max - The raw `maximum` keyword value\n * @returns The derived `min` / `max` pair, either possibly `undefined`\n *\n * @example\n * ```ts\n * deriveRangeBounds(0, 120) // { min: 0, max: 120 }\n * deriveRangeBounds(5, 1) // {} — contradictory, dropped\n * ```\n */\nexport function deriveRangeBounds(\n\tmin: unknown,\n\tmax: unknown,\n): { readonly min?: number; readonly max?: number } {\n\tconst lo = isFiniteNumber(min) ? min : undefined\n\tconst hi = isFiniteNumber(max) ? max : undefined\n\tif (lo !== undefined && hi !== undefined && lo > hi) return {}\n\treturn { min: lo, max: hi }\n}\n\n/**\n * Build an {@link ObjectShape} from a JSON Schema object node's `properties` /\n * `required` / `additionalProperties` keywords — the object-specialized branch\n * of {@link buildShapeFromNode}.\n *\n * @remarks\n * `properties` (when a record) contributes one child shape per own key, capped\n * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}\n * unless it appears as a string entry of `required`. A property whose value is\n * not itself a record widens to {@link jsonShape}. `additionalProperties`:\n * `false` closes the object; a record value recurses into it (`objectShape`\n * validates extras against that shape); anything else — `true`, absent, or\n * malformed — leaves the object OPEN (`true`), matching JSON Schema's own\n * absent-means-open default and the fact that {@link valueToSchema} /\n * {@link samplesToSchema} always emit the keyword explicitly, so an absent\n * value only arises from a hand-written schema. When `properties` has MORE\n * keys than {@link INFER_BREADTH_LIMIT}, the schema's own\n * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —\n * a dropped key's value could otherwise fail a `false` or record-valued rest\n * shape it was never checked against — mirroring `inferObject`'s\n * `truncated ? true : !closed` rule (inferers.ts:485). The accumulator uses a\n * null-prototype record so a property literally named `__proto__` becomes an\n * own data key rather than mutating the prototype, mirroring\n * {@link inferObject} (inferers.ts).\n *\n * @param schema - The object schema node\n * @param depth - Remaining descent budget passed to child properties\n * @param visited - The ancestor set guarding against cycles — recursion\n * state owned by the {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakSet` changes cycle-detection behavior and is not\n * supported usage\n * @param memo - A per-call `(schema node, remaining depth) → shape` cache —\n * recursion state owned by the {@link schemaToShape} entry point; passing\n * a shared or pre-populated `WeakMap` changes caching behavior and is not\n * supported usage\n * @param description - The node's already-extracted `description`, if any\n * @returns The built object shape\n *\n * @example\n * ```ts\n * buildObjectShape(\n * \t{ type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },\n * \tINFER_DEPTH_LIMIT,\n * \tnew WeakSet(),\n * \tnew WeakMap(),\n * \tundefined,\n * )\n * // objectShape({ id: integerShape() }, { additionalProperties: true })\n * ```\n */\nexport function buildObjectShape(\n\tschema: JSONSchema,\n\tdepth: number,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, ContractShape>>,\n\tdescription: string | undefined,\n): ContractShape {\n\tconst propertiesSource = isRecord(schema.properties) ? schema.properties : undefined\n\tconst requiredSource = isArray(schema.required)\n\t\t? schema.required.filter((entry): entry is string => isString(entry))\n\t\t: []\n\t// Honest typing: a null-prototype accumulator so a property literally\n\t// named '__proto__' becomes an own data key instead of mutating the\n\t// prototype — the same pattern inferObject uses (inferers.ts).\n\tconst properties: Record<string, ContractShape> = Object.create(null)\n\tlet truncated = false\n\tif (propertiesSource) {\n\t\tconst allKeys = Object.keys(propertiesSource)\n\t\ttruncated = allKeys.length > INFER_BREADTH_LIMIT\n\t\tconst keys = allKeys.slice(0, INFER_BREADTH_LIMIT)\n\t\tfor (const key of keys) {\n\t\t\tconst child = propertiesSource[key]\n\t\t\tconst childShape = isRecord(child)\n\t\t\t\t? schemaNodeToShape(child, depth - 1, visited, memo)\n\t\t\t\t: jsonShape()\n\t\t\tproperties[key] = requiredSource.includes(key) ? childShape : optionalShape(childShape)\n\t\t}\n\t}\n\tconst extra = schema.additionalProperties\n\tconst additionalProperties: boolean | ContractShape = truncated\n\t\t? true\n\t\t: extra === false\n\t\t\t? false\n\t\t\t: isRecord(extra)\n\t\t\t\t? schemaNodeToShape(extra, depth - 1, visited, memo)\n\t\t\t\t: true\n\treturn objectShape(properties, { additionalProperties, description })\n}\n\n/**\n * Build a {@link ContractShape} for one JSON Schema node — the recursive\n * spine of {@link schemaToShape}, shared with per-child recursion via\n * {@link schemaNodeToShape}.\n *\n * @remarks\n * Every keyword is read defensively (the node's static `JSONSchema` type is\n * NOT trusted at runtime — a caller-supplied node may be adversarial), so a\n * malformed keyword falls through to the next rule instead of throwing.\n * Precedence, top-down:\n *\n * 1. `enum` — an array with at least one string/number/boolean entry (finite\n * numbers only) becomes a {@link literalShape} over the filtered entries.\n * Non-primitive / non-finite entries are dropped; an empty result falls\n * through.\n * 2. `oneOf` — an array with at least one record entry becomes an\n * {@link oneOfShape} over the recursively-built variants, provided the\n * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the\n * limit, building a subset union would be strictly narrower than the\n * schema's full union (a value matching only a dropped variant would be\n * wrongly rejected), so the whole node widens to {@link jsonShape} instead\n * of sampling a subset.\n * 3. `anyOf` — identically, via {@link unionShape}.\n * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —\n * the matching primitive shape, with length/range bounds derived via\n * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node\n * additionally drops its bounds when they describe an EMPTY integer range\n * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`\n * rejects — so the result is always a valid shape.\n * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into\n * a record-valued `items` (widening to {@link jsonShape} otherwise), with\n * bounds from `minItems` / `maxItems`.\n * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a\n * record-valued `properties` — delegates to {@link buildObjectShape}.\n * 7. Everything else — an empty schema, an unrecognized/absent `type`,\n * exhausted depth/breadth, or an attempt failure — widens to\n * {@link jsonShape} (the exact inverse of `compileSchema(jsonShape())`,\n * and where the inferers themselves bottom out at their own limits).\n *\n * `format` and `pattern` are NEVER read into the compiled shape — `format` is\n * annotation-only and `pattern` compiling an attacker-supplied string into a\n * `RegExp` is a ReDoS vector. `description`, when a string, carries through to\n * the produced shape's `description` option.\n *\n * @param schema - The schema node to convert\n * @param depth - Remaining descent budget (0 halts recursion with `jsonShape()`)\n * @param visited - The ancestor set guarding against cycles — recursion\n * state owned by the {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakSet` changes cycle-detection behavior and is not\n * supported usage\n * @param memo - A per-call `(schema node, remaining depth) → shape` cache\n * guarding against exponential re-conversion of a\n * shared-reference schema DAG — recursion state owned by the\n * {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakMap` changes caching behavior and is not\n * supported usage\n * @returns The built shape for `schema`\n *\n * @example\n * ```ts\n * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())\n * // stringShape({ min: 1 })\n * ```\n */\nexport function buildShapeFromNode(\n\tschema: JSONSchema,\n\tdepth: number,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, ContractShape>>,\n): ContractShape {\n\tconst description = isString(schema.description) ? schema.description : undefined\n\n\tif (isArray(schema.enum)) {\n\t\tconst literals = schema.enum.filter(\n\t\t\t(entry): entry is string | number | boolean =>\n\t\t\t\tisString(entry) || isFiniteNumber(entry) || isBoolean(entry),\n\t\t)\n\t\tif (literals.length > 0) return literalShape(literals, { description })\n\t}\n\n\tif (isArray(schema.oneOf)) {\n\t\tconst records = schema.oneOf.filter((entry): entry is JSONSchema => isRecord(entry))\n\t\tif (records.length > INFER_BREADTH_LIMIT) return jsonShape({ description })\n\t\tconst variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo))\n\t\tif (variants.length > 0) return oneOfShape(...variants)\n\t}\n\n\tif (isArray(schema.anyOf)) {\n\t\tconst records = schema.anyOf.filter((entry): entry is JSONSchema => isRecord(entry))\n\t\tif (records.length > INFER_BREADTH_LIMIT) return jsonShape({ description })\n\t\tconst variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo))\n\t\tif (variants.length > 0) return unionShape(...variants)\n\t}\n\n\tconst type = isString(schema.type) ? schema.type : undefined\n\n\tif (type === 'string') {\n\t\tconst bounds = deriveLengthBounds(schema.minLength, schema.maxLength)\n\t\treturn stringShape({ min: bounds.min, max: bounds.max, description })\n\t}\n\tif (type === 'number') {\n\t\tconst bounds = deriveRangeBounds(schema.minimum, schema.maximum)\n\t\treturn numberShape({ min: bounds.min, max: bounds.max, description })\n\t}\n\tif (type === 'integer') {\n\t\tconst bounds = deriveRangeBounds(schema.minimum, schema.maximum)\n\t\tconst emptyRange =\n\t\t\tMath.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) >\n\t\t\tMath.floor(bounds.max ?? Number.POSITIVE_INFINITY)\n\t\treturn integerShape(\n\t\t\temptyRange ? { description } : { min: bounds.min, max: bounds.max, description },\n\t\t)\n\t}\n\tif (type === 'boolean') return booleanShape({ description })\n\tif (type === 'null') return nullShape({ description })\n\n\tif (type === 'array') {\n\t\tconst items = isRecord(schema.items)\n\t\t\t? schemaNodeToShape(schema.items, depth - 1, visited, memo)\n\t\t\t: jsonShape()\n\t\tconst bounds = deriveLengthBounds(schema.minItems, schema.maxItems)\n\t\treturn arrayShape(items, { min: bounds.min, max: bounds.max, description })\n\t}\n\n\tif (type === 'object' || (type === undefined && isRecord(schema.properties))) {\n\t\treturn buildObjectShape(schema, depth, visited, memo, description)\n\t}\n\n\treturn jsonShape({ description })\n}\n\n/**\n * Convert one JSON Schema node into a {@link ContractShape} — the recursion\n * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for\n * every child (`items`, `properties` values, `additionalProperties`,\n * `oneOf` / `anyOf` variants).\n *\n * @remarks\n * Total: never throws. Guards depth exhaustion, a non-record node (the\n * node's static `JSONSchema` type is not trusted at runtime), and a cyclic\n * re-encounter of `schema` — all three widen to {@link jsonShape}. The\n * ancestor set is added to and removed from around the WHOLE subtree\n * conversion (not permanently), so a DAG-shaped schema reached twice via two\n * different, non-cyclic paths does not false-positive as a cycle. The\n * subtree conversion itself runs inside {@link attempt}, so a hostile\n * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error\n * — it degrades to {@link jsonShape} instead. A same-node re-conversion at\n * the same remaining `depth` is served from `memo` (guards a\n * shared-reference schema DAG against exponential blowup), mirroring\n * {@link inferObject} / {@link inferArray} (inferers.ts).\n *\n * @param schema - The schema node to convert\n * @param depth - Remaining descent budget\n * @param visited - The ancestor set guarding against cycles — recursion\n * state owned by the {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakSet` changes cycle-detection behavior and is not\n * supported usage\n * @param memo - A per-call `(schema node, remaining depth) → shape` cache —\n * recursion state owned by the {@link schemaToShape} entry point; passing\n * a shared or pre-populated `WeakMap` changes caching behavior and is not\n * supported usage\n * @returns The built shape for `schema`, or {@link jsonShape} on any failure\n *\n * @example\n * ```ts\n * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())\n * // booleanShape()\n * ```\n */\nexport function schemaNodeToShape(\n\tschema: JSONSchema,\n\tdepth: number,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, ContractShape>>,\n): ContractShape {\n\tif (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return jsonShape()\n\tconst cached = memo.get(schema)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(schema)\n\tconst outcome = attempt(() => buildShapeFromNode(schema, depth, visited, memo))\n\tvisited.delete(schema)\n\tconst shape = outcome.success ? outcome.value : jsonShape()\n\tlet depths = memo.get(schema)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(schema, depths)\n\t}\n\tdepths.set(depth, shape)\n\treturn shape\n}\n\n/**\n * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}\n * — the inverse of {@link compileSchema}, and the validating sibling of\n * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).\n *\n * @remarks\n * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or\n * outright hostile (throwing-getter Proxy) `schema` value all degrade to\n * {@link jsonShape} rather than escaping as an error, so\n * `createContract(schemaToShape(x))` is safe to call for any `x`. See\n * {@link buildShapeFromNode} for the exact per-keyword precedence.\n *\n * `format` and `pattern` are NEVER asserted by the compiled shape — `format`\n * is annotation-only (per the JSON Schema spec, it never narrows validation\n * on its own) and compiling an attacker-controlled `pattern` string into a\n * `RegExp` is a ReDoS vector; both keywords are read only far enough to be\n * ignored. Any node the walk cannot express — an empty `{}`, an\n * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a\n * cyclic re-encounter — widens to {@link jsonShape} (accept any JSON), never\n * narrows: the round trip `compileGuard(schemaToShape(valueToSchema(v)))(v)`\n * holds for every `v`, with widening as the only source of looseness.\n *\n * @param schema - The JSON Schema value to convert\n * @returns The built {@link ContractShape}\n *\n * @example\n * ```ts\n * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }])\n * const contract = createContract(schemaToShape(schema))\n * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' }\n * contract.parse({ id: 'nope' }) // undefined\n * ```\n */\nexport function schemaToShape(schema: JSONSchema): ContractShape {\n\treturn schemaNodeToShape(schema, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBAA+C,O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iBAAiB,QAAQ,OAAO,SAAS,MAAM,WAAW;CAGlE,OAAO,UAAU,EAAE,YAAY,CAAC;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,kBACf,QACA,OACA,SACA,MACgB;CAChB,IAAI,EAAE,QAAQ,MAAM,CAAC,SAAS,MAAM,KAAK,QAAQ,IAAI,MAAM,GAAG,OAAO,UAAU;CAC/E,MAAM,SAAS,KAAK,IAAI,MAAM,CAAC,EAAE,IAAI,KAAK;CAC1C,IAAI,QAAQ,OAAO;CACnB,QAAQ,IAAI,MAAM;CAClB,MAAM,UAAU,cAAc,mBAAmB,QAAQ,OAAO,SAAS,IAAI,CAAC;CAC9E,QAAQ,OAAO,MAAM;CACrB,MAAM,QAAQ,QAAQ,UAAU,QAAQ,QAAQ,UAAU;CAC1D,IAAI,SAAS,KAAK,IAAI,MAAM;CAC5B,IAAI,CAAC,QAAQ;EACZ,yBAAS,IAAI,IAAI;EACjB,KAAK,IAAI,QAAQ,MAAM;CACxB;CACA,OAAO,IAAI,OAAO,KAAK;CACvB,OAAO;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,cAAc,QAAmC;CAChE,OAAO,kBAAkB,QAAA,oBAA2B,IAAI,QAAQ,mBAAG,IAAI,QAAQ,CAAC;AACjF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/cloners.ts","../../../src/core/combinators.ts","../../../src/core/parsers.ts","../../../src/core/compilers.ts","../../../src/core/inferers.ts","../../../src/core/shapers.ts"],"sourcesContent":["import type { JSONSchemaType } from './types.js'\n\n// JSON-related constants. Kept as plain frozen data so the shipped combinators\n// and parsers operate on them directly — there is deliberately no bespoke\n// JSON-Schema guard (AGENTS §14 — the deep recursive validators stay out by\n// design).\n\n/**\n * The seven standard JSON Schema `type` names, frozen.\n *\n * @remarks\n * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose\n * it with the shipped primitives instead of reaching for a bespoke guard:\n * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and\n * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`\n * is the parser.\n *\n * @example\n * ```ts\n * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'\n *\n * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>\n * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined\n * ```\n */\nexport const JSON_SCHEMA_TYPES: readonly JSONSchemaType[] = Object.freeze([\n\t'null',\n\t'boolean',\n\t'object',\n\t'array',\n\t'number',\n\t'integer',\n\t'string',\n])\n\n// Reporting-surface bounds (`compileReporter` / `ContractInterface.explain`).\n\n/**\n * The maximum number of {@link Fault} entries a single `explain` report ever\n * returns, frozen.\n *\n * @remarks\n * Bounds the report against adversarial input (a giant array, a wide record) —\n * `compileReporter` collects faults in stable pre-order and stops once this cap\n * is reached, so the report size (and the work to build it) stays finite and\n * deterministic regardless of the input's size.\n */\nexport const FAULT_LIMIT = 64\n\n/**\n * The maximum character length of a {@link preview}-rendered string, frozen.\n *\n * @remarks\n * A previewed string longer than this is clipped with a trailing `…` so a\n * {@link Fault}'s `received` field never embeds an unbounded amount of\n * untrusted text.\n */\nexport const PREVIEW_LIMIT = 64\n\n// Runtime recursion and generation bounds.\n\n/**\n * The maximum number of active {@link lazyOf} invocations for one lazy guard,\n * frozen.\n *\n * @remarks\n * Bounds explicitly recursive guards before the JavaScript call stack becomes\n * the limiting mechanism. An invocation beyond this depth returns `false`, and\n * the counter unwinds after every contained guard call.\n *\n * @example\n * ```ts\n * GUARD_DEPTH_LIMIT // 512\n * ```\n */\nexport const GUARD_DEPTH_LIMIT = 512\n\n/**\n * The maximum supported nesting depth of a compiled contract shape, frozen.\n *\n * @remarks\n * {@link validateShape} rejects the next level with a depth-coded\n * {@link ContractError} before recursive artifact compilation begins, so a\n * finite but pathologically deep developer-authored shape fails predictably\n * instead of reaching the JavaScript call-stack limit.\n *\n * @example\n * ```ts\n * COMPILE_DEPTH_LIMIT // 512\n * ```\n */\nexport const COMPILE_DEPTH_LIMIT = 512\n\n/**\n * The maximum number of candidate-generation attempts for a constrained\n * generated value, frozen.\n *\n * @remarks\n * Provides one deterministic work bound for generators that must retry a\n * candidate against a contract constraint.\n *\n * @example\n * ```ts\n * GENERATION_ATTEMPT_LIMIT // 32\n * ```\n */\nexport const GENERATION_ATTEMPT_LIMIT = 32\n\n// Value-to-schema inference bounds (`valueToSchema` / `samplesToSchema`).\n\n/**\n * The default maximum object/array nesting depth {@link valueToSchema} walks,\n * frozen.\n *\n * @remarks\n * Bounds inference against adversarial or cyclic runtime input — once the\n * remaining depth budget reaches zero, inference stops descending and emits\n * the empty accept-anything schema `{}` for that branch instead of recursing\n * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.\n */\nexport const INFER_DEPTH_LIMIT = 32\n\n/**\n * The default maximum number of object properties / array elements\n * {@link valueToSchema} samples per container, frozen.\n *\n * @remarks\n * Bounds the work (and the emitted schema's size) against a wide record or a\n * huge array — properties/elements beyond this cap are never inspected.\n * Overridable per call via {@link ValueToSchemaOptions.maxProperties}.\n */\nexport const INFER_BREADTH_LIMIT = 256\n\n/**\n * The default maximum number of distinct values a multi-sample slot may hold\n * before enum inference gives up and falls back to a bare `type`, frozen.\n *\n * @remarks\n * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}\n * will emit — a slot with distinct-value count at or above this limit is\n * treated as unbounded (an ID column, not a category) and never gets an\n * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}\n * (which gates whether enum inference runs at all).\n */\nexport const INFER_ENUM_LIMIT = 12\n\n/**\n * The maximum string length {@link stringToFormat} attempts to classify,\n * frozen.\n *\n * @remarks\n * Bounds per-string format-detection work: a value longer than this returns\n * `undefined` immediately, before any pattern match runs. 128 sits\n * comfortably above the longest real format token — an RFC 3339 date-time\n * with fractional seconds and a UTC offset — so no legitimate classification\n * changes; only pathologically long strings (a multi-megabyte payload passed\n * as a candidate email/URI) are skipped.\n */\nexport const FORMAT_MAX_LENGTH = 128\n\n/**\n * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats\n * (`uuid` / `email` / `uri`), frozen as data.\n *\n * @remarks\n * The ISO-8601 date/time formats are NOT listed here — they additionally\n * require an attempt-guarded `Date` validity check, so their pattern lives\n * inline in `stringToFormat` rather than as reusable standalone data.\n */\nexport const FORMAT_PATTERNS: Readonly<Record<'uuid' | 'email' | 'uri', RegExp>> = Object.freeze({\n\tuuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n\temail: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n\turi: /^[a-z][a-z0-9+.-]*:\\/\\//i,\n})\n","import type { ContractErrorContext, ContractErrorOptions } from './types.js'\n\n/**\n * Error carrying a machine-readable contract category and optional context.\n *\n * @example\n * ```ts\n * const error = new ContractError('Minimum exceeds maximum', {\n * \tcode: 'range',\n * \tcontext: { path: ['properties', 'age'] },\n * })\n * ```\n */\nexport class ContractError extends Error {\n\toverride readonly name = 'ContractError'\n\treadonly code\n\treadonly context: ContractErrorContext | undefined\n\n\t/**\n\t * Create a contract error.\n\t *\n\t * @param message - Human-readable error description\n\t * @param options - Machine-readable category, optional context, and optional cause\n\t */\n\tconstructor(message: string, options: ContractErrorOptions) {\n\t\tconst cause = options.cause\n\t\tsuper(message, cause === undefined ? undefined : { cause })\n\t\tthis.code = options.code\n\t\tthis.context = options.context\n\t}\n}\n\n/**\n * Determine whether an unknown value is a {@link ContractError}.\n *\n * @param value - The value to inspect\n * @returns `true` only when the value is a `ContractError`\n *\n * @example\n * ```ts\n * isContractError(new ContractError('Invalid shape', { code: 'placement' })) // true\n * isContractError(new Error('Invalid shape')) // false\n * ```\n */\nexport function isContractError(value: unknown): value is ContractError {\n\ttry {\n\t\treturn value instanceof ContractError\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type {\n\tAnyAsyncFunction,\n\tAnyConstructor,\n\tAnyFunction,\n\tJSONPrimitive,\n\tJSONValue,\n\tZeroArgAsyncFunction,\n\tZeroArgFunction,\n} from './types.js'\nimport { enumerableSymbolCount, holds, matchesJSONValue } from './helpers.js'\n\n// AGENTS §14: guards are total functions — a guard NEVER throws. Adversarial\n// input (hostile getters, exotic objects, cycles) returns `false`, never an\n// error. Guards built from a single `typeof` / strict-equality test are\n// immediately total — no probe of the value's internals can throw. Every\n// OTHER guard here probes the value in some way — a property read through\n// `Reflect.get`, a structural walk (`isPromiseLike`, `isIterable`,\n// `isAsyncIterable`, `isJSONValue`, `isRecord`), an `instanceof` check (which\n// invokes the target's `[Symbol.hasInstance]` / triggers a `getPrototypeOf`\n// trap), or an own-key enumeration (`isEmptyObject` / `isNonEmptyObject`) —\n// so a hostile getter, a revoked `Proxy`, or an exotic trap can throw\n// mid-probe. Totality is NOT automatic for these: each contains its whole\n// probe/walk in `holds` (see ./helpers.js) and returns `false` on a caught\n// throw. Every `instanceof`-based guard in this file routes through the\n// shared {@link isInstance} helper, which is the one place that containment\n// lives for that family.\n\n// === Primitive guards\n\n/** Determine whether a value is `null`.\n *\n * @example\n * ```ts\n * isNull(null) // true\n * isNull(undefined) // false\n * ```\n */\nexport function isNull(value: unknown): value is null {\n\treturn value === null\n}\n\n/** Determine whether a value is `undefined`.\n *\n * @example\n * ```ts\n * isUndefined(undefined) // true\n * isUndefined(null) // false\n * ```\n */\nexport function isUndefined(value: unknown): value is undefined {\n\treturn value === undefined\n}\n\n/** Determine whether a value is defined (neither `null` nor `undefined`).\n *\n * @example\n * ```ts\n * isDefined('hi') // true\n * isDefined(null) // false\n * isDefined(undefined) // false\n * ```\n */\nexport function isDefined<T>(value: T | null | undefined): value is T {\n\treturn value !== null && value !== undefined\n}\n\n/** Determine whether a value is a string.\n *\n * @example\n * ```ts\n * isString('hi') // true\n * isString(42) // false\n * ```\n */\nexport function isString(value: unknown): value is string {\n\treturn typeof value === 'string'\n}\n\n/**\n * Determine whether a value is a number.\n *\n * @remarks\n * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.\n *\n * @example\n * ```ts\n * isNumber(42) // true\n * isNumber(Number.NaN) // true — NaN is still a number\n * isNumber('42') // false\n * ```\n */\nexport function isNumber(value: unknown): value is number {\n\treturn typeof value === 'number'\n}\n\n/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).\n *\n * @example\n * ```ts\n * isFiniteNumber(42) // true\n * isFiniteNumber(Number.NaN) // false\n * isFiniteNumber(Infinity) // false\n * ```\n */\nexport function isFiniteNumber(value: unknown): value is number {\n\treturn typeof value === 'number' && Number.isFinite(value)\n}\n\n/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).\n *\n * @example\n * ```ts\n * isInteger(3) // true\n * isInteger(3.5) // false\n * ```\n */\nexport function isInteger(value: unknown): value is number {\n\treturn Number.isInteger(value)\n}\n\n/** Determine whether a value is a boolean.\n *\n * @example\n * ```ts\n * isBoolean(true) // true\n * isBoolean(1) // false\n * ```\n */\nexport function isBoolean(value: unknown): value is boolean {\n\treturn typeof value === 'boolean'\n}\n\n/** Determine whether a value is exactly `true`.\n *\n * @example\n * ```ts\n * isTrue(true) // true\n * isTrue(false) // false\n * ```\n */\nexport function isTrue(value: unknown): value is true {\n\treturn value === true\n}\n\n/** Determine whether a value is exactly `false`.\n *\n * @example\n * ```ts\n * isFalse(false) // true\n * isFalse(true) // false\n * ```\n */\nexport function isFalse(value: unknown): value is false {\n\treturn value === false\n}\n\n/** Determine whether a value is a bigint.\n *\n * @example\n * ```ts\n * isBigInt(1n) // true\n * isBigInt(1) // false\n * ```\n */\nexport function isBigInt(value: unknown): value is bigint {\n\treturn typeof value === 'bigint'\n}\n\n/** Determine whether a value is a symbol.\n *\n * @example\n * ```ts\n * isSymbol(Symbol('x')) // true\n * isSymbol('x') // false\n * ```\n */\nexport function isSymbol(value: unknown): value is symbol {\n\treturn typeof value === 'symbol'\n}\n\n/** Determine whether a value is callable.\n *\n * @example\n * ```ts\n * isFunction(() => {}) // true\n * isFunction({}) // false\n * ```\n */\nexport function isFunction(value: unknown): value is AnyFunction {\n\treturn typeof value === 'function'\n}\n\n/** Determine whether a value is a string or `null`.\n *\n * @example\n * ```ts\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function isNullableString(value: unknown): value is string | null {\n\treturn value === null || isString(value)\n}\n\n/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).\n *\n * @example\n * ```ts\n * isNullableNumber(42) // true\n * isNullableNumber(null) // true\n * isNullableNumber('hi') // false\n * ```\n */\nexport function isNullableNumber(value: unknown): value is number | null {\n\treturn value === null || isNumber(value)\n}\n\n/** Determine whether a value is a boolean or `null`.\n *\n * @example\n * ```ts\n * isNullableBoolean(true) // true\n * isNullableBoolean(null) // true\n * isNullableBoolean(1) // false\n * ```\n */\nexport function isNullableBoolean(value: unknown): value is boolean | null {\n\treturn value === null || isBoolean(value)\n}\n\n// === Built-in guards\n//\n// The `instanceof`-based guard families below (Date/RegExp/Error/Promise,\n// Map/Set/WeakMap/WeakSet, the typed-array guards) are same-realm checks:\n// `instanceof` compares against the constructor's prototype in the CURRENT\n// realm, so a value built by another realm (a different `vm.Context`, iframe,\n// or worker global) fails even when it is structurally identical. This is a\n// known, accepted limitation — cross-realm identity would require duck-typing\n// every built-in, which trades soundness for portability.\n\n/**\n * Determine whether a value is an instance of a constructor, contained against\n * a throwing `instanceof` check.\n *\n * @remarks\n * The low-level total helper every `instanceof`-based guard in this file (and\n * the `instanceOf` combinator) routes through. A bare `value instanceof X` is\n * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a\n * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when\n * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This\n * wraps the check in {@link holds} (see ./helpers.js) so any such throw\n * yields `false` instead of escaping.\n *\n * @param value - The value to test\n * @param ctor - The constructor to test against\n * @returns `true` when `value instanceof ctor`, `false` on a non-match or a\n * contained throw\n *\n * @example\n * ```ts\n * isInstance(new Date(), Date) // true\n * isInstance({}, Date) // false\n * ```\n */\nexport function isInstance<C>(\n\tvalue: unknown,\n\tctor: C,\n): value is InstanceType<C & AnyConstructor<object>> {\n\t// `ctor` is narrowed to a function through `isFunction` before the `instanceof`\n\t// check — an unconstrained generic RHS loses TS's built-in instanceof leniency\n\t// once nested inside another generic call (the `holds` callback), so the\n\t// narrowing keeps this call legal without a constraint that would reject\n\t// combinators.ts's `instanceOf`, which validates `ctor` separately.\n\tconst target: unknown = ctor\n\treturn holds(() => isFunction(target) && value instanceof target)\n}\n\n/** Determine whether a value is a `Date`.\n *\n * @example\n * ```ts\n * isDate(new Date()) // true\n * isDate('2024-01-01') // false\n * ```\n */\nexport function isDate(value: unknown): value is Date {\n\treturn isInstance(value, Date)\n}\n\n/** Determine whether a value is a `RegExp`.\n *\n * @example\n * ```ts\n * isRegExp(/a/) // true\n * isRegExp('a') // false\n * ```\n */\nexport function isRegExp(value: unknown): value is RegExp {\n\treturn isInstance(value, RegExp)\n}\n\n/** Determine whether a value is an `Error`.\n *\n * @example\n * ```ts\n * isError(new Error('boom')) // true\n * isError('boom') // false\n * ```\n */\nexport function isError(value: unknown): value is Error {\n\treturn isInstance(value, Error)\n}\n\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve()) // true\n * isPromise({ then() {} }) // false\n * ```\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n\treturn isInstance(value, Promise)\n}\n\n/**\n * Determine whether a value is promise-like — an object exposing callable\n * `then`, `catch`, and `finally` methods.\n *\n * @remarks\n * Accepts any object with all three methods, not only native `Promise`\n * instances. Use {@link isPromise} when you specifically need `instanceof Promise`.\n *\n * @example\n * ```ts\n * isPromiseLike(Promise.resolve()) // true\n * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true\n * isPromiseLike({ then() {} }) // false\n * ```\n */\nexport function isPromiseLike<T = unknown>(\n\tvalue: unknown,\n): value is Promise<T> | (PromiseLike<T> & { catch: unknown; finally: unknown }) {\n\treturn holds(() => {\n\t\tif (!isObject(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst thenValue = Reflect.get(value, 'then')\n\t\tconst catchValue = Reflect.get(value, 'catch')\n\t\tconst finallyValue = Reflect.get(value, 'finally')\n\t\treturn isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue)\n\t})\n}\n\n/** Determine whether a value is an `ArrayBuffer`.\n *\n * @example\n * ```ts\n * isArrayBuffer(new ArrayBuffer(8)) // true\n * isArrayBuffer([]) // false\n * ```\n */\nexport function isArrayBuffer(value: unknown): value is ArrayBuffer {\n\treturn isInstance(value, ArrayBuffer)\n}\n\n/**\n * Determine whether a value is a `SharedArrayBuffer`.\n *\n * @remarks\n * Guards the global existence of `SharedArrayBuffer` first — safe where it is\n * absent or disabled (e.g. a context that is not cross-origin isolated).\n *\n * @example\n * ```ts\n * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true\n * isSharedArrayBuffer(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n\treturn typeof SharedArrayBuffer !== 'undefined' && isInstance(value, SharedArrayBuffer)\n}\n\n// === Protocol guards\n\n/**\n * Determine whether a value implements the iterable protocol (`Symbol.iterator`).\n *\n * @remarks\n * Strings are explicitly included: a string has a callable `Symbol.iterator`\n * but is not an object, so the generic object path alone would miss it.\n *\n * @example\n * ```ts\n * isIterable([1, 2]) // true\n * isIterable('abc') // true\n * isIterable({ a: 1 }) // false\n * ```\n */\nexport function isIterable<T = unknown>(value: unknown): value is Iterable<T> {\n\treturn holds(() => {\n\t\tif (isString(value)) {\n\t\t\treturn true\n\t\t}\n\t\treturn isObject(value) && isFunction(Reflect.get(value, Symbol.iterator))\n\t})\n}\n\n/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).\n *\n * @example\n * ```ts\n * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true\n * isAsyncIterable([1, 2]) // false\n * ```\n */\nexport function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T> {\n\treturn holds(() => isObject(value) && isFunction(Reflect.get(value, Symbol.asyncIterator)))\n}\n\n// === Object & collection guards\n\n/**\n * Determine whether a value is a non-null object.\n *\n * @remarks\n * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use\n * {@link isRecord} when you need a plain-record check.\n *\n * @example\n * ```ts\n * isObject({}) // true\n * isObject([]) // true\n * isObject(null) // false\n * ```\n */\nexport function isObject(value: unknown): value is object {\n\treturn typeof value === 'object' && value !== null\n}\n\n/**\n * Determine whether a value is a plain record (object literal or null-prototype),\n * not an array or class instance.\n *\n * @remarks\n * Use instead of {@link isObject} to distinguish a plain `{}` /\n * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain\n * test is realm-agnostic: rather than comparing against the current realm's\n * `Object.prototype` (which a plain object from another `vm.Context`, iframe,\n * or worker would fail), it accepts any value whose prototype is `null`, OR\n * whose prototype's own prototype is `null` — the shape every plain object\n * has in every realm, since `Object.prototype` itself always sits one step\n * above `null`. Arrays and class instances are still rejected: an array's\n * prototype chain runs through `Array.prototype` before `null`, and a class\n * instance's runs through the class's own prototype. The whole body runs\n * inside `holds` (AGENTS §14) so a revoked `Proxy` or a hostile\n * `getPrototypeOf` trap cannot escape as a thrown error.\n *\n * @example\n * ```ts\n * isRecord({ a: 1 }) // true\n * isRecord(Object.create(null)) // true\n * isRecord([]) // false\n * isRecord(new Date()) // false\n * ```\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn holds(() => {\n\t\tif (!isObject(value) || isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\treturn prototype === null || Object.getPrototypeOf(prototype) === null\n\t})\n}\n\n/** Determine whether a value is a `Map`.\n *\n * @example\n * ```ts\n * isMap(new Map()) // true\n * isMap({}) // false\n * ```\n */\nexport function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V> {\n\treturn isInstance(value, Map)\n}\n\n/** Determine whether a value is a `Set`.\n *\n * @example\n * ```ts\n * isSet(new Set()) // true\n * isSet([]) // false\n * ```\n */\nexport function isSet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isInstance(value, Set)\n}\n\n/** Determine whether a value is a `WeakMap`.\n *\n * @example\n * ```ts\n * isWeakMap(new WeakMap()) // true\n * isWeakMap({}) // false\n * ```\n */\nexport function isWeakMap(value: unknown): value is WeakMap<object, unknown> {\n\treturn isInstance(value, WeakMap)\n}\n\n/** Determine whether a value is a `WeakSet`.\n *\n * @example\n * ```ts\n * isWeakSet(new WeakSet()) // true\n * isWeakSet({}) // false\n * ```\n */\nexport function isWeakSet(value: unknown): value is WeakSet<object> {\n\treturn isInstance(value, WeakSet)\n}\n\n// === Array & typed-array guards\n\n/** Determine whether a value is an array.\n *\n * @example\n * ```ts\n * isArray([1, 2]) // true\n * isArray('12') // false\n * ```\n */\nexport function isArray<T = unknown>(value: unknown): value is readonly T[] {\n\treturn holds(() => Array.isArray(value))\n}\n\n/** Determine whether a value is a `DataView`.\n *\n * @example\n * ```ts\n * isDataView(new DataView(new ArrayBuffer(8))) // true\n * isDataView(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isDataView(value: unknown): value is DataView<ArrayBufferLike> {\n\treturn isInstance(value, DataView)\n}\n\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).\n *\n * @example\n * ```ts\n * isArrayBufferView(new Uint8Array(4)) // true\n * isArrayBufferView([1, 2, 3, 4]) // false\n * ```\n */\nexport function isArrayBufferView(value: unknown): value is ArrayBufferView {\n\treturn holds(() => ArrayBuffer.isView(value))\n}\n\n/** Determine whether a value is an `Int8Array`.\n *\n * @example\n * ```ts\n * isInt8Array(new Int8Array(2)) // true\n * isInt8Array(new Uint8Array(2)) // false\n * ```\n */\nexport function isInt8Array(value: unknown): value is Int8Array {\n\treturn isInstance(value, Int8Array)\n}\n\n/** Determine whether a value is a `Uint8Array`.\n *\n * @example\n * ```ts\n * isUint8Array(new Uint8Array(2)) // true\n * isUint8Array(new Int8Array(2)) // false\n * ```\n */\nexport function isUint8Array(value: unknown): value is Uint8Array {\n\treturn isInstance(value, Uint8Array)\n}\n\n/** Determine whether a value is a `Uint8ClampedArray`.\n *\n * @example\n * ```ts\n * isUint8ClampedArray(new Uint8ClampedArray(2)) // true\n * isUint8ClampedArray(new Uint8Array(2)) // false\n * ```\n */\nexport function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray {\n\treturn isInstance(value, Uint8ClampedArray)\n}\n\n/** Determine whether a value is an `Int16Array`.\n *\n * @example\n * ```ts\n * isInt16Array(new Int16Array(2)) // true\n * isInt16Array(new Int8Array(2)) // false\n * ```\n */\nexport function isInt16Array(value: unknown): value is Int16Array {\n\treturn isInstance(value, Int16Array)\n}\n\n/** Determine whether a value is a `Uint16Array`.\n *\n * @example\n * ```ts\n * isUint16Array(new Uint16Array(2)) // true\n * isUint16Array(new Int16Array(2)) // false\n * ```\n */\nexport function isUint16Array(value: unknown): value is Uint16Array {\n\treturn isInstance(value, Uint16Array)\n}\n\n/** Determine whether a value is an `Int32Array`.\n *\n * @example\n * ```ts\n * isInt32Array(new Int32Array(2)) // true\n * isInt32Array(new Int16Array(2)) // false\n * ```\n */\nexport function isInt32Array(value: unknown): value is Int32Array {\n\treturn isInstance(value, Int32Array)\n}\n\n/** Determine whether a value is a `Uint32Array`.\n *\n * @example\n * ```ts\n * isUint32Array(new Uint32Array(2)) // true\n * isUint32Array(new Int32Array(2)) // false\n * ```\n */\nexport function isUint32Array(value: unknown): value is Uint32Array {\n\treturn isInstance(value, Uint32Array)\n}\n\n/** Determine whether a value is a `Float32Array`.\n *\n * @example\n * ```ts\n * isFloat32Array(new Float32Array(2)) // true\n * isFloat32Array(new Float64Array(2)) // false\n * ```\n */\nexport function isFloat32Array(value: unknown): value is Float32Array {\n\treturn isInstance(value, Float32Array)\n}\n\n/** Determine whether a value is a `Float64Array`.\n *\n * @example\n * ```ts\n * isFloat64Array(new Float64Array(2)) // true\n * isFloat64Array(new Float32Array(2)) // false\n * ```\n */\nexport function isFloat64Array(value: unknown): value is Float64Array {\n\treturn isInstance(value, Float64Array)\n}\n\n/**\n * Determine whether a value is a `BigInt64Array`.\n *\n * @remarks\n * Guards the global existence of `BigInt64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigInt64Array(new BigInt64Array(2)) // true\n * isBigInt64Array(new Float64Array(2)) // false\n * ```\n */\nexport function isBigInt64Array(value: unknown): value is BigInt64Array {\n\treturn typeof BigInt64Array !== 'undefined' && isInstance(value, BigInt64Array)\n}\n\n/**\n * Determine whether a value is a `BigUint64Array`.\n *\n * @remarks\n * Guards the global existence of `BigUint64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigUint64Array(new BigUint64Array(2)) // true\n * isBigUint64Array(new BigInt64Array(2)) // false\n * ```\n */\nexport function isBigUint64Array(value: unknown): value is BigUint64Array {\n\treturn typeof BigUint64Array !== 'undefined' && isInstance(value, BigUint64Array)\n}\n\n// === Emptiness guards\n\n/** Determine whether a value is the empty string `''`.\n *\n * @example\n * ```ts\n * isEmptyString('') // true\n * isEmptyString('a') // false\n * ```\n */\nexport function isEmptyString(value: unknown): value is '' {\n\treturn isString(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty array.\n *\n * @example\n * ```ts\n * isEmptyArray([]) // true\n * isEmptyArray([1]) // false\n * ```\n */\nexport function isEmptyArray(value: unknown): value is readonly [] {\n\treturn holds(() => isArray(value) && value.length === 0)\n}\n\n/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).\n *\n * @example\n * ```ts\n * isEmptyObject({}) // true\n * isEmptyObject({ a: 1 }) // false\n * ```\n */\nexport function isEmptyObject(value: unknown): value is Record<string | symbol, never> {\n\treturn holds(\n\t\t() => isRecord(value) && Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0,\n\t)\n}\n\n/** Determine whether a value is an empty `Map`.\n *\n * @example\n * ```ts\n * isEmptyMap(new Map()) // true\n * isEmptyMap(new Map([['a', 1]])) // false\n * ```\n */\nexport function isEmptyMap(value: unknown): value is ReadonlyMap<never, never> {\n\treturn holds(() => isMap(value) && value.size === 0)\n}\n\n/** Determine whether a value is an empty `Set`.\n *\n * @example\n * ```ts\n * isEmptySet(new Set()) // true\n * isEmptySet(new Set([1])) // false\n * ```\n */\nexport function isEmptySet(value: unknown): value is ReadonlySet<never> {\n\treturn holds(() => isSet(value) && value.size === 0)\n}\n\n/** Determine whether a value is a non-empty string (at least one character).\n *\n * @example\n * ```ts\n * isNonEmptyString('a') // true\n * isNonEmptyString('') // false\n * ```\n */\nexport function isNonEmptyString(value: unknown): value is string {\n\treturn isString(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty array (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptyArray([1]) // true\n * isNonEmptyArray([]) // false\n * ```\n */\nexport function isNonEmptyArray<T = unknown>(value: unknown): value is readonly [T, ...T[]] {\n\treturn holds(() => isArray<T>(value) && value.length > 0)\n}\n\n/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).\n *\n * @example\n * ```ts\n * isNonEmptyObject({ a: 1 }) // true\n * isNonEmptyObject({}) // false\n * ```\n */\nexport function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown> {\n\treturn holds(\n\t\t() => isRecord(value) && (Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0),\n\t)\n}\n\n/** Determine whether a value is a non-empty `Map` (at least one entry).\n *\n * @example\n * ```ts\n * isNonEmptyMap(new Map([['a', 1]])) // true\n * isNonEmptyMap(new Map()) // false\n * ```\n */\nexport function isNonEmptyMap<K = unknown, V = unknown>(\n\tvalue: unknown,\n): value is ReadonlyMap<K, V> {\n\treturn holds(() => isMap<K, V>(value) && value.size > 0)\n}\n\n/** Determine whether a value is a non-empty `Set` (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptySet(new Set([1])) // true\n * isNonEmptySet(new Set()) // false\n * ```\n */\nexport function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn holds(() => isSet<T>(value) && value.size > 0)\n}\n\n// === Function guards\n\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).\n *\n * @example\n * ```ts\n * isZeroArg(() => {}) // true\n * isZeroArg((a) => a) // false\n * ```\n */\nexport function isZeroArg(value: unknown): value is ZeroArgFunction {\n\treturn holds(() => isFunction(value) && value.length === 0)\n}\n\n/**\n * Determine whether a value is a native `async function`.\n *\n * @remarks\n * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is\n * unreliable across realms. The `?.` keeps the guard total (§14): a function\n * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.\n *\n * @example\n * ```ts\n * isAsyncFunction(async () => {}) // true\n * isAsyncFunction(() => {}) // false\n * ```\n */\nexport function isAsyncFunction(value: unknown): value is AnyAsyncFunction {\n\treturn holds(() => isFunction(value) && value.constructor?.name === 'AsyncFunction')\n}\n\n/** Determine whether a value is a generator function (`function*`).\n *\n * @example\n * ```ts\n * isGeneratorFunction(function* () {}) // true\n * isGeneratorFunction(() => {}) // false\n * ```\n */\nexport function isGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => Generator<unknown, unknown, unknown> {\n\treturn holds(() => isFunction(value) && value.constructor?.name === 'GeneratorFunction')\n}\n\n/** Determine whether a value is an async generator function (`async function*`).\n *\n * @example\n * ```ts\n * isAsyncGeneratorFunction(async function* () {}) // true\n * isAsyncGeneratorFunction(function* () {}) // false\n * ```\n */\nexport function isAsyncGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => AsyncGenerator<unknown, unknown, unknown> {\n\treturn holds(() => isFunction(value) && value.constructor?.name === 'AsyncGeneratorFunction')\n}\n\n/** Determine whether a value is a zero-argument async function.\n *\n * @example\n * ```ts\n * isZeroArgAsync(async () => {}) // true\n * isZeroArgAsync(async (a) => a) // false\n * ```\n */\nexport function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction {\n\treturn isZeroArg(value) && isAsyncFunction(value)\n}\n\n/** Determine whether a value is a zero-argument generator function.\n *\n * @example\n * ```ts\n * isZeroArgGenerator(function* () {}) // true\n * isZeroArgGenerator(function* (a) {}) // false\n * ```\n */\nexport function isZeroArgGenerator(\n\tvalue: unknown,\n): value is () => Generator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isGeneratorFunction(value)\n}\n\n/** Determine whether a value is a zero-argument async generator function.\n *\n * @example\n * ```ts\n * isZeroArgAsyncGenerator(async function* () {}) // true\n * isZeroArgAsyncGenerator(async function* (a) {}) // false\n * ```\n */\nexport function isZeroArgAsyncGenerator(\n\tvalue: unknown,\n): value is () => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isAsyncGeneratorFunction(value)\n}\n\n/**\n * Determine whether a value can be used as a `new`-target constructor.\n *\n * @remarks\n * Probes with `Reflect.construct(String, [], value)`: a real constructor\n * succeeds, while arrow functions, plain functions, and non-functions throw\n * and yield `false`. Never throws. Backs the `instanceOf` combinator.\n *\n * @example\n * ```ts\n * isConstructor(class X {}) // true\n * isConstructor(() => {}) // false\n * ```\n */\nexport function isConstructor(value: unknown): value is AnyConstructor<object> {\n\treturn holds(() => {\n\t\tif (!isFunction(value)) {\n\t\t\treturn false\n\t\t}\n\t\tReflect.construct(String, [], value)\n\t\treturn true\n\t})\n}\n\n// === JSON\n\n/**\n * Determine whether a value is a cycle-safe JSON value.\n *\n * @remarks\n * Total guard: never throws, returns `false` for cycles, functions, `Date`\n * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records\n * are walked with an ancestor set so recursive input fails instead of hanging.\n * The whole walk runs inside `holds` (AGENTS §14): a hostile getter on a\n * record property, or a revoked `Proxy` anywhere in the structure, is caught\n * and yields `false` instead of escaping as a thrown error.\n *\n * @param value - The value to test\n * @returns `true` when the value has a JSON representation\n *\n * @example\n * ```ts\n * isJSONValue({ nested: [1, 'x', null] }) // true\n * isJSONValue(Number.NaN) // false\n * ```\n */\nexport function isJSONValue(value: unknown): value is JSONValue {\n\treturn holds(() => matchesJSONValue(value, new WeakSet()))\n}\n\n/**\n * Determine whether a value is a primitive JSON value.\n *\n * @remarks\n * The flat leaf of any JSON document: `null`, a string, a **finite** number, or\n * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON\n * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.\n *\n * The recursive {@link isJSONValue} guard is shipped and stays total with\n * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and\n * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with\n * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.\n *\n * @param value - The value to test\n * @returns `true` when `value` is `null`, a string, a finite number, or a boolean\n *\n * @example\n * ```ts\n * isJSONPrimitive(null) // true\n * isJSONPrimitive('hi') // true\n * isJSONPrimitive(42) // true\n * isJSONPrimitive(Number.NaN) // false — not representable in JSON\n * isJSONPrimitive({}) // false\n * ```\n */\nexport function isJSONPrimitive(value: unknown): value is JSONPrimitive {\n\treturn isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value)\n}\n","import type {\n\tContractShape,\n\tFaultKind,\n\tFieldPath,\n\tJSONSchema,\n\tRandomFunction,\n\tResult,\n} from './types.js'\nimport { PREVIEW_LIMIT } from './constants.js'\nimport { ContractError } from './errors.js'\nimport {\n\tisBigInt,\n\tisBoolean,\n\tisFiniteNumber,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisString,\n\tisSymbol,\n} from './validators.js'\n\n// === Result helpers\n\n/**\n * Invoke a callback and capture its outcome as a {@link Result}, never letting\n * a throw escape.\n *\n * @remarks\n * The sanctioned never-throw boundary for the guards (AGENTS §14). The\n * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied\n * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a\n * `boolean`. This converts a throwing callback into a `Failure` so the\n * surrounding guard can treat it as a non-match instead of propagating the\n * exception, written once and shared rather than copy-pasted as ad-hoc\n * `try`/`catch`. The sole hand-written exception is {@link isContractError},\n * whose local boundary avoids an `errors` → `helpers` dependency inversion.\n *\n * @param callback - The callback to invoke with no arguments\n * @returns A `Success` carrying the return value, or a `Failure` carrying the\n * thrown reason normalised to an `Error`\n *\n * @example\n * ```ts\n * const outcome = attempt(() => predicate(value))\n * return outcome.success && outcome.value\n * ```\n */\nexport function attempt<T>(callback: () => T): Result<T> {\n\ttry {\n\t\treturn { success: true, value: callback() }\n\t} catch (reason) {\n\t\ttry {\n\t\t\tconst error = reason instanceof Error ? reason : new Error(String(reason))\n\t\t\treturn { success: false, error }\n\t\t} catch {\n\t\t\treturn { success: false, error: new Error('Unknown thrown value') }\n\t\t}\n\t}\n}\n\n/**\n * Invoke a predicate through the sanctioned never-throw boundary.\n *\n * @param callback - The predicate to invoke with no arguments\n * @returns `true` only when the callback returns the boolean value `true`\n *\n * @example\n * ```ts\n * holds(() => value instanceof Widget) // false when inspection throws\n * ```\n */\nexport function holds(callback: () => boolean): boolean {\n\tconst outcome = attempt(callback)\n\treturn outcome.success && outcome.value === true\n}\n\n/**\n * Snapshot an object's own enumerable string keys through a total boundary.\n *\n * @remarks\n * This is the package-wide runtime property view used by compiled object\n * guards, parsers, reporters, schema inference, and owned schema cloning. It\n * matches the object-key view serialized by `JSON.stringify`: inherited,\n * symbol, and non-enumerable properties are excluded. A hostile Proxy trap\n * returns `undefined` rather than escaping.\n *\n * @param value - The object whose keys to snapshot\n * @returns A frozen owned key list, or `undefined` when enumeration throws\n *\n * @example\n * ```ts\n * enumerableKeys({ visible: 1 }) // ['visible']\n * ```\n */\nexport function enumerableKeys(value: object): readonly string[] | undefined {\n\tconst outcome = attempt(() => Object.keys(value))\n\treturn outcome.success ? Object.freeze([...outcome.value]) : undefined\n}\n\n/**\n * Draw and validate one generator random sample.\n *\n * @param random - The caller-supplied random source\n * @param shape - The shape category consuming the sample\n * @returns A finite sample in `[0, 1)`\n * @throws {ContractError} When the source throws or returns outside `[0, 1)`\n *\n * @example\n * ```ts\n * drawRandom(() => 0.5, 'number') // 0.5\n * ```\n */\nexport function drawRandom(random: RandomFunction, shape: string): number {\n\tconst outcome = attempt(random)\n\tif (!outcome.success) {\n\t\tthrow new ContractError('drawRandom: the random source threw', {\n\t\t\tcode: 'random',\n\t\t\tcontext: { shape, limit: '[0, 1)', received: 'threw' },\n\t\t\tcause: outcome.error,\n\t\t})\n\t}\n\tconst sample = outcome.value\n\tif (!isFiniteNumber(sample) || sample < 0 || sample >= 1) {\n\t\tthrow new ContractError('drawRandom: the random source must return a value in [0, 1)', {\n\t\t\tcode: 'random',\n\t\t\tcontext: { shape, limit: '[0, 1)', received: String(sample) },\n\t\t})\n\t}\n\treturn sample\n}\n\n// === Record-field access\n\n/**\n * Resolve a (possibly nested) field value from a record by a key or key path.\n *\n * @remarks\n * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a\n * string array descends left-to-right through nested objects. Intermediates may\n * be any object — records, class instances, or arrays indexed by string. Returns\n * `undefined` the moment a segment is missing or lands on a non-object, so the\n * lookup is total — even against a hostile getter or Proxy trap that throws on\n * read, contained via {@link attempt} so the throw never escapes.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The resolved value, or `undefined`\n *\n * @example\n * ```ts\n * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'\n * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)\n * resolveField({ a: 1 }, ['a', 'b']) // undefined\n * ```\n */\nexport function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown {\n\tconst keys = isString(path) ? [path] : path\n\tlet current: unknown = record\n\tfor (const key of keys) {\n\t\tif (!isObject(current)) return undefined\n\t\tconst container = current\n\t\tconst outcome = attempt(() => Reflect.get(container, key))\n\t\tif (!outcome.success) return undefined\n\t\tcurrent = outcome.value\n\t}\n\treturn current\n}\n\n/**\n * Match an unknown value against the recursive JSON value structure.\n *\n * @remarks\n * The caller-owned ancestor set tracks only the active traversal path, so\n * cycles fail while shared references across sibling branches remain valid.\n * The set belongs to one traversal from one entry point; passing a shared or\n * pre-populated set is unsupported. Arrays and plain records recurse through\n * this helper; class instances and non-finite numbers are rejected.\n *\n * @param entry - The value to inspect\n * @param ancestors - Objects on the active traversal path\n * @returns `true` when the value is a cycle-free JSON value\n *\n * @example\n * ```ts\n * matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true\n * matchesJSONValue(Number.NaN, new WeakSet()) // false\n * ```\n */\nexport function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>): boolean {\n\tif (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true\n\tif (Array.isArray(entry)) {\n\t\tif (ancestors.has(entry)) return false\n\t\tancestors.add(entry)\n\t\tlet valid = true\n\t\tfor (let index = 0; index < entry.length; index += 1) {\n\t\t\tif (!Object.hasOwn(entry, index) || !matchesJSONValue(entry[index], ancestors)) {\n\t\t\t\tvalid = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tancestors.delete(entry)\n\t\treturn valid\n\t}\n\tif (!isRecord(entry)) return false\n\tif (ancestors.has(entry)) return false\n\tancestors.add(entry)\n\tconst valid = Object.values(entry).every((value) => matchesJSONValue(value, ancestors))\n\tancestors.delete(entry)\n\treturn valid\n}\n\n// === Random\n\n/**\n * Build a deterministic pseudo-random source seeded from a single number.\n *\n * @remarks\n * A mulberry32 generator — the same seed always yields the same sequence, so\n * generated seed data is reproducible across runs. Used as the default random\n * source for {@link compileGenerator}, seeded from the wall clock so casual\n * callers still get varied output without passing a source themselves.\n *\n * @param seed - The seed for the sequence\n * @returns A {@link RandomFunction} returning values in `[0, 1)`\n *\n * @example\n * ```ts\n * const random = seededRandom(42)\n * random() // always the same first value for seed 42\n * ```\n */\nexport function seededRandom(seed: number): RandomFunction {\n\tlet state = seed >>> 0\n\treturn () => {\n\t\tstate = (state + 0x6d2b79f5) >>> 0\n\t\tlet t = state\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1)\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296\n\t}\n}\n\n/**\n * Count the enumerable own-symbol keys on a value.\n *\n * @remarks\n * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose\n * descriptor is `enumerable` are counted. Backs the object-emptiness guards\n * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an\n * enumerable symbol is not mistaken for empty.\n *\n * @param value - The object to inspect\n * @returns The number of enumerable own-symbol keys\n *\n * @example\n * ```ts\n * const flag = Symbol('flag')\n * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1\n * enumerableSymbolCount({}) // 0\n * ```\n */\nexport function enumerableSymbolCount(value: object): number {\n\tlet count = 0\n\tfor (const symbol of Object.getOwnPropertySymbols(value)) {\n\t\tif (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) {\n\t\t\tcount += 1\n\t\t}\n\t}\n\treturn count\n}\n\n/**\n * Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape\n * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never\n * an assertion (AGENTS §14).\n *\n * @remarks\n * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a\n * tool advertises its `parameters` as an open record. The two are structurally compatible but not\n * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema\n * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's\n * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open\n * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.\n *\n * @param schema - The compiled JSON Schema (a contract's `schema`)\n * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record\n *\n * @example\n * ```ts\n * import { createContract, schemaToParameters } from '@src/core'\n *\n * const contract = createContract(shape)\n * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises\n * ```\n */\nexport function schemaToParameters(\n\tschema: JSONSchema,\n): Readonly<Record<string, unknown>> | undefined {\n\treturn isRecord(schema) ? schema : undefined\n}\n\n/**\n * Wrap a non-object `JSONSchema` root in a single-property object schema, so\n * an inferred primitive/array/union schema can flow into {@link schemaToParameters}\n * as an MCP-compatible `inputSchema`.\n *\n * @remarks\n * Total and deterministic. `schema.type === 'object'` passes through\n * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only\n * schema with no `type`, or the empty `{}`) is wrapped as a single required\n * `value` property: `{ type: 'object', properties: { value: schema },\n * required: ['value'], additionalProperties: false }`. Composition:\n * `schemaToParameters(schemaToObject(valueToSchema(payload)))`.\n *\n * @param schema - The schema to wrap\n * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema\n *\n * @example\n * ```ts\n * schemaToObject({ type: 'string' })\n * // { type: 'object', properties: { value: { type: 'string' } },\n * // required: ['value'], additionalProperties: false }\n * schemaToObject({ type: 'object', properties: {} }) // unchanged\n * ```\n */\nexport function schemaToObject(schema: JSONSchema): JSONSchema {\n\tif (schema.type === 'object') return schema\n\treturn {\n\t\ttype: 'object',\n\t\tproperties: { value: schema },\n\t\trequired: ['value'],\n\t\tadditionalProperties: false,\n\t}\n}\n\n// === Inference option sanitization\n\n/**\n * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to\n * a finite non-negative integer, falling back to a default for anything else.\n *\n * @remarks\n * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or\n * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard\n * (`NaN <= 0` is `false`, so recursion never halts), and a negative\n * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key\n * instead of capping the list (a fractional value has a similarly undefined\n * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`\n * is `false` — since an unbounded budget is exactly the adversarial case the\n * caps exist to prevent. A valid finite non-negative integer passes through\n * unchanged.\n *\n * @param value - The candidate budget value\n * @param fallback - The default to use when `value` is not a finite\n * non-negative integer\n * @returns A finite non-negative integer budget\n *\n * @example\n * ```ts\n * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT\n * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT\n * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4\n * ```\n */\nexport function sanitizeBudget(value: number | undefined, fallback: number): number {\n\treturn typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : fallback\n}\n\n// === Reporting\n\n/**\n * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s\n * `received` field.\n *\n * @remarks\n * A primitive renders as its literal: a string is `JSON.stringify`-escaped and\n * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when\n * clipped); a number / boolean / bigint / symbol renders via `String`; `null`\n * and `undefined` render as their own name. Everything else — a plain object,\n * an array, a function, a class instance, a `Map` — is NEVER traversed or\n * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),\n * so a hostile or enormous structure can never blow up the preview.\n *\n * @param value - The value to preview\n * @returns A short descriptive string, always safe to embed in a diagnostic\n *\n * @example\n * ```ts\n * preview('hi') // '\"hi\"'\n * preview(42) // '42'\n * preview(null) // 'null'\n * preview({ a: 1 }) // 'object'\n * preview([1, 2, 3]) // 'object'\n * ```\n */\nexport function preview(value: unknown): string {\n\tif (value === null) return 'null'\n\tif (value === undefined) return 'undefined'\n\tif (isString(value)) {\n\t\tconst text = JSON.stringify(value)\n\t\treturn text.length > PREVIEW_LIMIT ? `${text.slice(0, PREVIEW_LIMIT)}…` : text\n\t}\n\tif (isNumber(value) || isBoolean(value)) return String(value)\n\tif (isBigInt(value)) return `${value}n`\n\tif (isSymbol(value)) return value.toString()\n\treturn typeof value\n}\n\n/**\n * Project a {@link ContractShape} to the {@link FaultKind} it describes.\n *\n * @remarks\n * A structural mapping used by {@link compileReporter} to fill a `Fault`'s\n * `expected` field: most shapes map to their own `type` (`numberShape` maps to\n * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /\n * `nullableShape` project through to their inner shape's kind, and `rawShape`\n * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.\n *\n * @param shape - The shape to project\n * @returns The shape's {@link FaultKind}\n *\n * @example\n * ```ts\n * shapeToKind(stringShape()) // 'string'\n * shapeToKind(integerShape()) // 'integer'\n * shapeToKind(optionalShape(nullShape())) // 'null'\n * ```\n */\nexport function shapeToKind(shape: ContractShape): FaultKind {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn shape.integer === true ? 'integer' : 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'null':\n\t\t\treturn 'null'\n\t\tcase 'literal':\n\t\t\treturn 'literal'\n\t\tcase 'array':\n\t\t\treturn 'array'\n\t\tcase 'object':\n\t\t\treturn 'object'\n\t\tcase 'union':\n\t\t\treturn 'union'\n\t\tcase 'json':\n\t\t\treturn 'json'\n\t\tcase 'optional':\n\t\t\treturn shapeToKind(shape.inner)\n\t\tcase 'nullable':\n\t\t\treturn shapeToKind(shape.inner)\n\t\tcase 'raw':\n\t\t\treturn 'json'\n\t}\n}\n","import type { ContractShape, JSONRecord, JSONSchema, JSONValue, StringShape } from './types.js'\nimport { ContractError, isContractError } from './errors.js'\nimport { attempt, enumerableKeys } from './helpers.js'\nimport { isRecord } from './validators.js'\n\n/**\n * Deep-clone exact JSON data into an owned frozen snapshot.\n *\n * @remarks\n * Traverses iteratively so deeply nested input cannot exhaust the call stack.\n * Repeated noncyclic aliases are duplicated because JSON persistence represents\n * a tree, while a structural back-edge on the active path is rejected as a\n * cycle. Arrays are rebuilt as standard dense arrays and records as\n * null-prototype objects; every produced node is frozen after its children are\n * wired. Array keys must be exactly `length` plus every canonical index.\n * Writable and configurable index flags are normalized rather than treated as\n * JSON data, so frozen arrays remain valid. Property descriptors are inspected\n * without reading values through accessors, and every hostile reflective\n * operation is contained before a new clone-coded error is exposed.\n *\n * @param value - The unknown value to validate and snapshot\n * @returns The primitive unchanged, or a deeply cloned and frozen JSON graph\n * @throws {ContractError} When the value is not exact acyclic JSON data or traversal fails\n *\n * @example\n * ```ts\n * const source = { settings: { enabled: true } }\n * const clone = cloneJSONValue(source)\n * source.settings.enabled = false\n * clone // { settings: { enabled: true } }\n * ```\n */\nexport function cloneJSONValue(value: unknown): JSONValue {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number') {\n\t\tif (Number.isFinite(value)) return value\n\t\tthrow new ContractError('cloneJSONValue: number is not finite', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'json' },\n\t\t})\n\t}\n\tif (typeof value !== 'object') {\n\t\tthrow new ContractError('cloneJSONValue: value is not JSON data', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'json' },\n\t\t})\n\t}\n\n\tconst arrayOutcome = attempt(() => Array.isArray(value))\n\tif (!arrayOutcome.success) {\n\t\tthrow new ContractError('cloneJSONValue: value brand could not be inspected', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'json' },\n\t\t})\n\t}\n\n\tlet root: JSONValue[] | JSONRecord\n\tif (arrayOutcome.value) {\n\t\troot = []\n\t} else if (isRecord(value)) {\n\t\troot = Object.create(null)\n\t} else {\n\t\tthrow new ContractError('cloneJSONValue: object is not a plain record', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'json' },\n\t\t})\n\t}\n\n\tconst active = new WeakSet<object>()\n\tactive.add(value)\n\tconst pending: {\n\t\treadonly source: object\n\t\treadonly clone: JSONValue[] | JSONRecord\n\t\treadonly array: boolean\n\t\tentries: readonly (readonly [key: string, value: unknown])[] | undefined\n\t\tindex: number\n\t}[] = [\n\t\t{\n\t\t\tsource: value,\n\t\t\tclone: root,\n\t\t\tarray: arrayOutcome.value,\n\t\t\tentries: undefined,\n\t\t\tindex: 0,\n\t\t},\n\t]\n\n\twhile (pending.length > 0) {\n\t\tconst frame = pending[pending.length - 1]\n\t\tif (frame === undefined) continue\n\n\t\tif (frame.entries === undefined) {\n\t\t\tconst keysOutcome = attempt(() => Reflect.ownKeys(frame.source))\n\t\t\tif (!keysOutcome.success) {\n\t\t\t\tthrow new ContractError('cloneJSONValue: own keys could not be inspected', {\n\t\t\t\t\tcode: 'clone',\n\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst keys = keysOutcome.value\n\t\t\tconst entries: [key: string, value: unknown][] = []\n\n\t\t\tif (frame.array) {\n\t\t\t\tconst lengthOutcome = attempt(() =>\n\t\t\t\t\tReflect.getOwnPropertyDescriptor(frame.source, 'length'),\n\t\t\t\t)\n\t\t\t\tif (!lengthOutcome.success) {\n\t\t\t\t\tthrow new ContractError('cloneJSONValue: array length could not be inspected', {\n\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst lengthDescriptor = lengthOutcome.value\n\t\t\t\tif (\n\t\t\t\t\tlengthDescriptor === undefined ||\n\t\t\t\t\t!('value' in lengthDescriptor) ||\n\t\t\t\t\ttypeof lengthDescriptor.value !== 'number' ||\n\t\t\t\t\t!Number.isInteger(lengthDescriptor.value) ||\n\t\t\t\t\tlengthDescriptor.value < 0 ||\n\t\t\t\t\tlengthDescriptor.value > 4_294_967_295 ||\n\t\t\t\t\tlengthDescriptor.enumerable !== false ||\n\t\t\t\t\tlengthDescriptor.configurable !== false\n\t\t\t\t) {\n\t\t\t\t\tthrow new ContractError('cloneJSONValue: array is not intrinsic and dense', {\n\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tconst remaining = new Set(keys)\n\t\t\t\tif (!remaining.delete('length')) {\n\t\t\t\t\tthrow new ContractError('cloneJSONValue: array own keys are not exact', {\n\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tfor (let index = 0; index < lengthDescriptor.value; index += 1) {\n\t\t\t\t\tconst key = String(index)\n\t\t\t\t\tif (!remaining.delete(key)) {\n\t\t\t\t\t\tthrow new ContractError('cloneJSONValue: array own keys are not exact', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tconst descriptorOutcome = attempt(() =>\n\t\t\t\t\t\tReflect.getOwnPropertyDescriptor(frame.source, key),\n\t\t\t\t\t)\n\t\t\t\t\tif (!descriptorOutcome.success) {\n\t\t\t\t\t\tthrow new ContractError('cloneJSONValue: array index could not be inspected', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tconst descriptor = descriptorOutcome.value\n\t\t\t\t\tif (\n\t\t\t\t\t\tdescriptor === undefined ||\n\t\t\t\t\t\t!('value' in descriptor) ||\n\t\t\t\t\t\tdescriptor.enumerable !== true\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new ContractError('cloneJSONValue: array index is not enumerable data', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tentries.push([key, descriptor.value])\n\t\t\t\t}\n\t\t\t\tif (remaining.size !== 0) {\n\t\t\t\t\tthrow new ContractError('cloneJSONValue: array own keys are not exact', {\n\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tif (typeof key !== 'string') {\n\t\t\t\t\t\tthrow new ContractError('cloneJSONValue: record has a symbol property', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tconst descriptorOutcome = attempt(() =>\n\t\t\t\t\t\tReflect.getOwnPropertyDescriptor(frame.source, key),\n\t\t\t\t\t)\n\t\t\t\t\tif (!descriptorOutcome.success) {\n\t\t\t\t\t\tthrow new ContractError('cloneJSONValue: record property could not be inspected', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tconst descriptor = descriptorOutcome.value\n\t\t\t\t\tif (\n\t\t\t\t\t\tdescriptor === undefined ||\n\t\t\t\t\t\t!('value' in descriptor) ||\n\t\t\t\t\t\tdescriptor.enumerable !== true\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new ContractError('cloneJSONValue: record property is not enumerable data', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tentries.push([key, descriptor.value])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tframe.entries = entries\n\t\t}\n\n\t\tconst entry = frame.entries[frame.index]\n\t\tif (entry === undefined) {\n\t\t\tObject.freeze(frame.clone)\n\t\t\tactive.delete(frame.source)\n\t\t\tpending.pop()\n\t\t\tcontinue\n\t\t}\n\t\tframe.index += 1\n\n\t\tconst key = entry[0]\n\t\tconst source = entry[1]\n\t\tlet clone: JSONValue\n\t\tif (source === null || typeof source === 'string' || typeof source === 'boolean') {\n\t\t\tclone = source\n\t\t} else if (typeof source === 'number') {\n\t\t\tif (!Number.isFinite(source)) {\n\t\t\t\tthrow new ContractError('cloneJSONValue: number is not finite', {\n\t\t\t\t\tcode: 'clone',\n\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t})\n\t\t\t}\n\t\t\tclone = source\n\t\t} else if (typeof source === 'object') {\n\t\t\tif (active.has(source)) {\n\t\t\t\tthrow new ContractError('cloneJSONValue: cycle detected', {\n\t\t\t\t\tcode: 'clone',\n\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst childArrayOutcome = attempt(() => Array.isArray(source))\n\t\t\tif (!childArrayOutcome.success) {\n\t\t\t\tthrow new ContractError('cloneJSONValue: value brand could not be inspected', {\n\t\t\t\t\tcode: 'clone',\n\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t})\n\t\t\t}\n\t\t\tlet child: JSONValue[] | JSONRecord\n\t\t\tif (childArrayOutcome.value) {\n\t\t\t\tchild = []\n\t\t\t} else if (isRecord(source)) {\n\t\t\t\tchild = Object.create(null)\n\t\t\t} else {\n\t\t\t\tthrow new ContractError('cloneJSONValue: object is not a plain record', {\n\t\t\t\t\tcode: 'clone',\n\t\t\t\t\tcontext: { shape: 'json' },\n\t\t\t\t})\n\t\t\t}\n\t\t\tclone = child\n\t\t\tactive.add(source)\n\t\t\tpending.push({\n\t\t\t\tsource,\n\t\t\t\tclone: child,\n\t\t\t\tarray: childArrayOutcome.value,\n\t\t\t\tentries: undefined,\n\t\t\t\tindex: 0,\n\t\t\t})\n\t\t} else {\n\t\t\tthrow new ContractError('cloneJSONValue: property is not JSON data', {\n\t\t\t\tcode: 'clone',\n\t\t\t\tcontext: { shape: 'json' },\n\t\t\t})\n\t\t}\n\n\t\tObject.defineProperty(frame.clone, key, {\n\t\t\tvalue: clone,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t})\n\t}\n\n\treturn root\n}\n\n/**\n * Deep-clone an exact JSON object record into an owned frozen snapshot.\n *\n * @remarks\n * Adds a record-root boundary to {@link cloneJSONValue}. The output is a\n * deeply frozen null-prototype record, and repeated noncyclic aliases are\n * duplicated as independent JSON tree branches.\n *\n * @param value - The unknown record value to validate and snapshot\n * @returns A deeply cloned and frozen JSON record\n * @throws {ContractError} When the root is not a record, nested data is inexact, or traversal fails\n *\n * @example\n * ```ts\n * cloneJSONRecord({ attempt: 1 }) // frozen null-prototype record\n * ```\n */\nexport function cloneJSONRecord(value: unknown): JSONRecord {\n\tif (!isRecord(value)) {\n\t\tthrow new ContractError('cloneJSONRecord: value is not a plain record', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'json' },\n\t\t})\n\t}\n\tconst clone = cloneJSONValue(value)\n\tif (!isRecord(clone)) {\n\t\tthrow new ContractError('cloneJSONRecord: cloned value is not a record', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'json' },\n\t\t})\n\t}\n\treturn clone\n}\n\n/**\n * Deep-clone a JSON Schema graph into an owned frozen snapshot.\n *\n * @remarks\n * Walks arrays and records iteratively with a memo, preserving shared\n * references and closing cyclic edges onto their cloned nodes. Primitive\n * values and own enumerable string-keyed edges are copied; record nodes use\n * null prototypes, arrays retain only their intrinsic array prototype, and\n * every produced object is frozen after its edges are wired. Hostile traversal\n * throws a clone-coded {@link ContractError}, never a caller-owned raw error.\n *\n * @param schema - The JSON Schema graph to snapshot\n * @returns A deeply cloned and frozen JSON Schema graph\n * @throws {ContractError} When hostile schema traversal prevents ownership\n *\n * @example\n * ```ts\n * const child = { type: 'string' }\n * const clone = cloneSchema({ anyOf: [child, child] })\n * clone.anyOf?.[0] === clone.anyOf?.[1] // true\n * ```\n */\nexport function cloneSchema(schema: JSONSchema): JSONSchema {\n\ttry {\n\t\tconst root: JSONSchema = Object.create(null)\n\t\tconst memo = new Map<object, object>([[schema, root]])\n\t\tconst pending: {\n\t\t\treadonly source: object\n\t\t\treadonly clone: object\n\t\t\treadonly path: readonly string[]\n\t\t}[] = [{ source: schema, clone: root, path: [] }]\n\n\t\twhile (pending.length > 0) {\n\t\t\tconst frame = pending.pop()\n\t\t\tif (frame === undefined) continue\n\t\t\tconst keys = enumerableKeys(frame.source)\n\t\t\tif (keys === undefined) {\n\t\t\t\tthrow new ContractError('cloneSchema: property enumeration failed', {\n\t\t\t\t\tcode: 'clone',\n\t\t\t\t\tcontext: { path: frame.path, shape: 'schema' },\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst outcome = attempt(() => Reflect.get(frame.source, key))\n\t\t\t\tif (!outcome.success) {\n\t\t\t\t\tthrow new ContractError('cloneSchema: property access failed', {\n\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\tcontext: { path: [...frame.path, key], shape: 'schema' },\n\t\t\t\t\t\tcause: outcome.error,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst source = outcome.value\n\t\t\t\tlet clone: unknown = source\n\t\t\t\tif (typeof source === 'object' && source !== null) {\n\t\t\t\t\tconst existing = memo.get(source)\n\t\t\t\t\tif (existing !== undefined) {\n\t\t\t\t\t\tclone = existing\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst child: object = Array.isArray(source) ? [] : Object.create(null)\n\t\t\t\t\t\tmemo.set(source, child)\n\t\t\t\t\t\tpending.push({\n\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\tclone: child,\n\t\t\t\t\t\t\tpath: [...frame.path, key],\n\t\t\t\t\t\t})\n\t\t\t\t\t\tclone = child\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tObject.defineProperty(frame.clone, key, {\n\t\t\t\t\tvalue: clone,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tObject.freeze(frame.clone)\n\t\t}\n\n\t\treturn root\n\t} catch (reason) {\n\t\tif (reason instanceof ContractError) throw reason\n\t\tthrow new ContractError('cloneSchema: failed to create an owned schema snapshot', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'schema' },\n\t\t\tcause: reason,\n\t\t})\n\t}\n}\n\n/**\n * Deep-clone a contract shape graph into an owned frozen snapshot.\n *\n * @remarks\n * Uses an explicit memo to preserve shared-child identity and close cyclic\n * edges onto their cloned nodes. Shape-node shells are created iteratively,\n * then their structural edges are wired and their copied collections frozen.\n * String patterns are captured by source and flags behind an enumerable\n * accessor that returns a fresh frozen zero-state `RegExp` on every read.\n * A raw schema delegates to {@link cloneSchema}; every shape-graph read is\n * contained, so hostile traversal throws only a clone-coded\n * {@link ContractError}.\n *\n * @param shape - The contract shape graph to snapshot\n * @returns A deeply cloned and frozen shape graph\n * @throws {ContractError} When hostile shape or raw-schema traversal prevents ownership\n *\n * @example\n * ```ts\n * const child = arrayShape(stringShape())\n * const clone = cloneShape(objectShape({ first: child, second: child }))\n * clone.type === 'object' && clone.properties.first === clone.properties.second // true\n * ```\n */\nexport function cloneShape(shape: StringShape): StringShape\nexport function cloneShape(shape: ContractShape): ContractShape\nexport function cloneShape(shape: ContractShape): ContractShape {\n\ttry {\n\t\tconst memo = new Map<ContractShape, ContractShape>()\n\t\tconst pending: ContractShape[] = [shape]\n\t\tconst sources: ContractShape[] = []\n\t\tlet root = shape\n\n\t\twhile (pending.length > 0) {\n\t\t\tconst source = pending.pop()\n\t\t\tif (source === undefined || memo.has(source)) continue\n\n\t\t\tlet clone: ContractShape\n\t\t\tswitch (source.type) {\n\t\t\t\tcase 'string': {\n\t\t\t\t\tconst pattern = source.pattern\n\t\t\t\t\tconst fields: StringShape = {\n\t\t\t\t\t\ttype: 'string',\n\t\t\t\t\t\t...(source.min === undefined ? {} : { min: source.min }),\n\t\t\t\t\t\t...(source.max === undefined ? {} : { max: source.max }),\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tif (pattern === undefined) {\n\t\t\t\t\t\tclone = fields\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst patternSource = pattern.source\n\t\t\t\t\t\tconst patternFlags = pattern.flags\n\t\t\t\t\t\tclone = {\n\t\t\t\t\t\t\t...fields,\n\t\t\t\t\t\t\tget pattern() {\n\t\t\t\t\t\t\t\treturn Object.freeze(new RegExp(patternSource, patternFlags))\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'number':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\t...(source.min === undefined ? {} : { min: source.min }),\n\t\t\t\t\t\t...(source.max === undefined ? {} : { max: source.max }),\n\t\t\t\t\t\t...(source.integer === undefined ? {} : { integer: source.integer }),\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase 'boolean':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'boolean',\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase 'null':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'null',\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase 'literal':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'literal',\n\t\t\t\t\t\tvalues: Object.freeze([...source.values]),\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase 'array':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'array',\n\t\t\t\t\t\titems: source.items,\n\t\t\t\t\t\t...(source.min === undefined ? {} : { min: source.min }),\n\t\t\t\t\t\t...(source.max === undefined ? {} : { max: source.max }),\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tpending.push(source.items)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'object': {\n\t\t\t\t\tconst extra = source.additionalProperties\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: Object.create(null),\n\t\t\t\t\t\t...(extra === undefined || (extra !== true && extra !== false)\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { additionalProperties: extra }),\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tfor (const key of Object.keys(source.properties)) {\n\t\t\t\t\t\tconst child = source.properties[key]\n\t\t\t\t\t\tif (child !== undefined) pending.push(child)\n\t\t\t\t\t}\n\t\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) pending.push(extra)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'union':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'union',\n\t\t\t\t\t\tvariants: [],\n\t\t\t\t\t\t...(source.mode === undefined ? {} : { mode: source.mode }),\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tfor (const variant of source.variants) pending.push(variant)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'optional':\n\t\t\t\t\tclone = { type: 'optional', inner: source.inner }\n\t\t\t\t\tpending.push(source.inner)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'nullable':\n\t\t\t\t\tclone = { type: 'nullable', inner: source.inner }\n\t\t\t\t\tpending.push(source.inner)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'json':\n\t\t\t\t\tclone = {\n\t\t\t\t\t\ttype: 'json',\n\t\t\t\t\t\t...(source.description === undefined ? {} : { description: source.description }),\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase 'raw': {\n\t\t\t\t\tconst outcome = attempt(() => source.schema)\n\t\t\t\t\tif (!outcome.success) {\n\t\t\t\t\t\tthrow new ContractError('cloneShape: raw schema access failed', {\n\t\t\t\t\t\t\tcode: 'clone',\n\t\t\t\t\t\t\tcontext: { shape: 'raw' },\n\t\t\t\t\t\t\tcause: outcome.error,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tclone = { type: 'raw', schema: cloneSchema(outcome.value) }\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmemo.set(source, clone)\n\t\t\tif (source === shape) root = clone\n\t\t\tsources.push(source)\n\t\t}\n\n\t\tfor (const source of sources) {\n\t\t\tconst clone = memo.get(source)\n\t\t\tif (clone === undefined) continue\n\n\t\t\tswitch (source.type) {\n\t\t\t\tcase 'array': {\n\t\t\t\t\tconst items = memo.get(source.items)\n\t\t\t\t\tif (items !== undefined) Reflect.set(clone, 'items', items)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'object': {\n\t\t\t\t\tconst properties: Record<string, ContractShape> = Object.create(null)\n\t\t\t\t\tfor (const key of Object.keys(source.properties)) {\n\t\t\t\t\t\tconst child = source.properties[key]\n\t\t\t\t\t\tif (child === undefined) continue\n\t\t\t\t\t\tconst clonedChild = memo.get(child)\n\t\t\t\t\t\tif (clonedChild !== undefined) properties[key] = clonedChild\n\t\t\t\t\t}\n\t\t\t\t\tReflect.set(clone, 'properties', Object.freeze(properties))\n\t\t\t\t\tconst extra = source.additionalProperties\n\t\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\t\t\tconst clonedExtra = memo.get(extra)\n\t\t\t\t\t\tif (clonedExtra !== undefined) {\n\t\t\t\t\t\t\tReflect.set(clone, 'additionalProperties', clonedExtra)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'union': {\n\t\t\t\t\tconst variants: ContractShape[] = []\n\t\t\t\t\tfor (const variant of source.variants) {\n\t\t\t\t\t\tconst clonedVariant = memo.get(variant)\n\t\t\t\t\t\tif (clonedVariant !== undefined) variants.push(clonedVariant)\n\t\t\t\t\t}\n\t\t\t\t\tReflect.set(clone, 'variants', Object.freeze(variants))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'optional':\n\t\t\t\tcase 'nullable': {\n\t\t\t\t\tconst inner = memo.get(source.inner)\n\t\t\t\t\tif (inner !== undefined) Reflect.set(clone, 'inner', inner)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tObject.freeze(clone)\n\t\t}\n\n\t\treturn root\n\t} catch (reason) {\n\t\tif (isContractError(reason) && reason.code === 'clone') throw reason\n\t\tthrow new ContractError('cloneShape: failed to create an owned shape snapshot', {\n\t\t\tcode: 'clone',\n\t\t\tcontext: { shape: 'shape' },\n\t\t\tcause: reason,\n\t\t})\n\t}\n}\n\n/**\n * Take ownership of a contract shape node — the node itself when it is already\n * frozen, otherwise a {@link cloneShape} snapshot of its graph.\n *\n * @remarks\n * Builder- and `cloneShape`-produced frozen means owned: those nodes have frozen\n * `properties` / `variants` / `values` collections and pattern accessors that\n * return fresh frozen snapshots, so they cannot drift under a caller who still\n * holds an input reference or a previously read pattern. `Object.freeze` on a\n * hand-authored pattern shape is not an ownership marker because it cannot\n * protect `RegExp` internal slots; leave that shape unfrozen for this function\n * to snapshot, or pass it through {@link cloneShape} first.\n *\n * Every compiler entry point (`compileSchema` / `compileGuard` /\n * `compileParser` / `compileGenerator` / `compileReporter`) opens with this\n * call, and the check applies per node as the recursion descends: a frozen\n * parent is trusted for its own fields while each child is owned again at its\n * own level, so a hand-assembled graph that froze only part of itself is still\n * compiled from owned data.\n *\n * @param shape - The contract shape to own\n * @returns The shape itself when frozen, otherwise a deeply cloned frozen snapshot\n *\n * @example\n * ```ts\n * const authored = stringShape() // builders freeze\n * ownShape(authored) === authored // true\n * ownShape({ type: 'string' }) // a frozen snapshot — the literal is caller-owned\n * ```\n */\nexport function ownShape(shape: ContractShape): ContractShape {\n\treturn Object.isFrozen(shape) ? shape : cloneShape(shape)\n}\n","import type {\n\tFromGuards,\n\tGuard,\n\tGuardsShape,\n\tGuardType,\n\tIntersectionFromGuards,\n\tOptionalFromGuards,\n\tTupleFromGuards,\n} from './types.js'\nimport { GUARD_DEPTH_LIMIT } from './constants.js'\nimport {\n\tisArray,\n\tisConstructor,\n\tisFiniteNumber,\n\tisInstance,\n\tisMap,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisSet,\n\tisString,\n\tisSymbol,\n} from './validators.js'\nimport { holds } from './helpers.js'\n\n// Every combinator returns a `Guard<T>` — a total function (AGENTS §14). The\n// combinators that invoke a caller-supplied callback inside the guard body\n// contain the whole call via `holds`, so\n// the produced guard reports a non-match instead of propagating. The container\n// combinators likewise wrap their complete element/entry/key-read walk in\n// `holds` — a hostile Proxy trap, a throwing getter, a throwing\n// iterator, or a throwing caller-supplied predicate yields a non-match, never a\n// propagated throw.\n\n/**\n * Build a guard that accepts arrays whose every element satisfies `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringArray = arrayOf(isString)\n * isStringArray(['a', 'b']) // true\n * isStringArray(['a', 1]) // false\n * ```\n */\nexport function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] =>\n\t\tholds(() => {\n\t\t\tif (!isArray(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tif (!Object.hasOwn(value, index) || !elementGuard(value[index])) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n}\n\n/**\n * Build a guard that accepts fixed-arity tuples, testing each index with the\n * corresponding guard.\n *\n * @example\n * ```ts\n * const isPair = tupleOf(isString, isNumber)\n * isPair(['hello', 42]) // true\n * isPair(['hello']) // false — wrong arity\n * ```\n */\nexport function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<TupleFromGuards<Gs>>\nexport function tupleOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]>\nexport function tupleOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] =>\n\t\tholds(() => {\n\t\t\tif (!isArray(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (value.length !== guards.length) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let index = 0; index < guards.length; index += 1) {\n\t\t\t\tconst guard = guards[index]\n\t\t\t\tif (!Object.hasOwn(value, index) || guard === undefined || !guard(value[index])) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n}\n\n/**\n * Build a guard that accepts a provided literal primitive using SameValueZero\n * comparison.\n *\n * @remarks\n * Signed zero compares equal, while `NaN` compares equal to `NaN`. Two call\n * forms, one meaning: list the literals inline, or hand in one array of them.\n * The array form exists for a vocabulary that is machine-generated rather than\n * hand-written — a `literalShape` built from an untrusted schema's `enum`, say\n * — where spreading a list of tens of thousands of entries would exhaust the\n * engine's argument limit. `compileGuard` / `compileParser` / `compileReporter`\n * take the array form for exactly that reason.\n *\n * @param literals - The permitted literal primitives, listed inline or as one array\n * @returns A guard narrowing to the provided literal union\n *\n * @example\n * ```ts\n * const isRole = literalOf('admin', 'member', 'guest')\n * isRole('admin') // true\n * isRole('owner') // false\n *\n * const isSameRole = literalOf(['admin', 'member', 'guest']) // the same guard, from an array\n * ```\n */\nexport function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(\n\tliterals: Literals,\n): Guard<Literals[number]>\nexport function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(\n\t...literals: Literals\n): Guard<Literals[number]>\nexport function literalOf(\n\t...literals: ReadonlyArray<string | number | boolean | ReadonlyArray<string | number | boolean>>\n): Guard<string | number | boolean> {\n\tconst [first] = literals\n\tconst values: readonly unknown[] = literals.length === 1 && isArray(first) ? first : literals\n\tconst allowed = new Set<unknown>(values)\n\treturn (value: unknown): value is string | number | boolean => allowed.has(value)\n}\n\n/**\n * Build a guard that accepts instances of the provided constructor.\n *\n * @remarks\n * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,\n * so passing an arrow function does not silently produce a broken guard.\n *\n * @example\n * ```ts\n * const isDateValue = instanceOf(Date)\n * isDateValue(new Date()) // true\n * isDateValue({}) // false\n * ```\n */\nexport function instanceOf<C extends abstract new (...args: never) => object>(\n\tctor: C,\n): Guard<InstanceType<C>> {\n\treturn (value: unknown): value is InstanceType<C> =>\n\t\tisConstructor(ctor) && isObject(value) && isInstance(value, ctor)\n}\n\n/**\n * Build a guard from a native `enum` or any object whose values are strings or\n * numbers.\n *\n * @example\n * ```ts\n * enum Direction { Up = 'up', Down = 'down' }\n * const isDirection = enumOf(Direction)\n * isDirection('up') // true\n * isDirection('left') // false\n * ```\n */\nexport function enumOf<const E extends Record<string, string | number>>(\n\tenumeration: E,\n): Guard<E[keyof E]> {\n\tconst values = new Set(Object.values(enumeration))\n\treturn (value: unknown): value is E[keyof E] =>\n\t\t(isString(value) || isNumber(value)) && values.has(value)\n}\n\n/**\n * Build a guard that accepts `Set` instances whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringSet = setOf(isString)\n * isStringSet(new Set(['a', 'b'])) // true\n * isStringSet(new Set(['a', 1])) // false\n * ```\n */\nexport function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>> {\n\treturn (value: unknown): value is ReadonlySet<unknown> =>\n\t\tholds(() => {\n\t\t\tif (!isSet(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n}\n\n/**\n * Build a guard that accepts `Map` instances where every key satisfies\n * `keyGuard` and every value satisfies `valueGuard`.\n *\n * @example\n * ```ts\n * const isStringNumberMap = mapOf(isString, isNumber)\n * isStringNumberMap(new Map([['a', 1]])) // true\n * isStringNumberMap(new Map([[1, 'a']])) // false\n * ```\n */\nexport function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<ReadonlyMap<K, V>>\nexport function mapOf(\n\tkeyPredicate: (value: unknown) => boolean,\n\tvaluePredicate: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>>\nexport function mapOf(\n\tkeyGuard: (value: unknown) => boolean,\n\tvalueGuard: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>> {\n\treturn (value: unknown): value is ReadonlyMap<unknown, unknown> =>\n\t\tholds(() => {\n\t\t\tif (!isMap(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (const [key, entryValue] of value) {\n\t\t\t\tif (!keyGuard(key) || !valueGuard(entryValue)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n}\n\nexport function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>\nexport function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\toptional: K,\n): Guard<OptionalFromGuards<S, K>>\nexport function recordOf<S extends GuardsShape>(\n\tshape: S,\n\toptional: true,\n): Guard<Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>>\n\n/**\n * Build a guard that accepts plain records matching a guard shape.\n *\n * @remarks\n * Three calling modes depending on the `optional` argument:\n * - **No `optional`** — all shape keys required; extra keys rejected.\n * - **`optional: K[]`** — the listed keys are optional; all others required.\n * - **`optional: true`** — every shape key is optional.\n *\n * Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by\n * an inherited prototype member (`toString`, `constructor`, …) counts as absent.\n * A non-object / `null` / array input returns `false` rather than throwing. The\n * The exactness check inspects every own string key, including non-enumerable\n * keys. Symbol keys are ignored intentionally for JSON fidelity.\n *\n * @example\n * ```ts\n * const isUser = recordOf({ name: isString, age: isNumber })\n * isUser({ name: 'Ada', age: 36 }) // true\n * isUser({ name: 'Ada' }) // false — age missing\n *\n * const isPartial = recordOf({ name: isString, age: isNumber }, ['age'])\n * isPartial({ name: 'Ada' }) // true\n * ```\n */\nexport function recordOf<\n\tS extends GuardsShape,\n\tK extends ReadonlyArray<keyof S & string> | true | undefined,\n>(\n\tshape: S,\n\toptional?: K,\n): Guard<\n\tK extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S>\n> {\n\tconst allowed = new Set<string>()\n\tfor (const key of Reflect.ownKeys(shape)) {\n\t\tif (isString(key)) {\n\t\t\tallowed.add(key)\n\t\t}\n\t}\n\tconst optionalSet = new Set<string>(\n\t\toptional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : [],\n\t)\n\n\treturn (\n\t\tvalue: unknown,\n\t): value is K extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S> =>\n\t\tholds(() => {\n\t\t\tif (!isRecord(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\t\tif (isString(key) && !allowed.has(key)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const key of allowed) {\n\t\t\t\tconst present = Object.hasOwn(value, key)\n\t\t\t\tif (!optionalSet.has(key) && !present) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif (present) {\n\t\t\t\t\tconst guard = shape[key]\n\t\t\t\t\tif (guard === undefined || !guard(value[key])) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n}\n\n/**\n * Build a guard that accepts values that are own keys of the provided object.\n *\n * @remarks\n * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys\n * (`toString`, `constructor`, …) are rejected. An own property that shadows a\n * prototype name is accepted.\n *\n * @example\n * ```ts\n * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const\n * const isColorKey = keyOf(COLORS)\n * isColorKey('red') // true\n * isColorKey('purple') // false\n * isColorKey('toString') // false — inherited, not an own key\n * ```\n */\nexport function keyOf<const O extends Readonly<Record<PropertyKey, unknown>>>(\n\tvalue: O,\n): Guard<keyof O> {\n\treturn (entry: unknown): entry is keyof O =>\n\t\tholds(\n\t\t\t() => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry),\n\t\t)\n}\n\n/**\n * Build a new guard shape by keeping only the listed keys — the structural\n * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isName = recordOf(pickOf(full, ['name']))\n * isName({ name: 'Ada' }) // true\n * ```\n */\nexport function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Pick<S, K[number]> {\n\t// Honest typing: the accumulator IS the picked-shape type, so every write is\n\t// checked against `S[P]` — no `as` / `!` / `asserts`. The seed is a genuine\n\t// null-prototype empty object, filled before any read.\n\tconst result: { [P in K[number]]: S[P] } = Object.create(null)\n\tfor (const key of keys) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Build a new guard shape by removing the listed keys — the structural\n * equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isPublic = recordOf(omitOf(full, ['role']))\n * isPublic({ name: 'Ada', age: 36 }) // true\n * ```\n */\nexport function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Omit<S, K[number]> {\n\tconst skipped = new Set<PropertyKey>()\n\tfor (const key of keys) {\n\t\tskipped.add(key)\n\t}\n\t// Sound over-approximation: only kept keys are written, so the value\n\t// structurally satisfies `Omit<S, K[number]>`. Same honest typing as\n\t// `pickOf` — no `as` / `!` / `asserts`.\n\tconst result: { [P in keyof S]: S[P] } = Object.create(null)\n\tfor (const key in shape) {\n\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!skipped.has(key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Combine two guards with logical AND — passes only when both pass.\n *\n * @remarks\n * Use {@link whereOf} when the right side refines an already-narrowed type; use\n * `andOf` to combine two independent guards.\n *\n * @example\n * ```ts\n * const isShortString = andOf(isString, isNonEmptyString)\n * ```\n */\nexport function andOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A & B>\nexport function andOf<T, U extends T>(left: Guard<T>, right: (value: T) => value is U): Guard<U>\nexport function andOf<T>(left: Guard<T>, right: (value: T) => boolean): Guard<T>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => holds(() => left(value) && right(value))\n}\n\n/**\n * Combine two guards with logical OR — passes when at least one passes. For more\n * than two variants prefer {@link unionOf}.\n *\n * @example\n * ```ts\n * const isStringOrNumber = orOf(isString, isNumber)\n * ```\n */\nexport function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => holds(() => left(value) || right(value))\n}\n\n/**\n * Negate a guard or predicate — passes when `guard` returns `false`.\n *\n * @remarks\n * Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use\n * {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.\n *\n * @example\n * ```ts\n * const isNotNull = notOf(isNull)\n * ```\n */\nexport function notOf(guard: (value: unknown) => boolean): Guard<unknown> {\n\treturn (value: unknown): value is unknown => holds(() => !guard(value))\n}\n\n/**\n * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass\n * `base` but not `excluded`.\n *\n * @example\n * ```ts\n * const isNonEmpty = complementOf(isString, isEmptyString)\n * isNonEmpty('hi') // true\n * isNonEmpty('') // false\n * ```\n */\nexport function complementOf<TBase, TExcluded extends TBase>(\n\tbase: Guard<TBase>,\n\texcluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded),\n): Guard<Exclude<TBase, TExcluded>> {\n\treturn (value: unknown): value is Exclude<TBase, TExcluded> =>\n\t\tholds(() => base(value) && !excluded(value))\n}\n\n/**\n * Build a guard that accepts values matching at least one of the provided\n * guards — the variadic form of {@link orOf}.\n *\n * @example\n * ```ts\n * const isStringOrBoolean = unionOf(isString, isBoolean)\n * ```\n */\nexport function unionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<GuardType<Gs[number]>>\nexport function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>\nexport function unionOf(...guards: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown> {\n\treturn (value: unknown): value is unknown => holds(() => guards.some((guard) => guard(value)))\n}\n\n/**\n * Build a guard that accepts values matching ALL of the provided guards — the\n * variadic form of {@link andOf}.\n *\n * @example\n * ```ts\n * const isNonEmpty = intersectionOf(isString, isNonEmptyString)\n * ```\n */\nexport function intersectionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<IntersectionFromGuards<Gs>>\nexport function intersectionOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown>\nexport function intersectionOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => holds(() => guards.every((guard) => guard(value)))\n}\n\n/**\n * Refine a base guard with an additional predicate that runs only when the base\n * passes.\n *\n * @remarks\n * The predicate receives a value already narrowed to `T`. When the predicate is\n * itself a type guard (`value is U`), the result narrows to `Guard<U>` — it\n * passes only when the value is genuinely a `U`, so the narrowing is sound. Per\n * §14 the returned guard never throws: if `predicate` throws, the throw is\n * contained and the guard reports a non-match.\n *\n * @example\n * ```ts\n * const isPositive = whereOf(isNumber, (n) => n > 0)\n * isPositive(5) // true\n * isPositive(-1) // false\n *\n * // A narrowing predicate refines the result type to Guard<5>\n * const isFive = whereOf(isNumber, (n): n is 5 => n === 5)\n * ```\n */\nexport function whereOf<T, U extends T>(\n\tbase: Guard<T>,\n\tpredicate: (value: T) => value is U,\n): Guard<U>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T> {\n\treturn (value: unknown): value is T => holds(() => base(value) && predicate(value))\n}\n\n/**\n * Defer guard creation until first use by calling `thunk()` on every\n * invocation.\n *\n * @remarks\n * `thunk` is called on every guard call, not cached — this lets it close over a\n * binding assigned *after* `lazyOf` is called, the primary use case for\n * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard\n * it resolves to) is contained and reported as a non-match.\n *\n * Each lazy guard tracks its active invocation depth. An invocation that would\n * exceed {@link GUARD_DEPTH_LIMIT} returns `false` before resolving `thunk`; the\n * counter always unwinds after the contained call, so one deep or cyclic input\n * cannot poison later guard calls.\n *\n * @example\n * ```ts\n * type Tree = { value: number; children: Tree[] }\n * let isTree: Guard<Tree>\n * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })\n * ```\n */\nexport function lazyOf<T>(thunk: () => Guard<T>): Guard<T> {\n\tlet depth = 0\n\treturn (value: unknown): value is T => {\n\t\tif (depth >= GUARD_DEPTH_LIMIT) return false\n\t\tdepth += 1\n\t\ttry {\n\t\t\treturn holds(() => thunk()(value))\n\t\t} finally {\n\t\t\tdepth -= 1\n\t\t}\n\t}\n}\n\n/**\n * Build a guard that passes when the base passes AND the projection of the value\n * satisfies the target guard. Still narrows to `T` (the base type) — the target\n * check is a validity constraint on a derived view, not a type transformation.\n *\n * @remarks\n * `project` is a plain `(value: T) => U`. Per §14 the returned guard never\n * throws: a throw from `project` or `target` is contained and reported as a\n * non-match. (Unlike the reference implementation, there is no\n * \"curried projector\" branch — a projection that legitimately returns a function\n * would be double-invoked under that scheme. Compose explicitly if you need it.)\n *\n * @example\n * ```ts\n * const isBounded = transformOf(\n * isString,\n * (s) => s.trim().length,\n * whereOf(isNumber, (n) => n >= 1 && n <= 50),\n * )\n * isBounded('hello') // true\n * isBounded('') // false\n * ```\n */\nexport function transformOf<T, U>(\n\tbase: Guard<T>,\n\tproject: (value: T) => U,\n\ttarget: Guard<U>,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T> {\n\treturn (value: unknown): value is T => holds(() => base(value) && target(project(value)))\n}\n\n/**\n * Build a guard that accepts finite numbers within an inclusive `[min, max]`\n * range.\n *\n * @remarks\n * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /\n * `±Infinity` are rejected before any comparison runs. An absent bound never\n * constrains that side. Reused for a number's own value AND, applied to a\n * `.length`, for string and array length refinements — the single source of the\n * bound logic shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const inRange = boundsOf(1, 5)\n * inRange(3) // true\n * inRange(0) // false — below min\n * inRange(6) // false — above max\n *\n * const atLeastTwo = boundsOf(2)\n * atLeastTwo(2) // true — unbounded above\n * ```\n */\nexport function boundsOf(min?: number, max?: number): Guard<number> {\n\treturn whereOf(\n\t\tisFiniteNumber,\n\t\t(value) => (min === undefined || value >= min) && (max === undefined || value <= max),\n\t)\n}\n\n/**\n * Build a guard that accepts strings matching a regular expression.\n *\n * @remarks\n * Clones the pattern for the guard and strips the stateful `g` / `y` flags, so\n * repeated checks are stable and never change the caller's `lastIndex`.\n *\n * @param pattern - The regular expression to own and apply\n * @returns A stateless string guard\n *\n * @example\n * ```ts\n * const isHex = matchOf(/^[0-9a-f]+$/)\n * isHex('1a2f') // true\n * isHex('xyz') // false\n * ```\n */\nexport function matchOf(pattern: RegExp): Guard<string> {\n\tconst owned = new RegExp(pattern.source, pattern.flags.replaceAll('g', '').replaceAll('y', ''))\n\treturn whereOf(isString, (value) => owned.test(value))\n}\n\n/**\n * Build a guard that accepts strings satisfying optional length and pattern\n * refinements — `min` / `max` length and a `pattern`.\n *\n * @remarks\n * Composes {@link isString} with {@link boundsOf} on the string's `.length` and\n * an owned stateless pattern (the same refinement {@link matchOf} performs).\n * When all three options are absent it returns the bare {@link isString} guard\n * (the unconstrained fast path), so an unrefined string leaf pays no wrapping\n * cost. The single source of the string refinement shared by the compiled guard\n * and parser (compilers.ts).\n *\n * @param options - Optional length bounds and regular expression refinement\n * @returns A string guard enforcing the requested refinements\n *\n * @example\n * ```ts\n * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })\n * isSlug('hello-world') // true\n * isSlug('') // false — below min\n * isSlug('Hello') // false — pattern miss\n *\n * stringOf() // identical to isString\n * ```\n */\nexport function stringOf(options?: {\n\tmin?: number\n\tmax?: number\n\tpattern?: RegExp\n}): Guard<string> {\n\tconst min = options?.min\n\tconst max = options?.max\n\tconst source = options?.pattern\n\tconst pattern =\n\t\tsource === undefined\n\t\t\t? undefined\n\t\t\t: new RegExp(source.source, source.flags.replaceAll('g', '').replaceAll('y', ''))\n\tif (min === undefined && max === undefined && pattern === undefined) {\n\t\treturn isString\n\t}\n\tconst withinLength = boundsOf(min, max)\n\treturn whereOf(\n\t\tisString,\n\t\t(value) => withinLength(value.length) && (pattern === undefined || pattern.test(value)),\n\t)\n}\n\n/**\n * Extend a guard to also allow `null`.\n *\n * @example\n * ```ts\n * const isNullableString = nullableOf(isString)\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function nullableOf<T>(guard: Guard<T>): Guard<T | null> {\n\treturn (value: unknown): value is T | null => holds(() => value === null || guard(value))\n}\n\n/**\n * Extend a guard to also allow `undefined` — the optional counterpart of\n * {@link nullableOf}.\n *\n * @example\n * ```ts\n * const isOptionalString = optionalOf(isString)\n * isOptionalString('hi') // true\n * isOptionalString(undefined) // true\n * isOptionalString(null) // false\n * ```\n */\nexport function optionalOf<T>(guard: Guard<T>): Guard<T | undefined> {\n\treturn (value: unknown): value is T | undefined =>\n\t\tholds(() => value === undefined || guard(value))\n}\n","import type { Guard, JSONValue } from './types.js'\nimport type { FieldPath } from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisJSONValue,\n\tisNull,\n\tisNumber,\n\tisRecord,\n\tisString,\n} from './validators.js'\nimport { attempt, holds, resolveField } from './helpers.js'\n\n// AGENTS §14: a parser answers \"give me a `T` or nothing\" — it returns the\n// typed value or `undefined`, and it never throws. Each leaf parser here forms a\n// SOUND pair with the guard for its output TYPE: a guard-valid input is returned\n// UNCHANGED (by identity, never rejected), and every non-`undefined` output\n// satisfies that type guard. The pairings (verified in parsers.test.ts):\n//\n// parseString ↔ isString parseRecord ↔ isRecord\n// parseNumber ↔ isFiniteNumber parseArray ↔ arrayOf(guard) / isArray\n// parseInteger ↔ isInteger parseEnum ↔ literalOf(...allowed)\n// parseBoolean ↔ isBoolean parseNull ↔ isNull\n// parseJSONValue ↔ isJSONValue\n//\n// Coercion of NON-valid inputs (e.g. numeric strings → numbers) is a bonus on\n// top of soundness, not a violation of it — clause A only constrains inputs the\n// guard already accepts.\n//\n// These leaf parsers are deliberately TYPE-only: they know nothing about a\n// shape's `min` / `max` / `pattern` refinements. Those refinements are enforced\n// one layer up, by the compiled parser (compilers.ts `compileParser`), which\n// re-applies the shared refinement combinators (`stringOf` / `boundsOf`,\n// combinators.ts) after coercion — the same source the compiled guard uses. So `createContract(...).parse` IS sound against the FULL\n// guard (refinements included); the split keeps each leaf parser small while the\n// compiler composes the full soundness.\n//\n// Coercion policy — which types cross into which:\n// - number <-> string is BIDIRECTIONAL by design: parseNumber accepts a\n// numeric string ('42' -> 42) and parseString accepts a finite number,\n// stringifying it (42 -> '42'). Use isString / isFiniteNumber directly\n// (never the parser) when you need STRICT type rejection with no coercion.\n// - boolean is a coercion SINK, never a source: parseBoolean accepts\n// 'true'/'false'/'1'/'0' and 1/0 and coerces them TO a boolean, but\n// parseNumber and parseString both reject booleans outright — a boolean\n// never coerces INTO a number or string. This is intentional asymmetry:\n// '1' meaning \"the number one\" and '1' meaning \"true\" are genuinely\n// different domains, so only the boolean parser treats the numeric/string\n// forms as booleans.\n\n// === Primitive parsers\n\n/**\n * Parse an unknown value to a string.\n *\n * @remarks\n * A string is returned unchanged; a finite number is coerced to its decimal\n * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A string, or `undefined`\n *\n * @example\n * ```ts\n * parseString('hi') // 'hi'\n * parseString(42) // '42'\n * parseString(true) // undefined\n * ```\n */\nexport function parseString(value: unknown): string | undefined {\n\tif (isString(value)) return value\n\tif (isFiniteNumber(value)) return String(value)\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite number.\n *\n * @remarks\n * A finite number is returned unchanged; a non-blank numeric string is parsed\n * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every\n * other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumber(42) // 42\n * parseNumber('42') // 42\n * parseNumber('abc') // undefined\n * ```\n */\nexport function parseNumber(value: unknown): number | undefined {\n\tif (typeof value === 'number') {\n\t\treturn Number.isFinite(value) ? value : undefined\n\t}\n\tif (isString(value)) {\n\t\tif (value.trim() === '') return undefined\n\t\tconst parsed = Number(value)\n\t\treturn Number.isFinite(parsed) ? parsed : undefined\n\t}\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite integer.\n *\n * @remarks\n * Accepts whatever {@link parseNumber} accepts, then requires the result to have\n * no fractional part. `3.14` / `'3.14'` → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite integer, or `undefined`\n *\n * @example\n * ```ts\n * parseInteger(42) // 42\n * parseInteger(3.14) // undefined\n * ```\n */\nexport function parseInteger(value: unknown): number | undefined {\n\tconst parsed = parseNumber(value)\n\tif (parsed === undefined) return undefined\n\treturn Number.isInteger(parsed) ? parsed : undefined\n}\n\n/**\n * Parse an unknown value to a boolean.\n *\n * @remarks\n * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /\n * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything\n * else → `undefined`.\n *\n * @param value - The value to parse\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBoolean(true) // true\n * parseBoolean('1') // true\n * parseBoolean('nope') // undefined\n * ```\n */\nexport function parseBoolean(value: unknown): boolean | undefined {\n\tif (typeof value === 'boolean') return value\n\tif (value === 'true' || value === '1' || value === 1) return true\n\tif (value === 'false' || value === '0' || value === 0) return false\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to `null`.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel every other parser in this file uses. Only `null` passes;\n * every other value (including `undefined`) → `undefined`.\n *\n * @param value - The value to parse\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNull(null) // null\n * parseNull(undefined) // undefined\n * ```\n */\nexport function parseNull(value: unknown): null | undefined {\n\treturn isNull(value) ? value : undefined\n}\n\n// === Structural parsers\n\n/**\n * Parse an unknown value to a plain record — the input reference, never cloned.\n *\n * @param value - The value to parse\n * @returns The record, or `undefined`\n */\nexport function parseRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined\n}\n\n/**\n * Parse an unknown value to an array — the input reference, never cloned —\n * optionally guarding every element.\n *\n * @remarks\n * Without a `guard`, element types are NOT verified; let `T` default to\n * `unknown` rather than asserting a specific element type.\n *\n * @param value - The value to parse\n * @param guard - Optional element guard\n * @returns The array, or `undefined`\n *\n * @example\n * ```ts\n * parseArray([1, 2]) // [1, 2]\n * parseArray([1, 'x'], isNumber) // undefined\n * ```\n */\nexport function parseArray<T = unknown>(\n\tvalue: unknown,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\tif (!isArray<T>(value)) return undefined\n\tif (\n\t\tguard !== undefined &&\n\t\t!holds(() => {\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tif (!Object.hasOwn(value, index) || !guard(value[index])) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t) {\n\t\treturn undefined\n\t}\n\treturn value\n}\n\n/**\n * Parse an unknown value to a cycle-safe JSON value — the input reference,\n * never cloned.\n *\n * @remarks\n * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it\n * walks the entire tree via {@link isJSONValue} rather than checking only the\n * top-level shape. That walk is cycle-safe and total (never throws) because\n * `isJSONValue` runs its own probe inside a guard, so an adversarial\n * structure (a cycle, a hostile getter) yields `undefined` instead of hanging\n * or throwing.\n *\n * @param value - The value to parse\n * @returns The value, or `undefined` when it is not a valid JSON value\n *\n * @example\n * ```ts\n * parseJSONValue({ a: 1 }) // { a: 1 }\n * parseJSONValue(Number.NaN) // undefined\n * ```\n */\nexport function parseJSONValue(value: unknown): JSONValue | undefined {\n\treturn isJSONValue(value) ? value : undefined\n}\n\n// === Enum parser\n\n/**\n * Parse an unknown value as one of the allowed literal primitives.\n *\n * @remarks\n * Pairs with {@link literalOf} — both match by SameValueZero, so the\n * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive\n * (string, number, or boolean), not only strings. Matching is identity, never\n * cross-type coercion: `parseEnum('1', [1])` stays `undefined`. The allowed\n * values are copied into an owned frozen `Set`; hostile iteration returns\n * `undefined` rather than escaping.\n *\n * @param value - The value to parse\n * @param allowed - The permitted literal values\n * @returns The input when it matches an allowed literal by SameValueZero, or `undefined`\n *\n * @example\n * ```ts\n * parseEnum('b', ['a', 'b', 'c']) // 'b'\n * parseEnum('z', ['a', 'b', 'c']) // undefined\n * ```\n */\nexport function parseEnum<const T extends string | number | boolean>(\n\tvalue: unknown,\n\tallowed: readonly T[],\n): T | undefined\nexport function parseEnum(\n\tvalue: unknown,\n\tallowed: readonly (string | number | boolean)[],\n): string | number | boolean | undefined\nexport function parseEnum(\n\tvalue: unknown,\n\tallowed: readonly (string | number | boolean)[],\n): string | number | boolean | undefined {\n\tconst outcome = attempt(() => Object.freeze(new Set<unknown>(allowed)))\n\tif (!outcome.success || !outcome.value.has(value)) return undefined\n\treturn isString(value) || isNumber(value) || isBoolean(value) ? value : undefined\n}\n\n// === Record-field parsers\n\n/**\n * Read and parse a string field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A string, or `undefined`\n */\nexport function parseStringField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): string | undefined {\n\treturn parseString(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-number field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumberField({ age: '42' }, 'age') // 42\n * parseNumberField({}, 'age') // undefined\n * ```\n */\nexport function parseNumberField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseNumber(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-integer field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite integer, or `undefined`\n */\nexport function parseIntegerField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseInteger(resolveField(record, path))\n}\n\n/**\n * Read and parse a boolean field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBooleanField({ on: 'true' }, 'on') // true\n * parseBooleanField({}, 'on') // undefined\n * ```\n */\nexport function parseBooleanField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): boolean | undefined {\n\treturn parseBoolean(resolveField(record, path))\n}\n\n/**\n * Read and parse a `null` field from a record by key or nested key path.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel, which also covers a missing field.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNullField({ value: null }, 'value') // null\n * parseNullField({}, 'value') // undefined\n * ```\n */\nexport function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined {\n\treturn parseNull(resolveField(record, path))\n}\n\n/**\n * Read and parse a nested record field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A plain record, or `undefined`\n */\nexport function parseRecordField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): Record<string, unknown> | undefined {\n\treturn parseRecord(resolveField(record, path))\n}\n\n/**\n * Read and parse an array field from a record by key or nested key path,\n * optionally guarding elements.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param guard - Optional element guard\n * @returns An array, or `undefined`\n *\n * @example\n * ```ts\n * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]\n * parseArrayField({}, 'tags') // undefined\n * ```\n */\nexport function parseArrayField<T = unknown>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\treturn parseArray(resolveField(record, path), guard)\n}\n\n/**\n * Read and parse an enum field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param allowed - The permitted literal values\n * @returns The matched literal, or `undefined`\n */\nexport function parseEnumField<const T extends string | number | boolean>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tallowed: readonly T[],\n): T | undefined {\n\treturn parseEnum(resolveField(record, path), allowed)\n}\n\n/**\n * Read and parse a JSON-value field from a record by key or nested key path.\n *\n * @remarks\n * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that\n * function's remarks for why this differs from the shallow\n * {@link parseRecordField} / {@link parseArrayField}.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The value, or `undefined`\n *\n * @example\n * ```ts\n * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }\n * parseJSONValueField({}, 'data') // undefined\n * ```\n */\nexport function parseJSONValueField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): JSONValue | undefined {\n\treturn parseJSONValue(resolveField(record, path))\n}\n\n// === JSON\n\n/**\n * Parse a JSON string, returning `undefined` instead of throwing.\n *\n * @remarks\n * The safe boundary for untrusted JSON text: a malformed string yields\n * `undefined`, never an exception. Returns `unknown` — a successful parse proves\n * nothing about shape, so narrow the result with a guard (or use\n * {@link parseJSONAs}). A large document is not walked here; parsing is shallow\n * and lazy validation is the caller's to compose.\n *\n * @param value - The JSON string to parse\n * @returns The parsed value, or `undefined` when `value` is not valid JSON\n */\nexport function parseJSON(value: string): unknown {\n\ttry {\n\t\treturn JSON.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Parse a JSON string and validate the result against a guard.\n *\n * @remarks\n * The lazy, safe path from an untrusted string to a typed `T`: parse, then check\n * the parsed value with the guard you bring — typically one composed from the\n * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is\n * validated, so a large document is never walked in full unless the guard does.\n *\n * @param value - The JSON string to parse\n * @param guard - The guard for the expected shape\n * @returns The parsed value when it satisfies `guard`, otherwise `undefined`\n *\n * @example\n * ```ts\n * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })\n * parseJSONAs('{\"host\":\"localhost\",\"tags\":[\"a\"]}', isConfig) // { host: 'localhost', tags: ['a'] }\n * parseJSONAs('{\"host\":\"localhost\"}', isConfig) // undefined — guard fails\n * parseJSONAs('not json', isConfig) // undefined — never throws\n * ```\n */\nexport function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined {\n\tconst parsed = parseJSON(value)\n\tif (parsed === undefined) return undefined\n\tlet result: T | undefined = undefined\n\tholds(() => {\n\t\tif (!guard(parsed)) return false\n\t\tresult = parsed\n\t\treturn true\n\t})\n\treturn result\n}\n","import type {\n\tContractInterface,\n\tContractShape,\n\tFault,\n\tFaultKind,\n\tGuard,\n\tInfer,\n\tJSONSchema,\n\tParser,\n\tRandomFunction,\n} from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisInteger,\n\tisJSONValue,\n\tisNull,\n\tisRecord,\n\tisString,\n\tisUndefined,\n} from './validators.js'\nimport {\n\tattempt,\n\tdrawRandom,\n\tenumerableKeys,\n\tpreview,\n\tseededRandom,\n\tshapeToKind,\n} from './helpers.js'\nimport { COMPILE_DEPTH_LIMIT, FAULT_LIMIT, GENERATION_ATTEMPT_LIMIT } from './constants.js'\nimport { ContractError, isContractError } from './errors.js'\nimport { cloneSchema, cloneShape, ownShape } from './cloners.js'\nimport {\n\tarrayOf,\n\tboundsOf,\n\tintersectionOf,\n\tliteralOf,\n\tmatchOf,\n\tnullableOf,\n\torOf,\n\tstringOf,\n\tunionOf,\n\twhereOf,\n} from './combinators.js'\nimport { parseBoolean, parseInteger, parseNumber, parseRecord, parseString } from './parsers.js'\n\n// The compilers walk a finite, developer-authored shape tree (never cyclic) and\n// recurse on themselves — branches are kept inline and public per AGENTS §5,\n// never hidden behind private helpers. `compileGuard` / `compileParser` /\n// `compileReporter` reuse the existing combinators and parsers rather than\n// re-implementing them — including `literalOf` for literal membership, so\n// SameValueZero matching has one implementation package-wide. Every entry point\n// opens with `ownShape` (cloners.ts), the one place the frozen-means-owned\n// invariant lives.\n\n// === Validation\n\n/**\n * Gate recursive compiler work on shape depth and structural cycles.\n *\n * @remarks\n * Walks the shape graph iteratively in linear time and stack space, tracking\n * active ancestors so shared children remain legal. Every standalone compiler\n * calls this gate before its recursive branch begins. The depth check runs\n * before the active-ancestor check, so a back-edge first reached beyond\n * {@link COMPILE_DEPTH_LIMIT} reports `depth`; a shallower cycle reports\n * `cycle`.\n *\n * @param shape - The shape graph to gate\n * @returns Nothing; successful return means recursive compilation is depth-safe\n * @throws {ContractError} When the shape is cyclic or exceeds the compilation depth limit\n */\nexport function validateShapeDepth(shape: ContractShape): void {\n\tconst active = new WeakSet<ContractShape>()\n\tconst stack: (\n\t\t| { readonly operation: 'enter'; readonly shape: ContractShape; readonly depth: number }\n\t\t| { readonly operation: 'exit'; readonly shape: ContractShape }\n\t)[] = [{ operation: 'enter', shape, depth: 0 }]\n\n\twhile (stack.length > 0) {\n\t\tconst frame = stack.pop()\n\t\tif (frame === undefined) continue\n\t\tif (frame.operation === 'exit') {\n\t\t\tactive.delete(frame.shape)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst current = frame.shape\n\t\tif (frame.depth > COMPILE_DEPTH_LIMIT) {\n\t\t\tthrow new ContractError('validateShapeDepth: a shape exceeds the compilation depth limit', {\n\t\t\t\tcode: 'depth',\n\t\t\t\tcontext: { shape: current.type, limit: COMPILE_DEPTH_LIMIT },\n\t\t\t})\n\t\t}\n\t\tif (active.has(current)) {\n\t\t\tthrow new ContractError('validateShapeDepth: a shape graph may not contain a cycle', {\n\t\t\t\tcode: 'cycle',\n\t\t\t})\n\t\t}\n\t\tactive.add(current)\n\t\tstack.push({ operation: 'exit', shape: current })\n\n\t\tswitch (current.type) {\n\t\t\tcase 'array':\n\t\t\t\tstack.push({ operation: 'enter', shape: current.items, depth: frame.depth + 1 })\n\t\t\t\tbreak\n\t\t\tcase 'object': {\n\t\t\t\tconst extra = current.additionalProperties\n\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\t\tstack.push({ operation: 'enter', shape: extra, depth: frame.depth + 1 })\n\t\t\t\t}\n\t\t\t\tconst keys = Object.keys(current.properties)\n\t\t\t\tfor (let index = keys.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst key = keys[index]\n\t\t\t\t\tif (key === undefined) continue\n\t\t\t\t\tconst child = current.properties[key]\n\t\t\t\t\tif (child !== undefined) {\n\t\t\t\t\t\tstack.push({ operation: 'enter', shape: child, depth: frame.depth + 1 })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'union':\n\t\t\t\tfor (let index = current.variants.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst variant = current.variants[index]\n\t\t\t\t\tif (variant !== undefined) {\n\t\t\t\t\t\tstack.push({ operation: 'enter', shape: variant, depth: frame.depth + 1 })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'optional':\n\t\t\tcase 'nullable':\n\t\t\t\tstack.push({ operation: 'enter', shape: current.inner, depth: frame.depth + 1 })\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\n\t}\n}\n\n/**\n * Validate that a {@link ContractShape} graph is well-formed before\n * compilation.\n *\n * @remarks\n * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this\n * throws a coded {@link ContractError} immediately rather than surfacing as a\n * silently-wrong guard, parser, schema, or generator later. The iterative walk\n * tracks active ancestors, so a structural cycle reports its precise path while\n * a shared child reached through separate paths remains legal. Checks:\n *\n * - An {@link OptionalShape} is only legal as a direct object-property value —\n * `optionalShape` wrapping an array item, a union variant, another\n * optional/nullable's inner shape, `additionalProperties`, or the top-level\n * shape all throw. An object property IS the one legal placement: its value\n * is unwrapped to `.inner` before recursing, so `.inner` itself is validated\n * as a normal (non-optional-wrapping) shape.\n * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}\n * needs at least one value and rejects non-finite (`NaN` / `Infinity` /\n * `-Infinity`) number values.\n * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}\n * needs `min <= max` when both are set.\n * - Every present number bound is finite.\n * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer\n * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.\n * - Shape nesting may not exceed {@link COMPILE_DEPTH_LIMIT}; excessive depth\n * fails before recursive artifact compilation begins. Because the depth check\n * runs before the active-ancestor check, a back-edge first reached beyond the\n * limit reports `depth`; a cycle reached within the limit reports `cycle`.\n * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion\n * continues into array items, object properties (and `additionalProperties`\n * when it is a shape), union variants, and optional/nullable inner shapes.\n *\n * @param shape - The shape to validate\n * @throws {ContractError} When the shape is malformed or cyclic\n *\n * @example\n * ```ts\n * validateShape(stringShape({ min: 1, max: 10 })) // does not throw\n * validateShape(stringShape({ min: 10, max: 1 })) // throws\n * ```\n */\nexport function validateShape(shape: ContractShape): void {\n\tconst active = new WeakSet<ContractShape>()\n\tconst stack: (\n\t\t| {\n\t\t\t\treadonly operation: 'enter'\n\t\t\t\treadonly shape: ContractShape\n\t\t\t\treadonly path: readonly string[]\n\t\t\t\treadonly optional: boolean\n\t\t\t\treadonly depth: number\n\t\t }\n\t\t| { readonly operation: 'exit'; readonly shape: ContractShape }\n\t)[] = [{ operation: 'enter', shape, path: [], optional: false, depth: 0 }]\n\n\twhile (stack.length > 0) {\n\t\tconst frame = stack.pop()\n\t\tif (frame === undefined) continue\n\t\tif (frame.operation === 'exit') {\n\t\t\tactive.delete(frame.shape)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst current = frame.shape\n\t\tif (frame.depth > COMPILE_DEPTH_LIMIT) {\n\t\t\tthrow new ContractError('validateShape: a shape exceeds the compilation depth limit', {\n\t\t\t\tcode: 'depth',\n\t\t\t\tcontext: { path: frame.path, shape: current.type, limit: COMPILE_DEPTH_LIMIT },\n\t\t\t})\n\t\t}\n\t\tif (active.has(current)) {\n\t\t\tthrow new ContractError('validateShape: a shape graph may not contain a cycle', {\n\t\t\t\tcode: 'cycle',\n\t\t\t\tcontext: { path: frame.path },\n\t\t\t})\n\t\t}\n\t\tactive.add(current)\n\t\tstack.push({ operation: 'exit', shape: current })\n\n\t\tswitch (current.type) {\n\t\t\tcase 'string':\n\t\t\t\tif (current.min !== undefined && current.max !== undefined && current.min > current.max) {\n\t\t\t\t\tthrow new ContractError('validateShape: a string shape has min greater than max', {\n\t\t\t\t\t\tcode: 'range',\n\t\t\t\t\t\tcontext: { path: frame.path, shape: 'string' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'number':\n\t\t\t\tif (current.min !== undefined && !Number.isFinite(current.min)) {\n\t\t\t\t\tthrow new ContractError('validateShape: a number shape min must be finite', {\n\t\t\t\t\t\tcode: 'bound',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tpath: frame.path,\n\t\t\t\t\t\t\tshape: current.integer === true ? 'integer' : 'number',\n\t\t\t\t\t\t\tlimit: 'finite number',\n\t\t\t\t\t\t\treceived: String(current.min),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (current.max !== undefined && !Number.isFinite(current.max)) {\n\t\t\t\t\tthrow new ContractError('validateShape: a number shape max must be finite', {\n\t\t\t\t\t\tcode: 'bound',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tpath: frame.path,\n\t\t\t\t\t\t\tshape: current.integer === true ? 'integer' : 'number',\n\t\t\t\t\t\t\tlimit: 'finite number',\n\t\t\t\t\t\t\treceived: String(current.max),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (current.min !== undefined && current.max !== undefined && current.min > current.max) {\n\t\t\t\t\tthrow new ContractError('validateShape: a number shape has min greater than max', {\n\t\t\t\t\t\tcode: 'range',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tpath: frame.path,\n\t\t\t\t\t\t\tshape: current.integer === true ? 'integer' : 'number',\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (current.integer === true) {\n\t\t\t\t\tconst lo = Math.ceil(current.min ?? Number.NEGATIVE_INFINITY)\n\t\t\t\t\tconst hi = Math.floor(current.max ?? Number.POSITIVE_INFINITY)\n\t\t\t\t\tif (lo > hi) {\n\t\t\t\t\t\tthrow new ContractError(\n\t\t\t\t\t\t\t'validateShape: an integer number shape has an empty integer range',\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcode: 'range',\n\t\t\t\t\t\t\t\tcontext: { path: frame.path, shape: 'integer' },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'boolean':\n\t\t\tcase 'null':\n\t\t\tcase 'json':\n\t\t\tcase 'raw':\n\t\t\t\tbreak\n\t\t\tcase 'literal':\n\t\t\t\tif (current.values.length === 0) {\n\t\t\t\t\tthrow new ContractError('validateShape: a literal shape needs at least one value', {\n\t\t\t\t\t\tcode: 'empty',\n\t\t\t\t\t\tcontext: { path: frame.path, shape: 'literal' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tfor (const value of current.values) {\n\t\t\t\t\tif (typeof value === 'number' && !Number.isFinite(value)) {\n\t\t\t\t\t\tthrow new ContractError(\n\t\t\t\t\t\t\t'validateShape: a literal shape may not contain non-finite number values',\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcode: 'literal',\n\t\t\t\t\t\t\t\tcontext: { path: frame.path, shape: 'literal', received: String(value) },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'array':\n\t\t\t\tif (current.min !== undefined && current.max !== undefined && current.min > current.max) {\n\t\t\t\t\tthrow new ContractError('validateShape: an array shape has min greater than max', {\n\t\t\t\t\t\tcode: 'range',\n\t\t\t\t\t\tcontext: { path: frame.path, shape: 'array' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tstack.push({\n\t\t\t\t\toperation: 'enter',\n\t\t\t\t\tshape: current.items,\n\t\t\t\t\tpath: [...frame.path, 'items'],\n\t\t\t\t\toptional: false,\n\t\t\t\t\tdepth: frame.depth + 1,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\tcase 'object': {\n\t\t\t\tconst extra = current.additionalProperties\n\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\t\tstack.push({\n\t\t\t\t\t\toperation: 'enter',\n\t\t\t\t\t\tshape: extra,\n\t\t\t\t\t\tpath: [...frame.path, 'additionalProperties'],\n\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\tdepth: frame.depth + 1,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst keys = Object.keys(current.properties)\n\t\t\t\tfor (let index = keys.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst key = keys[index]\n\t\t\t\t\tif (key === undefined) continue\n\t\t\t\t\tconst child = current.properties[key]\n\t\t\t\t\tif (child === undefined) continue\n\t\t\t\t\tstack.push({\n\t\t\t\t\t\toperation: 'enter',\n\t\t\t\t\t\tshape: child,\n\t\t\t\t\t\tpath: [...frame.path, 'properties', key],\n\t\t\t\t\t\toptional: true,\n\t\t\t\t\t\tdepth: frame.depth + 1,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'union':\n\t\t\t\tif (current.variants.length === 0) {\n\t\t\t\t\tthrow new ContractError('validateShape: a union shape needs at least one variant', {\n\t\t\t\t\t\tcode: 'empty',\n\t\t\t\t\t\tcontext: { path: frame.path, shape: 'union' },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tfor (let index = current.variants.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst variant = current.variants[index]\n\t\t\t\t\tif (variant === undefined) continue\n\t\t\t\t\tstack.push({\n\t\t\t\t\t\toperation: 'enter',\n\t\t\t\t\t\tshape: variant,\n\t\t\t\t\t\tpath: [...frame.path, 'variants', String(index)],\n\t\t\t\t\t\toptional: false,\n\t\t\t\t\t\tdepth: frame.depth + 1,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'optional':\n\t\t\t\tif (!frame.optional) {\n\t\t\t\t\tthrow new ContractError(\n\t\t\t\t\t\t'validateShape: an optional shape may only appear as a direct object-property value',\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: 'placement',\n\t\t\t\t\t\t\tcontext: { path: frame.path, shape: 'optional' },\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tstack.push({\n\t\t\t\t\toperation: 'enter',\n\t\t\t\t\tshape: current.inner,\n\t\t\t\t\tpath: [...frame.path, 'inner'],\n\t\t\t\t\toptional: false,\n\t\t\t\t\tdepth: frame.depth + 1,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\tcase 'nullable':\n\t\t\t\tstack.push({\n\t\t\t\t\toperation: 'enter',\n\t\t\t\t\tshape: current.inner,\n\t\t\t\t\tpath: [...frame.path, 'inner'],\n\t\t\t\t\toptional: false,\n\t\t\t\t\tdepth: frame.depth + 1,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t}\n\t}\n}\n\n// === Schema\n\n/**\n * Compile a {@link ContractShape} into a JSON Schema document.\n *\n * @remarks\n * Object shapes emit `additionalProperties: false` (unless opened) and list only\n * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:\n * 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned\n * rather than retained by reference. Emission only — it never inspects a\n * runtime value. {@link validateShapeDepth} iteratively rejects excessive\n * nesting or cycles before recursive emission begins.\n *\n * @param shape - The shape to compile\n * @returns The emitted JSON Schema\n *\n * @example\n * ```ts\n * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }\n * ```\n */\nexport function compileSchema(shape: ContractShape): JSONSchema {\n\tconst owned = ownShape(shape)\n\tvalidateShapeDepth(owned)\n\tswitch (owned.type) {\n\t\tcase 'string':\n\t\t\treturn Object.freeze({\n\t\t\t\ttype: 'string',\n\t\t\t\t...(owned.min !== undefined ? { minLength: owned.min } : {}),\n\t\t\t\t...(owned.max !== undefined ? { maxLength: owned.max } : {}),\n\t\t\t\t...(owned.pattern !== undefined ? { pattern: owned.pattern.source } : {}),\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'number':\n\t\t\treturn Object.freeze({\n\t\t\t\ttype: owned.integer === true ? 'integer' : 'number',\n\t\t\t\t...(owned.min !== undefined ? { minimum: owned.min } : {}),\n\t\t\t\t...(owned.max !== undefined ? { maximum: owned.max } : {}),\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'boolean':\n\t\t\treturn Object.freeze({\n\t\t\t\ttype: 'boolean',\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'null':\n\t\t\treturn Object.freeze({\n\t\t\t\ttype: 'null',\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'json':\n\t\t\treturn Object.freeze({\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'literal':\n\t\t\treturn Object.freeze({\n\t\t\t\tenum: Object.freeze([...owned.values]),\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'array':\n\t\t\treturn Object.freeze({\n\t\t\t\ttype: 'array',\n\t\t\t\titems: compileSchema(owned.items),\n\t\t\t\t...(owned.min !== undefined ? { minItems: owned.min } : {}),\n\t\t\t\t...(owned.max !== undefined ? { maxItems: owned.max } : {}),\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'object': {\n\t\t\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\t\t\tconst required: string[] = []\n\t\t\tfor (const key of Object.keys(owned.properties)) {\n\t\t\t\tconst child = owned.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tproperties[key] = compileSchema(child)\n\t\t\t\tif (child.type !== 'optional') required.push(key)\n\t\t\t}\n\t\t\tconst extra = owned.additionalProperties\n\t\t\tconst additionalProperties: boolean | JSONSchema =\n\t\t\t\textra === true\n\t\t\t\t\t? true\n\t\t\t\t\t: extra !== undefined && extra !== false\n\t\t\t\t\t\t? compileSchema(extra)\n\t\t\t\t\t\t: false\n\t\t\treturn Object.freeze({\n\t\t\t\ttype: 'object',\n\t\t\t\t...(Object.keys(properties).length > 0 ? { properties: Object.freeze(properties) } : {}),\n\t\t\t\t...(required.length > 0 ? { required: Object.freeze(required) } : {}),\n\t\t\t\tadditionalProperties,\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\t}\n\t\tcase 'union':\n\t\t\treturn Object.freeze({\n\t\t\t\t...(owned.mode === 'oneOf'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toneOf: Object.freeze(owned.variants.map((variant) => compileSchema(variant))),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tanyOf: Object.freeze(owned.variants.map((variant) => compileSchema(variant))),\n\t\t\t\t\t\t}),\n\t\t\t\t...(owned.description !== undefined ? { description: owned.description } : {}),\n\t\t\t})\n\t\tcase 'optional':\n\t\t\treturn compileSchema(owned.inner)\n\t\tcase 'nullable':\n\t\t\treturn Object.freeze({\n\t\t\t\tanyOf: Object.freeze([compileSchema(owned.inner), Object.freeze({ type: 'null' })]),\n\t\t\t})\n\t\tcase 'raw':\n\t\t\treturn cloneSchema(owned.schema)\n\t}\n}\n\n// === Guard\n\n/**\n * Compile a {@link ContractShape} into a runtime type guard.\n *\n * @remarks\n * Reuses the combinators for structural and refined shapes, including\n * {@link literalOf} for SameValueZero literal matching. Compiled object shapes\n * observe own enumerable string keys through {@link enumerableKeys}, matching\n * their parser, reporter, and inference view for both open and closed objects.\n * Like every guard it is total — it never throws (AGENTS §14). The shape is\n * taken through {@link ownShape} first, so an unfrozen caller-owned graph\n * compiles from a snapshot. {@link validateShapeDepth} iteratively rejects\n * excessive nesting or cycles before recursive guard compilation begins.\n *\n * @param shape - The shape to compile\n * @returns A guard narrowing to the shape's inferred type\n *\n * @example\n * ```ts\n * const isUser = compileGuard(objectShape({ name: stringShape() }))\n * isUser({ name: 'Ada' }) // true\n * ```\n */\nexport function compileGuard<S extends ContractShape>(shape: S): Guard<Infer<S>>\nexport function compileGuard(shape: ContractShape): Guard<unknown>\nexport function compileGuard(shape: ContractShape): Guard<unknown> {\n\tconst owned = ownShape(shape)\n\tvalidateShapeDepth(owned)\n\tswitch (owned.type) {\n\t\tcase 'string':\n\t\t\t// `stringOf` returns bare `isString` when unrefined, else composes the\n\t\t\t// length-bounds + pattern refinement — the same guard the parser re-applies.\n\t\t\treturn stringOf({\n\t\t\t\t...(owned.min === undefined ? {} : { min: owned.min }),\n\t\t\t\t...(owned.max === undefined ? {} : { max: owned.max }),\n\t\t\t\t...(owned.pattern === undefined ? {} : { pattern: owned.pattern }),\n\t\t\t})\n\t\tcase 'number': {\n\t\t\tconst base = owned.integer === true ? isInteger : isFiniteNumber\n\t\t\tif (owned.min === undefined && owned.max === undefined) return base\n\t\t\t// `boundsOf` already refines `isFiniteNumber`; intersect with `isInteger`\n\t\t\t// when the leaf is an integer so both the integrality and the bounds hold.\n\t\t\treturn owned.integer === true\n\t\t\t\t? intersectionOf(isInteger, boundsOf(owned.min, owned.max))\n\t\t\t\t: boundsOf(owned.min, owned.max)\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn isBoolean\n\t\tcase 'null':\n\t\t\treturn isNull\n\t\tcase 'json':\n\t\t\treturn isJSONValue\n\t\tcase 'literal':\n\t\t\t// `literalOf` IS the package's literal match (SameValueZero over an owned\n\t\t\t// `Set`); the array form takes a machine-generated vocabulary no spread\n\t\t\t// could carry.\n\t\t\treturn literalOf(owned.values)\n\t\tcase 'array': {\n\t\t\tconst base = arrayOf(compileGuard(owned.items))\n\t\t\tif (owned.min === undefined && owned.max === undefined) return base\n\t\t\tconst withinLength = boundsOf(owned.min, owned.max)\n\t\t\treturn whereOf(base, (value) => withinLength(value.length))\n\t\t}\n\t\tcase 'object': {\n\t\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t\t// prototype — the same pattern `pickOf` uses (combinators.ts).\n\t\t\tconst map: Record<string, Guard<unknown>> = Object.create(null)\n\t\t\tconst optionalKeys: string[] = []\n\t\t\tfor (const key of Object.keys(owned.properties)) {\n\t\t\t\tconst child = owned.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional') {\n\t\t\t\t\tmap[key] = compileGuard(child.inner)\n\t\t\t\t\toptionalKeys.push(key)\n\t\t\t\t} else {\n\t\t\t\t\tmap[key] = compileGuard<ContractShape>(child)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst extra = owned.additionalProperties\n\t\t\tconst closed = extra === undefined || extra === false\n\t\t\tconst additional = closed || extra === true ? undefined : compileGuard(extra)\n\t\t\tconst required = Object.keys(map).filter((key) => !optionalKeys.includes(key))\n\t\t\treturn (value: unknown): value is unknown => {\n\t\t\t\tif (!isRecord(value)) return false\n\t\t\t\tconst keys = enumerableKeys(value)\n\t\t\t\tif (keys === undefined) return false\n\t\t\t\tconst present = new Set(keys)\n\t\t\t\tfor (const key of required) {\n\t\t\t\t\tif (!present.has(key)) return false\n\t\t\t\t}\n\t\t\t\t// Contain the whole key-enumeration + value-read walk — a hostile\n\t\t\t\t// getter on `value` must yield `false`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tfor (const key of keys) {\n\t\t\t\t\t\tconst guard = Object.hasOwn(map, key) ? map[key] : undefined\n\t\t\t\t\t\tif (guard !== undefined) {\n\t\t\t\t\t\t\tif (!guard(value[key])) return false\n\t\t\t\t\t\t} else if (closed) {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t} else if (additional !== undefined && !additional(value[key])) {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\treturn outcome.success && outcome.value\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst guards = owned.variants.map((variant) => compileGuard(variant))\n\t\t\t// A `oneOf`-mode union matches the emitted JSON Schema `oneOf` keyword —\n\t\t\t// EXACTLY one variant must guard-accept the value, not \"at least one\"\n\t\t\t// (unionOf's anyOf semantics). A value matching two-or-more variants is\n\t\t\t// rejected, since it would violate the compiled schema.\n\t\t\tif (owned.mode === 'oneOf') {\n\t\t\t\treturn (value: unknown): value is unknown =>\n\t\t\t\t\tguards.filter((guard) => guard(value)).length === 1\n\t\t\t}\n\t\t\treturn unionOf(...guards)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn orOf(isUndefined, compileGuard(owned.inner))\n\t\tcase 'nullable':\n\t\t\treturn nullableOf(compileGuard(owned.inner))\n\t\tcase 'raw':\n\t\t\treturn (value: unknown): value is unknown => value !== undefined\n\t}\n}\n\n// === Parser\n\n/**\n * Compile a {@link ContractShape} into an input parser.\n *\n * @remarks\n * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /\n * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a\n * whole on any required-field failure; a union returns a guard-valid value\n * unchanged, otherwise the first variant that both parses and guards wins.\n *\n * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same\n * combinators `compileGuard` uses — `stringOf` for a string's length/pattern,\n * `boundsOf` for a number's value and an array's length, and {@link literalOf}\n * for literal membership — so a value that coerces but violates a bound parses\n * to `undefined`. The result is full parse↔guard soundness (AGENTS §14): a\n * non-`undefined` parse always satisfies the contract's `is`, refinements\n * included. Object presence and extra-key processing use the same\n * own-enumerable-string snapshot as the guard, reporter, and inference. The\n * shape is taken through {@link ownShape} first, so an unfrozen caller-owned\n * graph compiles from a snapshot. {@link validateShapeDepth} iteratively\n * rejects excessive nesting or cycles before recursive parser compilation.\n *\n * @param shape - The shape to compile\n * @returns A parser yielding the shape's inferred type or `undefined`\n *\n * @example\n * ```ts\n * const parseUser = compileParser(objectShape({ name: stringShape() }))\n * parseUser({ name: 'Ada' }) // { name: 'Ada' }\n * ```\n */\nexport function compileParser<S extends ContractShape>(shape: S): Parser<Infer<S>>\nexport function compileParser(shape: ContractShape): Parser<unknown>\nexport function compileParser(shape: ContractShape): Parser<unknown> {\n\tconst owned = ownShape(shape)\n\tvalidateShapeDepth(owned)\n\tswitch (owned.type) {\n\t\tcase 'string': {\n\t\t\tif (owned.min === undefined && owned.max === undefined && owned.pattern === undefined) {\n\t\t\t\treturn parseString\n\t\t\t}\n\t\t\t// Coerce by type, then re-apply the SAME refinement the guard enforces (the\n\t\t\t// identical `stringOf`) — a value that parses but violates a bound or the\n\t\t\t// pattern fails the parse (returns `undefined`).\n\t\t\tconst guard = stringOf({\n\t\t\t\t...(owned.min === undefined ? {} : { min: owned.min }),\n\t\t\t\t...(owned.max === undefined ? {} : { max: owned.max }),\n\t\t\t\t...(owned.pattern === undefined ? {} : { pattern: owned.pattern }),\n\t\t\t})\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = parseString(value)\n\t\t\t\treturn parsed !== undefined && guard(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst base = owned.integer === true ? parseInteger : parseNumber\n\t\t\tif (owned.min === undefined && owned.max === undefined) return base\n\t\t\t// The same bound check the guard applies (integrality is already enforced by\n\t\t\t// `parseInteger`, so only the bounds need re-checking after coercion).\n\t\t\tconst within = boundsOf(owned.min, owned.max)\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = base(value)\n\t\t\t\treturn parsed !== undefined && within(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean\n\t\tcase 'null':\n\t\t\treturn (value) => (value === null ? null : undefined)\n\t\tcase 'json':\n\t\t\treturn (value) => (isJSONValue(value) ? value : undefined)\n\t\t// The literal parser trims a matching string but never numeric-coerces —\n\t\t// `'42'` never parses to the literal `42`; only an exact (post-trim) match\n\t\t// of one of the shape's `values` succeeds. This is an intended leniency,\n\t\t// not a soundness gap: a trimmed value is re-checked against `allowed`,\n\t\t// the same `literalOf` guard the compiled guard uses.\n\t\tcase 'literal': {\n\t\t\tconst allowed = literalOf(owned.values)\n\t\t\treturn (value) => {\n\t\t\t\tif (allowed(value)) return value\n\t\t\t\tif (isString(value)) {\n\t\t\t\t\tconst trimmed = value.trim()\n\t\t\t\t\tif (allowed(trimmed)) return trimmed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst item = compileParser(owned.items)\n\t\t\tconst unbounded = owned.min === undefined && owned.max === undefined\n\t\t\tconst withinLength = boundsOf(owned.min, owned.max)\n\t\t\treturn (value) => {\n\t\t\t\tif (!isArray(value)) return undefined\n\t\t\t\tconst result: unknown[] = []\n\t\t\t\tfor (const entry of value) {\n\t\t\t\t\tconst parsed = item(entry)\n\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\tresult.push(parsed)\n\t\t\t\t}\n\t\t\t\t// Enforce the SAME length bounds the guard does (coercion never changes\n\t\t\t\t// length, so this is checked once on the assembled result).\n\t\t\t\treturn unbounded || withinLength(result.length) ? result : undefined\n\t\t\t}\n\t\t}\n\t\t// A closed object (no `additionalProperties`) silently drops unknown keys\n\t\t// present on the input rather than failing the parse — an intended\n\t\t// coercion leniency (the compiled guard still rejects them; this only\n\t\t// matters for guard-invalid inputs handed to `parse`).\n\t\tcase 'object': {\n\t\t\tconst entries: { key: string; parse: Parser<unknown>; optional: boolean }[] = []\n\t\t\tfor (const key of Object.keys(owned.properties)) {\n\t\t\t\tconst child = owned.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\tentries.push({ key, parse: compileParser(optional ? child.inner : child), optional })\n\t\t\t}\n\t\t\tconst known = new Set(entries.map((entry) => entry.key))\n\t\t\tconst extra = owned.additionalProperties\n\t\t\tconst additional =\n\t\t\t\textra === undefined || extra === false || extra === true ? undefined : compileParser(extra)\n\t\t\tconst open = extra === true || additional !== undefined\n\t\t\treturn (value) => {\n\t\t\t\tconst record = parseRecord(value)\n\t\t\t\tif (record === undefined) return undefined\n\t\t\t\tconst keys = enumerableKeys(record)\n\t\t\t\tif (keys === undefined) return undefined\n\t\t\t\tconst present = new Set(keys)\n\t\t\t\t// Contain the whole record walk — a hostile getter on `record` must\n\t\t\t\t// yield `undefined`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\t// Honest typing: a null-prototype accumulator so an input own key\n\t\t\t\t\t// literally named '__proto__' lands as an own data key instead of\n\t\t\t\t\t// mutating the prototype (same pattern as `pickOf`).\n\t\t\t\t\tconst result: Record<string, unknown> = Object.create(null)\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tif (!present.has(entry.key)) {\n\t\t\t\t\t\t\tif (entry.optional) continue\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst raw = record[entry.key]\n\t\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\t\tif (entry.optional) continue\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst parsed = entry.parse(raw)\n\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\tresult[entry.key] = parsed\n\t\t\t\t\t}\n\t\t\t\t\tif (open) {\n\t\t\t\t\t\tfor (const key of keys) {\n\t\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\t\tif (additional === undefined) {\n\t\t\t\t\t\t\t\tresult[key] = record[key]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst parsed = additional(record[key])\n\t\t\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\t\t\tresult[key] = parsed\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn result\n\t\t\t\t})\n\t\t\t\treturn outcome.success ? outcome.value : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst variants = owned.variants.map((variant) => ({\n\t\t\t\tparse: compileParser(variant),\n\t\t\t\tguard: compileGuard(variant),\n\t\t\t}))\n\t\t\t// `oneOf` exactly-one semantics (documented on `oneOfShape`): judged on\n\t\t\t// the RAW input's guard matches only — no coercion fallback. Exactly one\n\t\t\t// variant's guard must accept the raw value; that variant's parser then\n\t\t\t// runs (its parse must equal the already guard-valid input by clause A).\n\t\t\t// Zero matches (no variant fits) or two-or-more matches (ambiguous —\n\t\t\t// which variant the value belongs to isn't well-defined) both fail the\n\t\t\t// parse, deliberately simpler than attempting a coercion-then-recheck\n\t\t\t// resolution for ambiguous input.\n\t\t\tif (owned.mode === 'oneOf') {\n\t\t\t\treturn (value) => {\n\t\t\t\t\tconst matches = variants.filter((variant) => variant.guard(value))\n\t\t\t\t\tconst [only] = matches\n\t\t\t\t\treturn matches.length === 1 && only !== undefined ? only.parse(value) : undefined\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (value) => {\n\t\t\t\t// Identity pass first (AGENTS §14 clause A): a value already valid\n\t\t\t\t// against ANY variant's guard is returned unchanged, so an earlier\n\t\t\t\t// variant's coercion never overwrites a guard-valid input.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tif (variant.guard(value)) return value\n\t\t\t\t}\n\t\t\t\t// Coercion pass: no variant matched as-is, so parse-then-guard,\n\t\t\t\t// first variant that both parses and guards wins.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst parsed = variant.parse(value)\n\t\t\t\t\tif (parsed !== undefined && variant.guard(parsed)) return parsed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'optional': {\n\t\t\tconst inner = compileParser(owned.inner)\n\t\t\treturn (value) => (value === undefined ? undefined : inner(value))\n\t\t}\n\t\tcase 'nullable': {\n\t\t\tconst inner = compileParser(owned.inner)\n\t\t\treturn (value) => (value === null ? null : inner(value))\n\t\t}\n\t\tcase 'raw':\n\t\t\treturn (value) => value\n\t}\n}\n\n// === Generator\n\n/**\n * Compile a {@link ContractShape} into a deterministic seed value.\n *\n * @remarks\n * The same shape and the same `random` source always produce the same value, so\n * seed data is reproducible. Defaults to a {@link seededRandom} source seeded\n * from the wall clock when none is supplied. Shape-generation failures throw a\n * {@link ContractError} with code `'generate'`; {@link drawRandom} failures use\n * code `'random'` and retain the consuming shape category in context.\n * Failures include a degenerate empty `literalShape` / `unionShape`, a\n * pattern-constrained `stringShape` whose generated sample cannot satisfy the\n * pattern, an invalid random sample, and a `rawShape` whose arbitrary embedded\n * schema cannot be auto-generated. {@link validateShapeDepth} iteratively\n * rejects excessive nesting or cycles before recursive generation begins.\n * `createContract` runs\n * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /\n * bounded shape is normally caught there; these throws remain here as defense\n * for standalone `compileGenerator` use. Union candidates are bounded by\n * {@link GENERATION_ATTEMPT_LIMIT} and accepted only when they satisfy the\n * union's compiled guard.\n *\n * @param shape - The shape to generate from\n * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)\n * @returns A value matching the shape\n * @throws {ContractError} When the shape or random source cannot produce a valid value\n *\n * @example\n * ```ts\n * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)\n * ```\n */\nexport function compileGenerator<S extends ContractShape>(\n\tshape: S,\n\trandom?: RandomFunction,\n): Infer<S>\nexport function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown\nexport function compileGenerator(\n\tshape: ContractShape,\n\trandom: RandomFunction = seededRandom(Date.now()),\n): unknown {\n\tconst owned = ownShape(shape)\n\tvalidateShapeDepth(owned)\n\tswitch (owned.type) {\n\t\tcase 'string': {\n\t\t\tconst min = owned.min ?? 0\n\t\t\tconst max = owned.max ?? Math.max(min, 12)\n\t\t\tconst length = Math.max(min, Math.min(max, 8))\n\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n\t\t\tlet value = ''\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tvalue += alphabet[Math.floor(drawRandom(random, 'string') * alphabet.length)]\n\t\t\t}\n\t\t\tif (owned.pattern !== undefined && !matchOf(owned.pattern)(value)) {\n\t\t\t\tthrow new ContractError(\n\t\t\t\t\t'compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way',\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'generate',\n\t\t\t\t\t\tcontext: { shape: 'string', limit: owned.pattern.source },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst sample = drawRandom(random, owned.integer === true ? 'integer' : 'number')\n\t\t\tif (owned.integer === true) {\n\t\t\t\tconst lo = Math.ceil(owned.min ?? (owned.max === undefined ? -100 : owned.max - 100))\n\t\t\t\tconst hi = Math.floor(owned.max ?? (owned.min === undefined ? 100 : owned.min + 100))\n\t\t\t\treturn lo === hi ? lo : Math.floor(lo * (1 - sample) + hi * sample)\n\t\t\t}\n\t\t\tconst lo = owned.min ?? (owned.max === undefined ? -100 : owned.max - 100)\n\t\t\tconst hi = owned.max ?? (owned.min === undefined ? 100 : owned.min + 100)\n\t\t\treturn lo === hi ? lo : lo * (1 - sample) + hi * sample\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn drawRandom(random, 'boolean') >= 0.5\n\t\tcase 'null':\n\t\t\treturn null\n\t\tcase 'json': {\n\t\t\tconst pick = Math.floor(drawRandom(random, 'json') * 5)\n\t\t\tif (pick === 0) return null\n\t\t\tif (pick === 1) return drawRandom(random, 'json') >= 0.5\n\t\t\tif (pick === 2) return Math.floor(drawRandom(random, 'json') * 1000)\n\t\t\tif (pick === 3) {\n\t\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\t\t\t\tlet value = ''\n\t\t\t\tfor (let index = 0; index < 6; index += 1) {\n\t\t\t\t\tvalue += alphabet[Math.floor(drawRandom(random, 'json') * alphabet.length)]\n\t\t\t\t}\n\t\t\t\treturn value\n\t\t\t}\n\t\t\treturn { value: Math.floor(drawRandom(random, 'json') * 1000) }\n\t\t}\n\t\tcase 'literal': {\n\t\t\tif (owned.values.length === 0) {\n\t\t\t\tthrow new ContractError('compileGenerator: a literal shape needs at least one value', {\n\t\t\t\t\tcode: 'generate',\n\t\t\t\t\tcontext: { shape: 'literal', limit: 1 },\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn owned.values[Math.floor(drawRandom(random, 'literal') * owned.values.length)]\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst lo = owned.min ?? Math.min(1, owned.max ?? 1)\n\t\t\tconst hi = owned.max ?? Math.max(lo, 3)\n\t\t\tconst length = Math.floor(drawRandom(random, 'array') * (hi - lo + 1)) + lo\n\t\t\tconst result: unknown[] = []\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tresult.push(compileGenerator(owned.items, random))\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'object': {\n\t\t\t// Honest typing: generated data is a value the caller keeps, so unlike the\n\t\t\t// guard's and parser's null-prototype property views it carries the normal\n\t\t\t// object prototype — `defineProperty` (never assignment) still lands a\n\t\t\t// '__proto__' key as an own data key rather than mutating that prototype.\n\t\t\tconst result: Record<string, unknown> = {}\n\t\t\tfor (const key of Object.keys(owned.properties)) {\n\t\t\t\tconst child = owned.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional' && drawRandom(random, 'object') < 0.3) continue\n\t\t\t\tObject.defineProperty(result, key, {\n\t\t\t\t\tvalue: compileGenerator(child, random),\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// An open object (additionalProperties is a shape, not a boolean) also\n\t\t\t// generates synthetic extra entries so the shape does not trivially\n\t\t\t// generate as `{}` — skip any collision with a declared property name.\n\t\t\tconst extra = owned.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\tconst count = 1 + Math.floor(drawRandom(random, 'object') * 2)\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst key = `key${index}`\n\t\t\t\t\tif (Object.hasOwn(result, key)) continue\n\t\t\t\t\tObject.defineProperty(result, key, {\n\t\t\t\t\t\tvalue: compileGenerator(extra, random),\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\twritable: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'union': {\n\t\t\tif (owned.variants.length === 0) {\n\t\t\t\tthrow new ContractError('compileGenerator: a union shape needs at least one variant', {\n\t\t\t\t\tcode: 'generate',\n\t\t\t\t\tcontext: { shape: 'union', limit: 1 },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst guard = compileGuard<ContractShape>(owned)\n\t\t\tconst attempts = Math.max(GENERATION_ATTEMPT_LIMIT, owned.variants.length)\n\t\t\tconst start = Math.floor(drawRandom(random, 'union') * owned.variants.length)\n\t\t\tfor (let attemptIndex = 0; attemptIndex < attempts; attemptIndex += 1) {\n\t\t\t\tconst variant = owned.variants[(start + attemptIndex) % owned.variants.length]\n\t\t\t\tif (variant === undefined) continue\n\t\t\t\tconst outcome = attempt(() => compileGenerator(variant, random))\n\t\t\t\tif (!outcome.success && isContractError(outcome.error) && outcome.error.code === 'random') {\n\t\t\t\t\tthrow outcome.error\n\t\t\t\t}\n\t\t\t\tif (outcome.success && guard(outcome.value)) return outcome.value\n\t\t\t}\n\t\t\tthrow new ContractError('compileGenerator: no union candidate satisfied the compiled guard', {\n\t\t\t\tcode: 'generate',\n\t\t\t\tcontext: { shape: 'union', limit: attempts },\n\t\t\t})\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileGenerator(owned.inner, random)\n\t\tcase 'nullable':\n\t\t\treturn drawRandom(random, 'nullable') < 0.2 ? null : compileGenerator(owned.inner, random)\n\t\tcase 'raw':\n\t\t\tthrow new ContractError(\n\t\t\t\t'compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way',\n\t\t\t\t{\n\t\t\t\t\tcode: 'generate',\n\t\t\t\t\tcontext: { shape: 'raw', limit: 'explicit value source' },\n\t\t\t\t},\n\t\t\t)\n\t}\n}\n\n// === Reporter\n\n/**\n * Compile a {@link ContractShape} into a structured fault report for a value —\n * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.\n *\n * @remarks\n * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards\n * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /\n * `isJSONValue` / …), so the soundness invariant\n * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`\n * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a\n * coercible value like `'42'` against a `numberShape` reports no fault, the\n * same leniency `parse` grants, even though the strict guard would reject it).\n *\n * Faults are collected in stable pre-order (declared key/index order); every\n * call — object, array, and union alike, including a union's `oneOf` \"no\n * match\" / \"no consensus\" summary fault prepended to its closest variant's\n * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the\n * bound holds at every level of nesting, not just the outermost container, on\n * adversarial input (a huge array, a wide record, a wide union of wide\n * records). A closed object's extra keys never\n * fault — `parse` silently drops them, so `explain` mirrors that leniency; an\n * open object with a constraining `additionalProperties` shape recurses extras\n * against it instead. A hostile getter or throwing `Proxy` trap is contained\n * via {@link attempt} and surfaces as a single top-level type fault, never a\n * throw (AGENTS §14). {@link validateShapeDepth} iteratively rejects excessive\n * shape nesting or cycles before recursive reporting begins.\n *\n * @param shape - The shape to report against\n * @param value - The value to check\n * @param path - The path prefix for faults produced at this call (defaults to the root)\n * @returns The faults found, empty when the value parses successfully\n *\n * @example\n * ```ts\n * const user = objectShape({ name: stringShape({ min: 1 }) })\n * compileReporter(user, { name: '' })\n * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '\"\"' }]\n * compileReporter(user, { name: 'Ada' }) // []\n * ```\n */\nexport function compileReporter(\n\tshape: ContractShape,\n\tvalue: unknown,\n\tpath: string[] = [],\n): readonly Fault[] {\n\tconst owned = ownShape(shape)\n\tvalidateShapeDepth(owned)\n\tswitch (owned.type) {\n\t\tcase 'string': {\n\t\t\tconst parsed = parseString(value)\n\t\t\tif (parsed === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'string', received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tif (owned.min !== undefined && parsed.length < owned.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: owned.min,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (owned.max !== undefined && parsed.length > owned.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: owned.max,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (owned.pattern !== undefined && !matchOf(owned.pattern)(parsed)) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'pattern',\n\t\t\t\t\tlimit: owned.pattern.source,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst kind: FaultKind = owned.integer === true ? 'integer' : 'number'\n\t\t\tconst parsed = parseNumber(value)\n\t\t\tif (parsed === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: kind, received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tif (owned.integer === true && !Number.isInteger(parsed)) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'integer',\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (owned.min !== undefined && parsed < owned.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: owned.min,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (owned.max !== undefined && parsed > owned.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: owned.max,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean(value) === undefined\n\t\t\t\t? [{ reason: 'type', path, expected: 'boolean', received: preview(value) }]\n\t\t\t\t: []\n\t\tcase 'null':\n\t\t\treturn value === null\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'null', received: preview(value) }]\n\t\tcase 'json':\n\t\t\treturn isJSONValue(value)\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'json', received: preview(value) }]\n\t\tcase 'literal': {\n\t\t\tconst allowed = literalOf(owned.values)\n\t\t\tconst matched = allowed(value) || (isString(value) && allowed(value.trim()))\n\t\t\treturn matched\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'literal', received: preview(value) }]\n\t\t}\n\t\tcase 'array': {\n\t\t\tif (!isArray(value)) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'array', received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tconst outcome = attempt(() => {\n\t\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\tfaults.push(...compileReporter(owned.items, value[index], [...path, String(index)]))\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!outcome.success) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'array', received: preview(value) }]\n\t\t\t}\n\t\t\tif (owned.min !== undefined && value.length < owned.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'array',\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: owned.min,\n\t\t\t\t\treceived: String(value.length),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (owned.max !== undefined && value.length > owned.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'array',\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: owned.max,\n\t\t\t\t\treceived: String(value.length),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults.length > FAULT_LIMIT ? faults.slice(0, FAULT_LIMIT) : faults\n\t\t}\n\t\tcase 'object': {\n\t\t\tif (!isRecord(value)) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\tconst record = value\n\t\t\tconst keys = enumerableKeys(record)\n\t\t\tif (keys === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\tconst present = new Set(keys)\n\t\t\tconst faults: Fault[] = []\n\t\t\tconst known = new Set<string>()\n\t\t\tconst outcome = attempt(() => {\n\t\t\t\tfor (const key of Object.keys(owned.properties)) {\n\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\tconst child = owned.properties[key]\n\t\t\t\t\tif (child === undefined) continue\n\t\t\t\t\tknown.add(key)\n\t\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\t\tconst inner = optional ? child.inner : child\n\t\t\t\t\t// Mirror the parser's presence gate exactly: only an own\n\t\t\t\t\t// enumerable string key is present. A present key with an\n\t\t\t\t\t// explicit `undefined` value is still treated like absence, so\n\t\t\t\t\t// `explain` never faults where `parse` silently skips it.\n\t\t\t\t\tif (!present.has(key)) {\n\t\t\t\t\t\tif (!optional) {\n\t\t\t\t\t\t\tfaults.push({ reason: 'missing', path: [...path, key], expected: shapeToKind(inner) })\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst raw = record[key]\n\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\tif (!optional) {\n\t\t\t\t\t\t\tfaults.push({ reason: 'missing', path: [...path, key], expected: shapeToKind(inner) })\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfaults.push(...compileReporter(inner, raw, [...path, key]))\n\t\t\t\t}\n\t\t\t\tconst extra = owned.additionalProperties\n\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\t\tfor (const key of keys) {\n\t\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\tfaults.push(...compileReporter(extra, record[key], [...path, key]))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!outcome.success) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\treturn faults.length > FAULT_LIMIT ? faults.slice(0, FAULT_LIMIT) : faults\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst perVariant = owned.variants.map((variant) => compileReporter(variant, value, path))\n\t\t\tlet bestIndex = 0\n\t\t\tfor (let index = 1; index < perVariant.length; index += 1) {\n\t\t\t\tconst current = perVariant[index]\n\t\t\t\tconst best = perVariant[bestIndex]\n\t\t\t\tif (current !== undefined && best !== undefined && current.length < best.length) {\n\t\t\t\t\tbestIndex = index\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst closest = perVariant[bestIndex] ?? []\n\t\t\tif (owned.mode === 'oneOf') {\n\t\t\t\tlet matched = 0\n\t\t\t\tfor (const variant of owned.variants) {\n\t\t\t\t\tif (compileGuard(variant)(value)) matched += 1\n\t\t\t\t}\n\t\t\t\tif (matched === 1) return []\n\t\t\t\tif (matched === 0) {\n\t\t\t\t\tconst summary: Fault = { reason: 'oneOf', path, matched: 0 }\n\t\t\t\t\treturn [summary, ...closest].slice(0, FAULT_LIMIT)\n\t\t\t\t}\n\t\t\t\treturn [{ reason: 'oneOf', path, matched }]\n\t\t\t}\n\t\t\tconst anyMatch = perVariant.some((variantFaults) => variantFaults.length === 0)\n\t\t\tif (anyMatch) return []\n\t\t\tconst summary: Fault = { reason: 'variant', path, variants: owned.variants.length }\n\t\t\treturn [summary, ...closest].slice(0, FAULT_LIMIT)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn value === undefined ? [] : compileReporter(owned.inner, value, path)\n\t\tcase 'nullable':\n\t\t\treturn value === null ? [] : compileReporter(owned.inner, value, path)\n\t\tcase 'raw':\n\t\t\treturn value === undefined\n\t\t\t\t? [{ reason: 'type', path, expected: 'json', received: preview(value) }]\n\t\t\t\t: []\n\t}\n}\n\n// === Contract\n\n/**\n * Compile a {@link ContractShape} into a {@link ContractInterface} — the five\n * lockstep outputs from one declaration.\n *\n * @remarks\n * Runs {@link validateShape} first — a malformed shape throws immediately\n * rather than compiling into a silently-wrong contract (AGENTS §12). It always\n * takes its own {@link cloneShape} snapshot — never merely a frozen node's word\n * — and hands that same graph to every artifact compiler.\n * Then it precompiles the deeply frozen owned schema, guard, and parser once;\n * `generate` walks the\n * snapshot per call with the supplied random source, and `explain` compiles the\n * diagnostic report via {@link compileReporter} at zero added compile-time cost\n * (it re-walks the snapshot per call, exactly like `generate`).\n *\n * @param shape - The shape to compile\n * @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`\n *\n * @example\n * ```ts\n * const user = createContract(objectShape({ name: stringShape(), age: integerShape() }))\n * user.is({ name: 'Ada', age: 36 }) // true\n * user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 }\n * user.schema // { type: 'object', properties: { … }, … }\n * ```\n */\nexport function createContract<S extends ContractShape>(shape: S): ContractInterface<Infer<S>>\nexport function createContract(shape: ContractShape): ContractInterface<unknown>\nexport function createContract(shape: ContractShape): ContractInterface<unknown> {\n\tconst snapshot = cloneShape(shape)\n\tvalidateShape(snapshot)\n\tconst schema = compileSchema(snapshot)\n\tconst guard = compileGuard(snapshot)\n\tconst parser = compileParser(snapshot)\n\treturn {\n\t\tschema,\n\t\tis: guard,\n\t\tparse(value: unknown): unknown {\n\t\t\treturn parser(value)\n\t\t},\n\t\texplain(value: unknown): readonly Fault[] {\n\t\t\treturn compileReporter(snapshot, value)\n\t\t},\n\t\tgenerate(random?: RandomFunction): unknown {\n\t\t\treturn compileGenerator(snapshot, random)\n\t\t},\n\t}\n}\n","import type { JSONSchema, SchemaFormat, ValueToSchemaOptions } from './types.js'\nimport {\n\tFORMAT_MAX_LENGTH,\n\tFORMAT_PATTERNS,\n\tINFER_BREADTH_LIMIT,\n\tINFER_DEPTH_LIMIT,\n\tINFER_ENUM_LIMIT,\n} from './constants.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisDate,\n\tisFiniteNumber,\n\tisInteger,\n\tisNull,\n\tisNumber,\n\tisRecord,\n\tisString,\n} from './validators.js'\nimport { attempt, enumerableKeys, sanitizeBudget } from './helpers.js'\n\n// The inferers walk an UNKNOWN, possibly adversarial runtime value (or a set\n// of example values) and emit a JSONSchema — the reverse direction of\n// compileSchema (compilers.ts), which walks a finite, developer-authored\n// ContractShape tree. Recursion here is runtime-only and bounded on three\n// axes: a WeakSet of ancestor objects/arrays (cycle safety), a decrementing\n// depth budget (INFER_DEPTH_LIMIT default), and a per-container sampling cap\n// (INFER_BREADTH_LIMIT default) — every branch stays total, per AGENTS §14.\n\n// === Canonicalization\n\n/**\n * Encode one value as a deterministic, key-sorted JSON string — the recursive\n * spine of {@link canonicalStringify}.\n *\n * @remarks\n * Arrays keep their element order; records sort their own keys before encoding,\n * recursively at every nesting level. Every other value is encoded by\n * `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0`\n * encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes.\n *\n * Returns `undefined` for anything JSON cannot encode: `undefined` itself, a\n * function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A\n * container carrying such a member is itself un-encodable and returns\n * `undefined` too, so the result is either a faithful encoding of the WHOLE\n * value or nothing — a partially-encoded key is never emitted. Traversal is NOT\n * contained here: a hostile getter or `Proxy` trap throws through to\n * {@link canonicalStringify}, which owns the single {@link attempt} boundary\n * for the walk.\n *\n * @param value - The value to encode\n * @param ancestors - Objects on the active traversal path, guarding cycles\n * @returns The deterministic encoding, or `undefined` when JSON cannot encode\n * `value`\n *\n * @example\n * ```ts\n * canonicalizeValue({ b: 1, a: 2 }, new WeakSet()) // '{\"a\":2,\"b\":1}'\n * canonicalizeValue(undefined, new WeakSet()) // undefined\n * ```\n */\nexport function canonicalizeValue(value: unknown, ancestors: WeakSet<object>): string | undefined {\n\tif (isArray(value)) {\n\t\tif (ancestors.has(value)) return undefined\n\t\tancestors.add(value)\n\t\tconst parts: string[] = []\n\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t// A hole is an absent element, not a value — the same `Object.hasOwn`\n\t\t\t// rule `arrayOf` and `matchesJSONValue` apply.\n\t\t\tconst part = Object.hasOwn(value, index)\n\t\t\t\t? canonicalizeValue(value[index], ancestors)\n\t\t\t\t: undefined\n\t\t\tif (part === undefined) {\n\t\t\t\tancestors.delete(value)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\tparts.push(part)\n\t\t}\n\t\tancestors.delete(value)\n\t\treturn `[${parts.join(',')}]`\n\t}\n\tif (isRecord(value)) {\n\t\tif (ancestors.has(value)) return undefined\n\t\tancestors.add(value)\n\t\tconst parts: string[] = []\n\t\tfor (const key of Object.keys(value).sort()) {\n\t\t\tconst part = canonicalizeValue(value[key], ancestors)\n\t\t\tif (part === undefined) {\n\t\t\t\tancestors.delete(value)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\tparts.push(`${JSON.stringify(key)}:${part}`)\n\t\t}\n\t\tancestors.delete(value)\n\t\treturn `{${parts.join(',')}}`\n\t}\n\t// `JSON.stringify` returns `undefined` (never a string) for `undefined`, a\n\t// function, and a symbol — exactly the values with no JSON encoding.\n\treturn JSON.stringify(value)\n}\n\n/**\n * Render a value as a deterministic, key-sorted JSON string — or `undefined`\n * when it has no faithful JSON encoding.\n *\n * @remarks\n * The stable-stringify backing {@link unifySchemas}'s de-duplication and\n * ordering: unlike `JSON.stringify`, object keys are sorted before encoding\n * (recursively, at every nesting level), so two structurally-equal\n * `JSONSchema` fragments built independently always canonicalize to the same\n * string. Pure host-independent ECMAScript with no environment-specific imports.\n *\n * TOTAL: it NEVER throws, for any input. It returns `undefined` — never a\n * partial or invalid encoding — for every value JSON cannot faithfully encode:\n *\n * - `undefined` itself, a function, a symbol, or an array hole (JSON encodes\n * none of them), at the top level or anywhere inside a container;\n * - a bigint (`JSON.stringify` throws on one);\n * - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline\n * {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic)\n * reference reached twice through different paths still encodes;\n * - hostile traversal — a throwing own-getter, a hostile `ownKeys` trap, or a\n * revoked `Proxy` anywhere in the value — contained via {@link attempt}.\n *\n * A caller therefore treats `undefined` as \"this value has no canonical key\",\n * never as an encoding: see {@link unifySchemas} (an un-keyed member cannot\n * participate in de-duplication or ordering) and {@link inferPrimitiveEnum} (an\n * un-keyed member makes the slot enum-ineligible).\n *\n * @param value - The value to canonicalize (a `JSONSchema` fragment, or any\n * nested piece of one)\n * @returns A deterministic string encoding of `value`, or `undefined` when JSON\n * cannot encode it\n *\n * @example\n * ```ts\n * canonicalStringify({ type: 'object', properties: {} }) ===\n * \tcanonicalStringify({ properties: {}, type: 'object' }) // true\n * canonicalStringify(Number.NaN) // 'null' — JSON.stringify semantics\n * canonicalStringify(undefined) // undefined\n * canonicalStringify(cyclicValue) // undefined\n * ```\n */\nexport function canonicalStringify(value: unknown): string | undefined {\n\tconst outcome = attempt(() => canonicalizeValue(value, new WeakSet()))\n\treturn outcome.success ? outcome.value : undefined\n}\n\n/**\n * Unify a list of inferred `JSONSchema` fragments into one schema.\n *\n * @remarks\n * De-duplicates by {@link canonicalStringify}, then applies the one\n * special-case subsumption inference performs: a bare `{ type: 'integer' }`\n * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`\n * (an integer sample is also a valid `number` sample). A single surviving\n * distinct schema is returned directly; two or more are wrapped as\n * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.\n * An empty input list returns the empty accept-anything schema `{}`.\n *\n * A member {@link canonicalStringify} cannot key — a cyclic, hostile, or\n * otherwise JSON-inexpressible fragment, which only a direct caller can supply\n * since the inferers always build plain encodable fragments — has NO\n * de-duplication key, so it can participate in neither de-duplication nor the\n * canonical-key ordering. It is KEPT (dropping a variant would narrow the\n * union, and unification only ever widens), appended in input order after the\n * sorted keyed members, so the result stays total and deterministic.\n *\n * @param schemas - The schemas to unify\n * @returns The unified schema\n *\n * @example\n * ```ts\n * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }\n * unifySchemas([{ type: 'string' }, { type: 'boolean' }])\n * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }\n * ```\n */\nexport function unifySchemas(schemas: readonly JSONSchema[]): JSONSchema {\n\tif (schemas.length === 0) return {}\n\tconst seen = new Map<string, JSONSchema>()\n\tconst unkeyed: JSONSchema[] = []\n\tfor (const schema of schemas) {\n\t\tconst key = canonicalStringify(schema)\n\t\tif (key === undefined) {\n\t\t\tunkeyed.push(schema)\n\t\t\tcontinue\n\t\t}\n\t\tif (!seen.has(key)) seen.set(key, schema)\n\t}\n\t// Both literals always canonicalize; the explicit checks keep the\n\t// subsumption total against `canonicalStringify`'s optional result.\n\tconst integerKey = canonicalStringify({ type: 'integer' })\n\tconst numberKey = canonicalStringify({ type: 'number' })\n\tif (\n\t\tintegerKey !== undefined &&\n\t\tnumberKey !== undefined &&\n\t\tseen.has(integerKey) &&\n\t\tseen.has(numberKey)\n\t) {\n\t\tseen.delete(integerKey)\n\t}\n\tconst distinct = [...seen.entries()]\n\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n\t\t.map(([, schema]) => schema)\n\tconst members = [...distinct, ...unkeyed]\n\tif (members.length <= 1) {\n\t\tconst [only] = members\n\t\treturn only ?? {}\n\t}\n\treturn { anyOf: members }\n}\n\n// === Format inference\n\n/**\n * Determine whether an ISO-8601-shaped string parses to a valid instant.\n *\n * @remarks\n * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never\n * throws on a string input, but a value like `2020-13-45` parses to an\n * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation\n * step behind {@link stringToFormat}'s `date` / `date-time` / `time`\n * branches, which pattern-match the shape first and confirm validity here.\n *\n * @param value - The candidate ISO-8601 string\n * @returns `true` when `value` parses to a real instant\n *\n * @example\n * ```ts\n * isValidISOInstant('2020-01-01') // true\n * isValidISOInstant('2020-13-45') // false\n * ```\n */\nexport function isValidISOInstant(value: string): boolean {\n\tconst outcome = attempt(() => {\n\t\tconst date = new Date(value)\n\t\treturn !Number.isNaN(date.getTime())\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Classify a string against the {@link SchemaFormat} vocabulary.\n *\n * @remarks\n * Total, pure, and deterministic. Fixed precedence, most specific first:\n * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first\n * match wins. The `date-time` / `date` / `time` branches require BOTH a\n * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity\n * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.\n * Returns `undefined` when no format matches (including the empty string).\n *\n * @param value - The string to classify\n * @returns The matched {@link SchemaFormat}, or `undefined`\n *\n * @example\n * ```ts\n * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'\n * stringToFormat('2024-01-15') // 'date'\n * stringToFormat('2020-13-45') // undefined — invalid date\n * stringToFormat('ada@example.com') // 'email'\n * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset\n * stringToFormat('10:30:00+02:00') // 'time'\n * ```\n */\nexport function stringToFormat(value: string): SchemaFormat | undefined {\n\tif (value.length > FORMAT_MAX_LENGTH) return undefined\n\tif (FORMAT_PATTERNS.uuid.test(value)) return 'uuid'\n\tif (\n\t\t/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n\t\tisValidISOInstant(value)\n\t) {\n\t\treturn 'date-time'\n\t}\n\tif (/^\\d{4}-\\d{2}-\\d{2}$/.test(value) && isValidISOInstant(value)) {\n\t\treturn 'date'\n\t}\n\tif (\n\t\t/^\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n\t\tisValidISOInstant(`1970-01-01T${value}`)\n\t) {\n\t\treturn 'time'\n\t}\n\tif (FORMAT_PATTERNS.email.test(value)) return 'email'\n\tif (FORMAT_PATTERNS.uri.test(value)) return 'uri'\n\treturn undefined\n}\n\n/**\n * Classify a list of sample values against the {@link SchemaFormat}\n * vocabulary, requiring unanimity.\n *\n * @remarks\n * A format is returned ONLY IF every value is a string AND every one maps to\n * the SAME {@link stringToFormat} result (including all mapping to\n * `undefined`, which itself returns `undefined` here). A single disagreeing\n * value, a non-string value, or an empty list all yield `undefined` — the\n * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})\n * relies on this unanimity so a slot with mixed string shapes emits a bare\n * `{ type: 'string' }` rather than an `anyOf` of formats.\n *\n * @param values - The sample values to classify\n * @returns The unanimous {@link SchemaFormat}, or `undefined`\n *\n * @example\n * ```ts\n * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'\n * samplesToFormat(['2024-01-01', 'not a date']) // undefined\n * samplesToFormat([]) // undefined\n * ```\n */\nexport function samplesToFormat(values: readonly unknown[]): SchemaFormat | undefined {\n\tif (values.length === 0 || !values.every((value) => isString(value))) return undefined\n\tconst formats = values.map((value) => stringToFormat(value))\n\tconst [first, ...rest] = formats\n\tif (first === undefined) return undefined\n\treturn rest.every((format) => format === first) ? first : undefined\n}\n\n// === Enum inference\n\n/**\n * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated\n * primitive slot — the multi-sample-only counterpart to\n * {@link stringToFormat} ({@link valueToSchema} never emits `enum`).\n *\n * @remarks\n * Fires only when ALL of: every value is the same primitive kind (all string\n * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed\n * slot never qualifies, and a slot containing `NaN` / `±Infinity` never\n * qualifies either, since {@link canonicalStringify} collapses `NaN` to\n * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2\n * values are given; the distinct-by-{@link canonicalStringify} count is LESS\n * than the value count (repetition required — separates a categorical column\n * from an ID column); and the distinct count is at most `limit`. The emitted\n * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s\n * `literalShape` emission. Members are sorted by canonical key for\n * deterministic output.\n *\n * A member {@link canonicalStringify} cannot key has no identity to\n * de-duplicate against, so the whole slot is enum-INELIGIBLE and returns\n * `undefined` — widening to the caller's bare `type` rather than emitting an\n * `enum` that might silently omit a value. (A string or finite number always\n * canonicalizes, so this only guards the total contract.)\n *\n * @param values - The collected slot values\n * @param limit - The maximum distinct-value count before giving up\n * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible\n *\n * @example\n * ```ts\n * inferPrimitiveEnum(['active', 'inactive', 'active'], 12)\n * // { enum: ['active', 'inactive'] }\n * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition\n * ```\n */\nexport function inferPrimitiveEnum(\n\tvalues: readonly unknown[],\n\tlimit: number,\n): JSONSchema | undefined {\n\tif (values.length < 2) return undefined\n\tconst allString = values.every((value) => isString(value))\n\tconst allNumber = !allString && values.every((value) => isFiniteNumber(value))\n\tif (!allString && !allNumber) return undefined\n\tconst distinct = new Map<string, string | number>()\n\tfor (const value of values) {\n\t\tif (!isString(value) && !isFiniteNumber(value)) continue\n\t\tconst key = canonicalStringify(value)\n\t\tif (key === undefined) return undefined\n\t\tdistinct.set(key, value)\n\t}\n\tif (distinct.size >= values.length || distinct.size > limit) return undefined\n\tconst sorted = [...distinct.entries()].sort(([left], [right]) =>\n\t\tleft < right ? -1 : left > right ? 1 : 0,\n\t)\n\treturn { enum: sorted.map(([, value]) => value) }\n}\n\n// === Single-value inference\n\n/**\n * Infer a `JSONSchema` fragment for one runtime value — the recursive spine\n * shared by {@link valueToSchema} and, per collected property/element, by\n * {@link inferArray} / {@link inferObject}.\n *\n * @remarks\n * Total: never throws, and terminates on cyclic input via `visited`. Leaf\n * classification order: `null`, boolean, integer (`Number.isInteger`\n * semantics — `-0` counts), finite non-integer number, string (gaining a\n * `format` keyword when `format` is on and {@link stringToFormat} matches),\n * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,\n * plus `format: 'date-time'` when `format` is on); everything else — a\n * NON-FINITE number (`NaN` / `±Infinity`), a function, a symbol, a bigint,\n * `undefined`, and other non-plain objects such as `Map` / `Set` — is the\n * empty accept-anything schema `{}`.\n *\n * A non-finite number bottoms out with the other JSON-inexpressible values on\n * purpose: JSON carries no `NaN` / `±Infinity` (`JSON.stringify(Number.NaN)`\n * is `'null'`), so `{ type: 'number' }` would ASSERT something a JSON Schema\n * validator rejects — and the shape {@link schemaToShape} builds from it would\n * reject the very sample it was inferred from. `{}` is the truthful\n * description, and it inverts to an accept-anything shape, keeping\n * `compileGuard(schemaToShape(valueToSchema(v)))(v)` true.\n *\n * @param value - The value to classify\n * @param depth - Remaining descent budget (0 halts recursion with `{}`)\n * @param breadth - The per-container sampling cap passed through to children\n * @param closed - Whether descended objects emit `additionalProperties: false`\n * @param format - Whether a string/`Date` leaf gains a `format` keyword\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred schema fragment for `value`\n *\n * @example\n * ```ts\n * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }\n * ```\n */\nexport function inferValue(\n\tvalue: unknown,\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (isNull(value)) return { type: 'null' }\n\tif (isBoolean(value)) return { type: 'boolean' }\n\tif (isInteger(value)) return { type: 'integer' }\n\tif (isFiniteNumber(value)) return { type: 'number' }\n\t// A non-finite number has no JSON representation at all, so it widens to\n\t// `{}` with the other inexpressible values rather than claiming a `number`\n\t// type no validator would accept it under.\n\tif (isNumber(value)) return {}\n\tif (isString(value)) {\n\t\tif (format) {\n\t\t\tconst detected = stringToFormat(value)\n\t\t\tif (detected) return { type: 'string', format: detected }\n\t\t}\n\t\treturn { type: 'string' }\n\t}\n\tif (isArray(value)) return inferArray(value, depth, breadth, closed, format, visited, memo)\n\tif (isRecord(value)) return inferObject(value, depth, breadth, closed, format, visited, memo)\n\tif (isDate(value)) return format ? { type: 'string', format: 'date-time' } : { type: 'string' }\n\treturn {}\n}\n\n/**\n * Infer a `JSONSchema` array fragment from an array's sampled elements.\n *\n * @remarks\n * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the\n * first `breadth` elements are classified via {@link inferValue} (one less\n * depth) and unified with {@link unifySchemas}: a single distinct element\n * schema becomes `items` directly; multiple distinct schemas become\n * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of\n * `value` both yield the empty schema `{}` instead of descending. A sparse\n * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before\n * sampling so every slot — including a hole — is visited as an explicit\n * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left\n * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.\n *\n * ALL reads of `value` — including its `length` — happen inside\n * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose\n * `get` trap throws) is exactly as contained as a throwing own-getter element\n * or a Proxy-over-array element access, and cannot escape as a thrown error.\n * On failure — or when the sampled/classified list ends up empty — this\n * returns `{ type: 'array' }` (no `items`), since `value` is still known to\n * be an array, mirroring the empty-array emission. A same-object\n * re-inference at the same remaining `depth` is served from `memo` instead\n * of recomputing (guards a shared-reference DAG against exponential blowup).\n *\n * @param value - The array to infer from\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of elements sampled\n * @param closed - Threaded through to nested object elements\n * @param format - Threaded through to nested string/`Date` elements\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred array schema\n *\n * @example\n * ```ts\n * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())\n * // { type: 'array', items: { type: 'number' } }\n * ```\n */\nexport function inferArray(\n\tvalue: readonly unknown[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (!(depth > 0) || visited.has(value)) return {}\n\t// At a node reached through a cycle at the SAME remaining depth via two\n\t// different paths, the memo may serve the first traversal's already\n\t// cycle-truncated fragment (`{}`) to the second path instead of a fully\n\t// re-descended schema — a sound, deterministic over-approximation, never\n\t// a false-reject (a schema too permissive, never too strict).\n\tconst cached = memo.get(value)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(value)\n\tconst outcome = attempt(() => {\n\t\tconst sampled = Array.from(value.slice(0, breadth))\n\t\treturn sampled.map((entry) =>\n\t\t\tinferValue(entry, depth - 1, breadth, closed, format, visited, memo),\n\t\t)\n\t})\n\tvisited.delete(value)\n\tconst schema: JSONSchema =\n\t\toutcome.success && outcome.value.length > 0\n\t\t\t? { type: 'array', items: unifySchemas(outcome.value) }\n\t\t\t: { type: 'array' }\n\tlet depths = memo.get(value)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(value, depths)\n\t}\n\tdepths.set(depth, schema)\n\treturn schema\n}\n\n/**\n * Infer a `JSONSchema` object fragment from a plain record's sampled\n * properties.\n *\n * @remarks\n * Own enumerable string keys via {@link enumerableKeys}, sorted\n * lexicographically for deterministic output, capped at `breadth`. This is the\n * same property view compiled object guards, parsers, and reporters use. Each\n * property value is read through {@link attempt} so a hostile getter cannot\n * escape as a thrown error; a property whose value is `undefined` is DROPPED\n * — JSON encodes no such property (`JSON.stringify({ a: undefined })` is\n * `'{}'`), so it contributes neither a `properties` entry nor a `required`\n * entry. Every other present key is required (single-value mode).\n *\n * Emits `additionalProperties: false` when `closed`, `true` otherwise —\n * mirroring {@link compileSchema}'s object-emission convention — EXCEPT when\n * the sampled key list no longer describes every key `value` actually carries,\n * which happens two ways: the own-key list exceeds `breadth` (truncation), or\n * a key was dropped for holding `undefined`. Either way `additionalProperties`\n * is forced to `true` regardless of `closed`, because a CLOSED schema built\n * from an incomplete key list would reject the very object it was inferred\n * from (`recordOf` rejects any own key the shape does not declare).\n *\n * Depth exhaustion or a cyclic re-encounter of `value` both yield `{}`. A\n * same-object re-inference at the same remaining `depth` is served from `memo`\n * instead of recomputing (guards a shared-reference DAG against exponential\n * blowup).\n *\n * @param value - The record to infer from\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties sampled\n * @param closed - Whether the emitted schema closes to unknown keys\n * @param format - Threaded through to nested string/`Date` properties\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred object schema\n *\n * @example\n * ```ts\n * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())\n * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],\n * // additionalProperties: false }\n * ```\n */\nexport function inferObject(\n\tvalue: Record<string, unknown>,\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (!(depth > 0) || visited.has(value)) return {}\n\tconst cached = memo.get(value)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(value)\n\t// Contain the whole key-enumeration + value-read walk — a hostile ownKeys\n\t// trap or property getter on `value` must yield {} for this object, never\n\t// throw (AGENTS §14) — mirroring compileGuard's object branch\n\t// (compilers.ts).\n\tconst outcome = attempt(() => {\n\t\tconst snapshot = enumerableKeys(value)\n\t\tif (snapshot === undefined) throw new Error('inferObject: property enumeration failed')\n\t\tconst allKeys = [...snapshot].sort()\n\t\tconst keys = allKeys.slice(0, breadth)\n\t\tconst truncated = allKeys.length > breadth\n\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t// prototype — the same pattern compileGuard / compileParser use\n\t\t// (compilers.ts).\n\t\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\t\tconst required: string[] = []\n\t\tlet dropped = false\n\t\tfor (const key of keys) {\n\t\t\tconst propertyValue = value[key]\n\t\t\tif (propertyValue === undefined) {\n\t\t\t\tdropped = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tproperties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo)\n\t\t\trequired.push(key)\n\t\t}\n\t\treturn { properties, required, partial: truncated || dropped }\n\t})\n\tvisited.delete(value)\n\tif (!outcome.success) return {}\n\tconst { properties, required, partial } = outcome.value\n\tconst schema: JSONSchema = {\n\t\ttype: 'object',\n\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t...(required.length > 0 ? { required } : {}),\n\t\tadditionalProperties: partial ? true : !closed,\n\t}\n\tlet depths = memo.get(value)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(value, depths)\n\t}\n\tdepths.set(depth, schema)\n\treturn schema\n}\n\n/**\n * Infer a `JSONSchema` for one unknown value — the reverse direction of\n * {@link compileSchema}.\n *\n * @remarks\n * Total: never throws, and is cycle/depth/breadth-bounded (see\n * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested\n * objects close to unknown keys (`additionalProperties: false`) by default;\n * pass `closed: false` to open them. `format` (default `false`) opts a\n * string/`Date` leaf into the `format` keyword. Structurally-equal inputs\n * infer byte-identical schemas (object keys and `anyOf` members are sorted).\n *\n * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'\n * }` — is structurally accepted by `schemaToParameters`, but MCP clients\n * expect an object-shaped `inputSchema`; wrap a non-object payload with\n * {@link schemaToObject} before advertising it as a tool's parameters.\n *\n * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a\n * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /\n * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,\n * fractional) — a hostile or malformed budget can never defeat the depth\n * guard or corrupt the sampled key/element list.\n *\n * @param value - The value to infer a schema from\n * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds\n * @returns The inferred `JSONSchema`\n *\n * @example\n * ```ts\n * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },\n * // tags: { type: 'array', items: { type: 'string' } } },\n * // required: ['id', 'name', 'tags'], additionalProperties: false }\n * ```\n */\nexport function valueToSchema(value: unknown, options?: ValueToSchemaOptions): JSONSchema {\n\tconst maxDepth = sanitizeBudget(options?.maxDepth, INFER_DEPTH_LIMIT)\n\tconst maxProperties = sanitizeBudget(options?.maxProperties, INFER_BREADTH_LIMIT)\n\tconst closed = options?.closed ?? true\n\tconst format = options?.format ?? false\n\treturn inferValue(value, maxDepth, maxProperties, closed, format, new WeakSet(), new WeakMap())\n}\n\n// === Multi-sample inference\n\n/**\n * Infer a `JSONSchema` for a collected slot of sample values — the shared\n * non-record recursion step behind {@link samplesToSchema} (top level) and\n * {@link inferRecordSamples} (per collected property).\n *\n * @remarks\n * When every value is itself a plain record, delegates to\n * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when\n * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,\n * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins\n * outright (ENUM > FORMAT > bare string). Failing that, each value is\n * classified independently via {@link inferValue} with `format` FORCED OFF\n * (the multi-sample seam: nested formats never compound into an `anyOf`) and\n * unified with {@link unifySchemas}; only when that unified result is exactly\n * `{ type: 'string' }` and the outer `format` flag is on does\n * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.\n *\n * @param samples - The collected slot values\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties/elements sampled per nested container\n * @param closed - Whether nested objects close to unknown keys\n * @param format - Whether a unanimous string slot gains a `format` keyword\n * @param enumOn - Whether low-cardinality primitive slots may emit `enum`\n * @returns The inferred schema for the slot\n *\n * @example\n * ```ts\n * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)\n * // { type: 'string', format: 'date' }\n * ```\n */\nexport function inferSamples(\n\tsamples: readonly unknown[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tenumOn: boolean,\n): JSONSchema {\n\tif (samples.length === 0) return {}\n\tif (samples.every((sample) => isRecord(sample))) {\n\t\treturn inferRecordSamples(samples, depth, breadth, closed, format, enumOn)\n\t}\n\tif (enumOn) {\n\t\tconst enumSchema = inferPrimitiveEnum(samples, INFER_ENUM_LIMIT)\n\t\tif (enumSchema) return enumSchema\n\t}\n\tconst schemas = samples.map((sample) =>\n\t\tinferValue(sample, depth, breadth, closed, false, new WeakSet(), new WeakMap()),\n\t)\n\tconst unified = unifySchemas(schemas)\n\tif (format && unified.type === 'string' && Object.keys(unified).length === 1) {\n\t\tconst detected = samplesToFormat(samples)\n\t\tif (detected) return { type: 'string', format: detected }\n\t}\n\treturn unified\n}\n\n/**\n * Infer a `JSONSchema` object fragment from a set of plain-record samples\n * (e.g. database rows) — the record-specialized branch of\n * {@link samplesToSchema}.\n *\n * @remarks\n * `properties` is the union of every sample's own keys (sorted, capped at\n * `breadth`); a key is `required` only when present (and non-`undefined`) in\n * EVERY sample. Each key's schema is inferred over the collected values for\n * that key via {@link inferSamples} itself (one less depth), so a\n * property that is itself an array/object of varying shape across rows is\n * unified the same way the top level is, and the same `format` / `enum`\n * gating applies per key. Unlike {@link inferObject}/\n * {@link inferArray}, this path carries no `visited` `WeakSet` — a value\n * shared by reference across multiple sample rows is legitimate (not a\n * cycle back to an ancestor), so termination on cyclic row data relies on\n * the decrementing `depth` budget alone.\n *\n * `additionalProperties` is forced to `true` regardless of `closed` whenever\n * the declared key list stops describing every key the rows carry — the same\n * incomplete-sample-opens-the-schema rule {@link inferObject} applies, so a\n * closed schema never rejects the very rows it was inferred from. That happens\n * three ways: the union of sample keys exceeds `breadth` (truncation); a\n * hostile getter defeats a key's value walk (which drops that key for ALL\n * rows — a deliberate all-or-nothing scope, not a per-row partial failure);\n * or some row carries the key as an own property holding `undefined`, which\n * JSON encodes as no property at all, so the key is dropped rather than\n * declared with a shape that row would fail. When the KEY walk itself fails\n * (a hostile `ownKeys` trap on any row), nothing is known and the whole slot\n * widens to `{}`.\n *\n * @param samples - The plain-record samples\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties sampled\n * @param closed - Whether the emitted schema closes to unknown keys\n * @param format - Whether a unanimous string column gains a `format` keyword\n * @param enumOn - Whether a low-cardinality column may emit `enum`\n * @returns The inferred object schema\n *\n * @example\n * ```ts\n * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },\n * // required: ['id'], additionalProperties: false }\n * ```\n */\nexport function inferRecordSamples(\n\tsamples: readonly Record<string, unknown>[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tenumOn: boolean,\n): JSONSchema {\n\tif (!(depth > 0)) return {}\n\t// Contain the whole key-enumeration walk — a hostile ownKeys trap on any\n\t// sample must yield an empty key set for this branch, never throw\n\t// (AGENTS §14).\n\tconst keySet = new Set<string>()\n\tfor (const sample of samples) {\n\t\tconst sampleKeys = enumerableKeys(sample)\n\t\tif (sampleKeys === undefined) return {}\n\t\tfor (const key of sampleKeys) keySet.add(key)\n\t}\n\tconst allKeys = [...keySet].sort()\n\tconst keys = allKeys.slice(0, breadth)\n\tconst truncated = allKeys.length > breadth\n\t// A failed key walk means nothing at all is known about these rows — not even\n\t// that they behave like readable objects — so the slot widens to `{}` rather\n\t// than claiming `type: 'object'`, whose compiled guard re-enumerates the same\n\t// hostile keys and would reject the very rows it was inferred from.\n\t// Honest typing: a null-prototype accumulator so a key literally named\n\t// '__proto__' becomes an own data key instead of mutating the prototype —\n\t// the same pattern compileGuard / compileParser use (compilers.ts).\n\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\tconst required: string[] = []\n\tlet partial = truncated\n\t// Bounded by depth alone: unlike inferObject/inferArray, this record-\n\t// sample path carries no `visited` WeakSet. A shared reference across\n\t// sample rows is legitimate data (not a cycle back to an ancestor), so\n\t// the decrementing depth budget is the sole termination guarantee here.\n\tfor (const key of keys) {\n\t\t// Contain the per-sample value read — a hostile getter on any sample\n\t\t// must yield an empty value list for this key, never throw\n\t\t// (AGENTS §14).\n\t\tconst valuesOutcome = attempt(() => {\n\t\t\tconst values: unknown[] = []\n\t\t\tlet dropped = false\n\t\t\tfor (const sample of samples) {\n\t\t\t\tconst propertyValue = sample[key]\n\t\t\t\tif (propertyValue === undefined) {\n\t\t\t\t\tif (Object.hasOwn(sample, key)) dropped = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvalues.push(propertyValue)\n\t\t\t}\n\t\t\treturn { values, dropped }\n\t\t})\n\t\tif (!valuesOutcome.success) {\n\t\t\tpartial = true\n\t\t\tcontinue\n\t\t}\n\t\tconst { values, dropped } = valuesOutcome.value\n\t\tif (dropped) {\n\t\t\tpartial = true\n\t\t\tcontinue\n\t\t}\n\t\tif (values.length > 0) {\n\t\t\tproperties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn)\n\t\t}\n\t\tif (values.length === samples.length) required.push(key)\n\t}\n\treturn {\n\t\ttype: 'object',\n\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t...(required.length > 0 ? { required } : {}),\n\t\tadditionalProperties: partial ? true : !closed,\n\t}\n}\n\n/**\n * Infer a `JSONSchema` from a set of example values — the multi-example\n * counterpart of {@link valueToSchema} (e.g. inferring one schema from\n * several database rows).\n *\n * @remarks\n * An empty `samples` array infers the empty accept-anything schema `{}`.\n * When every sample is a plain record, properties/required are unified\n * per-key across all samples (see {@link inferRecordSamples}) — a key\n * required iff present and non-`undefined` in every sample. Otherwise the\n * slot is inferred via {@link inferSamples} (independent {@link valueToSchema}\n * per sample, unified with {@link unifySchemas} — the same de-duplication and\n * `anyOf` ordering {@link inferArray} applies to element schemas). `format`\n * and `enum` (both default `false`) opt a low-cardinality/unanimous-format\n * slot into the corresponding keyword — see {@link inferSamples} for the\n * precedence and the multi-sample format-disabling seam. `maxDepth` /\n * `maxProperties` are sanitized via {@link sanitizeBudget} the same way\n * {@link valueToSchema} sanitizes them — see there for why.\n *\n * @param samples - The example values to infer a schema from\n * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds\n * @returns The inferred `JSONSchema`\n *\n * @example\n * ```ts\n * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },\n * // required: ['id'], additionalProperties: false }\n * samplesToSchema([]) // {}\n * ```\n */\nexport function samplesToSchema(\n\tsamples: readonly unknown[],\n\toptions?: ValueToSchemaOptions,\n): JSONSchema {\n\tconst maxDepth = sanitizeBudget(options?.maxDepth, INFER_DEPTH_LIMIT)\n\tconst maxProperties = sanitizeBudget(options?.maxProperties, INFER_BREADTH_LIMIT)\n\tconst closed = options?.closed ?? true\n\tconst format = options?.format ?? false\n\tconst enumOn = options?.enum ?? false\n\treturn inferSamples(samples, maxDepth, maxProperties, closed, format, enumOn)\n}\n","import type {\n\tArrayShape,\n\tArrayShapeOptions,\n\tBooleanShape,\n\tBooleanShapeOptions,\n\tContractShape,\n\tJSONSchema,\n\tJSONShape,\n\tJSONShapeOptions,\n\tLiteralShape,\n\tLiteralShapeOptions,\n\tNullableShape,\n\tNullShape,\n\tNullShapeOptions,\n\tNumberShape,\n\tNumberShapeOptions,\n\tObjectShape,\n\tObjectShapeOptions,\n\tOptionalShape,\n\tRawShape,\n\tRecordShapeOptions,\n\tStringShape,\n\tStringShapeOptions,\n\tUnionShape,\n} from './types.js'\nimport { cloneSchema, cloneShape } from './cloners.js'\nimport { INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT } from './constants.js'\nimport { ContractError } from './errors.js'\nimport { attempt } from './helpers.js'\nimport { isArray, isBoolean, isFiniteNumber, isInteger, isRecord, isString } from './validators.js'\n\n// The builders return the parameterized types.ts interfaces (e.g. `ArrayShape<S>`,\n// `ObjectShape<P>`), never inline object literals — the generic parameter keeps\n// `Infer<typeof shape>` exact while the return type still enforces conformance to\n// the shared shape interface.\n\n// Shape builders — pure constructors for the `ContractShape` union. Each returns\n// a plain descriptor; the compilers (compilers.ts) turn it into a guard, parser,\n// schema, and generator. The precise return types (e.g. literal tuples, generic\n// `items` / `properties`) are preserved so `Infer<typeof shape>` stays exact.\n\n// === Primitives\n\n/**\n * Build a string {@link StringShape}.\n *\n * @remarks\n * A supplied pattern is captured by source and flags. The shape exposes a fresh\n * frozen zero-state `RegExp` on every `pattern` read, so neither the caller's\n * original nor a value read from the shape can drift later compiled artifacts.\n *\n * @param options - Optional length (`min` / `max`), `pattern`, and `description`\n * @returns A string shape\n * @throws {ContractError} When a present bound is invalid or `pattern` has flags\n *\n * @example\n * ```ts\n * const name = stringShape({ min: 1, max: 80, description: 'Display name' })\n * ```\n */\nexport function stringShape(options?: StringShapeOptions): StringShape {\n\tconst pattern = options?.pattern\n\tif (options?.min !== undefined && (!Number.isSafeInteger(options.min) || options.min < 0)) {\n\t\tthrow new ContractError('stringShape: min must be a non-negative safe integer', {\n\t\t\tcode: 'bound',\n\t\t\tcontext: {\n\t\t\t\tshape: 'string',\n\t\t\t\tlimit: 'non-negative safe integer',\n\t\t\t\treceived: String(options.min),\n\t\t\t},\n\t\t})\n\t}\n\tif (options?.max !== undefined && (!Number.isSafeInteger(options.max) || options.max < 0)) {\n\t\tthrow new ContractError('stringShape: max must be a non-negative safe integer', {\n\t\t\tcode: 'bound',\n\t\t\tcontext: {\n\t\t\t\tshape: 'string',\n\t\t\t\tlimit: 'non-negative safe integer',\n\t\t\t\treceived: String(options.max),\n\t\t\t},\n\t\t})\n\t}\n\tif (pattern !== undefined && pattern.flags.length > 0) {\n\t\tthrow new ContractError(\n\t\t\t'stringShape: pattern must not use flags; use inline pattern constructs instead',\n\t\t\t{\n\t\t\t\tcode: 'pattern',\n\t\t\t\tcontext: { shape: 'string', received: pattern.toString() },\n\t\t\t},\n\t\t)\n\t}\n\treturn cloneShape({\n\t\ttype: 'string',\n\t\t...(options?.min === undefined ? {} : { min: options.min }),\n\t\t...(options?.max === undefined ? {} : { max: options.max }),\n\t\t...(pattern === undefined ? {} : { pattern }),\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build a numeric {@link NumberShape}.\n *\n * @param options - Optional bounds (`min` / `max`), `integer`, and `description`\n * @returns A number shape\n * @throws {ContractError} When a present bound is not finite\n *\n * @example\n * ```ts\n * const age = numberShape({ min: 0, max: 120 })\n * ```\n */\nexport function numberShape(options?: NumberShapeOptions): NumberShape {\n\tconst shape = options?.integer === true ? 'integer' : 'number'\n\tif (options?.min !== undefined && !Number.isFinite(options.min)) {\n\t\tthrow new ContractError('numberShape: min must be finite', {\n\t\t\tcode: 'bound',\n\t\t\tcontext: { shape, limit: 'finite number', received: String(options.min) },\n\t\t})\n\t}\n\tif (options?.max !== undefined && !Number.isFinite(options.max)) {\n\t\tthrow new ContractError('numberShape: max must be finite', {\n\t\t\tcode: 'bound',\n\t\t\tcontext: { shape, limit: 'finite number', received: String(options.max) },\n\t\t})\n\t}\n\treturn Object.freeze({\n\t\ttype: 'number',\n\t\t...(options?.min === undefined ? {} : { min: options.min }),\n\t\t...(options?.max === undefined ? {} : { max: options.max }),\n\t\t...(options?.integer === undefined ? {} : { integer: options.integer }),\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build an integer {@link NumberShape} — forces `integer: true`.\n *\n * @remarks\n * The emitted JSON Schema uses `\"type\": \"integer\"` and the guard rejects\n * fractional numbers.\n *\n * @param options - Optional bounds and `description` (no `integer` key)\n * @returns An integer number shape\n * @throws {ContractError} When a present bound is not finite\n */\nexport function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape {\n\treturn numberShape({ ...options, integer: true })\n}\n\n/**\n * Build a {@link BooleanShape}.\n *\n * @param options - Optional `description`\n * @returns A boolean shape\n *\n * @example\n * ```ts\n * const active = booleanShape({ description: 'Whether the record is active' })\n * ```\n */\nexport function booleanShape(options?: BooleanShapeOptions): BooleanShape {\n\treturn Object.freeze({\n\t\ttype: 'boolean',\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build a {@link NullShape}.\n *\n * @param options - Optional `description`\n * @returns A null shape\n *\n * @example\n * ```ts\n * const empty = nullShape()\n * ```\n */\nexport function nullShape(options?: NullShapeOptions): NullShape {\n\treturn Object.freeze({\n\t\ttype: 'null',\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build a literal shape from a fixed set of primitive values.\n *\n * @param values - The permitted literals\n * @param options - Optional `description`\n * @returns A literal shape whose `Infer` is the union of `values`\n *\n * @example\n * ```ts\n * const role = literalShape(['admin', 'member', 'guest'])\n * // Infer<typeof role> = 'admin' | 'member' | 'guest'\n *\n * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })\n * ```\n */\nexport function literalShape<const T extends readonly (string | number | boolean)[]>(\n\tvalues: T,\n\toptions?: LiteralShapeOptions,\n): LiteralShape<Readonly<T>>\nexport function literalShape(\n\tvalues: readonly (string | number | boolean)[],\n\toptions?: LiteralShapeOptions,\n): LiteralShape {\n\tconst snapshot = Object.freeze([...values])\n\treturn Object.freeze({\n\t\ttype: 'literal',\n\t\tvalues: snapshot,\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n// === Collections\n\n/**\n * Build an {@link ArrayShape} from an element shape.\n *\n * @param items - The element shape\n * @param options - Optional length bounds and `description`\n * @returns An array shape\n * @throws {ContractError} When a present bound is not a non-negative safe integer\n *\n * @example\n * ```ts\n * const tags = arrayShape(stringShape(), { max: 10 })\n * ```\n */\nexport function arrayShape<S extends ContractShape>(\n\titems: S,\n\toptions?: ArrayShapeOptions,\n): ArrayShape<S> {\n\tif (options?.min !== undefined && (!Number.isSafeInteger(options.min) || options.min < 0)) {\n\t\tthrow new ContractError('arrayShape: min must be a non-negative safe integer', {\n\t\t\tcode: 'bound',\n\t\t\tcontext: {\n\t\t\t\tshape: 'array',\n\t\t\t\tlimit: 'non-negative safe integer',\n\t\t\t\treceived: String(options.min),\n\t\t\t},\n\t\t})\n\t}\n\tif (options?.max !== undefined && (!Number.isSafeInteger(options.max) || options.max < 0)) {\n\t\tthrow new ContractError('arrayShape: max must be a non-negative safe integer', {\n\t\t\tcode: 'bound',\n\t\t\tcontext: {\n\t\t\t\tshape: 'array',\n\t\t\t\tlimit: 'non-negative safe integer',\n\t\t\t\treceived: String(options.max),\n\t\t\t},\n\t\t})\n\t}\n\treturn Object.freeze({\n\t\ttype: 'array',\n\t\titems,\n\t\t...(options?.min === undefined ? {} : { min: options.min }),\n\t\t...(options?.max === undefined ? {} : { max: options.max }),\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build an {@link ObjectShape} from a property map.\n *\n * @remarks\n * Wrap any property in {@link optionalShape} to allow its absence. By default\n * the compiled guard rejects unknown keys; pass `additionalProperties` to open\n * the object.\n *\n * @param properties - Map of property names to child shapes\n * @param options - Optional `additionalProperties` and `description`\n * @returns An object shape\n *\n * @example\n * ```ts\n * const user = objectShape({\n * \tname: stringShape({ min: 1 }),\n * \tage: integerShape({ min: 0, max: 120 }),\n * \tbio: optionalShape(stringShape()),\n * })\n * ```\n */\nexport function objectShape<\n\tP extends Readonly<Record<string, ContractShape>>,\n\tconst A extends boolean | ContractShape = false,\n>(properties: P, options?: ObjectShapeOptions<A>): ObjectShape<P, A> {\n\tconst snapshot: { [K in keyof P]: P[K] } = Object.create(null)\n\tfor (const key in properties) {\n\t\tif (Object.hasOwn(properties, key)) snapshot[key] = properties[key]\n\t}\n\treturn Object.freeze({\n\t\ttype: 'object',\n\t\tproperties: Object.freeze(snapshot),\n\t\t...(options?.additionalProperties === undefined\n\t\t\t? {}\n\t\t\t: { additionalProperties: options.additionalProperties }),\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build an open {@link ObjectShape} with no fixed properties — a dictionary.\n *\n * @remarks\n * Every value is validated against `values`; keys are unconstrained. Equivalent\n * to `objectShape({}, { additionalProperties: values })`.\n *\n * @param values - The shape every value must match\n * @param options - Optional `description`\n * @returns An open object shape\n *\n * @example\n * ```ts\n * const bindings = recordShape(numberShape()) // ~ Record<string, number>\n * ```\n */\nexport function recordShape<S extends ContractShape>(\n\tvalues: S,\n\toptions?: RecordShapeOptions,\n): ObjectShape<Record<never, never>, S> {\n\treturn Object.freeze({\n\t\ttype: 'object',\n\t\tproperties: Object.freeze({}),\n\t\tadditionalProperties: values,\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n// === Composition\n\n/**\n * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).\n *\n * @param variants - The candidate shapes; the first match wins at runtime\n * @returns A union shape whose `Infer` is the union of the variants\n *\n * @example\n * ```ts\n * const id = unionShape(stringShape(), integerShape())\n * // Infer<typeof id> = string | number\n * ```\n */\nexport function unionShape<V extends readonly ContractShape[]>(\n\t...variants: V\n): UnionShape<Readonly<V>> {\n\treturn Object.freeze({ type: 'union', variants: Object.freeze(variants) })\n}\n\n/**\n * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.\n *\n * @remarks\n * Unlike {@link unionShape} (`anyOf` — at least one variant matches),\n * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:\n *\n * - **Guard**: accepts the value only when exactly one variant's guard\n * accepts it. A value matching two-or-more variants — which would violate\n * the emitted `oneOf` schema — is rejected, even though it would pass\n * {@link unionShape}'s guard.\n * - **Parser**: judged on the RAW input's guard matches only, with NO\n * coercion fallback for an ambiguous input. When exactly one variant's\n * guard accepts the raw value, that variant's parser runs. Zero matches or\n * two-or-more matches both parse to `undefined` — a value ambiguous\n * between variants has no well-defined coercion target.\n *\n * Prefer {@link unionShape} when a value may legitimately satisfy more than\n * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer\n * `oneOfShape` when overlap between variants indicates malformed input that\n * must be rejected.\n *\n * @param variants - The candidate shapes\n * @returns A union shape with `mode: 'oneOf'`\n *\n * @example\n * ```ts\n * const id = oneOfShape(numberShape(), integerShape())\n * // 3 fails — matches both numberShape and integerShape\n * // 3.5 passes — matches numberShape only\n * ```\n */\nexport function oneOfShape<V extends readonly ContractShape[]>(\n\t...variants: V\n): UnionShape<Readonly<V>> {\n\treturn Object.freeze({\n\t\ttype: 'union',\n\t\tvariants: Object.freeze(variants),\n\t\tmode: 'oneOf',\n\t})\n}\n\n/**\n * Wrap a shape so it may be absent (`undefined`).\n *\n * @remarks\n * As an {@link objectShape} property, the field becomes a true optional property\n * in the inferred type.\n *\n * @param inner - The wrapped shape\n * @returns An optional shape\n */\nexport function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S> {\n\treturn Object.freeze({ type: 'optional', inner })\n}\n\n/**\n * Wrap a shape so it may be `null`.\n *\n * @param inner - The wrapped shape\n * @returns A nullable shape\n *\n * @example\n * ```ts\n * const bio = nullableShape(stringShape())\n * // Infer<typeof bio> = string | null\n * ```\n */\nexport function nullableShape<S extends ContractShape>(inner: S): NullableShape<S> {\n\treturn Object.freeze({ type: 'nullable', inner })\n}\n\n// === Escape hatch\n\n/**\n * Build a {@link JSONShape}.\n *\n * @remarks\n * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary\n * schema fragment and accepts every defined value at runtime, while `jsonShape`\n * validates that a value is real JSON (via {@link isJSONValue}).\n *\n * @param options - Optional `description`\n * @returns A JSON passthrough shape\n *\n * @example\n * ```ts\n * const payload = jsonShape({ description: 'Arbitrary JSON payload' })\n * ```\n */\nexport function jsonShape(options?: JSONShapeOptions): JSONShape {\n\treturn Object.freeze({\n\t\ttype: 'json',\n\t\t...(options?.description === undefined ? {} : { description: options.description }),\n\t})\n}\n\n/**\n * Build a {@link RawShape} from a JSON Schema fragment.\n *\n * @remarks\n * For values the shape DSL can't express. The compiled guard accepts every\n * DEFINED value — `undefined` alone fails, because it is the parser's failure\n * sentinel; wrap the shape in {@link optionalShape} to admit absence. The\n * parser passes a defined value through unchanged, and the fragment is\n * deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so\n * `rawShape(fragment).schema !== fragment` and later edits to the caller's\n * fragment cannot reach the shape. `compileSchema` re-emits that snapshot\n * structurally verbatim; `compileGenerator` throws, since an arbitrary embedded\n * schema has no auto-generatable sample.\n *\n * @param schema - The JSON Schema fragment to embed\n * @returns A raw shape owning a frozen copy of the fragment\n *\n * @example\n * ```ts\n * const custom = rawShape({ type: 'string', format: 'uuid' })\n * ```\n */\nexport function rawShape(schema: JSONSchema): RawShape {\n\treturn Object.freeze({ type: 'raw', schema: cloneSchema(schema) })\n}\n\n// === Schema inversion\n\n// schemaToShape walks an UNKNOWN, possibly adversarial runtime JSONSchema value\n// (a hand-written schema, or one produced by valueToSchema / samplesToSchema)\n// and emits a validating ContractShape — the reverse direction of\n// compileSchema (compilers.ts), which walks a finite, developer-authored\n// ContractShape tree and emits a JSONSchema. Recursion here is runtime-only\n// and bounded on three axes, mirroring the inferers: a WeakSet of ancestor\n// schema nodes (cycle safety), a decrementing depth budget (INFER_DEPTH_LIMIT\n// default), and a per-container sampling cap (INFER_BREADTH_LIMIT) on\n// properties/oneOf/anyOf entries — every branch stays total, per AGENTS §14.\n// Every keyword read is type-guarded: a malformed keyword is IGNORED, falling\n// through to the next rule, never thrown. `format` and `pattern` are NEVER\n// asserted — `format` is annotation-only, and compiling an attacker-supplied\n// `pattern` into a `RegExp` is a ReDoS vector — so neither keyword narrows the\n// compiled guard; the returned shape is always one `validateShape` accepts.\n//\n// Every widening — an empty/unrecognized node, an exhausted budget, a cycle, a\n// hostile throw — lands on `rawShape`, NOT `jsonShape`. `{}` is JSON Schema's\n// accept-anything schema, and `rawShape` is its exact inverse: its compiled\n// guard accepts every defined value, and it re-emits `{}` verbatim. `jsonShape`\n// also emits `{}` but its guard is the strictly narrower `isJSONValue`, so\n// widening through it would REJECT the exotic originals (`Map`, `Set`, a class\n// instance, a function, `NaN`) whose inferred schema is exactly `{}` — the\n// round trip below would then be a false claim. `jsonShape` remains the shape a\n// user AUTHORS to mean \"any JSON value\"; it is never inferred.\n\n/**\n * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON\n * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).\n *\n * @remarks\n * Total and pure. Either keyword is used only when it is a non-negative\n * safe integer (`Number.isSafeInteger` + `>= 0`); a malformed value (a string,\n * a negative number, `NaN`, `Infinity`, a fraction, or an unsafe integer) is\n * dropped as if absent. When both bounds are present and `min` exceeds `max`,\n * the PAIR is dropped entirely (an unbounded shape is always a legal widening\n * of a contradictory schema).\n *\n * @param min - The raw `minLength` / `minItems` keyword value\n * @param max - The raw `maxLength` / `maxItems` keyword value\n * @returns The derived `min` / `max` pair, either possibly `undefined`\n *\n * @example\n * ```ts\n * deriveLengthBounds(1, 10) // { min: 1, max: 10 }\n * deriveLengthBounds(10, 1) // {} — contradictory, dropped\n * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped\n * ```\n */\nexport function deriveLengthBounds(\n\tmin: unknown,\n\tmax: unknown,\n): { readonly min?: number; readonly max?: number } {\n\tconst lo = isInteger(min) && Number.isSafeInteger(min) && min >= 0 ? min : undefined\n\tconst hi = isInteger(max) && Number.isSafeInteger(max) && max >= 0 ? max : undefined\n\tif (lo !== undefined && hi !== undefined && lo > hi) return {}\n\treturn {\n\t\t...(lo === undefined ? {} : { min: lo }),\n\t\t...(hi === undefined ? {} : { max: hi }),\n\t}\n}\n\n/**\n * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema\n * range keywords (`minimum`/`maximum`).\n *\n * @remarks\n * Total and pure. Either keyword is used only when it is a finite number\n * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when\n * both bounds are present and `min` exceeds `max`, the PAIR is dropped\n * entirely, the same contradiction rule {@link deriveLengthBounds} applies.\n *\n * @param min - The raw `minimum` keyword value\n * @param max - The raw `maximum` keyword value\n * @returns The derived `min` / `max` pair, either possibly `undefined`\n *\n * @example\n * ```ts\n * deriveRangeBounds(0, 120) // { min: 0, max: 120 }\n * deriveRangeBounds(5, 1) // {} — contradictory, dropped\n * ```\n */\nexport function deriveRangeBounds(\n\tmin: unknown,\n\tmax: unknown,\n): { readonly min?: number; readonly max?: number } {\n\tconst lo = isFiniteNumber(min) ? min : undefined\n\tconst hi = isFiniteNumber(max) ? max : undefined\n\tif (lo !== undefined && hi !== undefined && lo > hi) return {}\n\treturn {\n\t\t...(lo === undefined ? {} : { min: lo }),\n\t\t...(hi === undefined ? {} : { max: hi }),\n\t}\n}\n\n/**\n * Build an {@link ObjectShape} from a JSON Schema object node's `properties` /\n * `required` / `additionalProperties` keywords — the object-specialized branch\n * of {@link buildShapeFromNode}.\n *\n * @remarks\n * `properties` (when a record) contributes one child shape per own key, capped\n * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}\n * unless it appears as a string entry of `required`. A property whose value is\n * not itself a record widens to {@link rawShape}. `additionalProperties`:\n * `false` closes the object; a record value recurses into it (`objectShape`\n * validates extras against that shape); anything else — `true`, absent, or\n * malformed — leaves the object OPEN (`true`), matching JSON Schema's own\n * absent-means-open default and the fact that {@link valueToSchema} /\n * {@link samplesToSchema} always emit the keyword explicitly, so an absent\n * value only arises from a hand-written schema. When `properties` has MORE\n * keys than {@link INFER_BREADTH_LIMIT}, the schema's own\n * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —\n * a dropped key's value could otherwise fail a `false` or record-valued rest\n * shape it was never checked against — mirroring {@link inferObject}'s\n * partial-key handling in `inferers.ts`. The accumulator uses a\n * null-prototype record so a property literally named `__proto__` becomes an\n * own data key rather than mutating the prototype, mirroring\n * {@link inferObject} (inferers.ts).\n *\n * @param schema - The object schema node\n * @param depth - Remaining descent budget passed to child properties\n * @param visited - The ancestor set guarding against cycles — recursion\n * state owned by the {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakSet` changes cycle-detection behavior and is not\n * supported usage\n * @param memo - A per-call `(schema node, remaining depth) → shape` cache —\n * recursion state owned by the {@link schemaToShape} entry point; passing\n * a shared or pre-populated `WeakMap` changes caching behavior and is not\n * supported usage\n * @param description - The node's already-extracted `description`, if any\n * @returns The built object shape\n *\n * @example\n * ```ts\n * buildObjectShape(\n * \t{ type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },\n * \tINFER_DEPTH_LIMIT,\n * \tnew WeakSet(),\n * \tnew WeakMap(),\n * \tundefined,\n * )\n * // objectShape({ id: integerShape() }, { additionalProperties: true })\n * ```\n */\nexport function buildObjectShape(\n\tschema: JSONSchema,\n\tdepth: number,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, ContractShape>>,\n\tdescription: string | undefined,\n): ContractShape {\n\tconst propertiesSource = isRecord(schema.properties) ? schema.properties : undefined\n\tconst requiredSource = isArray(schema.required)\n\t\t? schema.required.filter((entry): entry is string => isString(entry))\n\t\t: []\n\t// Honest typing: a null-prototype accumulator so a property literally\n\t// named '__proto__' becomes an own data key instead of mutating the\n\t// prototype — the same pattern inferObject uses (inferers.ts).\n\tconst properties: Record<string, ContractShape> = Object.create(null)\n\tlet truncated = false\n\tif (propertiesSource) {\n\t\tconst allKeys = Object.keys(propertiesSource)\n\t\ttruncated = allKeys.length > INFER_BREADTH_LIMIT\n\t\tconst keys = allKeys.slice(0, INFER_BREADTH_LIMIT)\n\t\tfor (const key of keys) {\n\t\t\tconst child = propertiesSource[key]\n\t\t\tconst childShape = isRecord(child)\n\t\t\t\t? schemaNodeToShape(child, depth - 1, visited, memo)\n\t\t\t\t: rawShape({})\n\t\t\tproperties[key] = requiredSource.includes(key) ? childShape : optionalShape(childShape)\n\t\t}\n\t}\n\tconst extra = schema.additionalProperties\n\tconst additionalProperties: boolean | ContractShape = truncated\n\t\t? true\n\t\t: extra === false\n\t\t\t? false\n\t\t\t: isRecord(extra)\n\t\t\t\t? schemaNodeToShape(extra, depth - 1, visited, memo)\n\t\t\t\t: true\n\treturn objectShape(properties, {\n\t\tadditionalProperties,\n\t\t...(description === undefined ? {} : { description }),\n\t})\n}\n\n/**\n * Build a {@link ContractShape} for one JSON Schema node — the recursive\n * spine of {@link schemaToShape}, shared with per-child recursion via\n * {@link schemaNodeToShape}.\n *\n * @remarks\n * Every keyword is read defensively (the node's static `JSONSchema` type is\n * NOT trusted at runtime — a caller-supplied node may be adversarial), so a\n * malformed keyword falls through to the next rule instead of throwing.\n * Precedence, top-down:\n *\n * 1. `enum` — an array with at least one string/number/boolean entry (finite\n * numbers only) becomes a {@link literalShape} over the filtered entries.\n * Non-primitive / non-finite entries are dropped; an empty result falls\n * through.\n * 2. `oneOf` — an array with at least one record entry becomes an\n * {@link oneOfShape} over the recursively-built variants, provided the\n * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the\n * limit, building a subset union would be strictly narrower than the\n * schema's full union (a value matching only a dropped variant would be\n * wrongly rejected), so the whole node widens to {@link rawShape} instead\n * of sampling a subset.\n * 3. `anyOf` — identically, via {@link unionShape}.\n * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —\n * the matching primitive shape, with length/range bounds derived via\n * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node\n * additionally drops its bounds when they describe an EMPTY integer range\n * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`\n * rejects — so the result is always a valid shape.\n * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into\n * a record-valued `items` (widening to {@link rawShape} otherwise), with\n * bounds from `minItems` / `maxItems`.\n * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a\n * record-valued `properties` — delegates to {@link buildObjectShape}.\n * 7. Everything else — an empty schema, an unrecognized/absent `type`,\n * exhausted depth/breadth, or an attempt failure — widens to\n * {@link rawShape}, whose guard accepts every defined value and whose\n * emitted schema is the same `{}` (plus `description`) the node carried.\n * This is the exact inverse of `{}`, JSON Schema's accept-anything schema,\n * and where the inferers themselves bottom out at their own limits.\n *\n * `format` and `pattern` are NEVER read into the compiled shape — `format` is\n * annotation-only and `pattern` compiling an attacker-supplied string into a\n * `RegExp` is a ReDoS vector. `description`, when a string, carries through to\n * the produced shape's `description` option.\n *\n * @param schema - The schema node to convert\n * @param depth - Remaining descent budget (0 halts recursion with `rawShape({})`)\n * @param visited - The ancestor set guarding against cycles — recursion\n * state owned by the {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakSet` changes cycle-detection behavior and is not\n * supported usage\n * @param memo - A per-call `(schema node, remaining depth) → shape` cache\n * guarding against exponential re-conversion of a\n * shared-reference schema DAG — recursion state owned by the\n * {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakMap` changes caching behavior and is not\n * supported usage\n * @returns The built shape for `schema`\n *\n * @example\n * ```ts\n * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())\n * // stringShape({ min: 1 })\n * ```\n */\nexport function buildShapeFromNode(\n\tschema: JSONSchema,\n\tdepth: number,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, ContractShape>>,\n): ContractShape {\n\tconst description = isString(schema.description) ? schema.description : undefined\n\n\tif (isArray(schema.enum)) {\n\t\tconst literals = schema.enum.filter(\n\t\t\t(entry): entry is string | number | boolean =>\n\t\t\t\tisString(entry) || isFiniteNumber(entry) || isBoolean(entry),\n\t\t)\n\t\tif (literals.length > 0) {\n\t\t\treturn literalShape(literals, description === undefined ? undefined : { description })\n\t\t}\n\t}\n\n\tif (isArray(schema.oneOf)) {\n\t\tconst records = schema.oneOf.filter((entry): entry is JSONSchema => isRecord(entry))\n\t\tif (records.length > INFER_BREADTH_LIMIT) {\n\t\t\treturn rawShape(description === undefined ? {} : { description })\n\t\t}\n\t\tconst variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo))\n\t\tif (variants.length > 0) return oneOfShape(...variants)\n\t}\n\n\tif (isArray(schema.anyOf)) {\n\t\tconst records = schema.anyOf.filter((entry): entry is JSONSchema => isRecord(entry))\n\t\tif (records.length > INFER_BREADTH_LIMIT) {\n\t\t\treturn rawShape(description === undefined ? {} : { description })\n\t\t}\n\t\tconst variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo))\n\t\tif (variants.length > 0) return unionShape(...variants)\n\t}\n\n\tconst type = isString(schema.type) ? schema.type : undefined\n\n\tif (type === 'string') {\n\t\tconst bounds = deriveLengthBounds(schema.minLength, schema.maxLength)\n\t\treturn stringShape({\n\t\t\t...bounds,\n\t\t\t...(description === undefined ? {} : { description }),\n\t\t})\n\t}\n\tif (type === 'number') {\n\t\tconst bounds = deriveRangeBounds(schema.minimum, schema.maximum)\n\t\treturn numberShape({\n\t\t\t...bounds,\n\t\t\t...(description === undefined ? {} : { description }),\n\t\t})\n\t}\n\tif (type === 'integer') {\n\t\tconst bounds = deriveRangeBounds(schema.minimum, schema.maximum)\n\t\tconst emptyRange =\n\t\t\tMath.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) >\n\t\t\tMath.floor(bounds.max ?? Number.POSITIVE_INFINITY)\n\t\treturn integerShape(\n\t\t\temptyRange\n\t\t\t\t? description === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: { description }\n\t\t\t\t: {\n\t\t\t\t\t\t...bounds,\n\t\t\t\t\t\t...(description === undefined ? {} : { description }),\n\t\t\t\t\t},\n\t\t)\n\t}\n\tif (type === 'boolean') {\n\t\treturn booleanShape(description === undefined ? undefined : { description })\n\t}\n\tif (type === 'null') {\n\t\treturn nullShape(description === undefined ? undefined : { description })\n\t}\n\n\tif (type === 'array') {\n\t\tconst items = isRecord(schema.items)\n\t\t\t? schemaNodeToShape(schema.items, depth - 1, visited, memo)\n\t\t\t: rawShape({})\n\t\tconst bounds = deriveLengthBounds(schema.minItems, schema.maxItems)\n\t\treturn arrayShape(items, {\n\t\t\t...bounds,\n\t\t\t...(description === undefined ? {} : { description }),\n\t\t})\n\t}\n\n\tif (type === 'object' || (type === undefined && isRecord(schema.properties))) {\n\t\treturn buildObjectShape(schema, depth, visited, memo, description)\n\t}\n\n\treturn rawShape(description === undefined ? {} : { description })\n}\n\n/**\n * Convert one JSON Schema node into a {@link ContractShape} — the recursion\n * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for\n * every child (`items`, `properties` values, `additionalProperties`,\n * `oneOf` / `anyOf` variants).\n *\n * @remarks\n * Total: never throws. Guards depth exhaustion, a non-record node (the\n * node's static `JSONSchema` type is not trusted at runtime), and a cyclic\n * re-encounter of `schema` — all three widen to {@link rawShape}. The\n * ancestor set is added to and removed from around the WHOLE subtree\n * conversion (not permanently), so a DAG-shaped schema reached twice via two\n * different, non-cyclic paths does not false-positive as a cycle. The\n * subtree conversion itself runs inside {@link attempt}, so a hostile\n * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error\n * — it degrades to {@link rawShape} instead. A same-node re-conversion at\n * the same remaining `depth` is served from `memo` (guards a\n * shared-reference schema DAG against exponential blowup), mirroring\n * {@link inferObject} / {@link inferArray} (inferers.ts).\n *\n * @param schema - The schema node to convert\n * @param depth - Remaining descent budget\n * @param visited - The ancestor set guarding against cycles — recursion\n * state owned by the {@link schemaToShape} entry point; passing a shared or\n * pre-populated `WeakSet` changes cycle-detection behavior and is not\n * supported usage\n * @param memo - A per-call `(schema node, remaining depth) → shape` cache —\n * recursion state owned by the {@link schemaToShape} entry point; passing\n * a shared or pre-populated `WeakMap` changes caching behavior and is not\n * supported usage\n * @returns The built shape for `schema`, or {@link rawShape} on any failure\n *\n * @example\n * ```ts\n * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())\n * // booleanShape()\n * ```\n */\nexport function schemaNodeToShape(\n\tschema: JSONSchema,\n\tdepth: number,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, ContractShape>>,\n): ContractShape {\n\tif (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return rawShape({})\n\tconst cached = memo.get(schema)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(schema)\n\tconst outcome = attempt(() => buildShapeFromNode(schema, depth, visited, memo))\n\tvisited.delete(schema)\n\tconst shape = outcome.success ? outcome.value : rawShape({})\n\tlet depths = memo.get(schema)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(schema, depths)\n\t}\n\tdepths.set(depth, shape)\n\treturn shape\n}\n\n/**\n * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}\n * — the inverse of {@link compileSchema}, and the validating sibling of\n * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).\n *\n * @remarks\n * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or\n * outright hostile (throwing-getter Proxy) `schema` value all degrade to\n * {@link rawShape} rather than escaping as an error, so\n * `createContract(schemaToShape(x))` is safe to call for any `x`. See\n * {@link buildShapeFromNode} for the exact per-keyword precedence.\n *\n * `format` and `pattern` are NEVER asserted by the compiled shape — `format`\n * is annotation-only (per the JSON Schema spec, it never narrows validation\n * on its own) and compiling an attacker-controlled `pattern` string into a\n * `RegExp` is a ReDoS vector; both keywords are read only far enough to be\n * ignored. Any node the walk cannot express — an empty `{}`, an\n * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a\n * cyclic re-encounter — widens to {@link rawShape} (accept any defined\n * value), never narrows.\n *\n * ROUND TRIP: `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` for\n * every `v` — including the values no JSON Schema keyword describes (`NaN`,\n * `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a\n * bigint, a cyclic or hostile host), which infer `{}` and widen back to an\n * accept-anything {@link rawShape}. Widening is the only source of looseness.\n * The law has three explicit host limits:\n *\n * - **Absence.** `undefined` is not a value: no compiled guard accepts it\n * (`rawShape` reserves it as the parser failure sentinel). So `undefined`\n * itself, an array element holding it, and an array HOLE (`arrayOf` requires\n * every index to be an own property, the same rule `isJSONValue` applies)\n * all fall outside the law. An OBJECT property holding `undefined` does not:\n * `valueToSchema` drops the key and opens the object, so the source object\n * is still accepted.\n * - **`Date` serialization.** A `Date` infers the schema of its JSON form\n * (`{ type: 'string' }`, plus `format: 'date-time'` when `format` is on), so\n * the law applies to `date.toISOString()` rather than the runtime instance.\n * - **Stateful access.** A getter whose result changes between inference and\n * guard evaluation can invalidate the sampled fact. Likewise, an array that\n * overrides iteration behavior can present different elements to the two\n * phases. The law applies only while the sampled host's observable own\n * enumerable string properties and array iteration remain stable.\n *\n * A widened node cannot be auto-generated: `rawShape` embeds an arbitrary\n * schema fragment, so `createContract(schemaToShape(x)).generate()` throws\n * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`\n * stay total.\n *\n * @param schema - The JSON Schema value to convert\n * @returns The built {@link ContractShape}\n *\n * @example\n * ```ts\n * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }])\n * const contract = createContract(schemaToShape(schema))\n * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' }\n * contract.parse({ id: 'nope' }) // undefined\n * ```\n */\nexport function schemaToShape(schema: JSONSchema): ContractShape {\n\treturn schemaNodeToShape(schema, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBAA+C,OAAO,OAAO;CACzE;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;AAcD,IAAa,cAAc;;;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