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