@orkestrel/contract 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,6 +46,66 @@ var FAULT_LIMIT = 64;
46
46
  * untrusted text.
47
47
  */
48
48
  var PREVIEW_LIMIT = 64;
49
+ /**
50
+ * The default maximum object/array nesting depth {@link valueToSchema} walks,
51
+ * frozen.
52
+ *
53
+ * @remarks
54
+ * Bounds inference against adversarial or cyclic runtime input — once the
55
+ * remaining depth budget reaches zero, inference stops descending and emits
56
+ * the empty accept-anything schema `{}` for that branch instead of recursing
57
+ * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.
58
+ */
59
+ var INFER_DEPTH_LIMIT = 32;
60
+ /**
61
+ * The default maximum number of object properties / array elements
62
+ * {@link valueToSchema} samples per container, frozen.
63
+ *
64
+ * @remarks
65
+ * Bounds the work (and the emitted schema's size) against a wide record or a
66
+ * huge array — properties/elements beyond this cap are never inspected.
67
+ * Overridable per call via {@link ValueToSchemaOptions.maxProperties}.
68
+ */
69
+ var INFER_BREADTH_LIMIT = 256;
70
+ /**
71
+ * The default maximum number of distinct values a multi-sample slot may hold
72
+ * before enum inference gives up and falls back to a bare `type`, frozen.
73
+ *
74
+ * @remarks
75
+ * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}
76
+ * will emit — a slot with distinct-value count at or above this limit is
77
+ * treated as unbounded (an ID column, not a category) and never gets an
78
+ * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}
79
+ * (which gates whether enum inference runs at all).
80
+ */
81
+ var INFER_ENUM_LIMIT = 12;
82
+ /**
83
+ * The maximum string length {@link stringToFormat} attempts to classify,
84
+ * frozen.
85
+ *
86
+ * @remarks
87
+ * Bounds per-string format-detection work: a value longer than this returns
88
+ * `undefined` immediately, before any pattern match runs. 128 sits
89
+ * comfortably above the longest real format token — an RFC 3339 date-time
90
+ * with fractional seconds and a UTC offset — so no legitimate classification
91
+ * changes; only pathologically long strings (a multi-megabyte payload passed
92
+ * as a candidate email/URI) are skipped.
93
+ */
94
+ var FORMAT_MAX_LENGTH = 128;
95
+ /**
96
+ * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats
97
+ * (`uuid` / `email` / `uri`), frozen as data.
98
+ *
99
+ * @remarks
100
+ * The ISO-8601 date/time formats are NOT listed here — they additionally
101
+ * require an attempt-guarded `Date` validity check, so their pattern lives
102
+ * inline in `stringToFormat` rather than as reusable standalone data.
103
+ */
104
+ var FORMAT_PATTERNS = Object.freeze({
105
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
106
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
107
+ uri: /^[a-z][a-z0-9+.-]*:\/\//i
108
+ });
49
109
  //#endregion
50
110
  //#region src/core/validators.ts
