@orkestrel/contract 0.0.1 → 0.0.2

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.
@@ -0,0 +1,2722 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/core/constants.ts
3
+ /**
4
+ * The seven standard JSON Schema `type` names, frozen.
5
+ *
6
+ * @remarks
7
+ * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose
8
+ * it with the shipped primitives instead of reaching for a bespoke guard:
9
+ * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and
10
+ * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`
11
+ * is the parser.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'
16
+ *
17
+ * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>
18
+ * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined
19
+ * ```
20
+ */
21
+ var JSON_SCHEMA_TYPES = Object.freeze([
22
+ "null",
23
+ "boolean",
24
+ "object",
25
+ "array",
26
+ "number",
27
+ "integer",
28
+ "string"
29
+ ]);
30
+ //#endregion
31
+ //#region src/core/validators.ts
32
+ /** Determine whether a value is `null`.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * isNull(null) // true
37
+ * isNull(undefined) // false
38
+ * ```
39
+ */
40
+ function isNull(value) {
41
+ return value === null;
42
+ }
43
+ /** Determine whether a value is `undefined`.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * isUndefined(undefined) // true
48
+ * isUndefined(null) // false
49
+ * ```
50
+ */
51
+ function isUndefined(value) {
52
+ return value === void 0;
53
+ }
54
+ /** Determine whether a value is defined (neither `null` nor `undefined`).
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * isDefined('hi') // true
59
+ * isDefined(null) // false
60
+ * isDefined(undefined) // false
61
+ * ```
62
+ */
63
+ function isDefined(value) {
64
+ return value !== null && value !== void 0;
65
+ }
66
+ /** Determine whether a value is a string. */
67
+ function isString(value) {
68
+ return typeof value === "string";
69
+ }
70
+ /**
71
+ * Determine whether a value is a number.
72
+ *
73
+ * @remarks
74
+ * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.
75
+ */
76
+ function isNumber(value) {
77
+ return typeof value === "number";
78
+ }
79
+ /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). */
80
+ function isFiniteNumber(value) {
81
+ return typeof value === "number" && Number.isFinite(value);
82
+ }
83
+ /** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * isInteger(3) // true
88
+ * isInteger(3.5) // false
89
+ * ```
90
+ */
91
+ function isInteger(value) {
92
+ return Number.isInteger(value);
93
+ }
94
+ /** Determine whether a value is a boolean.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * isBoolean(true) // true
99
+ * isBoolean(1) // false
100
+ * ```
101
+ */
102
+ function isBoolean(value) {
103
+ return typeof value === "boolean";
104
+ }
105
+ /** Determine whether a value is exactly `true`.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * isTrue(true) // true
110
+ * isTrue(false) // false
111
+ * ```
112
+ */
113
+ function isTrue(value) {
114
+ return value === true;
115
+ }
116
+ /** Determine whether a value is exactly `false`.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * isFalse(false) // true
121
+ * isFalse(true) // false
122
+ * ```
123
+ */
124
+ function isFalse(value) {
125
+ return value === false;
126
+ }
127
+ /** Determine whether a value is a bigint.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * isBigInt(1n) // true
132
+ * isBigInt(1) // false
133
+ * ```
134
+ */
135
+ function isBigInt(value) {
136
+ return typeof value === "bigint";
137
+ }
138
+ /** Determine whether a value is a symbol.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * isSymbol(Symbol('x')) // true
143
+ * isSymbol('x') // false
144
+ * ```
145
+ */
146
+ function isSymbol(value) {
147
+ return typeof value === "symbol";
148
+ }
149
+ /** Determine whether a value is callable.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * isFunction(() => {}) // true
154
+ * isFunction({}) // false
155
+ * ```
156
+ */
157
+ function isFunction(value) {
158
+ return typeof value === "function";
159
+ }
160
+ /** Determine whether a value is a string or `null`.
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * isNullableString('hi') // true
165
+ * isNullableString(null) // true
166
+ * isNullableString(42) // false
167
+ * ```
168
+ */
169
+ function isNullableString(value) {
170
+ return value === null || isString(value);
171
+ }
172
+ /** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * isNullableNumber(42) // true
177
+ * isNullableNumber(null) // true
178
+ * isNullableNumber('hi') // false
179
+ * ```
180
+ */
181
+ function isNullableNumber(value) {
182
+ return value === null || isNumber(value);
183
+ }
184
+ /** Determine whether a value is a boolean or `null`.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * isNullableBoolean(true) // true
189
+ * isNullableBoolean(null) // true
190
+ * isNullableBoolean(1) // false
191
+ * ```
192
+ */
193
+ function isNullableBoolean(value) {
194
+ return value === null || isBoolean(value);
195
+ }
196
+ /** Determine whether a value is a `Date`.
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * isDate(new Date()) // true
201
+ * isDate('2024-01-01') // false
202
+ * ```
203
+ */
204
+ function isDate(value) {
205
+ return value instanceof Date;
206
+ }
207
+ /** Determine whether a value is a `RegExp`.
208
+ *
209
+ * @example
210
+ * ```ts
211
+ * isRegExp(/a/) // true
212
+ * isRegExp('a') // false
213
+ * ```
214
+ */
215
+ function isRegExp(value) {
216
+ return value instanceof RegExp;
217
+ }
218
+ /** Determine whether a value is an `Error`.
219
+ *
220
+ * @example
221
+ * ```ts
222
+ * isError(new Error('boom')) // true
223
+ * isError('boom') // false
224
+ * ```
225
+ */
226
+ function isError(value) {
227
+ return value instanceof Error;
228
+ }
229
+ /** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * isPromise(Promise.resolve()) // true
234
+ * isPromise({ then() {} }) // false
235
+ * ```
236
+ */
237
+ function isPromise(value) {
238
+ return value instanceof Promise;
239
+ }
240
+ /**
241
+ * Determine whether a value is promise-like — an object exposing callable
242
+ * `then`, `catch`, and `finally` methods.
243
+ *
244
+ * @remarks
245
+ * Accepts any object with all three methods, not only native `Promise`
246
+ * instances. Use {@link isPromise} when you specifically need `instanceof Promise`.
247
+ *
248
+ * @example
249
+ * ```ts
250
+ * isPromiseLike(Promise.resolve()) // true
251
+ * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true
252
+ * isPromiseLike({ then() {} }) // false
253
+ * ```
254
+ */
255
+ function isPromiseLike(value) {
256
+ if (!isObject(value)) return false;
257
+ const outcome = attempt(() => {
258
+ const thenValue = Reflect.get(value, "then");
259
+ const catchValue = Reflect.get(value, "catch");
260
+ const finallyValue = Reflect.get(value, "finally");
261
+ return isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue);
262
+ });
263
+ return outcome.success && outcome.value;
264
+ }
265
+ /** Determine whether a value is an `ArrayBuffer`.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * isArrayBuffer(new ArrayBuffer(8)) // true
270
+ * isArrayBuffer([]) // false
271
+ * ```
272
+ */
273
+ function isArrayBuffer(value) {
274
+ return value instanceof ArrayBuffer;
275
+ }
276
+ /**
277
+ * Determine whether a value is a `SharedArrayBuffer`.
278
+ *
279
+ * @remarks
280
+ * Guards the global existence of `SharedArrayBuffer` first — safe where it is
281
+ * absent or disabled (e.g. a context that is not cross-origin isolated).
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true
286
+ * isSharedArrayBuffer(new ArrayBuffer(8)) // false
287
+ * ```
288
+ */
289
+ function isSharedArrayBuffer(value) {
290
+ return typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer;
291
+ }
292
+ /**
293
+ * Determine whether a value implements the iterable protocol (`Symbol.iterator`).
294
+ *
295
+ * @remarks
296
+ * Strings are explicitly included: a string has a callable `Symbol.iterator`
297
+ * but is not an object, so the generic object path alone would miss it.
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * isIterable([1, 2]) // true
302
+ * isIterable('abc') // true
303
+ * isIterable({ a: 1 }) // false
304
+ * ```
305
+ */
306
+ function isIterable(value) {
307
+ if (isString(value)) return true;
308
+ if (!isObject(value)) return false;
309
+ const outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)));
310
+ return outcome.success && outcome.value;
311
+ }
312
+ /** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true
317
+ * isAsyncIterable([1, 2]) // false
318
+ * ```
319
+ */
320
+ function isAsyncIterable(value) {
321
+ if (!isObject(value)) return false;
322
+ const outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)));
323
+ return outcome.success && outcome.value;
324
+ }
325
+ /**
326
+ * Determine whether a value is a non-null object.
327
+ *
328
+ * @remarks
329
+ * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use
330
+ * {@link isRecord} when you need a plain-record check.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * isObject({}) // true
335
+ * isObject([]) // true
336
+ * isObject(null) // false
337
+ * ```
338
+ */
339
+ function isObject(value) {
340
+ return typeof value === "object" && value !== null;
341
+ }
342
+ /**
343
+ * Determine whether a value is a plain record (object literal or null-prototype),
344
+ * not an array or class instance.
345
+ *
346
+ * @remarks
347
+ * Use instead of {@link isObject} to distinguish a plain `{}` /
348
+ * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
349
+ * test is realm-agnostic: rather than comparing against the current realm's
350
+ * `Object.prototype` (which a plain object from another `vm.Context`, iframe,
351
+ * or worker would fail), it accepts any value whose prototype is `null`, OR
352
+ * whose prototype's own prototype is `null` — the shape every plain object
353
+ * has in every realm, since `Object.prototype` itself always sits one step
354
+ * above `null`. Arrays and class instances are still rejected: an array's
355
+ * prototype chain runs through `Array.prototype` before `null`, and a class
356
+ * instance's runs through the class's own prototype. The whole body runs
357
+ * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
358
+ * `getPrototypeOf` trap cannot escape as a thrown error.
359
+ */
360
+ function isRecord(value) {
361
+ const outcome = attempt(() => {
362
+ if (!isObject(value) || isArray(value)) return false;
363
+ const prototype = Object.getPrototypeOf(value);
364
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
365
+ });
366
+ return outcome.success && outcome.value;
367
+ }
368
+ /** Determine whether a value is a `Map`.
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * isMap(new Map()) // true
373
+ * isMap({}) // false
374
+ * ```
375
+ */
376
+ function isMap(value) {
377
+ return value instanceof Map;
378
+ }
379
+ /** Determine whether a value is a `Set`.
380
+ *
381
+ * @example
382
+ * ```ts
383
+ * isSet(new Set()) // true
384
+ * isSet([]) // false
385
+ * ```
386
+ */
387
+ function isSet(value) {
388
+ return value instanceof Set;
389
+ }
390
+ /** Determine whether a value is a `WeakMap`.
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * isWeakMap(new WeakMap()) // true
395
+ * isWeakMap({}) // false
396
+ * ```
397
+ */
398
+ function isWeakMap(value) {
399
+ return value instanceof WeakMap;
400
+ }
401
+ /** Determine whether a value is a `WeakSet`.
402
+ *
403
+ * @example
404
+ * ```ts
405
+ * isWeakSet(new WeakSet()) // true
406
+ * isWeakSet({}) // false
407
+ * ```
408
+ */
409
+ function isWeakSet(value) {
410
+ return value instanceof WeakSet;
411
+ }
412
+ /** Determine whether a value is an array.
413
+ *
414
+ * @example
415
+ * ```ts
416
+ * isArray([1, 2]) // true
417
+ * isArray('12') // false
418
+ * ```
419
+ */
420
+ function isArray(value) {
421
+ return Array.isArray(value);
422
+ }
423
+ /** Determine whether a value is a `DataView`.
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * isDataView(new DataView(new ArrayBuffer(8))) // true
428
+ * isDataView(new ArrayBuffer(8)) // false
429
+ * ```
430
+ */
431
+ function isDataView(value) {
432
+ return value instanceof DataView;
433
+ }
434
+ /** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).
435
+ *
436
+ * @example
437
+ * ```ts
438
+ * isArrayBufferView(new Uint8Array(4)) // true
439
+ * isArrayBufferView([1, 2, 3, 4]) // false
440
+ * ```
441
+ */
442
+ function isArrayBufferView(value) {
443
+ return ArrayBuffer.isView(value);
444
+ }
445
+ /** Determine whether a value is an `Int8Array`.
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * isInt8Array(new Int8Array(2)) // true
450
+ * isInt8Array(new Uint8Array(2)) // false
451
+ * ```
452
+ */
453
+ function isInt8Array(value) {
454
+ return value instanceof Int8Array;
455
+ }
456
+ /** Determine whether a value is a `Uint8Array`.
457
+ *
458
+ * @example
459
+ * ```ts
460
+ * isUint8Array(new Uint8Array(2)) // true
461
+ * isUint8Array(new Int8Array(2)) // false
462
+ * ```
463
+ */
464
+ function isUint8Array(value) {
465
+ return value instanceof Uint8Array;
466
+ }
467
+ /** Determine whether a value is a `Uint8ClampedArray`.
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * isUint8ClampedArray(new Uint8ClampedArray(2)) // true
472
+ * isUint8ClampedArray(new Uint8Array(2)) // false
473
+ * ```
474
+ */
475
+ function isUint8ClampedArray(value) {
476
+ return value instanceof Uint8ClampedArray;
477
+ }
478
+ /** Determine whether a value is an `Int16Array`.
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * isInt16Array(new Int16Array(2)) // true
483
+ * isInt16Array(new Int8Array(2)) // false
484
+ * ```
485
+ */
486
+ function isInt16Array(value) {
487
+ return value instanceof Int16Array;
488
+ }
489
+ /** Determine whether a value is a `Uint16Array`.
490
+ *
491
+ * @example
492
+ * ```ts
493
+ * isUint16Array(new Uint16Array(2)) // true
494
+ * isUint16Array(new Int16Array(2)) // false
495
+ * ```
496
+ */
497
+ function isUint16Array(value) {
498
+ return value instanceof Uint16Array;
499
+ }
500
+ /** Determine whether a value is an `Int32Array`.
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * isInt32Array(new Int32Array(2)) // true
505
+ * isInt32Array(new Int16Array(2)) // false
506
+ * ```
507
+ */
508
+ function isInt32Array(value) {
509
+ return value instanceof Int32Array;
510
+ }
511
+ /** Determine whether a value is a `Uint32Array`.
512
+ *
513
+ * @example
514
+ * ```ts
515
+ * isUint32Array(new Uint32Array(2)) // true
516
+ * isUint32Array(new Int32Array(2)) // false
517
+ * ```
518
+ */
519
+ function isUint32Array(value) {
520
+ return value instanceof Uint32Array;
521
+ }
522
+ /** Determine whether a value is a `Float32Array`.
523
+ *
524
+ * @example
525
+ * ```ts
526
+ * isFloat32Array(new Float32Array(2)) // true
527
+ * isFloat32Array(new Float64Array(2)) // false
528
+ * ```
529
+ */
530
+ function isFloat32Array(value) {
531
+ return value instanceof Float32Array;
532
+ }
533
+ /** Determine whether a value is a `Float64Array`.
534
+ *
535
+ * @example
536
+ * ```ts
537
+ * isFloat64Array(new Float64Array(2)) // true
538
+ * isFloat64Array(new Float32Array(2)) // false
539
+ * ```
540
+ */
541
+ function isFloat64Array(value) {
542
+ return value instanceof Float64Array;
543
+ }
544
+ /**
545
+ * Determine whether a value is a `BigInt64Array`.
546
+ *
547
+ * @remarks
548
+ * Guards the global existence of `BigInt64Array` first — safe in environments
549
+ * that pre-date the BigInt typed-array additions.
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * isBigInt64Array(new BigInt64Array(2)) // true
554
+ * isBigInt64Array(new Float64Array(2)) // false
555
+ * ```
556
+ */
557
+ function isBigInt64Array(value) {
558
+ return typeof BigInt64Array !== "undefined" && value instanceof BigInt64Array;
559
+ }
560
+ /**
561
+ * Determine whether a value is a `BigUint64Array`.
562
+ *
563
+ * @remarks
564
+ * Guards the global existence of `BigUint64Array` first — safe in environments
565
+ * that pre-date the BigInt typed-array additions.
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * isBigUint64Array(new BigUint64Array(2)) // true
570
+ * isBigUint64Array(new BigInt64Array(2)) // false
571
+ * ```
572
+ */
573
+ function isBigUint64Array(value) {
574
+ return typeof BigUint64Array !== "undefined" && value instanceof BigUint64Array;
575
+ }
576
+ /** Determine whether a value is the empty string `''`.
577
+ *
578
+ * @example
579
+ * ```ts
580
+ * isEmptyString('') // true
581
+ * isEmptyString('a') // false
582
+ * ```
583
+ */
584
+ function isEmptyString(value) {
585
+ return isString(value) && value.length === 0;
586
+ }
587
+ /** Determine whether a value is an empty array.
588
+ *
589
+ * @example
590
+ * ```ts
591
+ * isEmptyArray([]) // true
592
+ * isEmptyArray([1]) // false
593
+ * ```
594
+ */
595
+ function isEmptyArray(value) {
596
+ return isArray(value) && value.length === 0;
597
+ }
598
+ /** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).
599
+ *
600
+ * @example
601
+ * ```ts
602
+ * isEmptyObject({}) // true
603
+ * isEmptyObject({ a: 1 }) // false
604
+ * ```
605
+ */
606
+ function isEmptyObject(value) {
607
+ if (!isRecord(value)) return false;
608
+ return Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0;
609
+ }
610
+ /** Determine whether a value is an empty `Map`.
611
+ *
612
+ * @example
613
+ * ```ts
614
+ * isEmptyMap(new Map()) // true
615
+ * isEmptyMap(new Map([['a', 1]])) // false
616
+ * ```
617
+ */
618
+ function isEmptyMap(value) {
619
+ return value instanceof Map && value.size === 0;
620
+ }
621
+ /** Determine whether a value is an empty `Set`.
622
+ *
623
+ * @example
624
+ * ```ts
625
+ * isEmptySet(new Set()) // true
626
+ * isEmptySet(new Set([1])) // false
627
+ * ```
628
+ */
629
+ function isEmptySet(value) {
630
+ return value instanceof Set && value.size === 0;
631
+ }
632
+ /** Determine whether a value is a non-empty string (at least one character).
633
+ *
634
+ * @example
635
+ * ```ts
636
+ * isNonEmptyString('a') // true
637
+ * isNonEmptyString('') // false
638
+ * ```
639
+ */
640
+ function isNonEmptyString(value) {
641
+ return isString(value) && value.length > 0;
642
+ }
643
+ /** Determine whether a value is a non-empty array (at least one element).
644
+ *
645
+ * @example
646
+ * ```ts
647
+ * isNonEmptyArray([1]) // true
648
+ * isNonEmptyArray([]) // false
649
+ * ```
650
+ */
651
+ function isNonEmptyArray(value) {
652
+ return isArray(value) && value.length > 0;
653
+ }
654
+ /** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).
655
+ *
656
+ * @example
657
+ * ```ts
658
+ * isNonEmptyObject({ a: 1 }) // true
659
+ * isNonEmptyObject({}) // false
660
+ * ```
661
+ */
662
+ function isNonEmptyObject(value) {
663
+ if (!isRecord(value)) return false;
664
+ return Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0;
665
+ }
666
+ /** Determine whether a value is a non-empty `Map` (at least one entry).
667
+ *
668
+ * @example
669
+ * ```ts
670
+ * isNonEmptyMap(new Map([['a', 1]])) // true
671
+ * isNonEmptyMap(new Map()) // false
672
+ * ```
673
+ */
674
+ function isNonEmptyMap(value) {
675
+ return value instanceof Map && value.size > 0;
676
+ }
677
+ /** Determine whether a value is a non-empty `Set` (at least one element).
678
+ *
679
+ * @example
680
+ * ```ts
681
+ * isNonEmptySet(new Set([1])) // true
682
+ * isNonEmptySet(new Set()) // false
683
+ * ```
684
+ */
685
+ function isNonEmptySet(value) {
686
+ return value instanceof Set && value.size > 0;
687
+ }
688
+ /** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).
689
+ *
690
+ * @example
691
+ * ```ts
692
+ * isZeroArg(() => {}) // true
693
+ * isZeroArg((a) => a) // false
694
+ * ```
695
+ */
696
+ function isZeroArg(value) {
697
+ return isFunction(value) && value.length === 0;
698
+ }
699
+ /**
700
+ * Determine whether a value is a native `async function`.
701
+ *
702
+ * @remarks
703
+ * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is
704
+ * unreliable across realms. The `?.` keeps the guard total (§14): a function
705
+ * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.
706
+ *
707
+ * @example
708
+ * ```ts
709
+ * isAsyncFunction(async () => {}) // true
710
+ * isAsyncFunction(() => {}) // false
711
+ * ```
712
+ */
713
+ function isAsyncFunction(value) {
714
+ return isFunction(value) && value.constructor?.name === "AsyncFunction";
715
+ }
716
+ /** Determine whether a value is a generator function (`function*`).
717
+ *
718
+ * @example
719
+ * ```ts
720
+ * isGeneratorFunction(function* () {}) // true
721
+ * isGeneratorFunction(() => {}) // false
722
+ * ```
723
+ */
724
+ function isGeneratorFunction(value) {
725
+ return isFunction(value) && value.constructor?.name === "GeneratorFunction";
726
+ }
727
+ /** Determine whether a value is an async generator function (`async function*`).
728
+ *
729
+ * @example
730
+ * ```ts
731
+ * isAsyncGeneratorFunction(async function* () {}) // true
732
+ * isAsyncGeneratorFunction(function* () {}) // false
733
+ * ```
734
+ */
735
+ function isAsyncGeneratorFunction(value) {
736
+ return isFunction(value) && value.constructor?.name === "AsyncGeneratorFunction";
737
+ }
738
+ /** Determine whether a value is a zero-argument async function.
739
+ *
740
+ * @example
741
+ * ```ts
742
+ * isZeroArgAsync(async () => {}) // true
743
+ * isZeroArgAsync(async (a) => a) // false
744
+ * ```
745
+ */
746
+ function isZeroArgAsync(value) {
747
+ return isZeroArg(value) && isAsyncFunction(value);
748
+ }
749
+ /** Determine whether a value is a zero-argument generator function.
750
+ *
751
+ * @example
752
+ * ```ts
753
+ * isZeroArgGenerator(function* () {}) // true
754
+ * isZeroArgGenerator(function* (a) {}) // false
755
+ * ```
756
+ */
757
+ function isZeroArgGenerator(value) {
758
+ return isZeroArg(value) && isGeneratorFunction(value);
759
+ }
760
+ /** Determine whether a value is a zero-argument async generator function.
761
+ *
762
+ * @example
763
+ * ```ts
764
+ * isZeroArgAsyncGenerator(async function* () {}) // true
765
+ * isZeroArgAsyncGenerator(async function* (a) {}) // false
766
+ * ```
767
+ */
768
+ function isZeroArgAsyncGenerator(value) {
769
+ return isZeroArg(value) && isAsyncGeneratorFunction(value);
770
+ }
771
+ /**
772
+ * Determine whether a value can be used as a `new`-target constructor.
773
+ *
774
+ * @remarks
775
+ * Probes with `Reflect.construct(String, [], value)`: a real constructor
776
+ * succeeds, while arrow functions, plain functions, and non-functions throw
777
+ * and yield `false`. Never throws. Backs the `instanceOf` combinator.
778
+ *
779
+ * @example
780
+ * ```ts
781
+ * isConstructor(class X {}) // true
782
+ * isConstructor(() => {}) // false
783
+ * ```
784
+ */
785
+ function isConstructor(value) {
786
+ if (!isFunction(value)) return false;
787
+ try {
788
+ Reflect.construct(String, [], value);
789
+ return true;
790
+ } catch {
791
+ return false;
792
+ }
793
+ }
794
+ /**
795
+ * Determine whether a value is a cycle-safe JSON value.
796
+ *
797
+ * @remarks
798
+ * Total guard: never throws, returns `false` for cycles, functions, `Date`
799
+ * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
800
+ * are walked with an ancestor set so recursive input fails instead of hanging.
801
+ * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a
802
+ * record property, or a revoked `Proxy` anywhere in the structure, is caught
803
+ * and yields `false` instead of escaping as a thrown error.
804
+ *
805
+ * @param value - The value to test
806
+ * @returns `true` when the value has a JSON representation
807
+ *
808
+ * @example
809
+ * ```ts
810
+ * isJSONValue({ nested: [1, 'x', null] }) // true
811
+ * isJSONValue(Number.NaN) // false
812
+ * ```
813
+ */
814
+ function isJSONValue(value) {
815
+ const ancestors = /* @__PURE__ */ new WeakSet();
816
+ const check = (entry) => {
817
+ if (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true;
818
+ if (Array.isArray(entry)) {
819
+ if (ancestors.has(entry)) return false;
820
+ ancestors.add(entry);
821
+ const valid = entry.every(check);
822
+ ancestors.delete(entry);
823
+ return valid;
824
+ }
825
+ if (!isRecord(entry)) return false;
826
+ if (ancestors.has(entry)) return false;
827
+ ancestors.add(entry);
828
+ const valid = Object.values(entry).every(check);
829
+ ancestors.delete(entry);
830
+ return valid;
831
+ };
832
+ const outcome = attempt(() => check(value));
833
+ return outcome.success && outcome.value;
834
+ }
835
+ /**
836
+ * Determine whether a value is a primitive JSON value.
837
+ *
838
+ * @remarks
839
+ * The flat leaf of any JSON document: `null`, a string, a **finite** number, or
840
+ * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON
841
+ * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.
842
+ *
843
+ * The recursive {@link isJSONValue} guard is shipped and stays total with
844
+ * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and
845
+ * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with
846
+ * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.
847
+ *
848
+ * @param value - The value to test
849
+ * @returns `true` when `value` is `null`, a string, a finite number, or a boolean
850
+ *
851
+ * @example
852
+ * ```ts
853
+ * isJSONPrimitive(null) // true
854
+ * isJSONPrimitive('hi') // true
855
+ * isJSONPrimitive(42) // true
856
+ * isJSONPrimitive(Number.NaN) // false — not representable in JSON
857
+ * isJSONPrimitive({}) // false
858
+ * ```
859
+ */
860
+ function isJSONPrimitive(value) {
861
+ return isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value);
862
+ }
863
+ //#endregion
864
+ //#region src/core/helpers.ts
865
+ /**
866
+ * Invoke a callback and capture its outcome as a {@link Result}, never letting
867
+ * a throw escape.
868
+ *
869
+ * @remarks
870
+ * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
871
+ * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
872
+ * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
873
+ * `boolean`. This converts a throwing callback into a `Failure` so the
874
+ * surrounding guard can treat it as a non-match instead of propagating the
875
+ * exception, written once and shared rather than copy-pasted as ad-hoc
876
+ * `try`/`catch`.
877
+ *
878
+ * @param callback - The callback to invoke with no arguments
879
+ * @returns A `Success` carrying the return value, or a `Failure` carrying the
880
+ * thrown reason normalised to an `Error`
881
+ *
882
+ * @example
883
+ * ```ts
884
+ * const outcome = attempt(() => predicate(value))
885
+ * return outcome.success && outcome.value
886
+ * ```
887
+ */
888
+ function attempt(callback) {
889
+ try {
890
+ return {
891
+ success: true,
892
+ value: callback()
893
+ };
894
+ } catch (reason) {
895
+ if (reason instanceof Error) return {
896
+ success: false,
897
+ error: reason
898
+ };
899
+ let message = "Unknown thrown value";
900
+ try {
901
+ message = String(reason);
902
+ } catch {}
903
+ return {
904
+ success: false,
905
+ error: new Error(message)
906
+ };
907
+ }
908
+ }
909
+ /**
910
+ * Resolve a (possibly nested) field value from a record by a key or key path.
911
+ *
912
+ * @remarks
913
+ * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a
914
+ * string array descends left-to-right through nested objects. Intermediates may
915
+ * be any object — records, class instances, or arrays indexed by string. Returns
916
+ * `undefined` the moment a segment is missing or lands on a non-object, so the
917
+ * lookup is total — even against a hostile getter or Proxy trap that throws on
918
+ * read, contained via {@link attempt} so the throw never escapes.
919
+ *
920
+ * @param record - The source record
921
+ * @param path - A property key, or a key path descending into nested objects
922
+ * @returns The resolved value, or `undefined`
923
+ *
924
+ * @example
925
+ * ```ts
926
+ * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'
927
+ * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)
928
+ * resolveField({ a: 1 }, ['a', 'b']) // undefined
929
+ * ```
930
+ */
931
+ function resolveField(record, path) {
932
+ const keys = isString(path) ? [path] : path;
933
+ let current = record;
934
+ for (const key of keys) {
935
+ if (!isObject(current)) return void 0;
936
+ const container = current;
937
+ const outcome = attempt(() => Reflect.get(container, key));
938
+ if (!outcome.success) return void 0;
939
+ current = outcome.value;
940
+ }
941
+ return current;
942
+ }
943
+ /**
944
+ * Build a deterministic pseudo-random source seeded from a single number.
945
+ *
946
+ * @remarks
947
+ * A mulberry32 generator — the same seed always yields the same sequence, so
948
+ * generated seed data is reproducible across runs. Used as the default random
949
+ * source for {@link compileGenerator}, seeded from the wall clock so casual
950
+ * callers still get varied output without passing a source themselves.
951
+ *
952
+ * @param seed - The seed for the sequence
953
+ * @returns A {@link RandomFunction} returning values in `[0, 1)`
954
+ *
955
+ * @example
956
+ * ```ts
957
+ * const random = seededRandom(42)
958
+ * random() // always the same first value for seed 42
959
+ * ```
960
+ */
961
+ function seededRandom(seed) {
962
+ let state = seed >>> 0;
963
+ return () => {
964
+ state = state + 1831565813 >>> 0;
965
+ let t = state;
966
+ t = Math.imul(t ^ t >>> 15, t | 1);
967
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
968
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
969
+ };
970
+ }
971
+ /**
972
+ * Count the enumerable own-symbol keys on a value.
973
+ *
974
+ * @remarks
975
+ * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose
976
+ * descriptor is `enumerable` are counted. Backs the object-emptiness guards
977
+ * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an
978
+ * enumerable symbol is not mistaken for empty.
979
+ *
980
+ * @param value - The object to inspect
981
+ * @returns The number of enumerable own-symbol keys
982
+ *
983
+ * @example
984
+ * ```ts
985
+ * const flag = Symbol('flag')
986
+ * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1
987
+ * enumerableSymbolCount({}) // 0
988
+ * ```
989
+ */
990
+ function enumerableSymbolCount(value) {
991
+ let count = 0;
992
+ for (const symbol of Object.getOwnPropertySymbols(value)) if (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) count += 1;
993
+ return count;
994
+ }
995
+ /**
996
+ * Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape
997
+ * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never
998
+ * an assertion (AGENTS §14).
999
+ *
1000
+ * @remarks
1001
+ * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a
1002
+ * tool advertises its `parameters` as an open record. The two are structurally compatible but not
1003
+ * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema
1004
+ * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's
1005
+ * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open
1006
+ * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.
1007
+ *
1008
+ * @param schema - The compiled JSON Schema (a contract's `schema`)
1009
+ * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record
1010
+ *
1011
+ * @example
1012
+ * ```ts
1013
+ * import { createContract, schemaToParameters } from '@src/core'
1014
+ *
1015
+ * const contract = createContract(shape)
1016
+ * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises
1017
+ * ```
1018
+ */
1019
+ function schemaToParameters(schema) {
1020
+ return isRecord(schema) ? schema : void 0;
1021
+ }
1022
+ //#endregion
1023
+ //#region src/core/combinators.ts
1024
+ function arrayOf(elementGuard) {
1025
+ return (value) => {
1026
+ if (!isArray(value)) return false;
1027
+ const outcome = attempt(() => value.every(elementGuard));
1028
+ return outcome.success && outcome.value;
1029
+ };
1030
+ }
1031
+ function tupleOf(...guards) {
1032
+ return (value) => {
1033
+ if (!isArray(value)) return false;
1034
+ const outcome = attempt(() => {
1035
+ if (value.length !== guards.length) return false;
1036
+ for (let index = 0; index < guards.length; index += 1) {
1037
+ const guard = guards[index];
1038
+ if (!guard?.(value[index])) return false;
1039
+ }
1040
+ return true;
1041
+ });
1042
+ return outcome.success && outcome.value;
1043
+ };
1044
+ }
1045
+ /**
1046
+ * Build a guard that accepts values identical (via `Object.is`) to one of the
1047
+ * provided literal primitives.
1048
+ *
1049
+ * @example
1050
+ * ```ts
1051
+ * const isRole = literalOf('admin', 'member', 'guest')
1052
+ * isRole('admin') // true
1053
+ * isRole('owner') // false
1054
+ * ```
1055
+ */
1056
+ function literalOf(...literals) {
1057
+ return (value) => literals.some((literal) => Object.is(literal, value));
1058
+ }
1059
+ /**
1060
+ * Build a guard that accepts instances of the provided constructor.
1061
+ *
1062
+ * @remarks
1063
+ * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,
1064
+ * so passing an arrow function does not silently produce a broken guard.
1065
+ *
1066
+ * @example
1067
+ * ```ts
1068
+ * const isDateValue = instanceOf(Date)
1069
+ * isDateValue(new Date()) // true
1070
+ * isDateValue({}) // false
1071
+ * ```
1072
+ */
1073
+ function instanceOf(ctor) {
1074
+ return (value) => isConstructor(ctor) && isObject(value) && value instanceof ctor;
1075
+ }
1076
+ /**
1077
+ * Build a guard from a native `enum` or any object whose values are strings or
1078
+ * numbers.
1079
+ *
1080
+ * @example
1081
+ * ```ts
1082
+ * enum Direction { Up = 'up', Down = 'down' }
1083
+ * const isDirection = enumOf(Direction)
1084
+ * isDirection('up') // true
1085
+ * isDirection('left') // false
1086
+ * ```
1087
+ */
1088
+ function enumOf(enumeration) {
1089
+ const values = new Set(Object.values(enumeration));
1090
+ return (value) => (isString(value) || isNumber(value)) && values.has(value);
1091
+ }
1092
+ function setOf(elementGuard) {
1093
+ return (value) => {
1094
+ if (!isSet(value)) return false;
1095
+ const outcome = attempt(() => {
1096
+ for (const entry of value) if (!elementGuard(entry)) return false;
1097
+ return true;
1098
+ });
1099
+ return outcome.success && outcome.value;
1100
+ };
1101
+ }
1102
+ function mapOf(keyGuard, valueGuard) {
1103
+ return (value) => {
1104
+ if (!isMap(value)) return false;
1105
+ const outcome = attempt(() => {
1106
+ for (const [key, entryValue] of value) if (!keyGuard(key) || !valueGuard(entryValue)) return false;
1107
+ return true;
1108
+ });
1109
+ return outcome.success && outcome.value;
1110
+ };
1111
+ }
1112
+ /**
1113
+ * Build a guard that accepts plain records matching a guard shape.
1114
+ *
1115
+ * @remarks
1116
+ * Three calling modes depending on the `optional` argument:
1117
+ * - **No `optional`** — all shape keys required; extra keys rejected.
1118
+ * - **`optional: K[]`** — the listed keys are optional; all others required.
1119
+ * - **`optional: true`** — every shape key is optional.
1120
+ *
1121
+ * Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by
1122
+ * an inherited prototype member (`toString`, `constructor`, …) counts as absent.
1123
+ * A non-object / `null` / array input returns `false` rather than throwing. The
1124
+ * extra-key check only inspects `Object.keys` (string keys), so an extra
1125
+ * enumerable SYMBOL key is never rejected — intentional, for JSON fidelity, and
1126
+ * matches the compiled guard.
1127
+ *
1128
+ * @example
1129
+ * ```ts
1130
+ * const isUser = recordOf({ name: isString, age: isNumber })
1131
+ * isUser({ name: 'Ada', age: 36 }) // true
1132
+ * isUser({ name: 'Ada' }) // false — age missing
1133
+ *
1134
+ * const isPartial = recordOf({ name: isString, age: isNumber }, ['age'])
1135
+ * isPartial({ name: 'Ada' }) // true
1136
+ * ```
1137
+ */
1138
+ function recordOf(shape, optional) {
1139
+ const allowed = /* @__PURE__ */ new Set();
1140
+ for (const key in shape) if (Object.prototype.hasOwnProperty.call(shape, key)) allowed.add(key);
1141
+ const optionalSet = new Set(optional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : []);
1142
+ return (value) => {
1143
+ if (!isRecord(value)) return false;
1144
+ const outcome = attempt(() => {
1145
+ for (const key of Object.keys(value)) if (!allowed.has(key)) return false;
1146
+ for (const key in shape) {
1147
+ if (!Object.prototype.hasOwnProperty.call(shape, key)) continue;
1148
+ const present = Object.hasOwn(value, key);
1149
+ if (!optionalSet.has(key) && !present) return false;
1150
+ if (present) {
1151
+ const guard = shape[key];
1152
+ if (!guard(value[key])) return false;
1153
+ }
1154
+ }
1155
+ return true;
1156
+ });
1157
+ return outcome.success && outcome.value;
1158
+ };
1159
+ }
1160
+ function iterableOf(elementGuard) {
1161
+ return (value) => {
1162
+ if (!isIterable(value)) return false;
1163
+ const outcome = attempt(() => {
1164
+ for (const entry of value) if (!elementGuard(entry)) return false;
1165
+ return true;
1166
+ });
1167
+ return outcome.success && outcome.value;
1168
+ };
1169
+ }
1170
+ /**
1171
+ * Build a guard that accepts values that are own keys of the provided object.
1172
+ *
1173
+ * @remarks
1174
+ * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys
1175
+ * (`toString`, `constructor`, …) are rejected. An own property that shadows a
1176
+ * prototype name is accepted.
1177
+ *
1178
+ * @example
1179
+ * ```ts
1180
+ * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const
1181
+ * const isColorKey = keyOf(COLORS)
1182
+ * isColorKey('red') // true
1183
+ * isColorKey('purple') // false
1184
+ * isColorKey('toString') // false — inherited, not an own key
1185
+ * ```
1186
+ */
1187
+ function keyOf(value) {
1188
+ return (entry) => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry);
1189
+ }
1190
+ /**
1191
+ * Build a new guard shape by keeping only the listed keys — the structural
1192
+ * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.
1193
+ *
1194
+ * @example
1195
+ * ```ts
1196
+ * const full = { name: isString, age: isNumber, role: isString }
1197
+ * const isName = recordOf(pickOf(full, ['name']))
1198
+ * isName({ name: 'Ada' }) // true
1199
+ * ```
1200
+ */
1201
+ function pickOf(shape, keys) {
1202
+ const result = Object.create(null);
1203
+ for (const key of keys) if (Object.prototype.hasOwnProperty.call(shape, key)) result[key] = shape[key];
1204
+ return result;
1205
+ }
1206
+ /**
1207
+ * Build a new guard shape by removing the listed keys — the structural
1208
+ * equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.
1209
+ *
1210
+ * @example
1211
+ * ```ts
1212
+ * const full = { name: isString, age: isNumber, role: isString }
1213
+ * const isPublic = recordOf(omitOf(full, ['role']))
1214
+ * isPublic({ name: 'Ada', age: 36 }) // true
1215
+ * ```
1216
+ */
1217
+ function omitOf(shape, keys) {
1218
+ const skipped = /* @__PURE__ */ new Set();
1219
+ for (const key of keys) skipped.add(key);
1220
+ const result = Object.create(null);
1221
+ for (const key in shape) {
1222
+ if (!Object.prototype.hasOwnProperty.call(shape, key)) continue;
1223
+ if (!skipped.has(key)) result[key] = shape[key];
1224
+ }
1225
+ return result;
1226
+ }
1227
+ function andOf(left, right) {
1228
+ return (value) => left(value) && right(value);
1229
+ }
1230
+ function orOf(left, right) {
1231
+ return (value) => left(value) || right(value);
1232
+ }
1233
+ /**
1234
+ * Negate a guard or predicate — passes when `guard` returns `false`.
1235
+ *
1236
+ * @remarks
1237
+ * Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use
1238
+ * {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.
1239
+ *
1240
+ * @example
1241
+ * ```ts
1242
+ * const isNotNull = notOf(isNull)
1243
+ * ```
1244
+ */
1245
+ function notOf(guard) {
1246
+ return (value) => !guard(value);
1247
+ }
1248
+ /**
1249
+ * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass
1250
+ * `base` but not `excluded`.
1251
+ *
1252
+ * @example
1253
+ * ```ts
1254
+ * const isNonEmpty = complementOf(isString, isEmptyString)
1255
+ * isNonEmpty('hi') // true
1256
+ * isNonEmpty('') // false
1257
+ * ```
1258
+ */
1259
+ function complementOf(base, excluded) {
1260
+ return (value) => {
1261
+ if (!base(value)) return false;
1262
+ return !excluded(value);
1263
+ };
1264
+ }
1265
+ function unionOf(...guards) {
1266
+ return (value) => guards.some((guard) => guard(value));
1267
+ }
1268
+ function intersectionOf(...guards) {
1269
+ return (value) => guards.every((guard) => guard(value));
1270
+ }
1271
+ function whereOf(base, predicate) {
1272
+ return (value) => {
1273
+ if (!base(value)) return false;
1274
+ const outcome = attempt(() => predicate(value));
1275
+ return outcome.success && outcome.value;
1276
+ };
1277
+ }
1278
+ /**
1279
+ * Defer guard creation until first use by calling `thunk()` on every
1280
+ * invocation.
1281
+ *
1282
+ * @remarks
1283
+ * `thunk` is called on every guard call, not cached — this lets it close over a
1284
+ * binding assigned *after* `lazyOf` is called, the primary use case for
1285
+ * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
1286
+ * it resolves to) is contained and reported as a non-match.
1287
+ *
1288
+ * A recursive guard built this way has no cycle/depth detection: a cyclic or
1289
+ * pathologically deep input is stack-bounded — the overflow is contained and the
1290
+ * guard returns `false` rather than throwing, but it is not validated correctly
1291
+ * past that bound.
1292
+ *
1293
+ * @example
1294
+ * ```ts
1295
+ * type Tree = { value: number; children: Tree[] }
1296
+ * let isTree: Guard<Tree>
1297
+ * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })
1298
+ * ```
1299
+ */
1300
+ function lazyOf(thunk) {
1301
+ return (value) => {
1302
+ const outcome = attempt(() => thunk()(value));
1303
+ return outcome.success && outcome.value;
1304
+ };
1305
+ }
1306
+ function transformOf(base, project, target) {
1307
+ return (value) => {
1308
+ if (!base(value)) return false;
1309
+ const outcome = attempt(() => project(value));
1310
+ return outcome.success && target(outcome.value);
1311
+ };
1312
+ }
1313
+ /**
1314
+ * Build a guard that accepts finite numbers within an inclusive `[min, max]`
1315
+ * range.
1316
+ *
1317
+ * @remarks
1318
+ * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /
1319
+ * `±Infinity` are rejected before any comparison runs. An absent bound never
1320
+ * constrains that side. Reused for a number's own value AND, applied to a
1321
+ * `.length`, for string and array length refinements — the single source of the
1322
+ * bound logic shared by the compiled guard and parser (compilers.ts).
1323
+ *
1324
+ * @example
1325
+ * ```ts
1326
+ * const inRange = boundsOf(1, 5)
1327
+ * inRange(3) // true
1328
+ * inRange(0) // false — below min
1329
+ * inRange(6) // false — above max
1330
+ *
1331
+ * const atLeastTwo = boundsOf(2)
1332
+ * atLeastTwo(2) // true — unbounded above
1333
+ * ```
1334
+ */
1335
+ function boundsOf(min, max) {
1336
+ return whereOf(isFiniteNumber, (value) => (min === void 0 || value >= min) && (max === void 0 || value <= max));
1337
+ }
1338
+ /**
1339
+ * Build a guard that accepts strings matching a regular expression.
1340
+ *
1341
+ * @example
1342
+ * ```ts
1343
+ * const isHex = matchOf(/^[0-9a-f]+$/)
1344
+ * isHex('1a2f') // true
1345
+ * isHex('xyz') // false
1346
+ * ```
1347
+ */
1348
+ function matchOf(pattern) {
1349
+ return whereOf(isString, (value) => pattern.test(value));
1350
+ }
1351
+ /**
1352
+ * Build a guard that accepts strings satisfying optional length and pattern
1353
+ * refinements — `min` / `max` length and a `pattern`.
1354
+ *
1355
+ * @remarks
1356
+ * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
1357
+ * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns
1358
+ * the bare {@link isString} guard (the unconstrained fast path), so an
1359
+ * unrefined string leaf pays no wrapping cost. The single source of the string
1360
+ * refinement shared by the compiled guard and parser (compilers.ts).
1361
+ *
1362
+ * @example
1363
+ * ```ts
1364
+ * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })
1365
+ * isSlug('hello-world') // true
1366
+ * isSlug('') // false — below min
1367
+ * isSlug('Hello') // false — pattern miss
1368
+ *
1369
+ * stringOf() // identical to isString
1370
+ * ```
1371
+ */
1372
+ function stringOf(options) {
1373
+ const min = options?.min;
1374
+ const max = options?.max;
1375
+ const pattern = options?.pattern;
1376
+ if (min === void 0 && max === void 0 && pattern === void 0) return isString;
1377
+ const withinLength = boundsOf(min, max);
1378
+ return whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || pattern.test(value)));
1379
+ }
1380
+ /**
1381
+ * Extend a guard to also allow `null`.
1382
+ *
1383
+ * @example
1384
+ * ```ts
1385
+ * const isNullableString = nullableOf(isString)
1386
+ * isNullableString('hi') // true
1387
+ * isNullableString(null) // true
1388
+ * isNullableString(42) // false
1389
+ * ```
1390
+ */
1391
+ function nullableOf(guard) {
1392
+ return (value) => value === null || guard(value);
1393
+ }
1394
+ /**
1395
+ * Extend a guard to also allow `undefined` — the optional counterpart of
1396
+ * {@link nullableOf}.
1397
+ *
1398
+ * @example
1399
+ * ```ts
1400
+ * const isOptionalString = optionalOf(isString)
1401
+ * isOptionalString('hi') // true
1402
+ * isOptionalString(undefined) // true
1403
+ * isOptionalString(null) // false
1404
+ * ```
1405
+ */
1406
+ function optionalOf(guard) {
1407
+ return (value) => value === void 0 || guard(value);
1408
+ }
1409
+ //#endregion
1410
+ //#region src/core/parsers.ts
1411
+ /**
1412
+ * Parse an unknown value to a string.
1413
+ *
1414
+ * @remarks
1415
+ * A string is returned unchanged; a finite number is coerced to its decimal
1416
+ * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.
1417
+ *
1418
+ * @param value - The value to parse
1419
+ * @returns A string, or `undefined`
1420
+ *
1421
+ * @example
1422
+ * ```ts
1423
+ * parseString('hi') // 'hi'
1424
+ * parseString(42) // '42'
1425
+ * parseString(true) // undefined
1426
+ * ```
1427
+ */
1428
+ function parseString(value) {
1429
+ if (isString(value)) return value;
1430
+ if (isFiniteNumber(value)) return String(value);
1431
+ }
1432
+ /**
1433
+ * Parse an unknown value to a finite number.
1434
+ *
1435
+ * @remarks
1436
+ * A finite number is returned unchanged; a non-blank numeric string is parsed
1437
+ * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every
1438
+ * other type → `undefined`.
1439
+ *
1440
+ * @param value - The value to parse
1441
+ * @returns A finite number, or `undefined`
1442
+ *
1443
+ * @example
1444
+ * ```ts
1445
+ * parseNumber(42) // 42
1446
+ * parseNumber('42') // 42
1447
+ * parseNumber('abc') // undefined
1448
+ * ```
1449
+ */
1450
+ function parseNumber(value) {
1451
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
1452
+ if (isString(value)) {
1453
+ if (value.trim() === "") return void 0;
1454
+ const parsed = Number(value);
1455
+ return Number.isFinite(parsed) ? parsed : void 0;
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Parse an unknown value to a finite integer.
1460
+ *
1461
+ * @remarks
1462
+ * Accepts whatever {@link parseNumber} accepts, then requires the result to have
1463
+ * no fractional part. `3.14` / `'3.14'` → `undefined`.
1464
+ *
1465
+ * @param value - The value to parse
1466
+ * @returns A finite integer, or `undefined`
1467
+ *
1468
+ * @example
1469
+ * ```ts
1470
+ * parseInteger(42) // 42
1471
+ * parseInteger(3.14) // undefined
1472
+ * ```
1473
+ */
1474
+ function parseInteger(value) {
1475
+ const parsed = parseNumber(value);
1476
+ if (parsed === void 0) return void 0;
1477
+ return Number.isInteger(parsed) ? parsed : void 0;
1478
+ }
1479
+ /**
1480
+ * Parse an unknown value to a boolean.
1481
+ *
1482
+ * @remarks
1483
+ * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /
1484
+ * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything
1485
+ * else → `undefined`.
1486
+ *
1487
+ * @param value - The value to parse
1488
+ * @returns A boolean, or `undefined`
1489
+ *
1490
+ * @example
1491
+ * ```ts
1492
+ * parseBoolean(true) // true
1493
+ * parseBoolean('1') // true
1494
+ * parseBoolean('nope') // undefined
1495
+ * ```
1496
+ */
1497
+ function parseBoolean(value) {
1498
+ if (typeof value === "boolean") return value;
1499
+ if (value === "true" || value === "1" || value === 1) return true;
1500
+ if (value === "false" || value === "0" || value === 0) return false;
1501
+ }
1502
+ /**
1503
+ * Parse an unknown value to `null`.
1504
+ *
1505
+ * @remarks
1506
+ * A successful parse returns `null` itself — distinct from the `undefined`
1507
+ * failure sentinel every other parser in this file uses. Only `null` passes;
1508
+ * every other value (including `undefined`) → `undefined`.
1509
+ *
1510
+ * @param value - The value to parse
1511
+ * @returns `null` on a successful parse, or `undefined`
1512
+ *
1513
+ * @example
1514
+ * ```ts
1515
+ * parseNull(null) // null
1516
+ * parseNull(undefined) // undefined
1517
+ * ```
1518
+ */
1519
+ function parseNull(value) {
1520
+ return isNull(value) ? value : void 0;
1521
+ }
1522
+ /**
1523
+ * Parse an unknown value to a plain record — the input reference, never cloned.
1524
+ *
1525
+ * @param value - The value to parse
1526
+ * @returns The record, or `undefined`
1527
+ */
1528
+ function parseRecord(value) {
1529
+ return isRecord(value) ? value : void 0;
1530
+ }
1531
+ /**
1532
+ * Parse an unknown value to an array — the input reference, never cloned —
1533
+ * optionally guarding every element.
1534
+ *
1535
+ * @remarks
1536
+ * Without a `guard`, element types are NOT verified; let `T` default to
1537
+ * `unknown` rather than asserting a specific element type.
1538
+ *
1539
+ * @param value - The value to parse
1540
+ * @param guard - Optional element guard
1541
+ * @returns The array, or `undefined`
1542
+ *
1543
+ * @example
1544
+ * ```ts
1545
+ * parseArray([1, 2]) // [1, 2]
1546
+ * parseArray([1, 'x'], isNumber) // undefined
1547
+ * ```
1548
+ */
1549
+ function parseArray(value, guard) {
1550
+ if (!isArray(value)) return void 0;
1551
+ if (guard !== void 0 && !value.every(guard)) return void 0;
1552
+ return value;
1553
+ }
1554
+ /**
1555
+ * Parse an unknown value to a cycle-safe JSON value — the input reference,
1556
+ * never cloned.
1557
+ *
1558
+ * @remarks
1559
+ * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it
1560
+ * walks the entire tree via {@link isJSONValue} rather than checking only the
1561
+ * top-level shape. That walk is cycle-safe and total (never throws) because
1562
+ * `isJSONValue` runs its own probe inside a guard, so an adversarial
1563
+ * structure (a cycle, a hostile getter) yields `undefined` instead of hanging
1564
+ * or throwing.
1565
+ *
1566
+ * @param value - The value to parse
1567
+ * @returns The value, or `undefined` when it is not a valid JSON value
1568
+ *
1569
+ * @example
1570
+ * ```ts
1571
+ * parseJSONValue({ a: 1 }) // { a: 1 }
1572
+ * parseJSONValue(Number.NaN) // undefined
1573
+ * ```
1574
+ */
1575
+ function parseJSONValue(value) {
1576
+ return isJSONValue(value) ? value : void 0;
1577
+ }
1578
+ /**
1579
+ * Parse an unknown value as one of the allowed literal primitives.
1580
+ *
1581
+ * @remarks
1582
+ * Pairs with {@link literalOf} — both match by `Object.is`, so the
1583
+ * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
1584
+ * (string, number, or boolean), not only strings. Matching is identity, never
1585
+ * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
1586
+ *
1587
+ * @param value - The value to parse
1588
+ * @param allowed - The permitted literal values
1589
+ * @returns The matched literal (by identity), or `undefined`
1590
+ *
1591
+ * @example
1592
+ * ```ts
1593
+ * parseEnum('b', ['a', 'b', 'c']) // 'b'
1594
+ * parseEnum('z', ['a', 'b', 'c']) // undefined
1595
+ * ```
1596
+ */
1597
+ function parseEnum(value, allowed) {
1598
+ for (const option of allowed) if (Object.is(value, option)) return option;
1599
+ }
1600
+ /**
1601
+ * Read and parse a string field from a record by key or nested key path.
1602
+ *
1603
+ * @param record - The source record
1604
+ * @param path - A property key, or a key path descending into nested objects
1605
+ * @returns A string, or `undefined`
1606
+ */
1607
+ function parseStringField(record, path) {
1608
+ return parseString(resolveField(record, path));
1609
+ }
1610
+ /**
1611
+ * Read and parse a finite-number field from a record by key or nested key path.
1612
+ *
1613
+ * @param record - The source record
1614
+ * @param path - A property key, or a key path descending into nested objects
1615
+ * @returns A finite number, or `undefined`
1616
+ *
1617
+ * @example
1618
+ * ```ts
1619
+ * parseNumberField({ age: '42' }, 'age') // 42
1620
+ * parseNumberField({}, 'age') // undefined
1621
+ * ```
1622
+ */
1623
+ function parseNumberField(record, path) {
1624
+ return parseNumber(resolveField(record, path));
1625
+ }
1626
+ /**
1627
+ * Read and parse a finite-integer field from a record by key or nested key path.
1628
+ *
1629
+ * @param record - The source record
1630
+ * @param path - A property key, or a key path descending into nested objects
1631
+ * @returns A finite integer, or `undefined`
1632
+ */
1633
+ function parseIntegerField(record, path) {
1634
+ return parseInteger(resolveField(record, path));
1635
+ }
1636
+ /**
1637
+ * Read and parse a boolean field from a record by key or nested key path.
1638
+ *
1639
+ * @param record - The source record
1640
+ * @param path - A property key, or a key path descending into nested objects
1641
+ * @returns A boolean, or `undefined`
1642
+ *
1643
+ * @example
1644
+ * ```ts
1645
+ * parseBooleanField({ on: 'true' }, 'on') // true
1646
+ * parseBooleanField({}, 'on') // undefined
1647
+ * ```
1648
+ */
1649
+ function parseBooleanField(record, path) {
1650
+ return parseBoolean(resolveField(record, path));
1651
+ }
1652
+ /**
1653
+ * Read and parse a `null` field from a record by key or nested key path.
1654
+ *
1655
+ * @remarks
1656
+ * A successful parse returns `null` itself — distinct from the `undefined`
1657
+ * failure sentinel, which also covers a missing field.
1658
+ *
1659
+ * @param record - The source record
1660
+ * @param path - A property key, or a key path descending into nested objects
1661
+ * @returns `null` on a successful parse, or `undefined`
1662
+ *
1663
+ * @example
1664
+ * ```ts
1665
+ * parseNullField({ value: null }, 'value') // null
1666
+ * parseNullField({}, 'value') // undefined
1667
+ * ```
1668
+ */
1669
+ function parseNullField(record, path) {
1670
+ return parseNull(resolveField(record, path));
1671
+ }
1672
+ /**
1673
+ * Read and parse a nested record field from a record by key or nested key path.
1674
+ *
1675
+ * @param record - The source record
1676
+ * @param path - A property key, or a key path descending into nested objects
1677
+ * @returns A plain record, or `undefined`
1678
+ */
1679
+ function parseRecordField(record, path) {
1680
+ return parseRecord(resolveField(record, path));
1681
+ }
1682
+ /**
1683
+ * Read and parse an array field from a record by key or nested key path,
1684
+ * optionally guarding elements.
1685
+ *
1686
+ * @param record - The source record
1687
+ * @param path - A property key, or a key path descending into nested objects
1688
+ * @param guard - Optional element guard
1689
+ * @returns An array, or `undefined`
1690
+ *
1691
+ * @example
1692
+ * ```ts
1693
+ * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]
1694
+ * parseArrayField({}, 'tags') // undefined
1695
+ * ```
1696
+ */
1697
+ function parseArrayField(record, path, guard) {
1698
+ return parseArray(resolveField(record, path), guard);
1699
+ }
1700
+ /**
1701
+ * Read and parse an enum field from a record by key or nested key path.
1702
+ *
1703
+ * @param record - The source record
1704
+ * @param path - A property key, or a key path descending into nested objects
1705
+ * @param allowed - The permitted literal values
1706
+ * @returns The matched literal, or `undefined`
1707
+ */
1708
+ function parseEnumField(record, path, allowed) {
1709
+ return parseEnum(resolveField(record, path), allowed);
1710
+ }
1711
+ /**
1712
+ * Read and parse a JSON-value field from a record by key or nested key path.
1713
+ *
1714
+ * @remarks
1715
+ * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that
1716
+ * function's remarks for why this differs from the shallow
1717
+ * {@link parseRecordField} / {@link parseArrayField}.
1718
+ *
1719
+ * @param record - The source record
1720
+ * @param path - A property key, or a key path descending into nested objects
1721
+ * @returns The value, or `undefined`
1722
+ *
1723
+ * @example
1724
+ * ```ts
1725
+ * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }
1726
+ * parseJSONValueField({}, 'data') // undefined
1727
+ * ```
1728
+ */
1729
+ function parseJSONValueField(record, path) {
1730
+ return parseJSONValue(resolveField(record, path));
1731
+ }
1732
+ /**
1733
+ * Parse a JSON string, returning `undefined` instead of throwing.
1734
+ *
1735
+ * @remarks
1736
+ * The safe boundary for untrusted JSON text: a malformed string yields
1737
+ * `undefined`, never an exception. Returns `unknown` — a successful parse proves
1738
+ * nothing about shape, so narrow the result with a guard (or use
1739
+ * {@link parseJSONAs}). A large document is not walked here; parsing is shallow
1740
+ * and lazy validation is the caller's to compose.
1741
+ *
1742
+ * @param value - The JSON string to parse
1743
+ * @returns The parsed value, or `undefined` when `value` is not valid JSON
1744
+ */
1745
+ function parseJSON(value) {
1746
+ try {
1747
+ return JSON.parse(value);
1748
+ } catch {
1749
+ return;
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Parse a JSON string and validate the result against a guard.
1754
+ *
1755
+ * @remarks
1756
+ * The lazy, safe path from an untrusted string to a typed `T`: parse, then check
1757
+ * the parsed value with the guard you bring — typically one composed from the
1758
+ * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is
1759
+ * validated, so a large document is never walked in full unless the guard does.
1760
+ *
1761
+ * @param value - The JSON string to parse
1762
+ * @param guard - The guard for the expected shape
1763
+ * @returns The parsed value when it satisfies `guard`, otherwise `undefined`
1764
+ *
1765
+ * @example
1766
+ * ```ts
1767
+ * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })
1768
+ * parseJSONAs('{"host":"localhost","tags":["a"]}', isConfig) // { host: 'localhost', tags: ['a'] }
1769
+ * parseJSONAs('{"host":"localhost"}', isConfig) // undefined — guard fails
1770
+ * parseJSONAs('not json', isConfig) // undefined — never throws
1771
+ * ```
1772
+ */
1773
+ function parseJSONAs(value, guard) {
1774
+ const parsed = parseJSON(value);
1775
+ if (parsed === void 0) return void 0;
1776
+ return guard(parsed) ? parsed : void 0;
1777
+ }
1778
+ //#endregion
1779
+ //#region src/core/compilers.ts
1780
+ /**
1781
+ * Validate that a {@link ContractShape} tree is well-formed — a pure recursive
1782
+ * prepass run before compilation.
1783
+ *
1784
+ * @remarks
1785
+ * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
1786
+ * throws a plain `Error` immediately rather than surfacing as a silently-wrong
1787
+ * guard, parser, schema, or generator later. Checks, recursively:
1788
+ *
1789
+ * - An {@link OptionalShape} is only legal as a direct object-property value —
1790
+ * `optionalShape` wrapping an array item, a union variant, another
1791
+ * optional/nullable's inner shape, `additionalProperties`, or the top-level
1792
+ * shape all throw. An object property IS the one legal placement: its value
1793
+ * is unwrapped to `.inner` before recursing, so `.inner` itself is validated
1794
+ * as a normal (non-optional-wrapping) shape.
1795
+ * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}
1796
+ * needs at least one value and rejects non-finite (`NaN` / `Infinity` /
1797
+ * `-Infinity`) number values.
1798
+ * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
1799
+ * needs `min <= max` when both are set.
1800
+ * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
1801
+ * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
1802
+ * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
1803
+ * continues into array items, object properties (and `additionalProperties`
1804
+ * when it is a shape), union variants, and optional/nullable inner shapes.
1805
+ *
1806
+ * @param shape - The shape to validate
1807
+ * @throws {Error} When the shape is malformed
1808
+ *
1809
+ * @example
1810
+ * ```ts
1811
+ * validateShape(stringShape({ min: 1, max: 10 })) // does not throw
1812
+ * validateShape(stringShape({ min: 10, max: 1 })) // throws
1813
+ * ```
1814
+ */
1815
+ function validateShape(shape) {
1816
+ switch (shape.type) {
1817
+ case "string":
1818
+ if (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error("validateShape: a string shape has min greater than max");
1819
+ return;
1820
+ case "number":
1821
+ if (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error("validateShape: a number shape has min greater than max");
1822
+ if (shape.integer === true) {
1823
+ if (Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY) > Math.floor(shape.max ?? Number.POSITIVE_INFINITY)) throw new Error("validateShape: an integer number shape has an empty integer range");
1824
+ }
1825
+ return;
1826
+ case "boolean":
1827
+ case "null":
1828
+ case "json":
1829
+ case "raw": return;
1830
+ case "literal":
1831
+ if (shape.values.length === 0) throw new Error("validateShape: a literal shape needs at least one value");
1832
+ for (const value of shape.values) if (typeof value === "number" && !Number.isFinite(value)) throw new Error("validateShape: a literal shape may not contain non-finite number values");
1833
+ return;
1834
+ case "array":
1835
+ if (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error("validateShape: an array shape has min greater than max");
1836
+ validateShape(shape.items);
1837
+ return;
1838
+ case "object": {
1839
+ for (const key of Object.keys(shape.properties)) {
1840
+ const child = shape.properties[key];
1841
+ if (child === void 0) continue;
1842
+ validateShape(child.type === "optional" ? child.inner : child);
1843
+ }
1844
+ const extra = shape.additionalProperties;
1845
+ if (extra !== void 0 && extra !== true && extra !== false) validateShape(extra);
1846
+ return;
1847
+ }
1848
+ case "union":
1849
+ if (shape.variants.length === 0) throw new Error("validateShape: a union shape needs at least one variant");
1850
+ for (const variant of shape.variants) validateShape(variant);
1851
+ return;
1852
+ case "optional": throw new Error("validateShape: an optional shape may only appear as a direct object-property value");
1853
+ case "nullable":
1854
+ validateShape(shape.inner);
1855
+ return;
1856
+ }
1857
+ }
1858
+ /**
1859
+ * Compile a {@link ContractShape} into a JSON Schema document.
1860
+ *
1861
+ * @remarks
1862
+ * Object shapes emit `additionalProperties: false` (unless opened) and list only
1863
+ * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
1864
+ * 'null' }`. Emission only — it never inspects a runtime value.
1865
+ *
1866
+ * @param shape - The shape to compile
1867
+ * @returns The emitted JSON Schema
1868
+ *
1869
+ * @example
1870
+ * ```ts
1871
+ * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }
1872
+ * ```
1873
+ */
1874
+ function compileSchema(shape) {
1875
+ switch (shape.type) {
1876
+ case "string": return {
1877
+ type: "string",
1878
+ ...shape.min !== void 0 ? { minLength: shape.min } : {},
1879
+ ...shape.max !== void 0 ? { maxLength: shape.max } : {},
1880
+ ...shape.pattern !== void 0 ? { pattern: shape.pattern.source } : {},
1881
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1882
+ };
1883
+ case "number": return {
1884
+ type: shape.integer === true ? "integer" : "number",
1885
+ ...shape.min !== void 0 ? { minimum: shape.min } : {},
1886
+ ...shape.max !== void 0 ? { maximum: shape.max } : {},
1887
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1888
+ };
1889
+ case "boolean": return {
1890
+ type: "boolean",
1891
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1892
+ };
1893
+ case "null": return {
1894
+ type: "null",
1895
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1896
+ };
1897
+ case "json": return { ...shape.description !== void 0 ? { description: shape.description } : {} };
1898
+ case "literal": return {
1899
+ enum: [...shape.values],
1900
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1901
+ };
1902
+ case "array": return {
1903
+ type: "array",
1904
+ items: compileSchema(shape.items),
1905
+ ...shape.min !== void 0 ? { minItems: shape.min } : {},
1906
+ ...shape.max !== void 0 ? { maxItems: shape.max } : {},
1907
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1908
+ };
1909
+ case "object": {
1910
+ const properties = {};
1911
+ const required = [];
1912
+ for (const key of Object.keys(shape.properties)) {
1913
+ const child = shape.properties[key];
1914
+ if (child === void 0) continue;
1915
+ properties[key] = compileSchema(child);
1916
+ if (child.type !== "optional") required.push(key);
1917
+ }
1918
+ const extra = shape.additionalProperties;
1919
+ const additionalProperties = extra === true ? true : extra !== void 0 && extra !== false ? compileSchema(extra) : false;
1920
+ return {
1921
+ type: "object",
1922
+ ...Object.keys(properties).length > 0 ? { properties } : {},
1923
+ ...required.length > 0 ? { required } : {},
1924
+ additionalProperties,
1925
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1926
+ };
1927
+ }
1928
+ case "union": return {
1929
+ ...shape.mode === "oneOf" ? { oneOf: shape.variants.map((variant) => compileSchema(variant)) } : { anyOf: shape.variants.map((variant) => compileSchema(variant)) },
1930
+ ...shape.description !== void 0 ? { description: shape.description } : {}
1931
+ };
1932
+ case "optional": return compileSchema(shape.inner);
1933
+ case "nullable": return { anyOf: [compileSchema(shape.inner), { type: "null" }] };
1934
+ case "raw": return shape.schema;
1935
+ }
1936
+ }
1937
+ /**
1938
+ * Compile a {@link ContractShape} into a runtime type guard.
1939
+ *
1940
+ * @remarks
1941
+ * Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,
1942
+ * `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,
1943
+ * and `whereOf` for constraint refinement. Like every guard it is total — it
1944
+ * never throws (AGENTS §14).
1945
+ *
1946
+ * @param shape - The shape to compile
1947
+ * @returns A guard narrowing to the shape's inferred type
1948
+ *
1949
+ * @example
1950
+ * ```ts
1951
+ * const isUser = compileGuard(objectShape({ name: stringShape() }))
1952
+ * isUser({ name: 'Ada' }) // true
1953
+ * ```
1954
+ */
1955
+ function compileGuard(shape) {
1956
+ switch (shape.type) {
1957
+ case "string": return stringOf({
1958
+ min: shape.min,
1959
+ max: shape.max,
1960
+ pattern: shape.pattern
1961
+ });
1962
+ case "number": {
1963
+ const base = shape.integer === true ? isInteger : isFiniteNumber;
1964
+ if (shape.min === void 0 && shape.max === void 0) return base;
1965
+ return shape.integer === true ? intersectionOf(isInteger, boundsOf(shape.min, shape.max)) : boundsOf(shape.min, shape.max);
1966
+ }
1967
+ case "boolean": return isBoolean;
1968
+ case "null": return isNull;
1969
+ case "json": return isJSONValue;
1970
+ case "literal": return literalOf(...shape.values);
1971
+ case "array": {
1972
+ const base = arrayOf(compileGuard(shape.items));
1973
+ if (shape.min === void 0 && shape.max === void 0) return base;
1974
+ const withinLength = boundsOf(shape.min, shape.max);
1975
+ return whereOf(base, (value) => withinLength(value.length));
1976
+ }
1977
+ case "object": {
1978
+ const map = Object.create(null);
1979
+ const optionalKeys = [];
1980
+ for (const key of Object.keys(shape.properties)) {
1981
+ const child = shape.properties[key];
1982
+ if (child === void 0) continue;
1983
+ if (child.type === "optional") {
1984
+ map[key] = compileGuard(child.inner);
1985
+ optionalKeys.push(key);
1986
+ } else map[key] = compileGuard(child);
1987
+ }
1988
+ const extra = shape.additionalProperties;
1989
+ if (extra === void 0 || extra === false) return optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map);
1990
+ const additional = extra === true ? void 0 : compileGuard(extra);
1991
+ const required = Object.keys(map).filter((key) => !optionalKeys.includes(key));
1992
+ return (value) => {
1993
+ if (!isRecord(value)) return false;
1994
+ for (const key of required) if (!Object.hasOwn(value, key)) return false;
1995
+ const outcome = attempt(() => {
1996
+ for (const key of Object.keys(value)) {
1997
+ const guard = Object.hasOwn(map, key) ? map[key] : void 0;
1998
+ if (guard !== void 0) {
1999
+ if (!guard(value[key])) return false;
2000
+ } else if (additional !== void 0 && !additional(value[key])) return false;
2001
+ }
2002
+ return true;
2003
+ });
2004
+ return outcome.success && outcome.value;
2005
+ };
2006
+ }
2007
+ case "union": return unionOf(...shape.variants.map((variant) => compileGuard(variant)));
2008
+ case "optional": return orOf(isUndefined, compileGuard(shape.inner));
2009
+ case "nullable": return nullableOf(compileGuard(shape.inner));
2010
+ case "raw": return (_value) => true;
2011
+ }
2012
+ }
2013
+ /**
2014
+ * Compile a {@link ContractShape} into an input parser.
2015
+ *
2016
+ * @remarks
2017
+ * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /
2018
+ * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a
2019
+ * whole on any required-field failure; a union returns a guard-valid value
2020
+ * unchanged, otherwise the first variant that both parses and guards wins.
2021
+ *
2022
+ * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same
2023
+ * combinators `compileGuard` uses — `stringOf` for a string's length/pattern and
2024
+ * `boundsOf` for a number's value and an array's length — so a value that coerces
2025
+ * but violates a bound parses to `undefined`. The result is full parse↔guard
2026
+ * soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's
2027
+ * `is`, refinements included.
2028
+ *
2029
+ * @param shape - The shape to compile
2030
+ * @returns A parser yielding the shape's inferred type or `undefined`
2031
+ *
2032
+ * @example
2033
+ * ```ts
2034
+ * const parseUser = compileParser(objectShape({ name: stringShape() }))
2035
+ * parseUser({ name: 'Ada' }) // { name: 'Ada' }
2036
+ * ```
2037
+ */
2038
+ function compileParser(shape) {
2039
+ switch (shape.type) {
2040
+ case "string": {
2041
+ if (shape.min === void 0 && shape.max === void 0 && shape.pattern === void 0) return parseString;
2042
+ const guard = stringOf({
2043
+ min: shape.min,
2044
+ max: shape.max,
2045
+ pattern: shape.pattern
2046
+ });
2047
+ return (value) => {
2048
+ const parsed = parseString(value);
2049
+ return parsed !== void 0 && guard(parsed) ? parsed : void 0;
2050
+ };
2051
+ }
2052
+ case "number": {
2053
+ const base = shape.integer === true ? parseInteger : parseNumber;
2054
+ if (shape.min === void 0 && shape.max === void 0) return base;
2055
+ const within = boundsOf(shape.min, shape.max);
2056
+ return (value) => {
2057
+ const parsed = base(value);
2058
+ return parsed !== void 0 && within(parsed) ? parsed : void 0;
2059
+ };
2060
+ }
2061
+ case "boolean": return parseBoolean;
2062
+ case "null": return (value) => value === null ? null : void 0;
2063
+ case "json": return (value) => isJSONValue(value) ? value : void 0;
2064
+ case "literal": {
2065
+ const allowed = new Set(shape.values);
2066
+ return (value) => {
2067
+ if (allowed.has(value)) return value;
2068
+ if (isString(value)) {
2069
+ const trimmed = value.trim();
2070
+ if (allowed.has(trimmed)) return trimmed;
2071
+ }
2072
+ };
2073
+ }
2074
+ case "array": {
2075
+ const item = compileParser(shape.items);
2076
+ const unbounded = shape.min === void 0 && shape.max === void 0;
2077
+ const withinLength = boundsOf(shape.min, shape.max);
2078
+ return (value) => {
2079
+ if (!isArray(value)) return void 0;
2080
+ const result = [];
2081
+ for (const entry of value) {
2082
+ const parsed = item(entry);
2083
+ if (parsed === void 0) return void 0;
2084
+ result.push(parsed);
2085
+ }
2086
+ return unbounded || withinLength(result.length) ? result : void 0;
2087
+ };
2088
+ }
2089
+ case "object": {
2090
+ const entries = [];
2091
+ for (const key of Object.keys(shape.properties)) {
2092
+ const child = shape.properties[key];
2093
+ if (child === void 0) continue;
2094
+ const optional = child.type === "optional";
2095
+ entries.push({
2096
+ key,
2097
+ parse: compileParser(optional ? child.inner : child),
2098
+ optional
2099
+ });
2100
+ }
2101
+ const known = new Set(entries.map((entry) => entry.key));
2102
+ const extra = shape.additionalProperties;
2103
+ const additional = extra === void 0 || extra === false || extra === true ? void 0 : compileParser(extra);
2104
+ const open = extra === true || additional !== void 0;
2105
+ return (value) => {
2106
+ const record = parseRecord(value);
2107
+ if (record === void 0) return void 0;
2108
+ const outcome = attempt(() => {
2109
+ const result = Object.create(null);
2110
+ for (const entry of entries) {
2111
+ const raw = record[entry.key];
2112
+ if (raw === void 0) {
2113
+ if (entry.optional) continue;
2114
+ return;
2115
+ }
2116
+ const parsed = entry.parse(raw);
2117
+ if (parsed === void 0) return void 0;
2118
+ result[entry.key] = parsed;
2119
+ }
2120
+ if (open) for (const key of Object.keys(record)) {
2121
+ if (known.has(key)) continue;
2122
+ if (additional === void 0) result[key] = record[key];
2123
+ else {
2124
+ const parsed = additional(record[key]);
2125
+ if (parsed === void 0) return void 0;
2126
+ result[key] = parsed;
2127
+ }
2128
+ }
2129
+ return result;
2130
+ });
2131
+ return outcome.success ? outcome.value : void 0;
2132
+ };
2133
+ }
2134
+ case "union": {
2135
+ const variants = shape.variants.map((variant) => ({
2136
+ parse: compileParser(variant),
2137
+ guard: compileGuard(variant)
2138
+ }));
2139
+ return (value) => {
2140
+ for (const variant of variants) if (variant.guard(value)) return value;
2141
+ for (const variant of variants) {
2142
+ const parsed = variant.parse(value);
2143
+ if (parsed !== void 0 && variant.guard(parsed)) return parsed;
2144
+ }
2145
+ };
2146
+ }
2147
+ case "optional": {
2148
+ const inner = compileParser(shape.inner);
2149
+ return (value) => value === void 0 ? void 0 : inner(value);
2150
+ }
2151
+ case "nullable": {
2152
+ const inner = compileParser(shape.inner);
2153
+ return (value) => value === null ? null : inner(value);
2154
+ }
2155
+ case "raw": return (value) => value;
2156
+ }
2157
+ }
2158
+ /**
2159
+ * Compile a {@link ContractShape} into a deterministic seed value.
2160
+ *
2161
+ * @remarks
2162
+ * The same shape and the same `random` source always produce the same value, so
2163
+ * seed data is reproducible. Defaults to a {@link seededRandom} source seeded
2164
+ * from the wall clock when none is supplied. Throws on a degenerate empty
2165
+ * `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose
2166
+ * generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded
2167
+ * schema is arbitrary and cannot be auto-generated) — a programmer error that
2168
+ * cannot generate a value (AGENTS §12). `createContract` runs
2169
+ * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /
2170
+ * bounded shape is normally caught there; these throws remain here as defense
2171
+ * for standalone `compileGenerator` use.
2172
+ *
2173
+ * @param shape - The shape to generate from
2174
+ * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)
2175
+ * @returns A value matching the shape
2176
+ *
2177
+ * @example
2178
+ * ```ts
2179
+ * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)
2180
+ * ```
2181
+ */
2182
+ function compileGenerator(shape, random = seededRandom(Date.now())) {
2183
+ switch (shape.type) {
2184
+ case "string": {
2185
+ const min = shape.min ?? 0;
2186
+ const max = shape.max ?? Math.max(min, 12);
2187
+ const length = Math.max(min, Math.min(max, 8));
2188
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
2189
+ let value = "";
2190
+ for (let index = 0; index < length; index += 1) value += alphabet[Math.floor(random() * 36)];
2191
+ if (shape.pattern !== void 0 && !shape.pattern.test(value)) throw new Error("compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way");
2192
+ return value;
2193
+ }
2194
+ case "number": {
2195
+ const min = shape.min ?? 0;
2196
+ const max = shape.max ?? 100;
2197
+ if (shape.integer === true) {
2198
+ const lo = Math.ceil(min);
2199
+ const hi = Math.floor(max);
2200
+ return Math.floor(random() * (hi - lo + 1)) + lo;
2201
+ }
2202
+ return random() * (max - min) + min;
2203
+ }
2204
+ case "boolean": return random() >= .5;
2205
+ case "null": return null;
2206
+ case "json": {
2207
+ const pick = Math.floor(random() * 5);
2208
+ if (pick === 0) return null;
2209
+ if (pick === 1) return random() >= .5;
2210
+ if (pick === 2) return Math.floor(random() * 1e3);
2211
+ if (pick === 3) {
2212
+ const alphabet = "abcdefghijklmnopqrstuvwxyz";
2213
+ let value = "";
2214
+ for (let index = 0; index < 6; index += 1) value += alphabet[Math.floor(random() * 26)];
2215
+ return value;
2216
+ }
2217
+ return { value: Math.floor(random() * 1e3) };
2218
+ }
2219
+ case "literal":
2220
+ if (shape.values.length === 0) throw new Error("compileGenerator: a literal shape needs at least one value");
2221
+ return shape.values[Math.floor(random() * shape.values.length)];
2222
+ case "array": {
2223
+ const lo = shape.min ?? Math.min(1, shape.max ?? 1);
2224
+ const hi = shape.max ?? Math.max(lo, 3);
2225
+ const length = Math.floor(random() * (hi - lo + 1)) + lo;
2226
+ const result = [];
2227
+ for (let index = 0; index < length; index += 1) result.push(compileGenerator(shape.items, random));
2228
+ return result;
2229
+ }
2230
+ case "object": {
2231
+ const result = {};
2232
+ for (const key of Object.keys(shape.properties)) {
2233
+ const child = shape.properties[key];
2234
+ if (child === void 0) continue;
2235
+ if (child.type === "optional" && random() < .3) continue;
2236
+ result[key] = compileGenerator(child, random);
2237
+ }
2238
+ const extra = shape.additionalProperties;
2239
+ if (extra !== void 0 && extra !== true && extra !== false) {
2240
+ const count = 1 + Math.floor(random() * 2);
2241
+ for (let index = 0; index < count; index += 1) {
2242
+ const key = `key${index}`;
2243
+ if (Object.hasOwn(result, key)) continue;
2244
+ result[key] = compileGenerator(extra, random);
2245
+ }
2246
+ }
2247
+ return result;
2248
+ }
2249
+ case "union":
2250
+ if (shape.variants.length === 0) throw new Error("compileGenerator: a union shape needs at least one variant");
2251
+ return compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random);
2252
+ case "optional": return compileGenerator(shape.inner, random);
2253
+ case "nullable": return random() < .2 ? null : compileGenerator(shape.inner, random);
2254
+ case "raw": throw new Error("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way");
2255
+ }
2256
+ }
2257
+ function createContract(shape) {
2258
+ validateShape(shape);
2259
+ const schema = compileSchema(shape);
2260
+ const guard = compileGuard(shape);
2261
+ const parser = compileParser(shape);
2262
+ return {
2263
+ schema,
2264
+ is: guard,
2265
+ parse(value) {
2266
+ return parser(value);
2267
+ },
2268
+ generate(random) {
2269
+ return compileGenerator(shape, random);
2270
+ }
2271
+ };
2272
+ }
2273
+ //#endregion
2274
+ //#region src/core/shapers.ts
2275
+ /**
2276
+ * Build a string {@link StringShape}.
2277
+ *
2278
+ * @param options - Optional length (`min` / `max`), `pattern`, and `description`
2279
+ * @returns A string shape
2280
+ *
2281
+ * @example
2282
+ * ```ts
2283
+ * const name = stringShape({ min: 1, max: 80, description: 'Display name' })
2284
+ * ```
2285
+ */
2286
+ function stringShape(options) {
2287
+ return {
2288
+ type: "string",
2289
+ min: options?.min,
2290
+ max: options?.max,
2291
+ pattern: options?.pattern,
2292
+ description: options?.description
2293
+ };
2294
+ }
2295
+ /**
2296
+ * Build a numeric {@link NumberShape}.
2297
+ *
2298
+ * @param options - Optional bounds (`min` / `max`), `integer`, and `description`
2299
+ * @returns A number shape
2300
+ *
2301
+ * @example
2302
+ * ```ts
2303
+ * const age = numberShape({ min: 0, max: 120 })
2304
+ * ```
2305
+ */
2306
+ function numberShape(options) {
2307
+ return {
2308
+ type: "number",
2309
+ min: options?.min,
2310
+ max: options?.max,
2311
+ integer: options?.integer,
2312
+ description: options?.description
2313
+ };
2314
+ }
2315
+ /**
2316
+ * Build an integer {@link NumberShape} — forces `integer: true`.
2317
+ *
2318
+ * @remarks
2319
+ * The emitted JSON Schema uses `"type": "integer"` and the guard rejects
2320
+ * fractional numbers.
2321
+ *
2322
+ * @param options - Optional bounds and `description` (no `integer` key)
2323
+ * @returns An integer number shape
2324
+ */
2325
+ function integerShape(options) {
2326
+ return {
2327
+ type: "number",
2328
+ integer: true,
2329
+ min: options?.min,
2330
+ max: options?.max,
2331
+ description: options?.description
2332
+ };
2333
+ }
2334
+ /**
2335
+ * Build a {@link BooleanShape}.
2336
+ *
2337
+ * @param options - Optional `description`
2338
+ * @returns A boolean shape
2339
+ *
2340
+ * @example
2341
+ * ```ts
2342
+ * const active = booleanShape({ description: 'Whether the record is active' })
2343
+ * ```
2344
+ */
2345
+ function booleanShape(options) {
2346
+ return {
2347
+ type: "boolean",
2348
+ description: options?.description
2349
+ };
2350
+ }
2351
+ /**
2352
+ * Build a {@link NullShape}.
2353
+ *
2354
+ * @param options - Optional `description`
2355
+ * @returns A null shape
2356
+ *
2357
+ * @example
2358
+ * ```ts
2359
+ * const empty = nullShape()
2360
+ * ```
2361
+ */
2362
+ function nullShape(options) {
2363
+ return {
2364
+ type: "null",
2365
+ description: options?.description
2366
+ };
2367
+ }
2368
+ /**
2369
+ * Build a literal shape from a fixed set of primitive values.
2370
+ *
2371
+ * @param values - The permitted literals
2372
+ * @param options - Optional `description`
2373
+ * @returns A literal shape whose `Infer` is the union of `values`
2374
+ *
2375
+ * @example
2376
+ * ```ts
2377
+ * const role = literalShape(['admin', 'member', 'guest'])
2378
+ * // Infer<typeof role> = 'admin' | 'member' | 'guest'
2379
+ *
2380
+ * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
2381
+ * ```
2382
+ */
2383
+ function literalShape(values, options) {
2384
+ return {
2385
+ type: "literal",
2386
+ values,
2387
+ description: options?.description
2388
+ };
2389
+ }
2390
+ /**
2391
+ * Build an {@link ArrayShape} from an element shape.
2392
+ *
2393
+ * @param items - The element shape
2394
+ * @param options - Optional length bounds and `description`
2395
+ * @returns An array shape
2396
+ *
2397
+ * @example
2398
+ * ```ts
2399
+ * const tags = arrayShape(stringShape(), { max: 10 })
2400
+ * ```
2401
+ */
2402
+ function arrayShape(items, options) {
2403
+ return {
2404
+ type: "array",
2405
+ items,
2406
+ min: options?.min,
2407
+ max: options?.max,
2408
+ description: options?.description
2409
+ };
2410
+ }
2411
+ /**
2412
+ * Build an {@link ObjectShape} from a property map.
2413
+ *
2414
+ * @remarks
2415
+ * Wrap any property in {@link optionalShape} to allow its absence. By default
2416
+ * the compiled guard rejects unknown keys; pass `additionalProperties` to open
2417
+ * the object.
2418
+ *
2419
+ * @param properties - Map of property names to child shapes
2420
+ * @param options - Optional `additionalProperties` and `description`
2421
+ * @returns An object shape
2422
+ *
2423
+ * @example
2424
+ * ```ts
2425
+ * const user = objectShape({
2426
+ * name: stringShape({ min: 1 }),
2427
+ * age: integerShape({ min: 0, max: 120 }),
2428
+ * bio: optionalShape(stringShape()),
2429
+ * })
2430
+ * ```
2431
+ */
2432
+ function objectShape(properties, options) {
2433
+ return {
2434
+ type: "object",
2435
+ properties,
2436
+ additionalProperties: options?.additionalProperties,
2437
+ description: options?.description
2438
+ };
2439
+ }
2440
+ /**
2441
+ * Build an open {@link ObjectShape} with no fixed properties — a dictionary.
2442
+ *
2443
+ * @remarks
2444
+ * Every value is validated against `values`; keys are unconstrained. Equivalent
2445
+ * to `objectShape({}, { additionalProperties: values })`.
2446
+ *
2447
+ * @param values - The shape every value must match
2448
+ * @param options - Optional `description`
2449
+ * @returns An open object shape
2450
+ *
2451
+ * @example
2452
+ * ```ts
2453
+ * const bindings = recordShape(numberShape()) // ~ Record<string, number>
2454
+ * ```
2455
+ */
2456
+ function recordShape(values, options) {
2457
+ return {
2458
+ type: "object",
2459
+ properties: {},
2460
+ additionalProperties: values,
2461
+ description: options?.description
2462
+ };
2463
+ }
2464
+ /**
2465
+ * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
2466
+ *
2467
+ * @param variants - The candidate shapes; the first match wins at runtime
2468
+ * @returns A union shape whose `Infer` is the union of the variants
2469
+ *
2470
+ * @example
2471
+ * ```ts
2472
+ * const id = unionShape(stringShape(), integerShape())
2473
+ * // Infer<typeof id> = string | number
2474
+ * ```
2475
+ */
2476
+ function unionShape(...variants) {
2477
+ return {
2478
+ type: "union",
2479
+ variants
2480
+ };
2481
+ }
2482
+ /**
2483
+ * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
2484
+ *
2485
+ * @remarks
2486
+ * Runtime behavior is identical to {@link unionShape} — only the emitted schema
2487
+ * keyword differs (`oneOf` vs `anyOf`).
2488
+ *
2489
+ * @param variants - The candidate shapes
2490
+ * @returns A union shape with `mode: 'oneOf'`
2491
+ *
2492
+ * @example
2493
+ * ```ts
2494
+ * const id = oneOfShape(stringShape(), integerShape())
2495
+ * // Infer<typeof id> = string | number
2496
+ * ```
2497
+ */
2498
+ function oneOfShape(...variants) {
2499
+ return {
2500
+ type: "union",
2501
+ variants,
2502
+ mode: "oneOf"
2503
+ };
2504
+ }
2505
+ /**
2506
+ * Wrap a shape so it may be absent (`undefined`).
2507
+ *
2508
+ * @remarks
2509
+ * As an {@link objectShape} property, the field becomes a true optional property
2510
+ * in the inferred type.
2511
+ *
2512
+ * @param inner - The wrapped shape
2513
+ * @returns An optional shape
2514
+ */
2515
+ function optionalShape(inner) {
2516
+ return {
2517
+ type: "optional",
2518
+ inner
2519
+ };
2520
+ }
2521
+ /**
2522
+ * Wrap a shape so it may be `null`.
2523
+ *
2524
+ * @param inner - The wrapped shape
2525
+ * @returns A nullable shape
2526
+ *
2527
+ * @example
2528
+ * ```ts
2529
+ * const bio = nullableShape(stringShape())
2530
+ * // Infer<typeof bio> = string | null
2531
+ * ```
2532
+ */
2533
+ function nullableShape(inner) {
2534
+ return {
2535
+ type: "nullable",
2536
+ inner
2537
+ };
2538
+ }
2539
+ /**
2540
+ * Build a {@link JSONShape}.
2541
+ *
2542
+ * @remarks
2543
+ * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
2544
+ * schema fragment and accepts anything at runtime, while `jsonShape` validates
2545
+ * that a value is real JSON (via {@link isJSONValue}).
2546
+ *
2547
+ * @param options - Optional `description`
2548
+ * @returns A JSON passthrough shape
2549
+ *
2550
+ * @example
2551
+ * ```ts
2552
+ * const payload = jsonShape({ description: 'Arbitrary JSON payload' })
2553
+ * ```
2554
+ */
2555
+ function jsonShape(options) {
2556
+ return {
2557
+ type: "json",
2558
+ description: options?.description
2559
+ };
2560
+ }
2561
+ /**
2562
+ * Build a {@link RawShape} from a JSON Schema fragment.
2563
+ *
2564
+ * @remarks
2565
+ * For values the shape DSL can't express. The compiled guard accepts any value;
2566
+ * the parser passes it through; the schema is emitted verbatim.
2567
+ *
2568
+ * @param schema - The JSON Schema fragment to embed
2569
+ * @returns A raw shape
2570
+ *
2571
+ * @example
2572
+ * ```ts
2573
+ * const custom = rawShape({ type: 'string', format: 'uuid' })
2574
+ * ```
2575
+ */
2576
+ function rawShape(schema) {
2577
+ return {
2578
+ type: "raw",
2579
+ schema
2580
+ };
2581
+ }
2582
+ //#endregion
2583
+ exports.JSON_SCHEMA_TYPES = JSON_SCHEMA_TYPES;
2584
+ exports.andOf = andOf;
2585
+ exports.arrayOf = arrayOf;
2586
+ exports.arrayShape = arrayShape;
2587
+ exports.attempt = attempt;
2588
+ exports.booleanShape = booleanShape;
2589
+ exports.boundsOf = boundsOf;
2590
+ exports.compileGenerator = compileGenerator;
2591
+ exports.compileGuard = compileGuard;
2592
+ exports.compileParser = compileParser;
2593
+ exports.compileSchema = compileSchema;
2594
+ exports.complementOf = complementOf;
2595
+ exports.createContract = createContract;
2596
+ exports.enumOf = enumOf;
2597
+ exports.enumerableSymbolCount = enumerableSymbolCount;
2598
+ exports.instanceOf = instanceOf;
2599
+ exports.integerShape = integerShape;
2600
+ exports.intersectionOf = intersectionOf;
2601
+ exports.isArray = isArray;
2602
+ exports.isArrayBuffer = isArrayBuffer;
2603
+ exports.isArrayBufferView = isArrayBufferView;
2604
+ exports.isAsyncFunction = isAsyncFunction;
2605
+ exports.isAsyncGeneratorFunction = isAsyncGeneratorFunction;
2606
+ exports.isAsyncIterable = isAsyncIterable;
2607
+ exports.isBigInt = isBigInt;
2608
+ exports.isBigInt64Array = isBigInt64Array;
2609
+ exports.isBigUint64Array = isBigUint64Array;
2610
+ exports.isBoolean = isBoolean;
2611
+ exports.isConstructor = isConstructor;
2612
+ exports.isDataView = isDataView;
2613
+ exports.isDate = isDate;
2614
+ exports.isDefined = isDefined;
2615
+ exports.isEmptyArray = isEmptyArray;
2616
+ exports.isEmptyMap = isEmptyMap;
2617
+ exports.isEmptyObject = isEmptyObject;
2618
+ exports.isEmptySet = isEmptySet;
2619
+ exports.isEmptyString = isEmptyString;
2620
+ exports.isError = isError;
2621
+ exports.isFalse = isFalse;
2622
+ exports.isFiniteNumber = isFiniteNumber;
2623
+ exports.isFloat32Array = isFloat32Array;
2624
+ exports.isFloat64Array = isFloat64Array;
2625
+ exports.isFunction = isFunction;
2626
+ exports.isGeneratorFunction = isGeneratorFunction;
2627
+ exports.isInt16Array = isInt16Array;
2628
+ exports.isInt32Array = isInt32Array;
2629
+ exports.isInt8Array = isInt8Array;
2630
+ exports.isInteger = isInteger;
2631
+ exports.isIterable = isIterable;
2632
+ exports.isJSONPrimitive = isJSONPrimitive;
2633
+ exports.isJSONValue = isJSONValue;
2634
+ exports.isMap = isMap;
2635
+ exports.isNonEmptyArray = isNonEmptyArray;
2636
+ exports.isNonEmptyMap = isNonEmptyMap;
2637
+ exports.isNonEmptyObject = isNonEmptyObject;
2638
+ exports.isNonEmptySet = isNonEmptySet;
2639
+ exports.isNonEmptyString = isNonEmptyString;
2640
+ exports.isNull = isNull;
2641
+ exports.isNullableBoolean = isNullableBoolean;
2642
+ exports.isNullableNumber = isNullableNumber;
2643
+ exports.isNullableString = isNullableString;
2644
+ exports.isNumber = isNumber;
2645
+ exports.isObject = isObject;
2646
+ exports.isPromise = isPromise;
2647
+ exports.isPromiseLike = isPromiseLike;
2648
+ exports.isRecord = isRecord;
2649
+ exports.isRegExp = isRegExp;
2650
+ exports.isSet = isSet;
2651
+ exports.isSharedArrayBuffer = isSharedArrayBuffer;
2652
+ exports.isString = isString;
2653
+ exports.isSymbol = isSymbol;
2654
+ exports.isTrue = isTrue;
2655
+ exports.isUint16Array = isUint16Array;
2656
+ exports.isUint32Array = isUint32Array;
2657
+ exports.isUint8Array = isUint8Array;
2658
+ exports.isUint8ClampedArray = isUint8ClampedArray;
2659
+ exports.isUndefined = isUndefined;
2660
+ exports.isWeakMap = isWeakMap;
2661
+ exports.isWeakSet = isWeakSet;
2662
+ exports.isZeroArg = isZeroArg;
2663
+ exports.isZeroArgAsync = isZeroArgAsync;
2664
+ exports.isZeroArgAsyncGenerator = isZeroArgAsyncGenerator;
2665
+ exports.isZeroArgGenerator = isZeroArgGenerator;
2666
+ exports.iterableOf = iterableOf;
2667
+ exports.jsonShape = jsonShape;
2668
+ exports.keyOf = keyOf;
2669
+ exports.lazyOf = lazyOf;
2670
+ exports.literalOf = literalOf;
2671
+ exports.literalShape = literalShape;
2672
+ exports.mapOf = mapOf;
2673
+ exports.matchOf = matchOf;
2674
+ exports.notOf = notOf;
2675
+ exports.nullShape = nullShape;
2676
+ exports.nullableOf = nullableOf;
2677
+ exports.nullableShape = nullableShape;
2678
+ exports.numberShape = numberShape;
2679
+ exports.objectShape = objectShape;
2680
+ exports.omitOf = omitOf;
2681
+ exports.oneOfShape = oneOfShape;
2682
+ exports.optionalOf = optionalOf;
2683
+ exports.optionalShape = optionalShape;
2684
+ exports.orOf = orOf;
2685
+ exports.parseArray = parseArray;
2686
+ exports.parseArrayField = parseArrayField;
2687
+ exports.parseBoolean = parseBoolean;
2688
+ exports.parseBooleanField = parseBooleanField;
2689
+ exports.parseEnum = parseEnum;
2690
+ exports.parseEnumField = parseEnumField;
2691
+ exports.parseInteger = parseInteger;
2692
+ exports.parseIntegerField = parseIntegerField;
2693
+ exports.parseJSON = parseJSON;
2694
+ exports.parseJSONAs = parseJSONAs;
2695
+ exports.parseJSONValue = parseJSONValue;
2696
+ exports.parseJSONValueField = parseJSONValueField;
2697
+ exports.parseNull = parseNull;
2698
+ exports.parseNullField = parseNullField;
2699
+ exports.parseNumber = parseNumber;
2700
+ exports.parseNumberField = parseNumberField;
2701
+ exports.parseRecord = parseRecord;
2702
+ exports.parseRecordField = parseRecordField;
2703
+ exports.parseString = parseString;
2704
+ exports.parseStringField = parseStringField;
2705
+ exports.pickOf = pickOf;
2706
+ exports.rawShape = rawShape;
2707
+ exports.recordOf = recordOf;
2708
+ exports.recordShape = recordShape;
2709
+ exports.resolveField = resolveField;
2710
+ exports.schemaToParameters = schemaToParameters;
2711
+ exports.seededRandom = seededRandom;
2712
+ exports.setOf = setOf;
2713
+ exports.stringOf = stringOf;
2714
+ exports.stringShape = stringShape;
2715
+ exports.transformOf = transformOf;
2716
+ exports.tupleOf = tupleOf;
2717
+ exports.unionOf = unionOf;
2718
+ exports.unionShape = unionShape;
2719
+ exports.validateShape = validateShape;
2720
+ exports.whereOf = whereOf;
2721
+
2722
+ //# sourceMappingURL=index.cjs.map