51
111
  /** Determine whether a value is `null`.
@@ -1100,6 +1160,69 @@ function schemaToParameters(schema) {
1100
1160
  return isRecord(schema) ? schema : void 0;
1101
1161
  }
1102
1162
  /**
1163
+ * Wrap a non-object `JSONSchema` root in a single-property object schema, so
1164
+ * an inferred primitive/array/union schema can flow into {@link schemaToParameters}
1165
+ * as an MCP-compatible `inputSchema`.
1166
+ *
1167
+ * @remarks
1168
+ * Total and deterministic. `schema.type === 'object'` passes through
1169
+ * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only
1170
+ * schema with no `type`, or the empty `{}`) is wrapped as a single required
1171
+ * `value` property: `{ type: 'object', properties: { value: schema },
1172
+ * required: ['value'], additionalProperties: false }`. Composition:
1173
+ * `schemaToParameters(schemaToObject(valueToSchema(payload)))`.
1174
+ *
1175
+ * @param schema - The schema to wrap
1176
+ * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema
1177
+ *
1178
+ * @example
1179
+ * ```ts
1180
+ * schemaToObject({ type: 'string' })
1181
+ * // { type: 'object', properties: { value: { type: 'string' } },
1182
+ * // required: ['value'], additionalProperties: false }
1183
+ * schemaToObject({ type: 'object', properties: {} }) // unchanged
1184
+ * ```
1185
+ */
1186
+ function schemaToObject(schema) {
1187
+ if (schema.type === "object") return schema;
1188
+ return {
1189
+ type: "object",
1190
+ properties: { value: schema },
1191
+ required: ["value"],
1192
+ additionalProperties: false
1193
+ };
1194
+ }
1195
+ /**
1196
+ * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to
1197
+ * a finite non-negative integer, falling back to a default for anything else.
1198
+ *
1199
+ * @remarks
1200
+ * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or
1201
+ * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard
1202
+ * (`NaN <= 0` is `false`, so recursion never halts), and a negative
1203
+ * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key
1204
+ * instead of capping the list (a fractional value has a similarly undefined
1205
+ * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`
1206
+ * is `false` — since an unbounded budget is exactly the adversarial case the
1207
+ * caps exist to prevent. A valid finite non-negative integer passes through
1208
+ * unchanged.
1209
+ *
1210
+ * @param value - The candidate budget value
1211
+ * @param fallback - The default to use when `value` is not a finite
1212
+ * non-negative integer
1213
+ * @returns A finite non-negative integer budget
1214
+ *
1215
+ * @example
1216
+ * ```ts
1217
+ * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT
1218
+ * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT
1219
+ * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4
1220
+ * ```
1221
+ */
1222
+ function sanitizeBudget(value, fallback) {
1223
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fallback;
1224
+ }
1225
+ /**
1103
1226
  * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
1104
1227
  * `received` field.
1105
1228
  *
@@ -2623,6 +2746,590 @@ function createContract(shape) {
2623
2746
  };
2624
2747
  }
2625
2748
  //#endregion
2749
+ //#region src/core/inferers.ts
2750
+ /**
2751
+ * Render a value as a deterministic, key-sorted JSON string.
2752
+ *
2753
+ * @remarks
2754
+ * The stable-stringify backing {@link unifySchemas}'s de-duplication and
2755
+ * ordering: unlike `JSON.stringify`, object keys are sorted before encoding
2756
+ * (recursively, at every nesting level), so two structurally-equal
2757
+ * `JSONSchema` fragments built independently always canonicalize to the same
2758
+ * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.
2759
+ *
2760
+ * @param value - The value to canonicalize (a `JSONSchema` fragment, or any
2761
+ * nested piece of one)
2762
+ * @returns A deterministic string encoding of `value`
2763
+ *
2764
+ * @example
2765
+ * ```ts
2766
+ * canonicalStringify({ type: 'object', properties: {} }) ===
2767
+ * canonicalStringify({ properties: {}, type: 'object' }) // true
2768
+ * ```
2769
+ */
2770
+ function canonicalStringify(value) {
2771
+ if (isArray(value)) return `[${value.map((entry) => canonicalStringify(entry)).join(",")}]`;
2772
+ if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(value[key])}`).join(",")}}`;
2773
+ return JSON.stringify(value);
2774
+ }
2775
+ /**
2776
+ * Unify a list of inferred `JSONSchema` fragments into one schema.
2777
+ *
2778
+ * @remarks
2779
+ * De-duplicates by {@link canonicalStringify}, then applies the one
2780
+ * special-case subsumption inference performs: a bare `{ type: 'integer' }`
2781
+ * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`
2782
+ * (an integer sample is also a valid `number` sample). A single surviving
2783
+ * distinct schema is returned directly; two or more are wrapped as
2784
+ * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
2785
+ * An empty input list returns the empty accept-anything schema `{}`.
2786
+ *
2787
+ * @param schemas - The schemas to unify
2788
+ * @returns The unified schema
2789
+ *
2790
+ * @example
2791
+ * ```ts
2792
+ * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }
2793
+ * unifySchemas([{ type: 'string' }, { type: 'boolean' }])
2794
+ * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }
2795
+ * ```
2796
+ */
2797
+ function unifySchemas(schemas) {
2798
+ if (schemas.length === 0) return {};
2799
+ const seen = /* @__PURE__ */ new Map();
2800
+ for (const schema of schemas) {
2801
+ const key = canonicalStringify(schema);
2802
+ if (!seen.has(key)) seen.set(key, schema);
2803
+ }
2804
+ const integerKey = canonicalStringify({ type: "integer" });
2805
+ const numberKey = canonicalStringify({ type: "number" });
2806
+ if (seen.has(integerKey) && seen.has(numberKey)) seen.delete(integerKey);
2807
+ const distinct = [...seen.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, schema]) => schema);
2808
+ if (distinct.length <= 1) {
2809
+ const [only] = distinct;
2810
+ return only ?? {};
2811
+ }
2812
+ return { anyOf: distinct };
2813
+ }
2814
+ /**
2815
+ * Determine whether an ISO-8601-shaped string parses to a valid instant.
2816
+ *
2817
+ * @remarks
2818
+ * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never
2819
+ * throws on a string input, but a value like `2020-13-45` parses to an
2820
+ * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation
2821
+ * step behind {@link stringToFormat}'s `date` / `date-time` / `time`
2822
+ * branches, which pattern-match the shape first and confirm validity here.
2823
+ *
2824
+ * @param value - The candidate ISO-8601 string
2825
+ * @returns `true` when `value` parses to a real instant
2826
+ *
2827
+ * @example
2828
+ * ```ts
2829
+ * isValidISOInstant('2020-01-01') // true
2830
+ * isValidISOInstant('2020-13-45') // false
2831
+ * ```
2832
+ */
2833
+ function isValidISOInstant(value) {
2834
+ const outcome = attempt(() => {
2835
+ const date = new Date(value);
2836
+ return !Number.isNaN(date.getTime());
2837
+ });
2838
+ return outcome.success && outcome.value;
2839
+ }
2840
+ /**
2841
+ * Classify a string against the {@link SchemaFormat} vocabulary.
2842
+ *
2843
+ * @remarks
2844
+ * Total, pure, and deterministic. Fixed precedence, most specific first:
2845
+ * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first
2846
+ * match wins. The `date-time` / `date` / `time` branches require BOTH a
2847
+ * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity
2848
+ * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.
2849
+ * Returns `undefined` when no format matches (including the empty string).
2850
+ *
2851
+ * @param value - The string to classify
2852
+ * @returns The matched {@link SchemaFormat}, or `undefined`
2853
+ *
2854
+ * @example
2855
+ * ```ts
2856
+ * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'
2857
+ * stringToFormat('2024-01-15') // 'date'
2858
+ * stringToFormat('2020-13-45') // undefined — invalid date
2859
+ * stringToFormat('ada@example.com') // 'email'
2860
+ * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset
2861
+ * stringToFormat('10:30:00+02:00') // 'time'
2862
+ * ```
2863
+ */
2864
+ function stringToFormat(value) {
2865
+ if (value.length > 128) return void 0;
2866
+ if (FORMAT_PATTERNS.uuid.test(value)) return "uuid";
2867
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(value) && isValidISOInstant(value)) return "date-time";
2868
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value) && isValidISOInstant(value)) return "date";
2869
+ if (/^\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(value) && isValidISOInstant(`1970-01-01T${value}`)) return "time";
2870
+ if (FORMAT_PATTERNS.email.test(value)) return "email";
2871
+ if (FORMAT_PATTERNS.uri.test(value)) return "uri";
2872
+ }
2873
+ /**
2874
+ * Classify a list of sample values against the {@link SchemaFormat}
2875
+ * vocabulary, requiring unanimity.
2876
+ *
2877
+ * @remarks
2878
+ * A format is returned ONLY IF every value is a string AND every one maps to
2879
+ * the SAME {@link stringToFormat} result (including all mapping to
2880
+ * `undefined`, which itself returns `undefined` here). A single disagreeing
2881
+ * value, a non-string value, or an empty list all yield `undefined` — the
2882
+ * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})
2883
+ * relies on this unanimity so a slot with mixed string shapes emits a bare
2884
+ * `{ type: 'string' }` rather than an `anyOf` of formats.
2885
+ *
2886
+ * @param values - The sample values to classify
2887
+ * @returns The unanimous {@link SchemaFormat}, or `undefined`
2888
+ *
2889
+ * @example
2890
+ * ```ts
2891
+ * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'
2892
+ * samplesToFormat(['2024-01-01', 'not a date']) // undefined
2893
+ * samplesToFormat([]) // undefined
2894
+ * ```
2895
+ */
2896
+ function samplesToFormat(values) {
2897
+ if (values.length === 0 || !values.every((value) => isString(value))) return void 0;
2898
+ const [first, ...rest] = values.map((value) => stringToFormat(value));
2899
+ if (first === void 0) return void 0;
2900
+ return rest.every((format) => format === first) ? first : void 0;
2901
+ }
2902
+ /**
2903
+ * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated
2904
+ * primitive slot — the multi-sample-only counterpart to
2905
+ * {@link stringToFormat} ({@link valueToSchema} never emits `enum`).
2906
+ *
2907
+ * @remarks
2908
+ * Fires only when ALL of: every value is the same primitive kind (all string
2909
+ * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed
2910
+ * slot never qualifies, and a slot containing `NaN` / `±Infinity` never
2911
+ * qualifies either, since {@link canonicalStringify} collapses `NaN` to
2912
+ * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2
2913
+ * values are given; the distinct-by-{@link canonicalStringify} count is LESS
2914
+ * than the value count (repetition required — separates a categorical column
2915
+ * from an ID column); and the distinct count is at most `limit`. The emitted
2916
+ * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s
2917
+ * `literalShape` emission. Members are sorted by canonical key for
2918
+ * deterministic output.
2919
+ *
2920
+ * @param values - The collected slot values
2921
+ * @param limit - The maximum distinct-value count before giving up
2922
+ * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
2923
+ *
2924
+ * @example
2925
+ * ```ts
2926
+ * inferPrimitiveEnum(['active', 'inactive', 'active'], 12)
2927
+ * // { enum: ['active', 'inactive'] }
2928
+ * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition
2929
+ * ```
2930
+ */
2931
+ function inferPrimitiveEnum(values, limit) {
2932
+ if (values.length < 2) return void 0;
2933
+ const allString = values.every((value) => isString(value));
2934
+ const allNumber = !allString && values.every((value) => isFiniteNumber(value));
2935
+ if (!allString && !allNumber) return void 0;
2936
+ const distinct = /* @__PURE__ */ new Map();
2937
+ for (const value of values) if (isString(value) || isFiniteNumber(value)) distinct.set(canonicalStringify(value), value);
2938
+ if (distinct.size >= values.length || distinct.size > limit) return void 0;
2939
+ return { enum: [...distinct.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, value]) => value) };
2940
+ }
2941
+ /**
2942
+ * Infer a `JSONSchema` fragment for one runtime value — the recursive spine
2943
+ * shared by {@link valueToSchema} and, per collected property/element, by
2944
+ * {@link inferArray} / {@link inferObject}.
2945
+ *
2946
+ * @remarks
2947
+ * Total: never throws, and terminates on cyclic input via `visited`. Leaf
2948
+ * classification order: `null`, boolean, integer (`Number.isInteger`
2949
+ * semantics — `-0` counts), finite non-integer number, non-finite number
2950
+ * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
2951
+ * `format` keyword when `format` is on and {@link stringToFormat} matches),
2952
+ * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
2953
+ * plus `format: 'date-time'` when `format` is on); everything else
2954
+ * (function, symbol, bigint, `undefined`, and other non-plain objects such as
2955
+ * `Map` / `Set`) is the empty accept-anything schema `{}`.
2956
+ *
2957
+ * @param value - The value to classify
2958
+ * @param depth - Remaining descent budget (0 halts recursion with `{}`)
2959
+ * @param breadth - The per-container sampling cap passed through to children
2960
+ * @param closed - Whether descended objects emit `additionalProperties: false`
2961
+ * @param format - Whether a string/`Date` leaf gains a `format` keyword
2962
+ * @param visited - The ancestor set guarding against cycles
2963
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
2964
+ * against exponential re-inference of a shared-reference DAG
2965
+ * @returns The inferred schema fragment for `value`
2966
+ *
2967
+ * @example
2968
+ * ```ts
2969
+ * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }
2970
+ * ```
2971
+ */
2972
+ function inferValue(value, depth, breadth, closed, format, visited, memo) {
2973
+ if (isNull(value)) return { type: "null" };
2974
+ if (isBoolean(value)) return { type: "boolean" };
2975
+ if (isInteger(value)) return { type: "integer" };
2976
+ if (isFiniteNumber(value)) return { type: "number" };
2977
+ if (isNumber(value)) return { type: "number" };
2978
+ if (isString(value)) {
2979
+ if (format) {
2980
+ const detected = stringToFormat(value);
2981
+ if (detected) return {
2982
+ type: "string",
2983
+ format: detected
2984
+ };
2985
+ }
2986
+ return { type: "string" };
2987
+ }
2988
+ if (isArray(value)) return inferArray(value, depth, breadth, closed, format, visited, memo);
2989
+ if (isRecord(value)) return inferObject(value, depth, breadth, closed, format, visited, memo);
2990
+ if (isDate(value)) return format ? {
2991
+ type: "string",
2992
+ format: "date-time"
2993
+ } : { type: "string" };
2994
+ return {};
2995
+ }
2996
+ /**
2997
+ * Infer a `JSONSchema` array fragment from an array's sampled elements.
2998
+ *
2999
+ * @remarks
3000
+ * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the
3001
+ * first `breadth` elements are classified via {@link inferValue} (one less
3002
+ * depth) and unified with {@link unifySchemas}: a single distinct element
3003
+ * schema becomes `items` directly; multiple distinct schemas become
3004
+ * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of
3005
+ * `value` both yield the empty schema `{}` instead of descending. A sparse
3006
+ * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before
3007
+ * sampling so every slot — including a hole — is visited as an explicit
3008
+ * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left
3009
+ * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.
3010
+ *
3011
+ * ALL reads of `value` — including its `length` — happen inside
3012
+ * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose
3013
+ * `get` trap throws) is exactly as contained as a throwing own-getter element
3014
+ * or a Proxy-over-array element access, and cannot escape as a thrown error.
3015
+ * On failure — or when the sampled/classified list ends up empty — this
3016
+ * returns `{ type: 'array' }` (no `items`), since `value` is still known to
3017
+ * be an array, mirroring the empty-array emission. A same-object
3018
+ * re-inference at the same remaining `depth` is served from `memo` instead
3019
+ * of recomputing (guards a shared-reference DAG against exponential blowup).
3020
+ *
3021
+ * @param value - The array to infer from
3022
+ * @param depth - Remaining descent budget
3023
+ * @param breadth - The maximum number of elements sampled
3024
+ * @param closed - Threaded through to nested object elements
3025
+ * @param format - Threaded through to nested string/`Date` elements
3026
+ * @param visited - The ancestor set guarding against cycles
3027
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
3028
+ * against exponential re-inference of a shared-reference DAG
3029
+ * @returns The inferred array schema
3030
+ *
3031
+ * @example
3032
+ * ```ts
3033
+ * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())
3034
+ * // { type: 'array', items: { type: 'number' } }
3035
+ * ```
3036
+ */
3037
+ function inferArray(value, depth, breadth, closed, format, visited, memo) {
3038
+ if (!(depth > 0) || visited.has(value)) return {};
3039
+ const cached = memo.get(value)?.get(depth);
3040
+ if (cached) return cached;
3041
+ visited.add(value);
3042
+ const outcome = attempt(() => {
3043
+ return Array.from(value.slice(0, breadth)).map((entry) => inferValue(entry, depth - 1, breadth, closed, format, visited, memo));
3044
+ });
3045
+ visited.delete(value);
3046
+ const schema = outcome.success && outcome.value.length > 0 ? {
3047
+ type: "array",
3048
+ items: unifySchemas(outcome.value)
3049
+ } : { type: "array" };
3050
+ let depths = memo.get(value);
3051
+ if (!depths) {
3052
+ depths = /* @__PURE__ */ new Map();
3053
+ memo.set(value, depths);
3054
+ }
3055
+ depths.set(depth, schema);
3056
+ return schema;
3057
+ }
3058
+ /**
3059
+ * Infer a `JSONSchema` object fragment from a plain record's sampled
3060
+ * properties.
3061
+ *
3062
+ * @remarks
3063
+ * Own enumerable string keys via `Object.keys`, sorted lexicographically for
3064
+ * deterministic output, capped at `breadth`. Each property value is read
3065
+ * through {@link attempt} so a hostile getter cannot escape as a thrown
3066
+ * error; a property whose value is `undefined` (hostile-getter failure
3067
+ * included) is treated as ABSENT — it contributes neither a `properties`
3068
+ * entry nor a `required` entry. Every other present key is required (single-
3069
+ * value mode). Emits `additionalProperties: false` when `closed`, `true`
3070
+ * otherwise — mirroring {@link compileSchema}'s object-emission convention —
3071
+ * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means
3072
+ * the sampled schema no longer describes every property `value` actually
3073
+ * carries, so `additionalProperties` is forced to `true` regardless of
3074
+ * `closed` (a closed schema built from a truncated sample would otherwise
3075
+ * reject the very object it was inferred from). Depth exhaustion or a cyclic
3076
+ * re-encounter of `value` both yield `{}`. A same-object re-inference at the
3077
+ * same remaining `depth` is served from `memo` instead of recomputing
3078
+ * (guards a shared-reference DAG against exponential blowup).
3079
+ *
3080
+ * @param value - The record to infer from
3081
+ * @param depth - Remaining descent budget
3082
+ * @param breadth - The maximum number of properties sampled
3083
+ * @param closed - Whether the emitted schema closes to unknown keys
3084
+ * @param format - Threaded through to nested string/`Date` properties
3085
+ * @param visited - The ancestor set guarding against cycles
3086
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
3087
+ * against exponential re-inference of a shared-reference DAG
3088
+ * @returns The inferred object schema
3089
+ *
3090
+ * @example
3091
+ * ```ts
3092
+ * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())
3093
+ * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],
3094
+ * // additionalProperties: false }
3095
+ * ```
3096
+ */
3097
+ function inferObject(value, depth, breadth, closed, format, visited, memo) {
3098
+ if (!(depth > 0) || visited.has(value)) return {};
3099
+ const cached = memo.get(value)?.get(depth);
3100
+ if (cached) return cached;
3101
+ visited.add(value);
3102
+ const outcome = attempt(() => {
3103
+ const allKeys = Object.keys(value).sort();
3104
+ const keys = allKeys.slice(0, breadth);
3105
+ const truncated = allKeys.length > breadth;
3106
+ const properties = Object.create(null);
3107
+ const required = [];
3108
+ for (const key of keys) {
3109
+ const propertyValue = value[key];
3110
+ if (propertyValue === void 0) continue;
3111
+ properties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo);
3112
+ required.push(key);
3113
+ }
3114
+ return {
3115
+ properties,
3116
+ required,
3117
+ truncated
3118
+ };
3119
+ });
3120
+ visited.delete(value);
3121
+ if (!outcome.success) return {};
3122
+ const { properties, required, truncated } = outcome.value;
3123
+ const schema = {
3124
+ type: "object",
3125
+ ...Object.keys(properties).length > 0 ? { properties } : {},
3126
+ ...required.length > 0 ? { required } : {},
3127
+ additionalProperties: truncated ? true : !closed
3128
+ };
3129
+ let depths = memo.get(value);
3130
+ if (!depths) {
3131
+ depths = /* @__PURE__ */ new Map();
3132
+ memo.set(value, depths);
3133
+ }
3134
+ depths.set(depth, schema);
3135
+ return schema;
3136
+ }
3137
+ /**
3138
+ * Infer a `JSONSchema` for one unknown value — the reverse direction of
3139
+ * {@link compileSchema}.
3140
+ *
3141
+ * @remarks
3142
+ * Total: never throws, and is cycle/depth/breadth-bounded (see
3143
+ * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested
3144
+ * objects close to unknown keys (`additionalProperties: false`) by default;
3145
+ * pass `closed: false` to open them. `format` (default `false`) opts a
3146
+ * string/`Date` leaf into the `format` keyword. Structurally-equal inputs
3147
+ * infer byte-identical schemas (object keys and `anyOf` members are sorted).
3148
+ *
3149
+ * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'
3150
+ * }` — is structurally accepted by `schemaToParameters`, but MCP clients
3151
+ * expect an object-shaped `inputSchema`; wrap a non-object payload with
3152
+ * {@link schemaToObject} before advertising it as a tool's parameters.
3153
+ *
3154
+ * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a
3155
+ * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /
3156
+ * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,
3157
+ * fractional) — a hostile or malformed budget can never defeat the depth
3158
+ * guard or corrupt the sampled key/element list.
3159
+ *
3160
+ * @param value - The value to infer a schema from
3161
+ * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds
3162
+ * @returns The inferred `JSONSchema`
3163
+ *
3164
+ * @example
3165
+ * ```ts
3166
+ * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })
3167
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },
3168
+ * // tags: { type: 'array', items: { type: 'string' } } },
3169
+ * // required: ['id', 'name', 'tags'], additionalProperties: false }
3170
+ * ```
3171
+ */
3172
+ function valueToSchema(value, options) {
3173
+ return inferValue(value, sanitizeBudget(options?.maxDepth, 32), sanitizeBudget(options?.maxProperties, 256), options?.closed ?? true, options?.format ?? false, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap());
3174
+ }
3175
+ /**
3176
+ * Infer a `JSONSchema` for a collected slot of sample values — the shared
3177
+ * non-record recursion step behind {@link samplesToSchema} (top level) and
3178
+ * {@link inferRecordSamples} (per collected property).
3179
+ *
3180
+ * @remarks
3181
+ * When every value is itself a plain record, delegates to
3182
+ * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when
3183
+ * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,
3184
+ * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins
3185
+ * outright (ENUM > FORMAT > bare string). Failing that, each value is
3186
+ * classified independently via {@link inferValue} with `format` FORCED OFF
3187
+ * (the multi-sample seam: nested formats never compound into an `anyOf`) and
3188
+ * unified with {@link unifySchemas}; only when that unified result is exactly
3189
+ * `{ type: 'string' }` and the outer `format` flag is on does
3190
+ * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.
3191
+ *
3192
+ * @param samples - The collected slot values
3193
+ * @param depth - Remaining descent budget
3194
+ * @param breadth - The maximum number of properties/elements sampled per nested container
3195
+ * @param closed - Whether nested objects close to unknown keys
3196
+ * @param format - Whether a unanimous string slot gains a `format` keyword
3197
+ * @param enumOn - Whether low-cardinality primitive slots may emit `enum`
3198
+ * @returns The inferred schema for the slot
3199
+ *
3200
+ * @example
3201
+ * ```ts
3202
+ * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)
3203
+ * // { type: 'string', format: 'date' }
3204
+ * ```
3205
+ */
3206
+ function inferSamples(samples, depth, breadth, closed, format, enumOn) {
3207
+ if (samples.length === 0) return {};
3208
+ if (samples.every((sample) => isRecord(sample))) return inferRecordSamples(samples, depth, breadth, closed, format, enumOn);
3209
+ if (enumOn) {
3210
+ const enumSchema = inferPrimitiveEnum(samples, 12);
3211
+ if (enumSchema) return enumSchema;
3212
+ }
3213
+ const unified = unifySchemas(samples.map((sample) => inferValue(sample, depth, breadth, closed, false, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap())));
3214
+ if (format && unified.type === "string" && Object.keys(unified).length === 1) {
3215
+ const detected = samplesToFormat(samples);
3216
+ if (detected) return {
3217
+ type: "string",
3218
+ format: detected
3219
+ };
3220
+ }
3221
+ return unified;
3222
+ }
3223
+ /**
3224
+ * Infer a `JSONSchema` object fragment from a set of plain-record samples
3225
+ * (e.g. database rows) — the record-specialized branch of
3226
+ * {@link samplesToSchema}.
3227
+ *
3228
+ * @remarks
3229
+ * `properties` is the union of every sample's own keys (sorted, capped at
3230
+ * `breadth`); a key is `required` only when present (and non-`undefined`) in
3231
+ * EVERY sample. Each key's schema is inferred over the collected values for
3232
+ * that key via {@link inferSamples} itself (one less depth), so a
3233
+ * property that is itself an array/object of varying shape across rows is
3234
+ * unified the same way the top level is, and the same `format` / `enum`
3235
+ * gating applies per key. Unlike {@link inferObject}/
3236
+ * {@link inferArray}, this path carries no `visited` `WeakSet` — a value
3237
+ * shared by reference across multiple sample rows is legitimate (not a
3238
+ * cycle back to an ancestor), so termination on cyclic row data relies on
3239
+ * the decrementing `depth` budget alone. When the union of sample keys
3240
+ * exceeds `breadth`, the key list is truncated and `additionalProperties` is
3241
+ * forced to `true` regardless of `closed` — the same truncation-opens-the-
3242
+ * schema rule {@link inferObject} applies, so a closed schema built from a
3243
+ * truncated key union never rejects the very rows it was inferred from. A
3244
+ * hostile getter on ONE sample row drops that key for ALL rows (the whole
3245
+ * per-key value collection is a single {@link attempt}-contained walk) —
3246
+ * this is a deliberate all-or-nothing scope, not a per-row partial failure.
3247
+ *
3248
+ * @param samples - The plain-record samples
3249
+ * @param depth - Remaining descent budget
3250
+ * @param breadth - The maximum number of properties sampled
3251
+ * @param closed - Whether the emitted schema closes to unknown keys
3252
+ * @param format - Whether a unanimous string column gains a `format` keyword
3253
+ * @param enumOn - Whether a low-cardinality column may emit `enum`
3254
+ * @returns The inferred object schema
3255
+ *
3256
+ * @example
3257
+ * ```ts
3258
+ * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)
3259
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
3260
+ * // required: ['id'], additionalProperties: false }
3261
+ * ```
3262
+ */
3263
+ function inferRecordSamples(samples, depth, breadth, closed, format, enumOn) {
3264
+ if (!(depth > 0)) return {};
3265
+ const keysOutcome = attempt(() => {
3266
+ const keySet = /* @__PURE__ */ new Set();
3267
+ for (const sample of samples) for (const key of Object.keys(sample)) keySet.add(key);
3268
+ const allKeys = [...keySet].sort();
3269
+ return {
3270
+ keys: allKeys.slice(0, breadth),
3271
+ truncated: allKeys.length > breadth
3272
+ };
3273
+ });
3274
+ const keys = keysOutcome.success ? keysOutcome.value.keys : [];
3275
+ const truncated = keysOutcome.success && keysOutcome.value.truncated;
3276
+ const properties = Object.create(null);
3277
+ const required = [];
3278
+ for (const key of keys) {
3279
+ const valuesOutcome = attempt(() => {
3280
+ const values = [];
3281
+ for (const sample of samples) {
3282
+ const propertyValue = sample[key];
3283
+ if (propertyValue !== void 0) values.push(propertyValue);
3284
+ }
3285
+ return values;
3286
+ });
3287
+ const values = valuesOutcome.success ? valuesOutcome.value : [];
3288
+ if (values.length > 0) properties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn);
3289
+ if (values.length === samples.length) required.push(key);
3290
+ }
3291
+ return {
3292
+ type: "object",
3293
+ ...Object.keys(properties).length > 0 ? { properties } : {},
3294
+ ...required.length > 0 ? { required } : {},
3295
+ additionalProperties: truncated ? true : !closed
3296
+ };
3297
+ }
3298
+ /**
3299
+ * Infer a `JSONSchema` from a set of example values — the multi-example
3300
+ * counterpart of {@link valueToSchema} (e.g. inferring one schema from
3301
+ * several database rows).
3302
+ *
3303
+ * @remarks
3304
+ * An empty `samples` array infers the empty accept-anything schema `{}`.
3305
+ * When every sample is a plain record, properties/required are unified
3306
+ * per-key across all samples (see {@link inferRecordSamples}) — a key
3307
+ * required iff present and non-`undefined` in every sample. Otherwise the
3308
+ * slot is inferred via {@link inferSamples} (independent {@link valueToSchema}
3309
+ * per sample, unified with {@link unifySchemas} — the same de-duplication and
3310
+ * `anyOf` ordering {@link inferArray} applies to element schemas). `format`
3311
+ * and `enum` (both default `false`) opt a low-cardinality/unanimous-format
3312
+ * slot into the corresponding keyword — see {@link inferSamples} for the
3313
+ * precedence and the multi-sample format-disabling seam. `maxDepth` /
3314
+ * `maxProperties` are sanitized via {@link sanitizeBudget} the same way
3315
+ * {@link valueToSchema} sanitizes them — see there for why.
3316
+ *
3317
+ * @param samples - The example values to infer a schema from
3318
+ * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds
3319
+ * @returns The inferred `JSONSchema`
3320
+ *
3321
+ * @example
3322
+ * ```ts
3323
+ * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])
3324
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
3325
+ * // required: ['id'], additionalProperties: false }
3326
+ * samplesToSchema([]) // {}
3327
+ * ```
3328
+ */
3329
+ function samplesToSchema(samples, options) {
3330
+ return inferSamples(samples, sanitizeBudget(options?.maxDepth, 32), sanitizeBudget(options?.maxProperties, 256), options?.closed ?? true, options?.format ?? false, options?.enum ?? false);
3331
+ }
3332
+ //#endregion
2626
3333
  //#region src/core/shapers.ts
2627
3334
  /**
2628
3335
  * Build a string {@link StringShape}.
@@ -2947,7 +3654,349 @@ function rawShape(schema) {
2947
3654
  schema
2948
3655
  };
2949
3656
  }
3657
+ /**
3658
+ * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
3659
+ * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
3660
+ *
3661
+ * @remarks
3662
+ * Total and pure. Either keyword is used only when it is a non-negative
3663
+ * integer (`isInteger` + `>= 0`); a malformed value (a string, a negative
3664
+ * number, `NaN`, `Infinity`, a fraction) is dropped as if absent. When both
3665
+ * bounds are present and `min` exceeds `max`, the PAIR is dropped entirely
3666
+ * (an unbounded shape is always a legal widening of a contradictory schema).
3667
+ *
3668
+ * @param min - The raw `minLength` / `minItems` keyword value
3669
+ * @param max - The raw `maxLength` / `maxItems` keyword value
3670
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
3671
+ *
3672
+ * @example
3673
+ * ```ts
3674
+ * deriveLengthBounds(1, 10) // { min: 1, max: 10 }
3675
+ * deriveLengthBounds(10, 1) // {} — contradictory, dropped
3676
+ * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped
3677
+ * ```
3678
+ */
3679
+ function deriveLengthBounds(min, max) {
3680
+ const lo = isInteger(min) && min >= 0 ? min : void 0;
3681
+ const hi = isInteger(max) && max >= 0 ? max : void 0;
3682
+ if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
3683
+ return {
3684
+ min: lo,
3685
+ max: hi
3686
+ };
3687
+ }
3688
+ /**
3689
+ * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema
3690
+ * range keywords (`minimum`/`maximum`).
3691
+ *
3692
+ * @remarks
3693
+ * Total and pure. Either keyword is used only when it is a finite number
3694
+ * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when
3695
+ * both bounds are present and `min` exceeds `max`, the PAIR is dropped
3696
+ * entirely, the same contradiction rule {@link deriveLengthBounds} applies.
3697
+ *
3698
+ * @param min - The raw `minimum` keyword value
3699
+ * @param max - The raw `maximum` keyword value
3700
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
3701
+ *
3702
+ * @example
3703
+ * ```ts
3704
+ * deriveRangeBounds(0, 120) // { min: 0, max: 120 }
3705
+ * deriveRangeBounds(5, 1) // {} — contradictory, dropped
3706
+ * ```
3707
+ */
3708
+ function deriveRangeBounds(min, max) {
3709
+ const lo = isFiniteNumber(min) ? min : void 0;
3710
+ const hi = isFiniteNumber(max) ? max : void 0;
3711
+ if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
3712
+ return {
3713
+ min: lo,
3714
+ max: hi
3715
+ };
3716
+ }
3717
+ /**
3718
+ * Build an {@link ObjectShape} from a JSON Schema object node's `properties` /
3719
+ * `required` / `additionalProperties` keywords — the object-specialized branch
3720
+ * of {@link buildShapeFromNode}.
3721
+ *
3722
+ * @remarks
3723
+ * `properties` (when a record) contributes one child shape per own key, capped
3724
+ * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
3725
+ * unless it appears as a string entry of `required`. A property whose value is
3726
+ * not itself a record widens to {@link jsonShape}. `additionalProperties`:
3727
+ * `false` closes the object; a record value recurses into it (`objectShape`
3728
+ * validates extras against that shape); anything else — `true`, absent, or
3729
+ * malformed — leaves the object OPEN (`true`), matching JSON Schema's own
3730
+ * absent-means-open default and the fact that {@link valueToSchema} /
3731
+ * {@link samplesToSchema} always emit the keyword explicitly, so an absent
3732
+ * value only arises from a hand-written schema. When `properties` has MORE
3733
+ * keys than {@link INFER_BREADTH_LIMIT}, the schema's own
3734
+ * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
3735
+ * a dropped key's value could otherwise fail a `false` or record-valued rest
3736
+ * shape it was never checked against — mirroring `inferObject`'s
3737
+ * `truncated ? true : !closed` rule (inferers.ts:485). The accumulator uses a
3738
+ * null-prototype record so a property literally named `__proto__` becomes an
3739
+ * own data key rather than mutating the prototype, mirroring
3740
+ * {@link inferObject} (inferers.ts).
3741
+ *
3742
+ * @param schema - The object schema node
3743
+ * @param depth - Remaining descent budget passed to child properties
3744
+ * @param visited - The ancestor set guarding against cycles — recursion
3745
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3746
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3747
+ * supported usage
3748
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
3749
+ * recursion state owned by the {@link schemaToShape} entry point; passing
3750
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
3751
+ * supported usage
3752
+ * @param description - The node's already-extracted `description`, if any
3753
+ * @returns The built object shape
3754
+ *
3755
+ * @example
3756
+ * ```ts
3757
+ * buildObjectShape(
3758
+ * { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
3759
+ * INFER_DEPTH_LIMIT,
3760
+ * new WeakSet(),
3761
+ * new WeakMap(),
3762
+ * undefined,
3763
+ * )
3764
+ * // objectShape({ id: integerShape() }, { additionalProperties: true })
3765
+ * ```
3766
+ */
3767
+ function buildObjectShape(schema, depth, visited, memo, description) {
3768
+ const propertiesSource = isRecord(schema.properties) ? schema.properties : void 0;
3769
+ const requiredSource = isArray(schema.required) ? schema.required.filter((entry) => isString(entry)) : [];
3770
+ const properties = Object.create(null);
3771
+ let truncated = false;
3772
+ if (propertiesSource) {
3773
+ const allKeys = Object.keys(propertiesSource);
3774
+ truncated = allKeys.length > 256;
3775
+ const keys = allKeys.slice(0, 256);
3776
+ for (const key of keys) {
3777
+ const child = propertiesSource[key];
3778
+ const childShape = isRecord(child) ? schemaNodeToShape(child, depth - 1, visited, memo) : jsonShape();
3779
+ properties[key] = requiredSource.includes(key) ? childShape : optionalShape(childShape);
3780
+ }
3781
+ }
3782
+ const extra = schema.additionalProperties;
3783
+ return objectShape(properties, {
3784
+ additionalProperties: truncated ? true : extra === false ? false : isRecord(extra) ? schemaNodeToShape(extra, depth - 1, visited, memo) : true,
3785
+ description
3786
+ });
3787
+ }
3788
+ /**
3789
+ * Build a {@link ContractShape} for one JSON Schema node — the recursive
3790
+ * spine of {@link schemaToShape}, shared with per-child recursion via
3791
+ * {@link schemaNodeToShape}.
3792
+ *
3793
+ * @remarks
3794
+ * Every keyword is read defensively (the node's static `JSONSchema` type is
3795
+ * NOT trusted at runtime — a caller-supplied node may be adversarial), so a
3796
+ * malformed keyword falls through to the next rule instead of throwing.
3797
+ * Precedence, top-down:
3798
+ *
3799
+ * 1. `enum` — an array with at least one string/number/boolean entry (finite
3800
+ * numbers only) becomes a {@link literalShape} over the filtered entries.
3801
+ * Non-primitive / non-finite entries are dropped; an empty result falls
3802
+ * through.
3803
+ * 2. `oneOf` — an array with at least one record entry becomes an
3804
+ * {@link oneOfShape} over the recursively-built variants, provided the
3805
+ * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
3806
+ * limit, building a subset union would be strictly narrower than the
3807
+ * schema's full union (a value matching only a dropped variant would be
3808
+ * wrongly rejected), so the whole node widens to {@link jsonShape} instead
3809
+ * of sampling a subset.
3810
+ * 3. `anyOf` — identically, via {@link unionShape}.
3811
+ * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
3812
+ * the matching primitive shape, with length/range bounds derived via
3813
+ * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node
3814
+ * additionally drops its bounds when they describe an EMPTY integer range
3815
+ * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
3816
+ * rejects — so the result is always a valid shape.
3817
+ * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
3818
+ * a record-valued `items` (widening to {@link jsonShape} otherwise), with
3819
+ * bounds from `minItems` / `maxItems`.
3820
+ * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
3821
+ * record-valued `properties` — delegates to {@link buildObjectShape}.
3822
+ * 7. Everything else — an empty schema, an unrecognized/absent `type`,
3823
+ * exhausted depth/breadth, or an attempt failure — widens to
3824
+ * {@link jsonShape} (the exact inverse of `compileSchema(jsonShape())`,
3825
+ * and where the inferers themselves bottom out at their own limits).
3826
+ *
3827
+ * `format` and `pattern` are NEVER read into the compiled shape — `format` is
3828
+ * annotation-only and `pattern` compiling an attacker-supplied string into a
3829
+ * `RegExp` is a ReDoS vector. `description`, when a string, carries through to
3830
+ * the produced shape's `description` option.
3831
+ *
3832
+ * @param schema - The schema node to convert
3833
+ * @param depth - Remaining descent budget (0 halts recursion with `jsonShape()`)
3834
+ * @param visited - The ancestor set guarding against cycles — recursion
3835
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3836
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3837
+ * supported usage
3838
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache
3839
+ * guarding against exponential re-conversion of a
3840
+ * shared-reference schema DAG — recursion state owned by the
3841
+ * {@link schemaToShape} entry point; passing a shared or
3842
+ * pre-populated `WeakMap` changes caching behavior and is not
3843
+ * supported usage
3844
+ * @returns The built shape for `schema`
3845
+ *
3846
+ * @example
3847
+ * ```ts
3848
+ * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
3849
+ * // stringShape({ min: 1 })
3850
+ * ```
3851
+ */
3852
+ function buildShapeFromNode(schema, depth, visited, memo) {
3853
+ const description = isString(schema.description) ? schema.description : void 0;
3854
+ if (isArray(schema.enum)) {
3855
+ const literals = schema.enum.filter((entry) => isString(entry) || isFiniteNumber(entry) || isBoolean(entry));
3856
+ if (literals.length > 0) return literalShape(literals, { description });
3857
+ }
3858
+ if (isArray(schema.oneOf)) {
3859
+ const records = schema.oneOf.filter((entry) => isRecord(entry));
3860
+ if (records.length > 256) return jsonShape({ description });
3861
+ const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
3862
+ if (variants.length > 0) return oneOfShape(...variants);
3863
+ }
3864
+ if (isArray(schema.anyOf)) {
3865
+ const records = schema.anyOf.filter((entry) => isRecord(entry));
3866
+ if (records.length > 256) return jsonShape({ description });
3867
+ const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
3868
+ if (variants.length > 0) return unionShape(...variants);
3869
+ }
3870
+ const type = isString(schema.type) ? schema.type : void 0;
3871
+ if (type === "string") {
3872
+ const bounds = deriveLengthBounds(schema.minLength, schema.maxLength);
3873
+ return stringShape({
3874
+ min: bounds.min,
3875
+ max: bounds.max,
3876
+ description
3877
+ });
3878
+ }
3879
+ if (type === "number") {
3880
+ const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
3881
+ return numberShape({
3882
+ min: bounds.min,
3883
+ max: bounds.max,
3884
+ description
3885
+ });
3886
+ }
3887
+ if (type === "integer") {
3888
+ const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
3889
+ return integerShape(Math.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > Math.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? { description } : {
3890
+ min: bounds.min,
3891
+ max: bounds.max,
3892
+ description
3893
+ });
3894
+ }
3895
+ if (type === "boolean") return booleanShape({ description });
3896
+ if (type === "null") return nullShape({ description });
3897
+ if (type === "array") {
3898
+ const items = isRecord(schema.items) ? schemaNodeToShape(schema.items, depth - 1, visited, memo) : jsonShape();
3899
+ const bounds = deriveLengthBounds(schema.minItems, schema.maxItems);
3900
+ return arrayShape(items, {
3901
+ min: bounds.min,
3902
+ max: bounds.max,
3903
+ description
3904
+ });
3905
+ }
3906
+ if (type === "object" || type === void 0 && isRecord(schema.properties)) return buildObjectShape(schema, depth, visited, memo, description);
3907
+ return jsonShape({ description });
3908
+ }
3909
+ /**
3910
+ * Convert one JSON Schema node into a {@link ContractShape} — the recursion
3911
+ * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for
3912
+ * every child (`items`, `properties` values, `additionalProperties`,
3913
+ * `oneOf` / `anyOf` variants).
3914
+ *
3915
+ * @remarks
3916
+ * Total: never throws. Guards depth exhaustion, a non-record node (the
3917
+ * node's static `JSONSchema` type is not trusted at runtime), and a cyclic
3918
+ * re-encounter of `schema` — all three widen to {@link jsonShape}. The
3919
+ * ancestor set is added to and removed from around the WHOLE subtree
3920
+ * conversion (not permanently), so a DAG-shaped schema reached twice via two
3921
+ * different, non-cyclic paths does not false-positive as a cycle. The
3922
+ * subtree conversion itself runs inside {@link attempt}, so a hostile
3923
+ * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
3924
+ * — it degrades to {@link jsonShape} instead. A same-node re-conversion at
3925
+ * the same remaining `depth` is served from `memo` (guards a
3926
+ * shared-reference schema DAG against exponential blowup), mirroring
3927
+ * {@link inferObject} / {@link inferArray} (inferers.ts).
3928
+ *
3929
+ * @param schema - The schema node to convert
3930
+ * @param depth - Remaining descent budget
3931
+ * @param visited - The ancestor set guarding against cycles — recursion
3932
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3933
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3934
+ * supported usage
3935
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
3936
+ * recursion state owned by the {@link schemaToShape} entry point; passing
3937
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
3938
+ * supported usage
3939
+ * @returns The built shape for `schema`, or {@link jsonShape} on any failure
3940
+ *
3941
+ * @example
3942
+ * ```ts
3943
+ * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
3944
+ * // booleanShape()
3945
+ * ```
3946
+ */
3947
+ function schemaNodeToShape(schema, depth, visited, memo) {
3948
+ if (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return jsonShape();
3949
+ const cached = memo.get(schema)?.get(depth);
3950
+ if (cached) return cached;
3951
+ visited.add(schema);
3952
+ const outcome = attempt(() => buildShapeFromNode(schema, depth, visited, memo));
3953
+ visited.delete(schema);
3954
+ const shape = outcome.success ? outcome.value : jsonShape();
3955
+ let depths = memo.get(schema);
3956
+ if (!depths) {
3957
+ depths = /* @__PURE__ */ new Map();
3958
+ memo.set(schema, depths);
3959
+ }
3960
+ depths.set(depth, shape);
3961
+ return shape;
3962
+ }
3963
+ /**
3964
+ * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}
3965
+ * — the inverse of {@link compileSchema}, and the validating sibling of
3966
+ * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).
3967
+ *
3968
+ * @remarks
3969
+ * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
3970
+ * outright hostile (throwing-getter Proxy) `schema` value all degrade to
3971
+ * {@link jsonShape} rather than escaping as an error, so
3972
+ * `createContract(schemaToShape(x))` is safe to call for any `x`. See
3973
+ * {@link buildShapeFromNode} for the exact per-keyword precedence.
3974
+ *
3975
+ * `format` and `pattern` are NEVER asserted by the compiled shape — `format`
3976
+ * is annotation-only (per the JSON Schema spec, it never narrows validation
3977
+ * on its own) and compiling an attacker-controlled `pattern` string into a
3978
+ * `RegExp` is a ReDoS vector; both keywords are read only far enough to be
3979
+ * ignored. Any node the walk cannot express — an empty `{}`, an
3980
+ * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
3981
+ * cyclic re-encounter — widens to {@link jsonShape} (accept any JSON), never
3982
+ * narrows: the round trip `compileGuard(schemaToShape(valueToSchema(v)))(v)`
3983
+ * holds for every `v`, with widening as the only source of looseness.
3984
+ *
3985
+ * @param schema - The JSON Schema value to convert
3986
+ * @returns The built {@link ContractShape}
3987
+ *
3988
+ * @example
3989
+ * ```ts
3990
+ * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }])
3991
+ * const contract = createContract(schemaToShape(schema))
3992
+ * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' }
3993
+ * contract.parse({ id: 'nope' }) // undefined
3994
+ * ```
3995
+ */
3996
+ function schemaToShape(schema) {
3997
+ return schemaNodeToShape(schema, 32, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap());
3998
+ }
2950
3999
  //#endregion
2951
- export { FAULT_LIMIT, JSON_SCHEMA_TYPES, PREVIEW_LIMIT, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, createContract, enumOf, enumerableSymbolCount, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterableOf, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pickOf, preview, rawShape, recordOf, recordShape, resolveField, schemaToParameters, seededRandom, setOf, shapeToKind, stringOf, stringShape, transformOf, tupleOf, unionOf, unionShape, validateShape, whereOf };
4000
+ export { FAULT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, JSON_SCHEMA_TYPES, PREVIEW_LIMIT, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, buildObjectShape, buildShapeFromNode, canonicalStringify, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, createContract, deriveLengthBounds, deriveRangeBounds, enumOf, enumerableSymbolCount, inferArray, inferObject, inferPrimitiveEnum, inferRecordSamples, inferSamples, inferValue, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isValidISOInstant, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterableOf, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pickOf, preview, rawShape, recordOf, recordShape, resolveField, samplesToFormat, samplesToSchema, sanitizeBudget, schemaNodeToShape, schemaToObject, schemaToParameters, schemaToShape, seededRandom, setOf, shapeToKind, stringOf, stringShape, stringToFormat, transformOf, tupleOf, unifySchemas, unionOf, unionShape, validateShape, valueToSchema, whereOf };
2952
4001
 
2953
4002
  //# sourceMappingURL=index.js.map