@orkestrel/contract 0.0.7 → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -5
- package/dist/src/core/index.cjs +1653 -611
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +626 -137
- package/dist/src/core/index.d.ts +626 -137
- package/dist/src/core/index.js +1640 -611
- package/dist/src/core/index.js.map +1 -1
- package/package.json +13 -15
package/dist/src/core/index.cjs
CHANGED
|
@@ -48,6 +48,50 @@ var FAULT_LIMIT = 64;
|
|
|
48
48
|
*/
|
|
49
49
|
var PREVIEW_LIMIT = 64;
|
|
50
50
|
/**
|
|
51
|
+
* The maximum number of active {@link lazyOf} invocations for one lazy guard,
|
|
52
|
+
* frozen.
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* Bounds explicitly recursive guards before the JavaScript call stack becomes
|
|
56
|
+
* the limiting mechanism. An invocation beyond this depth returns `false`, and
|
|
57
|
+
* the counter unwinds after every contained guard call.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* GUARD_DEPTH_LIMIT // 512
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
var GUARD_DEPTH_LIMIT = 512;
|
|
65
|
+
/**
|
|
66
|
+
* The maximum supported nesting depth of a compiled contract shape, frozen.
|
|
67
|
+
*
|
|
68
|
+
* @remarks
|
|
69
|
+
* {@link validateShape} rejects the next level with a depth-coded
|
|
70
|
+
* {@link ContractError} before recursive artifact compilation begins, so a
|
|
71
|
+
* finite but pathologically deep developer-authored shape fails predictably
|
|
72
|
+
* instead of reaching the JavaScript call-stack limit.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```ts
|
|
76
|
+
* COMPILE_DEPTH_LIMIT // 512
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
var COMPILE_DEPTH_LIMIT = 512;
|
|
80
|
+
/**
|
|
81
|
+
* The maximum number of candidate-generation attempts for a constrained
|
|
82
|
+
* generated value, frozen.
|
|
83
|
+
*
|
|
84
|
+
* @remarks
|
|
85
|
+
* Provides one deterministic work bound for generators that must retry a
|
|
86
|
+
* candidate against a contract constraint.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* ```ts
|
|
90
|
+
* GENERATION_ATTEMPT_LIMIT // 32
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
var GENERATION_ATTEMPT_LIMIT = 32;
|
|
94
|
+
/**
|
|
51
95
|
* The default maximum object/array nesting depth {@link valueToSchema} walks,
|
|
52
96
|
* frozen.
|
|
53
97
|
*
|
|
@@ -108,6 +152,55 @@ var FORMAT_PATTERNS = Object.freeze({
|
|
|
108
152
|
uri: /^[a-z][a-z0-9+.-]*:\/\//i
|
|
109
153
|
});
|
|
110
154
|
//#endregion
|
|
155
|
+
//#region src/core/errors.ts
|
|
156
|
+
/**
|
|
157
|
+
* Error carrying a machine-readable contract category and optional context.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```ts
|
|
161
|
+
* const error = new ContractError('Minimum exceeds maximum', {
|
|
162
|
+
* code: 'range',
|
|
163
|
+
* context: { path: ['properties', 'age'] },
|
|
164
|
+
* })
|
|
165
|
+
* ```
|
|
166
|
+
*/
|
|
167
|
+
var ContractError = class extends Error {
|
|
168
|
+
name = "ContractError";
|
|
169
|
+
code;
|
|
170
|
+
context;
|
|
171
|
+
/**
|
|
172
|
+
* Create a contract error.
|
|
173
|
+
*
|
|
174
|
+
* @param message - Human-readable error description
|
|
175
|
+
* @param options - Machine-readable category, optional context, and optional cause
|
|
176
|
+
*/
|
|
177
|
+
constructor(message, options) {
|
|
178
|
+
const cause = options.cause;
|
|
179
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
180
|
+
this.code = options.code;
|
|
181
|
+
this.context = options.context;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* Determine whether an unknown value is a {@link ContractError}.
|
|
186
|
+
*
|
|
187
|
+
* @param value - The value to inspect
|
|
188
|
+
* @returns `true` only when the value is a `ContractError`
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* isContractError(new ContractError('Invalid shape', { code: 'placement' })) // true
|
|
193
|
+
* isContractError(new Error('Invalid shape')) // false
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
function isContractError(value) {
|
|
197
|
+
try {
|
|
198
|
+
return value instanceof ContractError;
|
|
199
|
+
} catch {
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
//#endregion
|
|
111
204
|
//#region src/core/validators.ts
|
|
112
205
|
/** Determine whether a value is `null`.
|
|
113
206
|
*
|
|
@@ -305,7 +398,7 @@ function isNullableBoolean(value) {
|
|
|
305
398
|
* NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
|
|
306
399
|
* revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
|
|
307
400
|
* `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
|
|
308
|
-
* wraps the check in {@link
|
|
401
|
+
* wraps the check in {@link holds} (see ./helpers.js) so any such throw
|
|
309
402
|
* yields `false` instead of escaping.
|
|
310
403
|
*
|
|
311
404
|
* @param value - The value to test
|
|
@@ -321,8 +414,7 @@ function isNullableBoolean(value) {
|
|
|
321
414
|
*/
|
|
322
415
|
function isInstance(value, ctor) {
|
|
323
416
|
const target = ctor;
|
|
324
|
-
|
|
325
|
-
return outcome.success && outcome.value;
|
|
417
|
+
return holds(() => isFunction(target) && value instanceof target);
|
|
326
418
|
}
|
|
327
419
|
/** Determine whether a value is a `Date`.
|
|
328
420
|
*
|
|
@@ -384,14 +476,13 @@ function isPromise(value) {
|
|
|
384
476
|
* ```
|
|
385
477
|
*/
|
|
386
478
|
function isPromiseLike(value) {
|
|
387
|
-
|
|
388
|
-
|
|
479
|
+
return holds(() => {
|
|
480
|
+
if (!isObject(value)) return false;
|
|
389
481
|
const thenValue = Reflect.get(value, "then");
|
|
390
482
|
const catchValue = Reflect.get(value, "catch");
|
|
391
483
|
const finallyValue = Reflect.get(value, "finally");
|
|
392
484
|
return isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue);
|
|
393
485
|
});
|
|
394
|
-
return outcome.success && outcome.value;
|
|
395
486
|
}
|
|
396
487
|
/** Determine whether a value is an `ArrayBuffer`.
|
|
397
488
|
*
|
|
@@ -435,10 +526,10 @@ function isSharedArrayBuffer(value) {
|
|
|
435
526
|
* ```
|
|
436
527
|
*/
|
|
437
528
|
function isIterable(value) {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
529
|
+
return holds(() => {
|
|
530
|
+
if (isString(value)) return true;
|
|
531
|
+
return isObject(value) && isFunction(Reflect.get(value, Symbol.iterator));
|
|
532
|
+
});
|
|
442
533
|
}
|
|
443
534
|
/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).
|
|
444
535
|
*
|
|
@@ -449,9 +540,7 @@ function isIterable(value) {
|
|
|
449
540
|
* ```
|
|
450
541
|
*/
|
|
451
542
|
function isAsyncIterable(value) {
|
|
452
|
-
|
|
453
|
-
const outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)));
|
|
454
|
-
return outcome.success && outcome.value;
|
|
543
|
+
return holds(() => isObject(value) && isFunction(Reflect.get(value, Symbol.asyncIterator)));
|
|
455
544
|
}
|
|
456
545
|
/**
|
|
457
546
|
* Determine whether a value is a non-null object.
|
|
@@ -485,7 +574,7 @@ function isObject(value) {
|
|
|
485
574
|
* above `null`. Arrays and class instances are still rejected: an array's
|
|
486
575
|
* prototype chain runs through `Array.prototype` before `null`, and a class
|
|
487
576
|
* instance's runs through the class's own prototype. The whole body runs
|
|
488
|
-
* inside `
|
|
577
|
+
* inside `holds` (AGENTS §14) so a revoked `Proxy` or a hostile
|
|
489
578
|
* `getPrototypeOf` trap cannot escape as a thrown error.
|
|
490
579
|
*
|
|
491
580
|
* @example
|
|
@@ -497,12 +586,11 @@ function isObject(value) {
|
|
|
497
586
|
* ```
|
|
498
587
|
*/
|
|
499
588
|
function isRecord(value) {
|
|
500
|
-
|
|
589
|
+
return holds(() => {
|
|
501
590
|
if (!isObject(value) || isArray(value)) return false;
|
|
502
591
|
const prototype = Object.getPrototypeOf(value);
|
|
503
592
|
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
504
593
|
});
|
|
505
|
-
return outcome.success && outcome.value;
|
|
506
594
|
}
|
|
507
595
|
/** Determine whether a value is a `Map`.
|
|
508
596
|
*
|
|
@@ -557,7 +645,7 @@ function isWeakSet(value) {
|
|
|
557
645
|
* ```
|
|
558
646
|
*/
|
|
559
647
|
function isArray(value) {
|
|
560
|
-
return Array.isArray(value);
|
|
648
|
+
return holds(() => Array.isArray(value));
|
|
561
649
|
}
|
|
562
650
|
/** Determine whether a value is a `DataView`.
|
|
563
651
|
*
|
|
@@ -579,7 +667,7 @@ function isDataView(value) {
|
|
|
579
667
|
* ```
|
|
580
668
|
*/
|
|
581
669
|
function isArrayBufferView(value) {
|
|
582
|
-
return ArrayBuffer.isView(value);
|
|
670
|
+
return holds(() => ArrayBuffer.isView(value));
|
|
583
671
|
}
|
|
584
672
|
/** Determine whether a value is an `Int8Array`.
|
|
585
673
|
*
|
|
@@ -732,7 +820,7 @@ function isEmptyString(value) {
|
|
|
732
820
|
* ```
|
|
733
821
|
*/
|
|
734
822
|
function isEmptyArray(value) {
|
|
735
|
-
return isArray(value) && value.length === 0;
|
|
823
|
+
return holds(() => isArray(value) && value.length === 0);
|
|
736
824
|
}
|
|
737
825
|
/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).
|
|
738
826
|
*
|
|
@@ -743,9 +831,7 @@ function isEmptyArray(value) {
|
|
|
743
831
|
* ```
|
|
744
832
|
*/
|
|
745
833
|
function isEmptyObject(value) {
|
|
746
|
-
|
|
747
|
-
const outcome = attempt(() => Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0);
|
|
748
|
-
return outcome.success && outcome.value;
|
|
834
|
+
return holds(() => isRecord(value) && Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0);
|
|
749
835
|
}
|
|
750
836
|
/** Determine whether a value is an empty `Map`.
|
|
751
837
|
*
|
|
@@ -756,7 +842,7 @@ function isEmptyObject(value) {
|
|
|
756
842
|
* ```
|
|
757
843
|
*/
|
|
758
844
|
function isEmptyMap(value) {
|
|
759
|
-
return isMap(value) && value.size === 0;
|
|
845
|
+
return holds(() => isMap(value) && value.size === 0);
|
|
760
846
|
}
|
|
761
847
|
/** Determine whether a value is an empty `Set`.
|
|
762
848
|
*
|
|
@@ -767,7 +853,7 @@ function isEmptyMap(value) {
|
|
|
767
853
|
* ```
|
|
768
854
|
*/
|
|
769
855
|
function isEmptySet(value) {
|
|
770
|
-
return isSet(value) && value.size === 0;
|
|
856
|
+
return holds(() => isSet(value) && value.size === 0);
|
|
771
857
|
}
|
|
772
858
|
/** Determine whether a value is a non-empty string (at least one character).
|
|
773
859
|
*
|
|
@@ -789,7 +875,7 @@ function isNonEmptyString(value) {
|
|
|
789
875
|
* ```
|
|
790
876
|
*/
|
|
791
877
|
function isNonEmptyArray(value) {
|
|
792
|
-
return isArray(value) && value.length > 0;
|
|
878
|
+
return holds(() => isArray(value) && value.length > 0);
|
|
793
879
|
}
|
|
794
880
|
/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).
|
|
795
881
|
*
|
|
@@ -800,9 +886,7 @@ function isNonEmptyArray(value) {
|
|
|
800
886
|
* ```
|
|
801
887
|
*/
|
|
802
888
|
function isNonEmptyObject(value) {
|
|
803
|
-
|
|
804
|
-
const outcome = attempt(() => Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0);
|
|
805
|
-
return outcome.success && outcome.value;
|
|
889
|
+
return holds(() => isRecord(value) && (Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0));
|
|
806
890
|
}
|
|
807
891
|
/** Determine whether a value is a non-empty `Map` (at least one entry).
|
|
808
892
|
*
|
|
@@ -813,7 +897,7 @@ function isNonEmptyObject(value) {
|
|
|
813
897
|
* ```
|
|
814
898
|
*/
|
|
815
899
|
function isNonEmptyMap(value) {
|
|
816
|
-
return isMap(value) && value.size > 0;
|
|
900
|
+
return holds(() => isMap(value) && value.size > 0);
|
|
817
901
|
}
|
|
818
902
|
/** Determine whether a value is a non-empty `Set` (at least one element).
|
|
819
903
|
*
|
|
@@ -824,7 +908,7 @@ function isNonEmptyMap(value) {
|
|
|
824
908
|
* ```
|
|
825
909
|
*/
|
|
826
910
|
function isNonEmptySet(value) {
|
|
827
|
-
return isSet(value) && value.size > 0;
|
|
911
|
+
return holds(() => isSet(value) && value.size > 0);
|
|
828
912
|
}
|
|
829
913
|
/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).
|
|
830
914
|
*
|
|
@@ -835,7 +919,7 @@ function isNonEmptySet(value) {
|
|
|
835
919
|
* ```
|
|
836
920
|
*/
|
|
837
921
|
function isZeroArg(value) {
|
|
838
|
-
return isFunction(value) && value.length === 0;
|
|
922
|
+
return holds(() => isFunction(value) && value.length === 0);
|
|
839
923
|
}
|
|
840
924
|
/**
|
|
841
925
|
* Determine whether a value is a native `async function`.
|
|
@@ -852,7 +936,7 @@ function isZeroArg(value) {
|
|
|
852
936
|
* ```
|
|
853
937
|
*/
|
|
854
938
|
function isAsyncFunction(value) {
|
|
855
|
-
return isFunction(value) && value.constructor?.name === "AsyncFunction";
|
|
939
|
+
return holds(() => isFunction(value) && value.constructor?.name === "AsyncFunction");
|
|
856
940
|
}
|
|
857
941
|
/** Determine whether a value is a generator function (`function*`).
|
|
858
942
|
*
|
|
@@ -863,7 +947,7 @@ function isAsyncFunction(value) {
|
|
|
863
947
|
* ```
|
|
864
948
|
*/
|
|
865
949
|
function isGeneratorFunction(value) {
|
|
866
|
-
return isFunction(value) && value.constructor?.name === "GeneratorFunction";
|
|
950
|
+
return holds(() => isFunction(value) && value.constructor?.name === "GeneratorFunction");
|
|
867
951
|
}
|
|
868
952
|
/** Determine whether a value is an async generator function (`async function*`).
|
|
869
953
|
*
|
|
@@ -874,7 +958,7 @@ function isGeneratorFunction(value) {
|
|
|
874
958
|
* ```
|
|
875
959
|
*/
|
|
876
960
|
function isAsyncGeneratorFunction(value) {
|
|
877
|
-
return isFunction(value) && value.constructor?.name === "AsyncGeneratorFunction";
|
|
961
|
+
return holds(() => isFunction(value) && value.constructor?.name === "AsyncGeneratorFunction");
|
|
878
962
|
}
|
|
879
963
|
/** Determine whether a value is a zero-argument async function.
|
|
880
964
|
*
|
|
@@ -924,13 +1008,11 @@ function isZeroArgAsyncGenerator(value) {
|
|
|
924
1008
|
* ```
|
|
925
1009
|
*/
|
|
926
1010
|
function isConstructor(value) {
|
|
927
|
-
|
|
928
|
-
|
|
1011
|
+
return holds(() => {
|
|
1012
|
+
if (!isFunction(value)) return false;
|
|
929
1013
|
Reflect.construct(String, [], value);
|
|
930
1014
|
return true;
|
|
931
|
-
}
|
|
932
|
-
return false;
|
|
933
|
-
}
|
|
1015
|
+
});
|
|
934
1016
|
}
|
|
935
1017
|
/**
|
|
936
1018
|
* Determine whether a value is a cycle-safe JSON value.
|
|
@@ -939,7 +1021,7 @@ function isConstructor(value) {
|
|
|
939
1021
|
* Total guard: never throws, returns `false` for cycles, functions, `Date`
|
|
940
1022
|
* instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
|
|
941
1023
|
* are walked with an ancestor set so recursive input fails instead of hanging.
|
|
942
|
-
* The whole walk runs inside `
|
|
1024
|
+
* The whole walk runs inside `holds` (AGENTS §14): a hostile getter on a
|
|
943
1025
|
* record property, or a revoked `Proxy` anywhere in the structure, is caught
|
|
944
1026
|
* and yields `false` instead of escaping as a thrown error.
|
|
945
1027
|
*
|
|
@@ -953,25 +1035,7 @@ function isConstructor(value) {
|
|
|
953
1035
|
* ```
|
|
954
1036
|
*/
|
|
955
1037
|
function isJSONValue(value) {
|
|
956
|
-
|
|
957
|
-
const check = (entry) => {
|
|
958
|
-
if (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true;
|
|
959
|
-
if (Array.isArray(entry)) {
|
|
960
|
-
if (ancestors.has(entry)) return false;
|
|
961
|
-
ancestors.add(entry);
|
|
962
|
-
const valid = entry.every(check);
|
|
963
|
-
ancestors.delete(entry);
|
|
964
|
-
return valid;
|
|
965
|
-
}
|
|
966
|
-
if (!isRecord(entry)) return false;
|
|
967
|
-
if (ancestors.has(entry)) return false;
|
|
968
|
-
ancestors.add(entry);
|
|
969
|
-
const valid = Object.values(entry).every(check);
|
|
970
|
-
ancestors.delete(entry);
|
|
971
|
-
return valid;
|
|
972
|
-
};
|
|
973
|
-
const outcome = attempt(() => check(value));
|
|
974
|
-
return outcome.success && outcome.value;
|
|
1038
|
+
return holds(() => matchesJSONValue(value, /* @__PURE__ */ new WeakSet()));
|
|
975
1039
|
}
|
|
976
1040
|
/**
|
|
977
1041
|
* Determine whether a value is a primitive JSON value.
|
|
@@ -1008,13 +1072,14 @@ function isJSONPrimitive(value) {
|
|
|
1008
1072
|
* a throw escape.
|
|
1009
1073
|
*
|
|
1010
1074
|
* @remarks
|
|
1011
|
-
* The
|
|
1075
|
+
* The sanctioned never-throw boundary for the guards (AGENTS §14). The
|
|
1012
1076
|
* `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
|
|
1013
1077
|
* callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
|
|
1014
1078
|
* `boolean`. This converts a throwing callback into a `Failure` so the
|
|
1015
1079
|
* surrounding guard can treat it as a non-match instead of propagating the
|
|
1016
1080
|
* exception, written once and shared rather than copy-pasted as ad-hoc
|
|
1017
|
-
* `try`/`catch`.
|
|
1081
|
+
* `try`/`catch`. The sole hand-written exception is {@link isContractError},
|
|
1082
|
+
* whose local boundary avoids an `errors` → `helpers` dependency inversion.
|
|
1018
1083
|
*
|
|
1019
1084
|
* @param callback - The callback to invoke with no arguments
|
|
1020
1085
|
* @returns A `Success` carrying the return value, or a `Failure` carrying the
|
|
@@ -1033,21 +1098,92 @@ function attempt(callback) {
|
|
|
1033
1098
|
value: callback()
|
|
1034
1099
|
};
|
|
1035
1100
|
} catch (reason) {
|
|
1036
|
-
if (reason instanceof Error) return {
|
|
1037
|
-
success: false,
|
|
1038
|
-
error: reason
|
|
1039
|
-
};
|
|
1040
|
-
let message = "Unknown thrown value";
|
|
1041
1101
|
try {
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1102
|
+
return {
|
|
1103
|
+
success: false,
|
|
1104
|
+
error: reason instanceof Error ? reason : new Error(String(reason))
|
|
1105
|
+
};
|
|
1106
|
+
} catch {
|
|
1107
|
+
return {
|
|
1108
|
+
success: false,
|
|
1109
|
+
error: /* @__PURE__ */ new Error("Unknown thrown value")
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1048
1112
|
}
|
|
1049
1113
|
}
|
|
1050
1114
|
/**
|
|
1115
|
+
* Invoke a predicate through the sanctioned never-throw boundary.
|
|
1116
|
+
*
|
|
1117
|
+
* @param callback - The predicate to invoke with no arguments
|
|
1118
|
+
* @returns `true` only when the callback returns the boolean value `true`
|
|
1119
|
+
*
|
|
1120
|
+
* @example
|
|
1121
|
+
* ```ts
|
|
1122
|
+
* holds(() => value instanceof Widget) // false when inspection throws
|
|
1123
|
+
* ```
|
|
1124
|
+
*/
|
|
1125
|
+
function holds(callback) {
|
|
1126
|
+
const outcome = attempt(callback);
|
|
1127
|
+
return outcome.success && outcome.value === true;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Snapshot an object's own enumerable string keys through a total boundary.
|
|
1131
|
+
*
|
|
1132
|
+
* @remarks
|
|
1133
|
+
* This is the package-wide runtime property view used by compiled object
|
|
1134
|
+
* guards, parsers, reporters, schema inference, and owned schema cloning. It
|
|
1135
|
+
* matches the object-key view serialized by `JSON.stringify`: inherited,
|
|
1136
|
+
* symbol, and non-enumerable properties are excluded. A hostile Proxy trap
|
|
1137
|
+
* returns `undefined` rather than escaping.
|
|
1138
|
+
*
|
|
1139
|
+
* @param value - The object whose keys to snapshot
|
|
1140
|
+
* @returns A frozen owned key list, or `undefined` when enumeration throws
|
|
1141
|
+
*
|
|
1142
|
+
* @example
|
|
1143
|
+
* ```ts
|
|
1144
|
+
* enumerableKeys({ visible: 1 }) // ['visible']
|
|
1145
|
+
* ```
|
|
1146
|
+
*/
|
|
1147
|
+
function enumerableKeys(value) {
|
|
1148
|
+
const outcome = attempt(() => Object.keys(value));
|
|
1149
|
+
return outcome.success ? Object.freeze([...outcome.value]) : void 0;
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Draw and validate one generator random sample.
|
|
1153
|
+
*
|
|
1154
|
+
* @param random - The caller-supplied random source
|
|
1155
|
+
* @param shape - The shape category consuming the sample
|
|
1156
|
+
* @returns A finite sample in `[0, 1)`
|
|
1157
|
+
* @throws {ContractError} When the source throws or returns outside `[0, 1)`
|
|
1158
|
+
*
|
|
1159
|
+
* @example
|
|
1160
|
+
* ```ts
|
|
1161
|
+
* drawRandom(() => 0.5, 'number') // 0.5
|
|
1162
|
+
* ```
|
|
1163
|
+
*/
|
|
1164
|
+
function drawRandom(random, shape) {
|
|
1165
|
+
const outcome = attempt(random);
|
|
1166
|
+
if (!outcome.success) throw new ContractError("drawRandom: the random source threw", {
|
|
1167
|
+
code: "random",
|
|
1168
|
+
context: {
|
|
1169
|
+
shape,
|
|
1170
|
+
limit: "[0, 1)",
|
|
1171
|
+
received: "threw"
|
|
1172
|
+
},
|
|
1173
|
+
cause: outcome.error
|
|
1174
|
+
});
|
|
1175
|
+
const sample = outcome.value;
|
|
1176
|
+
if (!isFiniteNumber(sample) || sample < 0 || sample >= 1) throw new ContractError("drawRandom: the random source must return a value in [0, 1)", {
|
|
1177
|
+
code: "random",
|
|
1178
|
+
context: {
|
|
1179
|
+
shape,
|
|
1180
|
+
limit: "[0, 1)",
|
|
1181
|
+
received: String(sample)
|
|
1182
|
+
}
|
|
1183
|
+
});
|
|
1184
|
+
return sample;
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1051
1187
|
* Resolve a (possibly nested) field value from a record by a key or key path.
|
|
1052
1188
|
*
|
|
1053
1189
|
* @remarks
|
|
@@ -1082,6 +1218,46 @@ function resolveField(record, path) {
|
|
|
1082
1218
|
return current;
|
|
1083
1219
|
}
|
|
1084
1220
|
/**
|
|
1221
|
+
* Match an unknown value against the recursive JSON value structure.
|
|
1222
|
+
*
|
|
1223
|
+
* @remarks
|
|
1224
|
+
* The caller-owned ancestor set tracks only the active traversal path, so
|
|
1225
|
+
* cycles fail while shared references across sibling branches remain valid.
|
|
1226
|
+
* The set belongs to one traversal from one entry point; passing a shared or
|
|
1227
|
+
* pre-populated set is unsupported. Arrays and plain records recurse through
|
|
1228
|
+
* this helper; class instances and non-finite numbers are rejected.
|
|
1229
|
+
*
|
|
1230
|
+
* @param entry - The value to inspect
|
|
1231
|
+
* @param ancestors - Objects on the active traversal path
|
|
1232
|
+
* @returns `true` when the value is a cycle-free JSON value
|
|
1233
|
+
*
|
|
1234
|
+
* @example
|
|
1235
|
+
* ```ts
|
|
1236
|
+
* matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true
|
|
1237
|
+
* matchesJSONValue(Number.NaN, new WeakSet()) // false
|
|
1238
|
+
* ```
|
|
1239
|
+
*/
|
|
1240
|
+
function matchesJSONValue(entry, ancestors) {
|
|
1241
|
+
if (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true;
|
|
1242
|
+
if (Array.isArray(entry)) {
|
|
1243
|
+
if (ancestors.has(entry)) return false;
|
|
1244
|
+
ancestors.add(entry);
|
|
1245
|
+
let valid = true;
|
|
1246
|
+
for (let index = 0; index < entry.length; index += 1) if (!Object.hasOwn(entry, index) || !matchesJSONValue(entry[index], ancestors)) {
|
|
1247
|
+
valid = false;
|
|
1248
|
+
break;
|
|
1249
|
+
}
|
|
1250
|
+
ancestors.delete(entry);
|
|
1251
|
+
return valid;
|
|
1252
|
+
}
|
|
1253
|
+
if (!isRecord(entry)) return false;
|
|
1254
|
+
if (ancestors.has(entry)) return false;
|
|
1255
|
+
ancestors.add(entry);
|
|
1256
|
+
const valid = Object.values(entry).every((value) => matchesJSONValue(value, ancestors));
|
|
1257
|
+
ancestors.delete(entry);
|
|
1258
|
+
return valid;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1085
1261
|
* Build a deterministic pseudo-random source seeded from a single number.
|
|
1086
1262
|
*
|
|
1087
1263
|
* @remarks
|
|
@@ -1297,41 +1473,338 @@ function shapeToKind(shape) {
|
|
|
1297
1473
|
}
|
|
1298
1474
|
}
|
|
1299
1475
|
//#endregion
|
|
1300
|
-
//#region src/core/
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1476
|
+
//#region src/core/cloners.ts
|
|
1477
|
+
/**
|
|
1478
|
+
* Deep-clone a JSON Schema graph into an owned frozen snapshot.
|
|
1479
|
+
*
|
|
1480
|
+
* @remarks
|
|
1481
|
+
* Walks arrays and records iteratively with a memo, preserving shared
|
|
1482
|
+
* references and closing cyclic edges onto their cloned nodes. Primitive
|
|
1483
|
+
* values and own enumerable string-keyed edges are copied; record nodes use
|
|
1484
|
+
* null prototypes, arrays retain only their intrinsic array prototype, and
|
|
1485
|
+
* every produced object is frozen after its edges are wired. Hostile traversal
|
|
1486
|
+
* throws a clone-coded {@link ContractError}, never a caller-owned raw error.
|
|
1487
|
+
*
|
|
1488
|
+
* @param schema - The JSON Schema graph to snapshot
|
|
1489
|
+
* @returns A deeply cloned and frozen JSON Schema graph
|
|
1490
|
+
* @throws {ContractError} When hostile schema traversal prevents ownership
|
|
1491
|
+
*
|
|
1492
|
+
* @example
|
|
1493
|
+
* ```ts
|
|
1494
|
+
* const child = { type: 'string' }
|
|
1495
|
+
* const clone = cloneSchema({ anyOf: [child, child] })
|
|
1496
|
+
* clone.anyOf?.[0] === clone.anyOf?.[1] // true
|
|
1497
|
+
* ```
|
|
1498
|
+
*/
|
|
1499
|
+
function cloneSchema(schema) {
|
|
1500
|
+
try {
|
|
1501
|
+
const root = Object.create(null);
|
|
1502
|
+
const memo = /* @__PURE__ */ new Map([[schema, root]]);
|
|
1503
|
+
const pending = [{
|
|
1504
|
+
source: schema,
|
|
1505
|
+
clone: root,
|
|
1506
|
+
path: []
|
|
1507
|
+
}];
|
|
1508
|
+
while (pending.length > 0) {
|
|
1509
|
+
const frame = pending.pop();
|
|
1510
|
+
if (frame === void 0) continue;
|
|
1511
|
+
const keys = enumerableKeys(frame.source);
|
|
1512
|
+
if (keys === void 0) throw new ContractError("cloneSchema: property enumeration failed", {
|
|
1513
|
+
code: "clone",
|
|
1514
|
+
context: {
|
|
1515
|
+
path: frame.path,
|
|
1516
|
+
shape: "schema"
|
|
1517
|
+
}
|
|
1518
|
+
});
|
|
1519
|
+
for (const key of keys) {
|
|
1520
|
+
const outcome = attempt(() => Reflect.get(frame.source, key));
|
|
1521
|
+
if (!outcome.success) throw new ContractError("cloneSchema: property access failed", {
|
|
1522
|
+
code: "clone",
|
|
1523
|
+
context: {
|
|
1524
|
+
path: [...frame.path, key],
|
|
1525
|
+
shape: "schema"
|
|
1526
|
+
},
|
|
1527
|
+
cause: outcome.error
|
|
1528
|
+
});
|
|
1529
|
+
const source = outcome.value;
|
|
1530
|
+
let clone = source;
|
|
1531
|
+
if (typeof source === "object" && source !== null) {
|
|
1532
|
+
const existing = memo.get(source);
|
|
1533
|
+
if (existing !== void 0) clone = existing;
|
|
1534
|
+
else {
|
|
1535
|
+
const child = Array.isArray(source) ? [] : Object.create(null);
|
|
1536
|
+
memo.set(source, child);
|
|
1537
|
+
pending.push({
|
|
1538
|
+
source,
|
|
1539
|
+
clone: child,
|
|
1540
|
+
path: [...frame.path, key]
|
|
1541
|
+
});
|
|
1542
|
+
clone = child;
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
Object.defineProperty(frame.clone, key, {
|
|
1546
|
+
value: clone,
|
|
1547
|
+
enumerable: true,
|
|
1548
|
+
configurable: true,
|
|
1549
|
+
writable: true
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
Object.freeze(frame.clone);
|
|
1553
|
+
}
|
|
1554
|
+
return root;
|
|
1555
|
+
} catch (reason) {
|
|
1556
|
+
if (reason instanceof ContractError) throw reason;
|
|
1557
|
+
throw new ContractError("cloneSchema: failed to create an owned schema snapshot", {
|
|
1558
|
+
code: "clone",
|
|
1559
|
+
context: { shape: "schema" },
|
|
1560
|
+
cause: reason
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1307
1563
|
}
|
|
1308
|
-
function
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
const
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1564
|
+
function cloneShape(shape) {
|
|
1565
|
+
try {
|
|
1566
|
+
const memo = /* @__PURE__ */ new Map();
|
|
1567
|
+
const pending = [shape];
|
|
1568
|
+
const sources = [];
|
|
1569
|
+
let root = shape;
|
|
1570
|
+
while (pending.length > 0) {
|
|
1571
|
+
const source = pending.pop();
|
|
1572
|
+
if (source === void 0 || memo.has(source)) continue;
|
|
1573
|
+
let clone;
|
|
1574
|
+
switch (source.type) {
|
|
1575
|
+
case "string": {
|
|
1576
|
+
const pattern = source.pattern;
|
|
1577
|
+
const fields = {
|
|
1578
|
+
type: "string",
|
|
1579
|
+
...source.min === void 0 ? {} : { min: source.min },
|
|
1580
|
+
...source.max === void 0 ? {} : { max: source.max },
|
|
1581
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1582
|
+
};
|
|
1583
|
+
if (pattern === void 0) clone = fields;
|
|
1584
|
+
else {
|
|
1585
|
+
const patternSource = pattern.source;
|
|
1586
|
+
const patternFlags = pattern.flags;
|
|
1587
|
+
clone = {
|
|
1588
|
+
...fields,
|
|
1589
|
+
get pattern() {
|
|
1590
|
+
return Object.freeze(new RegExp(patternSource, patternFlags));
|
|
1591
|
+
}
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
break;
|
|
1595
|
+
}
|
|
1596
|
+
case "number":
|
|
1597
|
+
clone = {
|
|
1598
|
+
type: "number",
|
|
1599
|
+
...source.min === void 0 ? {} : { min: source.min },
|
|
1600
|
+
...source.max === void 0 ? {} : { max: source.max },
|
|
1601
|
+
...source.integer === void 0 ? {} : { integer: source.integer },
|
|
1602
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1603
|
+
};
|
|
1604
|
+
break;
|
|
1605
|
+
case "boolean":
|
|
1606
|
+
clone = {
|
|
1607
|
+
type: "boolean",
|
|
1608
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1609
|
+
};
|
|
1610
|
+
break;
|
|
1611
|
+
case "null":
|
|
1612
|
+
clone = {
|
|
1613
|
+
type: "null",
|
|
1614
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1615
|
+
};
|
|
1616
|
+
break;
|
|
1617
|
+
case "literal":
|
|
1618
|
+
clone = {
|
|
1619
|
+
type: "literal",
|
|
1620
|
+
values: Object.freeze([...source.values]),
|
|
1621
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1622
|
+
};
|
|
1623
|
+
break;
|
|
1624
|
+
case "array":
|
|
1625
|
+
clone = {
|
|
1626
|
+
type: "array",
|
|
1627
|
+
items: source.items,
|
|
1628
|
+
...source.min === void 0 ? {} : { min: source.min },
|
|
1629
|
+
...source.max === void 0 ? {} : { max: source.max },
|
|
1630
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1631
|
+
};
|
|
1632
|
+
pending.push(source.items);
|
|
1633
|
+
break;
|
|
1634
|
+
case "object": {
|
|
1635
|
+
const extra = source.additionalProperties;
|
|
1636
|
+
clone = {
|
|
1637
|
+
type: "object",
|
|
1638
|
+
properties: Object.create(null),
|
|
1639
|
+
...extra === void 0 || extra !== true && extra !== false ? {} : { additionalProperties: extra },
|
|
1640
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1641
|
+
};
|
|
1642
|
+
for (const key of Object.keys(source.properties)) {
|
|
1643
|
+
const child = source.properties[key];
|
|
1644
|
+
if (child !== void 0) pending.push(child);
|
|
1645
|
+
}
|
|
1646
|
+
if (extra !== void 0 && extra !== true && extra !== false) pending.push(extra);
|
|
1647
|
+
break;
|
|
1648
|
+
}
|
|
1649
|
+
case "union":
|
|
1650
|
+
clone = {
|
|
1651
|
+
type: "union",
|
|
1652
|
+
variants: [],
|
|
1653
|
+
...source.mode === void 0 ? {} : { mode: source.mode },
|
|
1654
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1655
|
+
};
|
|
1656
|
+
for (const variant of source.variants) pending.push(variant);
|
|
1657
|
+
break;
|
|
1658
|
+
case "optional":
|
|
1659
|
+
clone = {
|
|
1660
|
+
type: "optional",
|
|
1661
|
+
inner: source.inner
|
|
1662
|
+
};
|
|
1663
|
+
pending.push(source.inner);
|
|
1664
|
+
break;
|
|
1665
|
+
case "nullable":
|
|
1666
|
+
clone = {
|
|
1667
|
+
type: "nullable",
|
|
1668
|
+
inner: source.inner
|
|
1669
|
+
};
|
|
1670
|
+
pending.push(source.inner);
|
|
1671
|
+
break;
|
|
1672
|
+
case "json":
|
|
1673
|
+
clone = {
|
|
1674
|
+
type: "json",
|
|
1675
|
+
...source.description === void 0 ? {} : { description: source.description }
|
|
1676
|
+
};
|
|
1677
|
+
break;
|
|
1678
|
+
case "raw": {
|
|
1679
|
+
const outcome = attempt(() => source.schema);
|
|
1680
|
+
if (!outcome.success) throw new ContractError("cloneShape: raw schema access failed", {
|
|
1681
|
+
code: "clone",
|
|
1682
|
+
context: { shape: "raw" },
|
|
1683
|
+
cause: outcome.error
|
|
1684
|
+
});
|
|
1685
|
+
clone = {
|
|
1686
|
+
type: "raw",
|
|
1687
|
+
schema: cloneSchema(outcome.value)
|
|
1688
|
+
};
|
|
1689
|
+
break;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
memo.set(source, clone);
|
|
1693
|
+
if (source === shape) root = clone;
|
|
1694
|
+
sources.push(source);
|
|
1695
|
+
}
|
|
1696
|
+
for (const source of sources) {
|
|
1697
|
+
const clone = memo.get(source);
|
|
1698
|
+
if (clone === void 0) continue;
|
|
1699
|
+
switch (source.type) {
|
|
1700
|
+
case "array": {
|
|
1701
|
+
const items = memo.get(source.items);
|
|
1702
|
+
if (items !== void 0) Reflect.set(clone, "items", items);
|
|
1703
|
+
break;
|
|
1704
|
+
}
|
|
1705
|
+
case "object": {
|
|
1706
|
+
const properties = Object.create(null);
|
|
1707
|
+
for (const key of Object.keys(source.properties)) {
|
|
1708
|
+
const child = source.properties[key];
|
|
1709
|
+
if (child === void 0) continue;
|
|
1710
|
+
const clonedChild = memo.get(child);
|
|
1711
|
+
if (clonedChild !== void 0) properties[key] = clonedChild;
|
|
1712
|
+
}
|
|
1713
|
+
Reflect.set(clone, "properties", Object.freeze(properties));
|
|
1714
|
+
const extra = source.additionalProperties;
|
|
1715
|
+
if (extra !== void 0 && extra !== true && extra !== false) {
|
|
1716
|
+
const clonedExtra = memo.get(extra);
|
|
1717
|
+
if (clonedExtra !== void 0) Reflect.set(clone, "additionalProperties", clonedExtra);
|
|
1718
|
+
}
|
|
1719
|
+
break;
|
|
1720
|
+
}
|
|
1721
|
+
case "union": {
|
|
1722
|
+
const variants = [];
|
|
1723
|
+
for (const variant of source.variants) {
|
|
1724
|
+
const clonedVariant = memo.get(variant);
|
|
1725
|
+
if (clonedVariant !== void 0) variants.push(clonedVariant);
|
|
1726
|
+
}
|
|
1727
|
+
Reflect.set(clone, "variants", Object.freeze(variants));
|
|
1728
|
+
break;
|
|
1729
|
+
}
|
|
1730
|
+
case "optional":
|
|
1731
|
+
case "nullable": {
|
|
1732
|
+
const inner = memo.get(source.inner);
|
|
1733
|
+
if (inner !== void 0) Reflect.set(clone, "inner", inner);
|
|
1734
|
+
break;
|
|
1735
|
+
}
|
|
1736
|
+
default: break;
|
|
1316
1737
|
}
|
|
1317
|
-
|
|
1738
|
+
Object.freeze(clone);
|
|
1739
|
+
}
|
|
1740
|
+
return root;
|
|
1741
|
+
} catch (reason) {
|
|
1742
|
+
if (isContractError(reason) && reason.code === "clone") throw reason;
|
|
1743
|
+
throw new ContractError("cloneShape: failed to create an owned shape snapshot", {
|
|
1744
|
+
code: "clone",
|
|
1745
|
+
context: { shape: "shape" },
|
|
1746
|
+
cause: reason
|
|
1318
1747
|
});
|
|
1319
|
-
|
|
1320
|
-
};
|
|
1748
|
+
}
|
|
1321
1749
|
}
|
|
1322
1750
|
/**
|
|
1323
|
-
*
|
|
1324
|
-
*
|
|
1751
|
+
* Take ownership of a contract shape node — the node itself when it is already
|
|
1752
|
+
* frozen, otherwise a {@link cloneShape} snapshot of its graph.
|
|
1753
|
+
*
|
|
1754
|
+
* @remarks
|
|
1755
|
+
* Builder- and `cloneShape`-produced frozen means owned: those nodes have frozen
|
|
1756
|
+
* `properties` / `variants` / `values` collections and pattern accessors that
|
|
1757
|
+
* return fresh frozen snapshots, so they cannot drift under a caller who still
|
|
1758
|
+
* holds an input reference or a previously read pattern. `Object.freeze` on a
|
|
1759
|
+
* hand-authored pattern shape is not an ownership marker because it cannot
|
|
1760
|
+
* protect `RegExp` internal slots; leave that shape unfrozen for this function
|
|
1761
|
+
* to snapshot, or pass it through {@link cloneShape} first.
|
|
1762
|
+
*
|
|
1763
|
+
* Every compiler entry point (`compileSchema` / `compileGuard` /
|
|
1764
|
+
* `compileParser` / `compileGenerator` / `compileReporter`) opens with this
|
|
1765
|
+
* call, and the check applies per node as the recursion descends: a frozen
|
|
1766
|
+
* parent is trusted for its own fields while each child is owned again at its
|
|
1767
|
+
* own level, so a hand-assembled graph that froze only part of itself is still
|
|
1768
|
+
* compiled from owned data.
|
|
1769
|
+
*
|
|
1770
|
+
* @param shape - The contract shape to own
|
|
1771
|
+
* @returns The shape itself when frozen, otherwise a deeply cloned frozen snapshot
|
|
1325
1772
|
*
|
|
1326
1773
|
* @example
|
|
1327
1774
|
* ```ts
|
|
1328
|
-
* const
|
|
1329
|
-
*
|
|
1330
|
-
*
|
|
1775
|
+
* const authored = stringShape() // builders freeze
|
|
1776
|
+
* ownShape(authored) === authored // true
|
|
1777
|
+
* ownShape({ type: 'string' }) // a frozen snapshot — the literal is caller-owned
|
|
1331
1778
|
* ```
|
|
1332
1779
|
*/
|
|
1780
|
+
function ownShape(shape) {
|
|
1781
|
+
return Object.isFrozen(shape) ? shape : cloneShape(shape);
|
|
1782
|
+
}
|
|
1783
|
+
//#endregion
|
|
1784
|
+
//#region src/core/combinators.ts
|
|
1785
|
+
function arrayOf(elementGuard) {
|
|
1786
|
+
return (value) => holds(() => {
|
|
1787
|
+
if (!isArray(value)) return false;
|
|
1788
|
+
for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !elementGuard(value[index])) return false;
|
|
1789
|
+
return true;
|
|
1790
|
+
});
|
|
1791
|
+
}
|
|
1792
|
+
function tupleOf(...guards) {
|
|
1793
|
+
return (value) => holds(() => {
|
|
1794
|
+
if (!isArray(value)) return false;
|
|
1795
|
+
if (value.length !== guards.length) return false;
|
|
1796
|
+
for (let index = 0; index < guards.length; index += 1) {
|
|
1797
|
+
const guard = guards[index];
|
|
1798
|
+
if (!Object.hasOwn(value, index) || guard === void 0 || !guard(value[index])) return false;
|
|
1799
|
+
}
|
|
1800
|
+
return true;
|
|
1801
|
+
});
|
|
1802
|
+
}
|
|
1333
1803
|
function literalOf(...literals) {
|
|
1334
|
-
|
|
1804
|
+
const [first] = literals;
|
|
1805
|
+
const values = literals.length === 1 && isArray(first) ? first : literals;
|
|
1806
|
+
const allowed = new Set(values);
|
|
1807
|
+
return (value) => allowed.has(value);
|
|
1335
1808
|
}
|
|
1336
1809
|
/**
|
|
1337
1810
|
* Build a guard that accepts instances of the provided constructor.
|
|
@@ -1367,24 +1840,18 @@ function enumOf(enumeration) {
|
|
|
1367
1840
|
return (value) => (isString(value) || isNumber(value)) && values.has(value);
|
|
1368
1841
|
}
|
|
1369
1842
|
function setOf(elementGuard) {
|
|
1370
|
-
return (value) => {
|
|
1843
|
+
return (value) => holds(() => {
|
|
1371
1844
|
if (!isSet(value)) return false;
|
|
1372
|
-
const
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
});
|
|
1376
|
-
return outcome.success && outcome.value;
|
|
1377
|
-
};
|
|
1845
|
+
for (const entry of value) if (!elementGuard(entry)) return false;
|
|
1846
|
+
return true;
|
|
1847
|
+
});
|
|
1378
1848
|
}
|
|
1379
1849
|
function mapOf(keyGuard, valueGuard) {
|
|
1380
|
-
return (value) => {
|
|
1850
|
+
return (value) => holds(() => {
|
|
1381
1851
|
if (!isMap(value)) return false;
|
|
1382
|
-
const
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
});
|
|
1386
|
-
return outcome.success && outcome.value;
|
|
1387
|
-
};
|
|
1852
|
+
for (const [key, entryValue] of value) if (!keyGuard(key) || !valueGuard(entryValue)) return false;
|
|
1853
|
+
return true;
|
|
1854
|
+
});
|
|
1388
1855
|
}
|
|
1389
1856
|
/**
|
|
1390
1857
|
* Build a guard that accepts plain records matching a guard shape.
|
|
@@ -1398,9 +1865,8 @@ function mapOf(keyGuard, valueGuard) {
|
|
|
1398
1865
|
* Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by
|
|
1399
1866
|
* an inherited prototype member (`toString`, `constructor`, …) counts as absent.
|
|
1400
1867
|
* A non-object / `null` / array input returns `false` rather than throwing. The
|
|
1401
|
-
*
|
|
1402
|
-
*
|
|
1403
|
-
* matches the compiled guard.
|
|
1868
|
+
* The exactness check inspects every own string key, including non-enumerable
|
|
1869
|
+
* keys. Symbol keys are ignored intentionally for JSON fidelity.
|
|
1404
1870
|
*
|
|
1405
1871
|
* @example
|
|
1406
1872
|
* ```ts
|
|
@@ -1414,35 +1880,21 @@ function mapOf(keyGuard, valueGuard) {
|
|
|
1414
1880
|
*/
|
|
1415
1881
|
function recordOf(shape, optional) {
|
|
1416
1882
|
const allowed = /* @__PURE__ */ new Set();
|
|
1417
|
-
for (const key
|
|
1883
|
+
for (const key of Reflect.ownKeys(shape)) if (isString(key)) allowed.add(key);
|
|
1418
1884
|
const optionalSet = new Set(optional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : []);
|
|
1419
|
-
return (value) => {
|
|
1885
|
+
return (value) => holds(() => {
|
|
1420
1886
|
if (!isRecord(value)) return false;
|
|
1421
|
-
const
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
if (
|
|
1428
|
-
const guard = shape[key];
|
|
1429
|
-
if (!guard(value[key])) return false;
|
|
1430
|
-
}
|
|
1887
|
+
for (const key of Reflect.ownKeys(value)) if (isString(key) && !allowed.has(key)) return false;
|
|
1888
|
+
for (const key of allowed) {
|
|
1889
|
+
const present = Object.hasOwn(value, key);
|
|
1890
|
+
if (!optionalSet.has(key) && !present) return false;
|
|
1891
|
+
if (present) {
|
|
1892
|
+
const guard = shape[key];
|
|
1893
|
+
if (guard === void 0 || !guard(value[key])) return false;
|
|
1431
1894
|
}
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
};
|
|
1436
|
-
}
|
|
1437
|
-
function iterableOf(elementGuard) {
|
|
1438
|
-
return (value) => {
|
|
1439
|
-
if (!isIterable(value)) return false;
|
|
1440
|
-
const outcome = attempt(() => {
|
|
1441
|
-
for (const entry of value) if (!elementGuard(entry)) return false;
|
|
1442
|
-
return true;
|
|
1443
|
-
});
|
|
1444
|
-
return outcome.success && outcome.value;
|
|
1445
|
-
};
|
|
1895
|
+
}
|
|
1896
|
+
return true;
|
|
1897
|
+
});
|
|
1446
1898
|
}
|
|
1447
1899
|
/**
|
|
1448
1900
|
* Build a guard that accepts values that are own keys of the provided object.
|
|
@@ -1462,7 +1914,7 @@ function iterableOf(elementGuard) {
|
|
|
1462
1914
|
* ```
|
|
1463
1915
|
*/
|
|
1464
1916
|
function keyOf(value) {
|
|
1465
|
-
return (entry) => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry);
|
|
1917
|
+
return (entry) => holds(() => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry));
|
|
1466
1918
|
}
|
|
1467
1919
|
/**
|
|
1468
1920
|
* Build a new guard shape by keeping only the listed keys — the structural
|
|
@@ -1502,10 +1954,10 @@ function omitOf(shape, keys) {
|
|
|
1502
1954
|
return result;
|
|
1503
1955
|
}
|
|
1504
1956
|
function andOf(left, right) {
|
|
1505
|
-
return (value) => left(value) && right(value);
|
|
1957
|
+
return (value) => holds(() => left(value) && right(value));
|
|
1506
1958
|
}
|
|
1507
1959
|
function orOf(left, right) {
|
|
1508
|
-
return (value) => left(value) || right(value);
|
|
1960
|
+
return (value) => holds(() => left(value) || right(value));
|
|
1509
1961
|
}
|
|
1510
1962
|
/**
|
|
1511
1963
|
* Negate a guard or predicate — passes when `guard` returns `false`.
|
|
@@ -1520,7 +1972,7 @@ function orOf(left, right) {
|
|
|
1520
1972
|
* ```
|
|
1521
1973
|
*/
|
|
1522
1974
|
function notOf(guard) {
|
|
1523
|
-
return (value) => !guard(value);
|
|
1975
|
+
return (value) => holds(() => !guard(value));
|
|
1524
1976
|
}
|
|
1525
1977
|
/**
|
|
1526
1978
|
* Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass
|
|
@@ -1534,23 +1986,16 @@ function notOf(guard) {
|
|
|
1534
1986
|
* ```
|
|
1535
1987
|
*/
|
|
1536
1988
|
function complementOf(base, excluded) {
|
|
1537
|
-
return (value) =>
|
|
1538
|
-
if (!base(value)) return false;
|
|
1539
|
-
return !excluded(value);
|
|
1540
|
-
};
|
|
1989
|
+
return (value) => holds(() => base(value) && !excluded(value));
|
|
1541
1990
|
}
|
|
1542
1991
|
function unionOf(...guards) {
|
|
1543
|
-
return (value) => guards.some((guard) => guard(value));
|
|
1992
|
+
return (value) => holds(() => guards.some((guard) => guard(value)));
|
|
1544
1993
|
}
|
|
1545
1994
|
function intersectionOf(...guards) {
|
|
1546
|
-
return (value) => guards.every((guard) => guard(value));
|
|
1995
|
+
return (value) => holds(() => guards.every((guard) => guard(value)));
|
|
1547
1996
|
}
|
|
1548
1997
|
function whereOf(base, predicate) {
|
|
1549
|
-
return (value) =>
|
|
1550
|
-
if (!base(value)) return false;
|
|
1551
|
-
const outcome = attempt(() => predicate(value));
|
|
1552
|
-
return outcome.success && outcome.value;
|
|
1553
|
-
};
|
|
1998
|
+
return (value) => holds(() => base(value) && predicate(value));
|
|
1554
1999
|
}
|
|
1555
2000
|
/**
|
|
1556
2001
|
* Defer guard creation until first use by calling `thunk()` on every
|
|
@@ -1562,10 +2007,10 @@ function whereOf(base, predicate) {
|
|
|
1562
2007
|
* self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
|
|
1563
2008
|
* it resolves to) is contained and reported as a non-match.
|
|
1564
2009
|
*
|
|
1565
|
-
*
|
|
1566
|
-
*
|
|
1567
|
-
*
|
|
1568
|
-
*
|
|
2010
|
+
* Each lazy guard tracks its active invocation depth. An invocation that would
|
|
2011
|
+
* exceed {@link GUARD_DEPTH_LIMIT} returns `false` before resolving `thunk`; the
|
|
2012
|
+
* counter always unwinds after the contained call, so one deep or cyclic input
|
|
2013
|
+
* cannot poison later guard calls.
|
|
1569
2014
|
*
|
|
1570
2015
|
* @example
|
|
1571
2016
|
* ```ts
|
|
@@ -1575,17 +2020,19 @@ function whereOf(base, predicate) {
|
|
|
1575
2020
|
* ```
|
|
1576
2021
|
*/
|
|
1577
2022
|
function lazyOf(thunk) {
|
|
2023
|
+
let depth = 0;
|
|
1578
2024
|
return (value) => {
|
|
1579
|
-
|
|
1580
|
-
|
|
2025
|
+
if (depth >= 512) return false;
|
|
2026
|
+
depth += 1;
|
|
2027
|
+
try {
|
|
2028
|
+
return holds(() => thunk()(value));
|
|
2029
|
+
} finally {
|
|
2030
|
+
depth -= 1;
|
|
2031
|
+
}
|
|
1581
2032
|
};
|
|
1582
2033
|
}
|
|
1583
2034
|
function transformOf(base, project, target) {
|
|
1584
|
-
return (value) =>
|
|
1585
|
-
if (!base(value)) return false;
|
|
1586
|
-
const outcome = attempt(() => project(value));
|
|
1587
|
-
return outcome.success && target(outcome.value);
|
|
1588
|
-
};
|
|
2035
|
+
return (value) => holds(() => base(value) && target(project(value)));
|
|
1589
2036
|
}
|
|
1590
2037
|
/**
|
|
1591
2038
|
* Build a guard that accepts finite numbers within an inclusive `[min, max]`
|
|
@@ -1615,6 +2062,13 @@ function boundsOf(min, max) {
|
|
|
1615
2062
|
/**
|
|
1616
2063
|
* Build a guard that accepts strings matching a regular expression.
|
|
1617
2064
|
*
|
|
2065
|
+
* @remarks
|
|
2066
|
+
* Clones the pattern for the guard and strips the stateful `g` / `y` flags, so
|
|
2067
|
+
* repeated checks are stable and never change the caller's `lastIndex`.
|
|
2068
|
+
*
|
|
2069
|
+
* @param pattern - The regular expression to own and apply
|
|
2070
|
+
* @returns A stateless string guard
|
|
2071
|
+
*
|
|
1618
2072
|
* @example
|
|
1619
2073
|
* ```ts
|
|
1620
2074
|
* const isHex = matchOf(/^[0-9a-f]+$/)
|
|
@@ -1623,7 +2077,8 @@ function boundsOf(min, max) {
|
|
|
1623
2077
|
* ```
|
|
1624
2078
|
*/
|
|
1625
2079
|
function matchOf(pattern) {
|
|
1626
|
-
|
|
2080
|
+
const owned = new RegExp(pattern.source, pattern.flags.replaceAll("g", "").replaceAll("y", ""));
|
|
2081
|
+
return whereOf(isString, (value) => owned.test(value));
|
|
1627
2082
|
}
|
|
1628
2083
|
/**
|
|
1629
2084
|
* Build a guard that accepts strings satisfying optional length and pattern
|
|
@@ -1631,10 +2086,14 @@ function matchOf(pattern) {
|
|
|
1631
2086
|
*
|
|
1632
2087
|
* @remarks
|
|
1633
2088
|
* Composes {@link isString} with {@link boundsOf} on the string's `.length` and
|
|
1634
|
-
* an
|
|
1635
|
-
* the bare {@link isString} guard
|
|
1636
|
-
* unrefined string leaf pays no wrapping
|
|
1637
|
-
* refinement shared by the compiled guard
|
|
2089
|
+
* an owned stateless pattern (the same refinement {@link matchOf} performs).
|
|
2090
|
+
* When all three options are absent it returns the bare {@link isString} guard
|
|
2091
|
+
* (the unconstrained fast path), so an unrefined string leaf pays no wrapping
|
|
2092
|
+
* cost. The single source of the string refinement shared by the compiled guard
|
|
2093
|
+
* and parser (compilers.ts).
|
|
2094
|
+
*
|
|
2095
|
+
* @param options - Optional length bounds and regular expression refinement
|
|
2096
|
+
* @returns A string guard enforcing the requested refinements
|
|
1638
2097
|
*
|
|
1639
2098
|
* @example
|
|
1640
2099
|
* ```ts
|
|
@@ -1649,7 +2108,8 @@ function matchOf(pattern) {
|
|
|
1649
2108
|
function stringOf(options) {
|
|
1650
2109
|
const min = options?.min;
|
|
1651
2110
|
const max = options?.max;
|
|
1652
|
-
const
|
|
2111
|
+
const source = options?.pattern;
|
|
2112
|
+
const pattern = source === void 0 ? void 0 : new RegExp(source.source, source.flags.replaceAll("g", "").replaceAll("y", ""));
|
|
1653
2113
|
if (min === void 0 && max === void 0 && pattern === void 0) return isString;
|
|
1654
2114
|
const withinLength = boundsOf(min, max);
|
|
1655
2115
|
return whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || pattern.test(value)));
|
|
@@ -1666,7 +2126,7 @@ function stringOf(options) {
|
|
|
1666
2126
|
* ```
|
|
1667
2127
|
*/
|
|
1668
2128
|
function nullableOf(guard) {
|
|
1669
|
-
return (value) => value === null || guard(value);
|
|
2129
|
+
return (value) => holds(() => value === null || guard(value));
|
|
1670
2130
|
}
|
|
1671
2131
|
/**
|
|
1672
2132
|
* Extend a guard to also allow `undefined` — the optional counterpart of
|
|
@@ -1681,7 +2141,7 @@ function nullableOf(guard) {
|
|
|
1681
2141
|
* ```
|
|
1682
2142
|
*/
|
|
1683
2143
|
function optionalOf(guard) {
|
|
1684
|
-
return (value) => value === void 0 || guard(value);
|
|
2144
|
+
return (value) => holds(() => value === void 0 || guard(value));
|
|
1685
2145
|
}
|
|
1686
2146
|
//#endregion
|
|
1687
2147
|
//#region src/core/parsers.ts
|
|
@@ -1825,7 +2285,10 @@ function parseRecord(value) {
|
|
|
1825
2285
|
*/
|
|
1826
2286
|
function parseArray(value, guard) {
|
|
1827
2287
|
if (!isArray(value)) return void 0;
|
|
1828
|
-
if (guard !== void 0 && !
|
|
2288
|
+
if (guard !== void 0 && !holds(() => {
|
|
2289
|
+
for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !guard(value[index])) return false;
|
|
2290
|
+
return true;
|
|
2291
|
+
})) return;
|
|
1829
2292
|
return value;
|
|
1830
2293
|
}
|
|
1831
2294
|
/**
|
|
@@ -1852,27 +2315,10 @@ function parseArray(value, guard) {
|
|
|
1852
2315
|
function parseJSONValue(value) {
|
|
1853
2316
|
return isJSONValue(value) ? value : void 0;
|
|
1854
2317
|
}
|
|
1855
|
-
/**
|
|
1856
|
-
* Parse an unknown value as one of the allowed literal primitives.
|
|
1857
|
-
*
|
|
1858
|
-
* @remarks
|
|
1859
|
-
* Pairs with {@link literalOf} — both match by `Object.is`, so the
|
|
1860
|
-
* `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
|
|
1861
|
-
* (string, number, or boolean), not only strings. Matching is identity, never
|
|
1862
|
-
* cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
|
|
1863
|
-
*
|
|
1864
|
-
* @param value - The value to parse
|
|
1865
|
-
* @param allowed - The permitted literal values
|
|
1866
|
-
* @returns The matched literal (by identity), or `undefined`
|
|
1867
|
-
*
|
|
1868
|
-
* @example
|
|
1869
|
-
* ```ts
|
|
1870
|
-
* parseEnum('b', ['a', 'b', 'c']) // 'b'
|
|
1871
|
-
* parseEnum('z', ['a', 'b', 'c']) // undefined
|
|
1872
|
-
* ```
|
|
1873
|
-
*/
|
|
1874
2318
|
function parseEnum(value, allowed) {
|
|
1875
|
-
|
|
2319
|
+
const outcome = attempt(() => Object.freeze(new Set(allowed)));
|
|
2320
|
+
if (!outcome.success || !outcome.value.has(value)) return void 0;
|
|
2321
|
+
return isString(value) || isNumber(value) || isBoolean(value) ? value : void 0;
|
|
1876
2322
|
}
|
|
1877
2323
|
/**
|
|
1878
2324
|
* Read and parse a string field from a record by key or nested key path.
|
|
@@ -2050,18 +2496,119 @@ function parseJSON(value) {
|
|
|
2050
2496
|
function parseJSONAs(value, guard) {
|
|
2051
2497
|
const parsed = parseJSON(value);
|
|
2052
2498
|
if (parsed === void 0) return void 0;
|
|
2053
|
-
|
|
2499
|
+
let result = void 0;
|
|
2500
|
+
holds(() => {
|
|
2501
|
+
if (!guard(parsed)) return false;
|
|
2502
|
+
result = parsed;
|
|
2503
|
+
return true;
|
|
2504
|
+
});
|
|
2505
|
+
return result;
|
|
2054
2506
|
}
|
|
2055
2507
|
//#endregion
|
|
2056
2508
|
//#region src/core/compilers.ts
|
|
2057
2509
|
/**
|
|
2058
|
-
*
|
|
2059
|
-
*
|
|
2510
|
+
* Gate recursive compiler work on shape depth and structural cycles.
|
|
2511
|
+
*
|
|
2512
|
+
* @remarks
|
|
2513
|
+
* Walks the shape graph iteratively in linear time and stack space, tracking
|
|
2514
|
+
* active ancestors so shared children remain legal. Every standalone compiler
|
|
2515
|
+
* calls this gate before its recursive branch begins. The depth check runs
|
|
2516
|
+
* before the active-ancestor check, so a back-edge first reached beyond
|
|
2517
|
+
* {@link COMPILE_DEPTH_LIMIT} reports `depth`; a shallower cycle reports
|
|
2518
|
+
* `cycle`.
|
|
2519
|
+
*
|
|
2520
|
+
* @param shape - The shape graph to gate
|
|
2521
|
+
* @returns Nothing; successful return means recursive compilation is depth-safe
|
|
2522
|
+
* @throws {ContractError} When the shape is cyclic or exceeds the compilation depth limit
|
|
2523
|
+
*/
|
|
2524
|
+
function validateShapeDepth(shape) {
|
|
2525
|
+
const active = /* @__PURE__ */ new WeakSet();
|
|
2526
|
+
const stack = [{
|
|
2527
|
+
operation: "enter",
|
|
2528
|
+
shape,
|
|
2529
|
+
depth: 0
|
|
2530
|
+
}];
|
|
2531
|
+
while (stack.length > 0) {
|
|
2532
|
+
const frame = stack.pop();
|
|
2533
|
+
if (frame === void 0) continue;
|
|
2534
|
+
if (frame.operation === "exit") {
|
|
2535
|
+
active.delete(frame.shape);
|
|
2536
|
+
continue;
|
|
2537
|
+
}
|
|
2538
|
+
const current = frame.shape;
|
|
2539
|
+
if (frame.depth > 512) throw new ContractError("validateShapeDepth: a shape exceeds the compilation depth limit", {
|
|
2540
|
+
code: "depth",
|
|
2541
|
+
context: {
|
|
2542
|
+
shape: current.type,
|
|
2543
|
+
limit: 512
|
|
2544
|
+
}
|
|
2545
|
+
});
|
|
2546
|
+
if (active.has(current)) throw new ContractError("validateShapeDepth: a shape graph may not contain a cycle", { code: "cycle" });
|
|
2547
|
+
active.add(current);
|
|
2548
|
+
stack.push({
|
|
2549
|
+
operation: "exit",
|
|
2550
|
+
shape: current
|
|
2551
|
+
});
|
|
2552
|
+
switch (current.type) {
|
|
2553
|
+
case "array":
|
|
2554
|
+
stack.push({
|
|
2555
|
+
operation: "enter",
|
|
2556
|
+
shape: current.items,
|
|
2557
|
+
depth: frame.depth + 1
|
|
2558
|
+
});
|
|
2559
|
+
break;
|
|
2560
|
+
case "object": {
|
|
2561
|
+
const extra = current.additionalProperties;
|
|
2562
|
+
if (extra !== void 0 && extra !== true && extra !== false) stack.push({
|
|
2563
|
+
operation: "enter",
|
|
2564
|
+
shape: extra,
|
|
2565
|
+
depth: frame.depth + 1
|
|
2566
|
+
});
|
|
2567
|
+
const keys = Object.keys(current.properties);
|
|
2568
|
+
for (let index = keys.length - 1; index >= 0; index -= 1) {
|
|
2569
|
+
const key = keys[index];
|
|
2570
|
+
if (key === void 0) continue;
|
|
2571
|
+
const child = current.properties[key];
|
|
2572
|
+
if (child !== void 0) stack.push({
|
|
2573
|
+
operation: "enter",
|
|
2574
|
+
shape: child,
|
|
2575
|
+
depth: frame.depth + 1
|
|
2576
|
+
});
|
|
2577
|
+
}
|
|
2578
|
+
break;
|
|
2579
|
+
}
|
|
2580
|
+
case "union":
|
|
2581
|
+
for (let index = current.variants.length - 1; index >= 0; index -= 1) {
|
|
2582
|
+
const variant = current.variants[index];
|
|
2583
|
+
if (variant !== void 0) stack.push({
|
|
2584
|
+
operation: "enter",
|
|
2585
|
+
shape: variant,
|
|
2586
|
+
depth: frame.depth + 1
|
|
2587
|
+
});
|
|
2588
|
+
}
|
|
2589
|
+
break;
|
|
2590
|
+
case "optional":
|
|
2591
|
+
case "nullable":
|
|
2592
|
+
stack.push({
|
|
2593
|
+
operation: "enter",
|
|
2594
|
+
shape: current.inner,
|
|
2595
|
+
depth: frame.depth + 1
|
|
2596
|
+
});
|
|
2597
|
+
break;
|
|
2598
|
+
default: break;
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2603
|
+
* Validate that a {@link ContractShape} graph is well-formed before
|
|
2604
|
+
* compilation.
|
|
2060
2605
|
*
|
|
2061
2606
|
* @remarks
|
|
2062
2607
|
* Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
|
|
2063
|
-
* throws a
|
|
2064
|
-
* guard, parser, schema, or generator later.
|
|
2608
|
+
* throws a coded {@link ContractError} immediately rather than surfacing as a
|
|
2609
|
+
* silently-wrong guard, parser, schema, or generator later. The iterative walk
|
|
2610
|
+
* tracks active ancestors, so a structural cycle reports its precise path while
|
|
2611
|
+
* a shared child reached through separate paths remains legal. Checks:
|
|
2065
2612
|
*
|
|
2066
2613
|
* - An {@link OptionalShape} is only legal as a direct object-property value —
|
|
2067
2614
|
* `optionalShape` wrapping an array item, a union variant, another
|
|
@@ -2074,14 +2621,19 @@ function parseJSONAs(value, guard) {
|
|
|
2074
2621
|
* `-Infinity`) number values.
|
|
2075
2622
|
* - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
|
|
2076
2623
|
* needs `min <= max` when both are set.
|
|
2624
|
+
* - Every present number bound is finite.
|
|
2077
2625
|
* - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
|
|
2078
2626
|
* range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
|
|
2627
|
+
* - Shape nesting may not exceed {@link COMPILE_DEPTH_LIMIT}; excessive depth
|
|
2628
|
+
* fails before recursive artifact compilation begins. Because the depth check
|
|
2629
|
+
* runs before the active-ancestor check, a back-edge first reached beyond the
|
|
2630
|
+
* limit reports `depth`; a cycle reached within the limit reports `cycle`.
|
|
2079
2631
|
* - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
|
|
2080
2632
|
* continues into array items, object properties (and `additionalProperties`
|
|
2081
2633
|
* when it is a shape), union variants, and optional/nullable inner shapes.
|
|
2082
2634
|
*
|
|
2083
2635
|
* @param shape - The shape to validate
|
|
2084
|
-
* @throws {
|
|
2636
|
+
* @throws {ContractError} When the shape is malformed or cyclic
|
|
2085
2637
|
*
|
|
2086
2638
|
* @example
|
|
2087
2639
|
* ```ts
|
|
@@ -2090,46 +2642,201 @@ function parseJSONAs(value, guard) {
|
|
|
2090
2642
|
* ```
|
|
2091
2643
|
*/
|
|
2092
2644
|
function validateShape(shape) {
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2645
|
+
const active = /* @__PURE__ */ new WeakSet();
|
|
2646
|
+
const stack = [{
|
|
2647
|
+
operation: "enter",
|
|
2648
|
+
shape,
|
|
2649
|
+
path: [],
|
|
2650
|
+
optional: false,
|
|
2651
|
+
depth: 0
|
|
2652
|
+
}];
|
|
2653
|
+
while (stack.length > 0) {
|
|
2654
|
+
const frame = stack.pop();
|
|
2655
|
+
if (frame === void 0) continue;
|
|
2656
|
+
if (frame.operation === "exit") {
|
|
2657
|
+
active.delete(frame.shape);
|
|
2658
|
+
continue;
|
|
2659
|
+
}
|
|
2660
|
+
const current = frame.shape;
|
|
2661
|
+
if (frame.depth > 512) throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
|
|
2662
|
+
code: "depth",
|
|
2663
|
+
context: {
|
|
2664
|
+
path: frame.path,
|
|
2665
|
+
shape: current.type,
|
|
2666
|
+
limit: 512
|
|
2101
2667
|
}
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2668
|
+
});
|
|
2669
|
+
if (active.has(current)) throw new ContractError("validateShape: a shape graph may not contain a cycle", {
|
|
2670
|
+
code: "cycle",
|
|
2671
|
+
context: { path: frame.path }
|
|
2672
|
+
});
|
|
2673
|
+
active.add(current);
|
|
2674
|
+
stack.push({
|
|
2675
|
+
operation: "exit",
|
|
2676
|
+
shape: current
|
|
2677
|
+
});
|
|
2678
|
+
switch (current.type) {
|
|
2679
|
+
case "string":
|
|
2680
|
+
if (current.min !== void 0 && current.max !== void 0 && current.min > current.max) throw new ContractError("validateShape: a string shape has min greater than max", {
|
|
2681
|
+
code: "range",
|
|
2682
|
+
context: {
|
|
2683
|
+
path: frame.path,
|
|
2684
|
+
shape: "string"
|
|
2685
|
+
}
|
|
2686
|
+
});
|
|
2687
|
+
break;
|
|
2688
|
+
case "number":
|
|
2689
|
+
if (current.min !== void 0 && !Number.isFinite(current.min)) throw new ContractError("validateShape: a number shape min must be finite", {
|
|
2690
|
+
code: "bound",
|
|
2691
|
+
context: {
|
|
2692
|
+
path: frame.path,
|
|
2693
|
+
shape: current.integer === true ? "integer" : "number",
|
|
2694
|
+
limit: "finite number",
|
|
2695
|
+
received: String(current.min)
|
|
2696
|
+
}
|
|
2697
|
+
});
|
|
2698
|
+
if (current.max !== void 0 && !Number.isFinite(current.max)) throw new ContractError("validateShape: a number shape max must be finite", {
|
|
2699
|
+
code: "bound",
|
|
2700
|
+
context: {
|
|
2701
|
+
path: frame.path,
|
|
2702
|
+
shape: current.integer === true ? "integer" : "number",
|
|
2703
|
+
limit: "finite number",
|
|
2704
|
+
received: String(current.max)
|
|
2705
|
+
}
|
|
2706
|
+
});
|
|
2707
|
+
if (current.min !== void 0 && current.max !== void 0 && current.min > current.max) throw new ContractError("validateShape: a number shape has min greater than max", {
|
|
2708
|
+
code: "range",
|
|
2709
|
+
context: {
|
|
2710
|
+
path: frame.path,
|
|
2711
|
+
shape: current.integer === true ? "integer" : "number"
|
|
2712
|
+
}
|
|
2713
|
+
});
|
|
2714
|
+
if (current.integer === true) {
|
|
2715
|
+
if (Math.ceil(current.min ?? Number.NEGATIVE_INFINITY) > Math.floor(current.max ?? Number.POSITIVE_INFINITY)) throw new ContractError("validateShape: an integer number shape has an empty integer range", {
|
|
2716
|
+
code: "range",
|
|
2717
|
+
context: {
|
|
2718
|
+
path: frame.path,
|
|
2719
|
+
shape: "integer"
|
|
2720
|
+
}
|
|
2721
|
+
});
|
|
2722
|
+
}
|
|
2723
|
+
break;
|
|
2724
|
+
case "boolean":
|
|
2725
|
+
case "null":
|
|
2726
|
+
case "json":
|
|
2727
|
+
case "raw": break;
|
|
2728
|
+
case "literal":
|
|
2729
|
+
if (current.values.length === 0) throw new ContractError("validateShape: a literal shape needs at least one value", {
|
|
2730
|
+
code: "empty",
|
|
2731
|
+
context: {
|
|
2732
|
+
path: frame.path,
|
|
2733
|
+
shape: "literal"
|
|
2734
|
+
}
|
|
2735
|
+
});
|
|
2736
|
+
for (const value of current.values) if (typeof value === "number" && !Number.isFinite(value)) throw new ContractError("validateShape: a literal shape may not contain non-finite number values", {
|
|
2737
|
+
code: "literal",
|
|
2738
|
+
context: {
|
|
2739
|
+
path: frame.path,
|
|
2740
|
+
shape: "literal",
|
|
2741
|
+
received: String(value)
|
|
2742
|
+
}
|
|
2743
|
+
});
|
|
2744
|
+
break;
|
|
2745
|
+
case "array":
|
|
2746
|
+
if (current.min !== void 0 && current.max !== void 0 && current.min > current.max) throw new ContractError("validateShape: an array shape has min greater than max", {
|
|
2747
|
+
code: "range",
|
|
2748
|
+
context: {
|
|
2749
|
+
path: frame.path,
|
|
2750
|
+
shape: "array"
|
|
2751
|
+
}
|
|
2752
|
+
});
|
|
2753
|
+
stack.push({
|
|
2754
|
+
operation: "enter",
|
|
2755
|
+
shape: current.items,
|
|
2756
|
+
path: [...frame.path, "items"],
|
|
2757
|
+
optional: false,
|
|
2758
|
+
depth: frame.depth + 1
|
|
2759
|
+
});
|
|
2760
|
+
break;
|
|
2761
|
+
case "object": {
|
|
2762
|
+
const extra = current.additionalProperties;
|
|
2763
|
+
if (extra !== void 0 && extra !== true && extra !== false) stack.push({
|
|
2764
|
+
operation: "enter",
|
|
2765
|
+
shape: extra,
|
|
2766
|
+
path: [...frame.path, "additionalProperties"],
|
|
2767
|
+
optional: false,
|
|
2768
|
+
depth: frame.depth + 1
|
|
2769
|
+
});
|
|
2770
|
+
const keys = Object.keys(current.properties);
|
|
2771
|
+
for (let index = keys.length - 1; index >= 0; index -= 1) {
|
|
2772
|
+
const key = keys[index];
|
|
2773
|
+
if (key === void 0) continue;
|
|
2774
|
+
const child = current.properties[key];
|
|
2775
|
+
if (child === void 0) continue;
|
|
2776
|
+
stack.push({
|
|
2777
|
+
operation: "enter",
|
|
2778
|
+
shape: child,
|
|
2779
|
+
path: [
|
|
2780
|
+
...frame.path,
|
|
2781
|
+
"properties",
|
|
2782
|
+
key
|
|
2783
|
+
],
|
|
2784
|
+
optional: true,
|
|
2785
|
+
depth: frame.depth + 1
|
|
2786
|
+
});
|
|
2787
|
+
}
|
|
2788
|
+
break;
|
|
2120
2789
|
}
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2790
|
+
case "union":
|
|
2791
|
+
if (current.variants.length === 0) throw new ContractError("validateShape: a union shape needs at least one variant", {
|
|
2792
|
+
code: "empty",
|
|
2793
|
+
context: {
|
|
2794
|
+
path: frame.path,
|
|
2795
|
+
shape: "union"
|
|
2796
|
+
}
|
|
2797
|
+
});
|
|
2798
|
+
for (let index = current.variants.length - 1; index >= 0; index -= 1) {
|
|
2799
|
+
const variant = current.variants[index];
|
|
2800
|
+
if (variant === void 0) continue;
|
|
2801
|
+
stack.push({
|
|
2802
|
+
operation: "enter",
|
|
2803
|
+
shape: variant,
|
|
2804
|
+
path: [
|
|
2805
|
+
...frame.path,
|
|
2806
|
+
"variants",
|
|
2807
|
+
String(index)
|
|
2808
|
+
],
|
|
2809
|
+
optional: false,
|
|
2810
|
+
depth: frame.depth + 1
|
|
2811
|
+
});
|
|
2812
|
+
}
|
|
2813
|
+
break;
|
|
2814
|
+
case "optional":
|
|
2815
|
+
if (!frame.optional) throw new ContractError("validateShape: an optional shape may only appear as a direct object-property value", {
|
|
2816
|
+
code: "placement",
|
|
2817
|
+
context: {
|
|
2818
|
+
path: frame.path,
|
|
2819
|
+
shape: "optional"
|
|
2820
|
+
}
|
|
2821
|
+
});
|
|
2822
|
+
stack.push({
|
|
2823
|
+
operation: "enter",
|
|
2824
|
+
shape: current.inner,
|
|
2825
|
+
path: [...frame.path, "inner"],
|
|
2826
|
+
optional: false,
|
|
2827
|
+
depth: frame.depth + 1
|
|
2828
|
+
});
|
|
2829
|
+
break;
|
|
2830
|
+
case "nullable":
|
|
2831
|
+
stack.push({
|
|
2832
|
+
operation: "enter",
|
|
2833
|
+
shape: current.inner,
|
|
2834
|
+
path: [...frame.path, "inner"],
|
|
2835
|
+
optional: false,
|
|
2836
|
+
depth: frame.depth + 1
|
|
2837
|
+
});
|
|
2838
|
+
break;
|
|
2124
2839
|
}
|
|
2125
|
-
case "union":
|
|
2126
|
-
if (shape.variants.length === 0) throw new Error("validateShape: a union shape needs at least one variant");
|
|
2127
|
-
for (const variant of shape.variants) validateShape(variant);
|
|
2128
|
-
return;
|
|
2129
|
-
case "optional": throw new Error("validateShape: an optional shape may only appear as a direct object-property value");
|
|
2130
|
-
case "nullable":
|
|
2131
|
-
validateShape(shape.inner);
|
|
2132
|
-
return;
|
|
2133
2840
|
}
|
|
2134
2841
|
}
|
|
2135
2842
|
/**
|
|
@@ -2138,7 +2845,10 @@ function validateShape(shape) {
|
|
|
2138
2845
|
* @remarks
|
|
2139
2846
|
* Object shapes emit `additionalProperties: false` (unless opened) and list only
|
|
2140
2847
|
* required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
|
|
2141
|
-
* 'null' }`.
|
|
2848
|
+
* 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned
|
|
2849
|
+
* rather than retained by reference. Emission only — it never inspects a
|
|
2850
|
+
* runtime value. {@link validateShapeDepth} iteratively rejects excessive
|
|
2851
|
+
* nesting or cycles before recursive emission begins.
|
|
2142
2852
|
*
|
|
2143
2853
|
* @param shape - The shape to compile
|
|
2144
2854
|
* @returns The emitted JSON Schema
|
|
@@ -2149,114 +2859,122 @@ function validateShape(shape) {
|
|
|
2149
2859
|
* ```
|
|
2150
2860
|
*/
|
|
2151
2861
|
function compileSchema(shape) {
|
|
2152
|
-
|
|
2153
|
-
|
|
2862
|
+
const owned = ownShape(shape);
|
|
2863
|
+
validateShapeDepth(owned);
|
|
2864
|
+
switch (owned.type) {
|
|
2865
|
+
case "string": return Object.freeze({
|
|
2154
2866
|
type: "string",
|
|
2155
|
-
...
|
|
2156
|
-
...
|
|
2157
|
-
...
|
|
2158
|
-
...
|
|
2159
|
-
};
|
|
2160
|
-
case "number": return {
|
|
2161
|
-
type:
|
|
2162
|
-
...
|
|
2163
|
-
...
|
|
2164
|
-
...
|
|
2165
|
-
};
|
|
2166
|
-
case "boolean": return {
|
|
2867
|
+
...owned.min !== void 0 ? { minLength: owned.min } : {},
|
|
2868
|
+
...owned.max !== void 0 ? { maxLength: owned.max } : {},
|
|
2869
|
+
...owned.pattern !== void 0 ? { pattern: owned.pattern.source } : {},
|
|
2870
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2871
|
+
});
|
|
2872
|
+
case "number": return Object.freeze({
|
|
2873
|
+
type: owned.integer === true ? "integer" : "number",
|
|
2874
|
+
...owned.min !== void 0 ? { minimum: owned.min } : {},
|
|
2875
|
+
...owned.max !== void 0 ? { maximum: owned.max } : {},
|
|
2876
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2877
|
+
});
|
|
2878
|
+
case "boolean": return Object.freeze({
|
|
2167
2879
|
type: "boolean",
|
|
2168
|
-
...
|
|
2169
|
-
};
|
|
2170
|
-
case "null": return {
|
|
2880
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2881
|
+
});
|
|
2882
|
+
case "null": return Object.freeze({
|
|
2171
2883
|
type: "null",
|
|
2172
|
-
...
|
|
2173
|
-
};
|
|
2174
|
-
case "json": return { ...
|
|
2175
|
-
case "literal": return {
|
|
2176
|
-
enum: [...
|
|
2177
|
-
...
|
|
2178
|
-
};
|
|
2179
|
-
case "array": return {
|
|
2884
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2885
|
+
});
|
|
2886
|
+
case "json": return Object.freeze({ ...owned.description !== void 0 ? { description: owned.description } : {} });
|
|
2887
|
+
case "literal": return Object.freeze({
|
|
2888
|
+
enum: Object.freeze([...owned.values]),
|
|
2889
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2890
|
+
});
|
|
2891
|
+
case "array": return Object.freeze({
|
|
2180
2892
|
type: "array",
|
|
2181
|
-
items: compileSchema(
|
|
2182
|
-
...
|
|
2183
|
-
...
|
|
2184
|
-
...
|
|
2185
|
-
};
|
|
2893
|
+
items: compileSchema(owned.items),
|
|
2894
|
+
...owned.min !== void 0 ? { minItems: owned.min } : {},
|
|
2895
|
+
...owned.max !== void 0 ? { maxItems: owned.max } : {},
|
|
2896
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2897
|
+
});
|
|
2186
2898
|
case "object": {
|
|
2187
|
-
const properties =
|
|
2899
|
+
const properties = Object.create(null);
|
|
2188
2900
|
const required = [];
|
|
2189
|
-
for (const key of Object.keys(
|
|
2190
|
-
const child =
|
|
2901
|
+
for (const key of Object.keys(owned.properties)) {
|
|
2902
|
+
const child = owned.properties[key];
|
|
2191
2903
|
if (child === void 0) continue;
|
|
2192
2904
|
properties[key] = compileSchema(child);
|
|
2193
2905
|
if (child.type !== "optional") required.push(key);
|
|
2194
2906
|
}
|
|
2195
|
-
const extra =
|
|
2907
|
+
const extra = owned.additionalProperties;
|
|
2196
2908
|
const additionalProperties = extra === true ? true : extra !== void 0 && extra !== false ? compileSchema(extra) : false;
|
|
2197
|
-
return {
|
|
2909
|
+
return Object.freeze({
|
|
2198
2910
|
type: "object",
|
|
2199
|
-
...Object.keys(properties).length > 0 ? { properties } : {},
|
|
2200
|
-
...required.length > 0 ? { required } : {},
|
|
2911
|
+
...Object.keys(properties).length > 0 ? { properties: Object.freeze(properties) } : {},
|
|
2912
|
+
...required.length > 0 ? { required: Object.freeze(required) } : {},
|
|
2201
2913
|
additionalProperties,
|
|
2202
|
-
...
|
|
2203
|
-
};
|
|
2914
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2915
|
+
});
|
|
2204
2916
|
}
|
|
2205
|
-
case "union": return {
|
|
2206
|
-
...
|
|
2207
|
-
...
|
|
2208
|
-
};
|
|
2209
|
-
case "optional": return compileSchema(
|
|
2210
|
-
case "nullable": return { anyOf: [compileSchema(
|
|
2211
|
-
case "raw": return
|
|
2917
|
+
case "union": return Object.freeze({
|
|
2918
|
+
...owned.mode === "oneOf" ? { oneOf: Object.freeze(owned.variants.map((variant) => compileSchema(variant))) } : { anyOf: Object.freeze(owned.variants.map((variant) => compileSchema(variant))) },
|
|
2919
|
+
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
2920
|
+
});
|
|
2921
|
+
case "optional": return compileSchema(owned.inner);
|
|
2922
|
+
case "nullable": return Object.freeze({ anyOf: Object.freeze([compileSchema(owned.inner), Object.freeze({ type: "null" })]) });
|
|
2923
|
+
case "raw": return cloneSchema(owned.schema);
|
|
2212
2924
|
}
|
|
2213
2925
|
}
|
|
2214
2926
|
function compileGuard(shape) {
|
|
2215
|
-
|
|
2927
|
+
const owned = ownShape(shape);
|
|
2928
|
+
validateShapeDepth(owned);
|
|
2929
|
+
switch (owned.type) {
|
|
2216
2930
|
case "string": return stringOf({
|
|
2217
|
-
min:
|
|
2218
|
-
max:
|
|
2219
|
-
pattern:
|
|
2931
|
+
...owned.min === void 0 ? {} : { min: owned.min },
|
|
2932
|
+
...owned.max === void 0 ? {} : { max: owned.max },
|
|
2933
|
+
...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
|
|
2220
2934
|
});
|
|
2221
2935
|
case "number": {
|
|
2222
|
-
const base =
|
|
2223
|
-
if (
|
|
2224
|
-
return
|
|
2936
|
+
const base = owned.integer === true ? isInteger : isFiniteNumber;
|
|
2937
|
+
if (owned.min === void 0 && owned.max === void 0) return base;
|
|
2938
|
+
return owned.integer === true ? intersectionOf(isInteger, boundsOf(owned.min, owned.max)) : boundsOf(owned.min, owned.max);
|
|
2225
2939
|
}
|
|
2226
2940
|
case "boolean": return isBoolean;
|
|
2227
2941
|
case "null": return isNull;
|
|
2228
2942
|
case "json": return isJSONValue;
|
|
2229
|
-
case "literal": return literalOf(
|
|
2943
|
+
case "literal": return literalOf(owned.values);
|
|
2230
2944
|
case "array": {
|
|
2231
|
-
const base = arrayOf(compileGuard(
|
|
2232
|
-
if (
|
|
2233
|
-
const withinLength = boundsOf(
|
|
2945
|
+
const base = arrayOf(compileGuard(owned.items));
|
|
2946
|
+
if (owned.min === void 0 && owned.max === void 0) return base;
|
|
2947
|
+
const withinLength = boundsOf(owned.min, owned.max);
|
|
2234
2948
|
return whereOf(base, (value) => withinLength(value.length));
|
|
2235
2949
|
}
|
|
2236
2950
|
case "object": {
|
|
2237
2951
|
const map = Object.create(null);
|
|
2238
2952
|
const optionalKeys = [];
|
|
2239
|
-
for (const key of Object.keys(
|
|
2240
|
-
const child =
|
|
2953
|
+
for (const key of Object.keys(owned.properties)) {
|
|
2954
|
+
const child = owned.properties[key];
|
|
2241
2955
|
if (child === void 0) continue;
|
|
2242
2956
|
if (child.type === "optional") {
|
|
2243
2957
|
map[key] = compileGuard(child.inner);
|
|
2244
2958
|
optionalKeys.push(key);
|
|
2245
2959
|
} else map[key] = compileGuard(child);
|
|
2246
2960
|
}
|
|
2247
|
-
const extra =
|
|
2248
|
-
|
|
2249
|
-
const additional = extra === true ? void 0 : compileGuard(extra);
|
|
2961
|
+
const extra = owned.additionalProperties;
|
|
2962
|
+
const closed = extra === void 0 || extra === false;
|
|
2963
|
+
const additional = closed || extra === true ? void 0 : compileGuard(extra);
|
|
2250
2964
|
const required = Object.keys(map).filter((key) => !optionalKeys.includes(key));
|
|
2251
2965
|
return (value) => {
|
|
2252
2966
|
if (!isRecord(value)) return false;
|
|
2253
|
-
|
|
2967
|
+
const keys = enumerableKeys(value);
|
|
2968
|
+
if (keys === void 0) return false;
|
|
2969
|
+
const present = new Set(keys);
|
|
2970
|
+
for (const key of required) if (!present.has(key)) return false;
|
|
2254
2971
|
const outcome = attempt(() => {
|
|
2255
|
-
for (const key of
|
|
2972
|
+
for (const key of keys) {
|
|
2256
2973
|
const guard = Object.hasOwn(map, key) ? map[key] : void 0;
|
|
2257
2974
|
if (guard !== void 0) {
|
|
2258
2975
|
if (!guard(value[key])) return false;
|
|
2259
|
-
} else if (
|
|
2976
|
+
} else if (closed) return false;
|
|
2977
|
+
else if (additional !== void 0 && !additional(value[key])) return false;
|
|
2260
2978
|
}
|
|
2261
2979
|
return true;
|
|
2262
2980
|
});
|
|
@@ -2264,23 +2982,25 @@ function compileGuard(shape) {
|
|
|
2264
2982
|
};
|
|
2265
2983
|
}
|
|
2266
2984
|
case "union": {
|
|
2267
|
-
const guards =
|
|
2268
|
-
if (
|
|
2985
|
+
const guards = owned.variants.map((variant) => compileGuard(variant));
|
|
2986
|
+
if (owned.mode === "oneOf") return (value) => guards.filter((guard) => guard(value)).length === 1;
|
|
2269
2987
|
return unionOf(...guards);
|
|
2270
2988
|
}
|
|
2271
|
-
case "optional": return orOf(isUndefined, compileGuard(
|
|
2272
|
-
case "nullable": return nullableOf(compileGuard(
|
|
2273
|
-
case "raw": return (
|
|
2989
|
+
case "optional": return orOf(isUndefined, compileGuard(owned.inner));
|
|
2990
|
+
case "nullable": return nullableOf(compileGuard(owned.inner));
|
|
2991
|
+
case "raw": return (value) => value !== void 0;
|
|
2274
2992
|
}
|
|
2275
2993
|
}
|
|
2276
2994
|
function compileParser(shape) {
|
|
2277
|
-
|
|
2995
|
+
const owned = ownShape(shape);
|
|
2996
|
+
validateShapeDepth(owned);
|
|
2997
|
+
switch (owned.type) {
|
|
2278
2998
|
case "string": {
|
|
2279
|
-
if (
|
|
2999
|
+
if (owned.min === void 0 && owned.max === void 0 && owned.pattern === void 0) return parseString;
|
|
2280
3000
|
const guard = stringOf({
|
|
2281
|
-
min:
|
|
2282
|
-
max:
|
|
2283
|
-
pattern:
|
|
3001
|
+
...owned.min === void 0 ? {} : { min: owned.min },
|
|
3002
|
+
...owned.max === void 0 ? {} : { max: owned.max },
|
|
3003
|
+
...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
|
|
2284
3004
|
});
|
|
2285
3005
|
return (value) => {
|
|
2286
3006
|
const parsed = parseString(value);
|
|
@@ -2288,9 +3008,9 @@ function compileParser(shape) {
|
|
|
2288
3008
|
};
|
|
2289
3009
|
}
|
|
2290
3010
|
case "number": {
|
|
2291
|
-
const base =
|
|
2292
|
-
if (
|
|
2293
|
-
const within = boundsOf(
|
|
3011
|
+
const base = owned.integer === true ? parseInteger : parseNumber;
|
|
3012
|
+
if (owned.min === void 0 && owned.max === void 0) return base;
|
|
3013
|
+
const within = boundsOf(owned.min, owned.max);
|
|
2294
3014
|
return (value) => {
|
|
2295
3015
|
const parsed = base(value);
|
|
2296
3016
|
return parsed !== void 0 && within(parsed) ? parsed : void 0;
|
|
@@ -2300,19 +3020,19 @@ function compileParser(shape) {
|
|
|
2300
3020
|
case "null": return (value) => value === null ? null : void 0;
|
|
2301
3021
|
case "json": return (value) => isJSONValue(value) ? value : void 0;
|
|
2302
3022
|
case "literal": {
|
|
2303
|
-
const allowed =
|
|
3023
|
+
const allowed = literalOf(owned.values);
|
|
2304
3024
|
return (value) => {
|
|
2305
|
-
if (allowed
|
|
3025
|
+
if (allowed(value)) return value;
|
|
2306
3026
|
if (isString(value)) {
|
|
2307
3027
|
const trimmed = value.trim();
|
|
2308
|
-
if (allowed
|
|
3028
|
+
if (allowed(trimmed)) return trimmed;
|
|
2309
3029
|
}
|
|
2310
3030
|
};
|
|
2311
3031
|
}
|
|
2312
3032
|
case "array": {
|
|
2313
|
-
const item = compileParser(
|
|
2314
|
-
const unbounded =
|
|
2315
|
-
const withinLength = boundsOf(
|
|
3033
|
+
const item = compileParser(owned.items);
|
|
3034
|
+
const unbounded = owned.min === void 0 && owned.max === void 0;
|
|
3035
|
+
const withinLength = boundsOf(owned.min, owned.max);
|
|
2316
3036
|
return (value) => {
|
|
2317
3037
|
if (!isArray(value)) return void 0;
|
|
2318
3038
|
const result = [];
|
|
@@ -2326,8 +3046,8 @@ function compileParser(shape) {
|
|
|
2326
3046
|
}
|
|
2327
3047
|
case "object": {
|
|
2328
3048
|
const entries = [];
|
|
2329
|
-
for (const key of Object.keys(
|
|
2330
|
-
const child =
|
|
3049
|
+
for (const key of Object.keys(owned.properties)) {
|
|
3050
|
+
const child = owned.properties[key];
|
|
2331
3051
|
if (child === void 0) continue;
|
|
2332
3052
|
const optional = child.type === "optional";
|
|
2333
3053
|
entries.push({
|
|
@@ -2337,15 +3057,22 @@ function compileParser(shape) {
|
|
|
2337
3057
|
});
|
|
2338
3058
|
}
|
|
2339
3059
|
const known = new Set(entries.map((entry) => entry.key));
|
|
2340
|
-
const extra =
|
|
3060
|
+
const extra = owned.additionalProperties;
|
|
2341
3061
|
const additional = extra === void 0 || extra === false || extra === true ? void 0 : compileParser(extra);
|
|
2342
3062
|
const open = extra === true || additional !== void 0;
|
|
2343
3063
|
return (value) => {
|
|
2344
3064
|
const record = parseRecord(value);
|
|
2345
3065
|
if (record === void 0) return void 0;
|
|
3066
|
+
const keys = enumerableKeys(record);
|
|
3067
|
+
if (keys === void 0) return void 0;
|
|
3068
|
+
const present = new Set(keys);
|
|
2346
3069
|
const outcome = attempt(() => {
|
|
2347
3070
|
const result = Object.create(null);
|
|
2348
3071
|
for (const entry of entries) {
|
|
3072
|
+
if (!present.has(entry.key)) {
|
|
3073
|
+
if (entry.optional) continue;
|
|
3074
|
+
return;
|
|
3075
|
+
}
|
|
2349
3076
|
const raw = record[entry.key];
|
|
2350
3077
|
if (raw === void 0) {
|
|
2351
3078
|
if (entry.optional) continue;
|
|
@@ -2355,7 +3082,7 @@ function compileParser(shape) {
|
|
|
2355
3082
|
if (parsed === void 0) return void 0;
|
|
2356
3083
|
result[entry.key] = parsed;
|
|
2357
3084
|
}
|
|
2358
|
-
if (open) for (const key of
|
|
3085
|
+
if (open) for (const key of keys) {
|
|
2359
3086
|
if (known.has(key)) continue;
|
|
2360
3087
|
if (additional === void 0) result[key] = record[key];
|
|
2361
3088
|
else {
|
|
@@ -2370,11 +3097,11 @@ function compileParser(shape) {
|
|
|
2370
3097
|
};
|
|
2371
3098
|
}
|
|
2372
3099
|
case "union": {
|
|
2373
|
-
const variants =
|
|
3100
|
+
const variants = owned.variants.map((variant) => ({
|
|
2374
3101
|
parse: compileParser(variant),
|
|
2375
3102
|
guard: compileGuard(variant)
|
|
2376
3103
|
}));
|
|
2377
|
-
if (
|
|
3104
|
+
if (owned.mode === "oneOf") return (value) => {
|
|
2378
3105
|
const matches = variants.filter((variant) => variant.guard(value));
|
|
2379
3106
|
const [only] = matches;
|
|
2380
3107
|
return matches.length === 1 && only !== void 0 ? only.parse(value) : void 0;
|
|
@@ -2388,89 +3115,143 @@ function compileParser(shape) {
|
|
|
2388
3115
|
};
|
|
2389
3116
|
}
|
|
2390
3117
|
case "optional": {
|
|
2391
|
-
const inner = compileParser(
|
|
3118
|
+
const inner = compileParser(owned.inner);
|
|
2392
3119
|
return (value) => value === void 0 ? void 0 : inner(value);
|
|
2393
3120
|
}
|
|
2394
3121
|
case "nullable": {
|
|
2395
|
-
const inner = compileParser(
|
|
3122
|
+
const inner = compileParser(owned.inner);
|
|
2396
3123
|
return (value) => value === null ? null : inner(value);
|
|
2397
3124
|
}
|
|
2398
3125
|
case "raw": return (value) => value;
|
|
2399
3126
|
}
|
|
2400
3127
|
}
|
|
2401
3128
|
function compileGenerator(shape, random = seededRandom(Date.now())) {
|
|
2402
|
-
|
|
3129
|
+
const owned = ownShape(shape);
|
|
3130
|
+
validateShapeDepth(owned);
|
|
3131
|
+
switch (owned.type) {
|
|
2403
3132
|
case "string": {
|
|
2404
|
-
const min =
|
|
2405
|
-
const max =
|
|
3133
|
+
const min = owned.min ?? 0;
|
|
3134
|
+
const max = owned.max ?? Math.max(min, 12);
|
|
2406
3135
|
const length = Math.max(min, Math.min(max, 8));
|
|
2407
3136
|
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
2408
3137
|
let value = "";
|
|
2409
|
-
for (let index = 0; index < length; index += 1) value += alphabet[Math.floor(random
|
|
2410
|
-
if (
|
|
3138
|
+
for (let index = 0; index < length; index += 1) value += alphabet[Math.floor(drawRandom(random, "string") * 36)];
|
|
3139
|
+
if (owned.pattern !== void 0 && !matchOf(owned.pattern)(value)) throw new ContractError("compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way", {
|
|
3140
|
+
code: "generate",
|
|
3141
|
+
context: {
|
|
3142
|
+
shape: "string",
|
|
3143
|
+
limit: owned.pattern.source
|
|
3144
|
+
}
|
|
3145
|
+
});
|
|
2411
3146
|
return value;
|
|
2412
3147
|
}
|
|
2413
3148
|
case "number": {
|
|
2414
|
-
const
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
const
|
|
2418
|
-
|
|
2419
|
-
return Math.floor(random() * (hi - lo + 1)) + lo;
|
|
3149
|
+
const sample = drawRandom(random, owned.integer === true ? "integer" : "number");
|
|
3150
|
+
if (owned.integer === true) {
|
|
3151
|
+
const lo = Math.ceil(owned.min ?? (owned.max === void 0 ? -100 : owned.max - 100));
|
|
3152
|
+
const hi = Math.floor(owned.max ?? (owned.min === void 0 ? 100 : owned.min + 100));
|
|
3153
|
+
return lo === hi ? lo : Math.floor(lo * (1 - sample) + hi * sample);
|
|
2420
3154
|
}
|
|
2421
|
-
|
|
3155
|
+
const lo = owned.min ?? (owned.max === void 0 ? -100 : owned.max - 100);
|
|
3156
|
+
const hi = owned.max ?? (owned.min === void 0 ? 100 : owned.min + 100);
|
|
3157
|
+
return lo === hi ? lo : lo * (1 - sample) + hi * sample;
|
|
2422
3158
|
}
|
|
2423
|
-
case "boolean": return random
|
|
3159
|
+
case "boolean": return drawRandom(random, "boolean") >= .5;
|
|
2424
3160
|
case "null": return null;
|
|
2425
3161
|
case "json": {
|
|
2426
|
-
const pick = Math.floor(random
|
|
3162
|
+
const pick = Math.floor(drawRandom(random, "json") * 5);
|
|
2427
3163
|
if (pick === 0) return null;
|
|
2428
|
-
if (pick === 1) return random
|
|
2429
|
-
if (pick === 2) return Math.floor(random
|
|
3164
|
+
if (pick === 1) return drawRandom(random, "json") >= .5;
|
|
3165
|
+
if (pick === 2) return Math.floor(drawRandom(random, "json") * 1e3);
|
|
2430
3166
|
if (pick === 3) {
|
|
2431
3167
|
const alphabet = "abcdefghijklmnopqrstuvwxyz";
|
|
2432
3168
|
let value = "";
|
|
2433
|
-
for (let index = 0; index < 6; index += 1) value += alphabet[Math.floor(random
|
|
3169
|
+
for (let index = 0; index < 6; index += 1) value += alphabet[Math.floor(drawRandom(random, "json") * 26)];
|
|
2434
3170
|
return value;
|
|
2435
3171
|
}
|
|
2436
|
-
return { value: Math.floor(random
|
|
3172
|
+
return { value: Math.floor(drawRandom(random, "json") * 1e3) };
|
|
2437
3173
|
}
|
|
2438
3174
|
case "literal":
|
|
2439
|
-
if (
|
|
2440
|
-
|
|
3175
|
+
if (owned.values.length === 0) throw new ContractError("compileGenerator: a literal shape needs at least one value", {
|
|
3176
|
+
code: "generate",
|
|
3177
|
+
context: {
|
|
3178
|
+
shape: "literal",
|
|
3179
|
+
limit: 1
|
|
3180
|
+
}
|
|
3181
|
+
});
|
|
3182
|
+
return owned.values[Math.floor(drawRandom(random, "literal") * owned.values.length)];
|
|
2441
3183
|
case "array": {
|
|
2442
|
-
const lo =
|
|
2443
|
-
const hi =
|
|
2444
|
-
const length = Math.floor(random
|
|
3184
|
+
const lo = owned.min ?? Math.min(1, owned.max ?? 1);
|
|
3185
|
+
const hi = owned.max ?? Math.max(lo, 3);
|
|
3186
|
+
const length = Math.floor(drawRandom(random, "array") * (hi - lo + 1)) + lo;
|
|
2445
3187
|
const result = [];
|
|
2446
|
-
for (let index = 0; index < length; index += 1) result.push(compileGenerator(
|
|
3188
|
+
for (let index = 0; index < length; index += 1) result.push(compileGenerator(owned.items, random));
|
|
2447
3189
|
return result;
|
|
2448
3190
|
}
|
|
2449
3191
|
case "object": {
|
|
2450
3192
|
const result = {};
|
|
2451
|
-
for (const key of Object.keys(
|
|
2452
|
-
const child =
|
|
3193
|
+
for (const key of Object.keys(owned.properties)) {
|
|
3194
|
+
const child = owned.properties[key];
|
|
2453
3195
|
if (child === void 0) continue;
|
|
2454
|
-
if (child.type === "optional" && random
|
|
2455
|
-
result
|
|
3196
|
+
if (child.type === "optional" && drawRandom(random, "object") < .3) continue;
|
|
3197
|
+
Object.defineProperty(result, key, {
|
|
3198
|
+
value: compileGenerator(child, random),
|
|
3199
|
+
enumerable: true,
|
|
3200
|
+
configurable: true,
|
|
3201
|
+
writable: true
|
|
3202
|
+
});
|
|
2456
3203
|
}
|
|
2457
|
-
const extra =
|
|
3204
|
+
const extra = owned.additionalProperties;
|
|
2458
3205
|
if (extra !== void 0 && extra !== true && extra !== false) {
|
|
2459
|
-
const count = 1 + Math.floor(random
|
|
3206
|
+
const count = 1 + Math.floor(drawRandom(random, "object") * 2);
|
|
2460
3207
|
for (let index = 0; index < count; index += 1) {
|
|
2461
3208
|
const key = `key${index}`;
|
|
2462
3209
|
if (Object.hasOwn(result, key)) continue;
|
|
2463
|
-
result
|
|
3210
|
+
Object.defineProperty(result, key, {
|
|
3211
|
+
value: compileGenerator(extra, random),
|
|
3212
|
+
enumerable: true,
|
|
3213
|
+
configurable: true,
|
|
3214
|
+
writable: true
|
|
3215
|
+
});
|
|
2464
3216
|
}
|
|
2465
3217
|
}
|
|
2466
3218
|
return result;
|
|
2467
3219
|
}
|
|
2468
|
-
case "union":
|
|
2469
|
-
if (
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
3220
|
+
case "union": {
|
|
3221
|
+
if (owned.variants.length === 0) throw new ContractError("compileGenerator: a union shape needs at least one variant", {
|
|
3222
|
+
code: "generate",
|
|
3223
|
+
context: {
|
|
3224
|
+
shape: "union",
|
|
3225
|
+
limit: 1
|
|
3226
|
+
}
|
|
3227
|
+
});
|
|
3228
|
+
const guard = compileGuard(owned);
|
|
3229
|
+
const attempts = Math.max(32, owned.variants.length);
|
|
3230
|
+
const start = Math.floor(drawRandom(random, "union") * owned.variants.length);
|
|
3231
|
+
for (let attemptIndex = 0; attemptIndex < attempts; attemptIndex += 1) {
|
|
3232
|
+
const variant = owned.variants[(start + attemptIndex) % owned.variants.length];
|
|
3233
|
+
if (variant === void 0) continue;
|
|
3234
|
+
const outcome = attempt(() => compileGenerator(variant, random));
|
|
3235
|
+
if (!outcome.success && isContractError(outcome.error) && outcome.error.code === "random") throw outcome.error;
|
|
3236
|
+
if (outcome.success && guard(outcome.value)) return outcome.value;
|
|
3237
|
+
}
|
|
3238
|
+
throw new ContractError("compileGenerator: no union candidate satisfied the compiled guard", {
|
|
3239
|
+
code: "generate",
|
|
3240
|
+
context: {
|
|
3241
|
+
shape: "union",
|
|
3242
|
+
limit: attempts
|
|
3243
|
+
}
|
|
3244
|
+
});
|
|
3245
|
+
}
|
|
3246
|
+
case "optional": return compileGenerator(owned.inner, random);
|
|
3247
|
+
case "nullable": return drawRandom(random, "nullable") < .2 ? null : compileGenerator(owned.inner, random);
|
|
3248
|
+
case "raw": throw new ContractError("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way", {
|
|
3249
|
+
code: "generate",
|
|
3250
|
+
context: {
|
|
3251
|
+
shape: "raw",
|
|
3252
|
+
limit: "explicit value source"
|
|
3253
|
+
}
|
|
3254
|
+
});
|
|
2474
3255
|
}
|
|
2475
3256
|
}
|
|
2476
3257
|
/**
|
|
@@ -2497,7 +3278,8 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
|
|
|
2497
3278
|
* open object with a constraining `additionalProperties` shape recurses extras
|
|
2498
3279
|
* against it instead. A hostile getter or throwing `Proxy` trap is contained
|
|
2499
3280
|
* via {@link attempt} and surfaces as a single top-level type fault, never a
|
|
2500
|
-
* throw (AGENTS §14).
|
|
3281
|
+
* throw (AGENTS §14). {@link validateShapeDepth} iteratively rejects excessive
|
|
3282
|
+
* shape nesting or cycles before recursive reporting begins.
|
|
2501
3283
|
*
|
|
2502
3284
|
* @param shape - The shape to report against
|
|
2503
3285
|
* @param value - The value to check
|
|
@@ -2513,7 +3295,9 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
|
|
|
2513
3295
|
* ```
|
|
2514
3296
|
*/
|
|
2515
3297
|
function compileReporter(shape, value, path = []) {
|
|
2516
|
-
|
|
3298
|
+
const owned = ownShape(shape);
|
|
3299
|
+
validateShapeDepth(owned);
|
|
3300
|
+
switch (owned.type) {
|
|
2517
3301
|
case "string": {
|
|
2518
3302
|
const parsed = parseString(value);
|
|
2519
3303
|
if (parsed === void 0) return [{
|
|
@@ -2523,34 +3307,34 @@ function compileReporter(shape, value, path = []) {
|
|
|
2523
3307
|
received: preview(value)
|
|
2524
3308
|
}];
|
|
2525
3309
|
const faults = [];
|
|
2526
|
-
if (
|
|
3310
|
+
if (owned.min !== void 0 && parsed.length < owned.min) faults.push({
|
|
2527
3311
|
reason: "constraint",
|
|
2528
3312
|
path,
|
|
2529
3313
|
expected: "string",
|
|
2530
3314
|
constraint: "min",
|
|
2531
|
-
limit:
|
|
3315
|
+
limit: owned.min,
|
|
2532
3316
|
received: preview(parsed)
|
|
2533
3317
|
});
|
|
2534
|
-
if (
|
|
3318
|
+
if (owned.max !== void 0 && parsed.length > owned.max) faults.push({
|
|
2535
3319
|
reason: "constraint",
|
|
2536
3320
|
path,
|
|
2537
3321
|
expected: "string",
|
|
2538
3322
|
constraint: "max",
|
|
2539
|
-
limit:
|
|
3323
|
+
limit: owned.max,
|
|
2540
3324
|
received: preview(parsed)
|
|
2541
3325
|
});
|
|
2542
|
-
if (
|
|
3326
|
+
if (owned.pattern !== void 0 && !matchOf(owned.pattern)(parsed)) faults.push({
|
|
2543
3327
|
reason: "constraint",
|
|
2544
3328
|
path,
|
|
2545
3329
|
expected: "string",
|
|
2546
3330
|
constraint: "pattern",
|
|
2547
|
-
limit:
|
|
3331
|
+
limit: owned.pattern.source,
|
|
2548
3332
|
received: preview(parsed)
|
|
2549
3333
|
});
|
|
2550
3334
|
return faults;
|
|
2551
3335
|
}
|
|
2552
3336
|
case "number": {
|
|
2553
|
-
const kind =
|
|
3337
|
+
const kind = owned.integer === true ? "integer" : "number";
|
|
2554
3338
|
const parsed = parseNumber(value);
|
|
2555
3339
|
if (parsed === void 0) return [{
|
|
2556
3340
|
reason: "type",
|
|
@@ -2559,27 +3343,27 @@ function compileReporter(shape, value, path = []) {
|
|
|
2559
3343
|
received: preview(value)
|
|
2560
3344
|
}];
|
|
2561
3345
|
const faults = [];
|
|
2562
|
-
if (
|
|
3346
|
+
if (owned.integer === true && !Number.isInteger(parsed)) faults.push({
|
|
2563
3347
|
reason: "constraint",
|
|
2564
3348
|
path,
|
|
2565
3349
|
expected: kind,
|
|
2566
3350
|
constraint: "integer",
|
|
2567
3351
|
received: preview(parsed)
|
|
2568
3352
|
});
|
|
2569
|
-
if (
|
|
3353
|
+
if (owned.min !== void 0 && parsed < owned.min) faults.push({
|
|
2570
3354
|
reason: "constraint",
|
|
2571
3355
|
path,
|
|
2572
3356
|
expected: kind,
|
|
2573
3357
|
constraint: "min",
|
|
2574
|
-
limit:
|
|
3358
|
+
limit: owned.min,
|
|
2575
3359
|
received: preview(parsed)
|
|
2576
3360
|
});
|
|
2577
|
-
if (
|
|
3361
|
+
if (owned.max !== void 0 && parsed > owned.max) faults.push({
|
|
2578
3362
|
reason: "constraint",
|
|
2579
3363
|
path,
|
|
2580
3364
|
expected: kind,
|
|
2581
3365
|
constraint: "max",
|
|
2582
|
-
limit:
|
|
3366
|
+
limit: owned.max,
|
|
2583
3367
|
received: preview(parsed)
|
|
2584
3368
|
});
|
|
2585
3369
|
return faults;
|
|
@@ -2603,8 +3387,8 @@ function compileReporter(shape, value, path = []) {
|
|
|
2603
3387
|
received: preview(value)
|
|
2604
3388
|
}];
|
|
2605
3389
|
case "literal": {
|
|
2606
|
-
const allowed =
|
|
2607
|
-
return allowed
|
|
3390
|
+
const allowed = literalOf(owned.values);
|
|
3391
|
+
return allowed(value) || isString(value) && allowed(value.trim()) ? [] : [{
|
|
2608
3392
|
reason: "type",
|
|
2609
3393
|
path,
|
|
2610
3394
|
expected: "literal",
|
|
@@ -2622,7 +3406,7 @@ function compileReporter(shape, value, path = []) {
|
|
|
2622
3406
|
if (!attempt(() => {
|
|
2623
3407
|
for (let index = 0; index < value.length; index += 1) {
|
|
2624
3408
|
if (faults.length >= 64) return;
|
|
2625
|
-
faults.push(...compileReporter(
|
|
3409
|
+
faults.push(...compileReporter(owned.items, value[index], [...path, String(index)]));
|
|
2626
3410
|
}
|
|
2627
3411
|
}).success) return [{
|
|
2628
3412
|
reason: "type",
|
|
@@ -2630,20 +3414,20 @@ function compileReporter(shape, value, path = []) {
|
|
|
2630
3414
|
expected: "array",
|
|
2631
3415
|
received: preview(value)
|
|
2632
3416
|
}];
|
|
2633
|
-
if (
|
|
3417
|
+
if (owned.min !== void 0 && value.length < owned.min) faults.push({
|
|
2634
3418
|
reason: "constraint",
|
|
2635
3419
|
path,
|
|
2636
3420
|
expected: "array",
|
|
2637
3421
|
constraint: "min",
|
|
2638
|
-
limit:
|
|
3422
|
+
limit: owned.min,
|
|
2639
3423
|
received: String(value.length)
|
|
2640
3424
|
});
|
|
2641
|
-
if (
|
|
3425
|
+
if (owned.max !== void 0 && value.length > owned.max) faults.push({
|
|
2642
3426
|
reason: "constraint",
|
|
2643
3427
|
path,
|
|
2644
3428
|
expected: "array",
|
|
2645
3429
|
constraint: "max",
|
|
2646
|
-
limit:
|
|
3430
|
+
limit: owned.max,
|
|
2647
3431
|
received: String(value.length)
|
|
2648
3432
|
});
|
|
2649
3433
|
return faults.length > 64 ? faults.slice(0, 64) : faults;
|
|
@@ -2656,16 +3440,32 @@ function compileReporter(shape, value, path = []) {
|
|
|
2656
3440
|
received: preview(value)
|
|
2657
3441
|
}];
|
|
2658
3442
|
const record = value;
|
|
3443
|
+
const keys = enumerableKeys(record);
|
|
3444
|
+
if (keys === void 0) return [{
|
|
3445
|
+
reason: "type",
|
|
3446
|
+
path,
|
|
3447
|
+
expected: "object",
|
|
3448
|
+
received: preview(value)
|
|
3449
|
+
}];
|
|
3450
|
+
const present = new Set(keys);
|
|
2659
3451
|
const faults = [];
|
|
2660
3452
|
const known = /* @__PURE__ */ new Set();
|
|
2661
3453
|
if (!attempt(() => {
|
|
2662
|
-
for (const key of Object.keys(
|
|
3454
|
+
for (const key of Object.keys(owned.properties)) {
|
|
2663
3455
|
if (faults.length >= 64) return;
|
|
2664
|
-
const child =
|
|
3456
|
+
const child = owned.properties[key];
|
|
2665
3457
|
if (child === void 0) continue;
|
|
2666
3458
|
known.add(key);
|
|
2667
3459
|
const optional = child.type === "optional";
|
|
2668
3460
|
const inner = optional ? child.inner : child;
|
|
3461
|
+
if (!present.has(key)) {
|
|
3462
|
+
if (!optional) faults.push({
|
|
3463
|
+
reason: "missing",
|
|
3464
|
+
path: [...path, key],
|
|
3465
|
+
expected: shapeToKind(inner)
|
|
3466
|
+
});
|
|
3467
|
+
continue;
|
|
3468
|
+
}
|
|
2669
3469
|
const raw = record[key];
|
|
2670
3470
|
if (raw === void 0) {
|
|
2671
3471
|
if (!optional) faults.push({
|
|
@@ -2677,8 +3477,8 @@ function compileReporter(shape, value, path = []) {
|
|
|
2677
3477
|
}
|
|
2678
3478
|
faults.push(...compileReporter(inner, raw, [...path, key]));
|
|
2679
3479
|
}
|
|
2680
|
-
const extra =
|
|
2681
|
-
if (extra !== void 0 && extra !== true && extra !== false) for (const key of
|
|
3480
|
+
const extra = owned.additionalProperties;
|
|
3481
|
+
if (extra !== void 0 && extra !== true && extra !== false) for (const key of keys) {
|
|
2682
3482
|
if (faults.length >= 64) return;
|
|
2683
3483
|
if (known.has(key)) continue;
|
|
2684
3484
|
faults.push(...compileReporter(extra, record[key], [...path, key]));
|
|
@@ -2692,7 +3492,7 @@ function compileReporter(shape, value, path = []) {
|
|
|
2692
3492
|
return faults.length > 64 ? faults.slice(0, 64) : faults;
|
|
2693
3493
|
}
|
|
2694
3494
|
case "union": {
|
|
2695
|
-
const perVariant =
|
|
3495
|
+
const perVariant = owned.variants.map((variant) => compileReporter(variant, value, path));
|
|
2696
3496
|
let bestIndex = 0;
|
|
2697
3497
|
for (let index = 1; index < perVariant.length; index += 1) {
|
|
2698
3498
|
const current = perVariant[index];
|
|
@@ -2700,9 +3500,9 @@ function compileReporter(shape, value, path = []) {
|
|
|
2700
3500
|
if (current !== void 0 && best !== void 0 && current.length < best.length) bestIndex = index;
|
|
2701
3501
|
}
|
|
2702
3502
|
const closest = perVariant[bestIndex] ?? [];
|
|
2703
|
-
if (
|
|
3503
|
+
if (owned.mode === "oneOf") {
|
|
2704
3504
|
let matched = 0;
|
|
2705
|
-
for (const variant of
|
|
3505
|
+
for (const variant of owned.variants) if (compileGuard(variant)(value)) matched += 1;
|
|
2706
3506
|
if (matched === 1) return [];
|
|
2707
3507
|
if (matched === 0) return [{
|
|
2708
3508
|
reason: "oneOf",
|
|
@@ -2719,19 +3519,25 @@ function compileReporter(shape, value, path = []) {
|
|
|
2719
3519
|
return [{
|
|
2720
3520
|
reason: "variant",
|
|
2721
3521
|
path,
|
|
2722
|
-
variants:
|
|
3522
|
+
variants: owned.variants.length
|
|
2723
3523
|
}, ...closest].slice(0, 64);
|
|
2724
3524
|
}
|
|
2725
|
-
case "optional": return value === void 0 ? [] : compileReporter(
|
|
2726
|
-
case "nullable": return value === null ? [] : compileReporter(
|
|
2727
|
-
case "raw": return [
|
|
3525
|
+
case "optional": return value === void 0 ? [] : compileReporter(owned.inner, value, path);
|
|
3526
|
+
case "nullable": return value === null ? [] : compileReporter(owned.inner, value, path);
|
|
3527
|
+
case "raw": return value === void 0 ? [{
|
|
3528
|
+
reason: "type",
|
|
3529
|
+
path,
|
|
3530
|
+
expected: "json",
|
|
3531
|
+
received: preview(value)
|
|
3532
|
+
}] : [];
|
|
2728
3533
|
}
|
|
2729
3534
|
}
|
|
2730
3535
|
function createContract(shape) {
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
const
|
|
2734
|
-
const
|
|
3536
|
+
const snapshot = cloneShape(shape);
|
|
3537
|
+
validateShape(snapshot);
|
|
3538
|
+
const schema = compileSchema(snapshot);
|
|
3539
|
+
const guard = compileGuard(snapshot);
|
|
3540
|
+
const parser = compileParser(snapshot);
|
|
2735
3541
|
return {
|
|
2736
3542
|
schema,
|
|
2737
3543
|
is: guard,
|
|
@@ -2739,39 +3545,123 @@ function createContract(shape) {
|
|
|
2739
3545
|
return parser(value);
|
|
2740
3546
|
},
|
|
2741
3547
|
explain(value) {
|
|
2742
|
-
return compileReporter(
|
|
3548
|
+
return compileReporter(snapshot, value);
|
|
2743
3549
|
},
|
|
2744
3550
|
generate(random) {
|
|
2745
|
-
return compileGenerator(
|
|
3551
|
+
return compileGenerator(snapshot, random);
|
|
2746
3552
|
}
|
|
2747
3553
|
};
|
|
2748
3554
|
}
|
|
2749
3555
|
//#endregion
|
|
2750
3556
|
//#region src/core/inferers.ts
|
|
2751
3557
|
/**
|
|
2752
|
-
*
|
|
3558
|
+
* Encode one value as a deterministic, key-sorted JSON string — the recursive
|
|
3559
|
+
* spine of {@link canonicalStringify}.
|
|
3560
|
+
*
|
|
3561
|
+
* @remarks
|
|
3562
|
+
* Arrays keep their element order; records sort their own keys before encoding,
|
|
3563
|
+
* recursively at every nesting level. Every other value is encoded by
|
|
3564
|
+
* `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0`
|
|
3565
|
+
* encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes.
|
|
3566
|
+
*
|
|
3567
|
+
* Returns `undefined` for anything JSON cannot encode: `undefined` itself, a
|
|
3568
|
+
* function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A
|
|
3569
|
+
* container carrying such a member is itself un-encodable and returns
|
|
3570
|
+
* `undefined` too, so the result is either a faithful encoding of the WHOLE
|
|
3571
|
+
* value or nothing — a partially-encoded key is never emitted. Traversal is NOT
|
|
3572
|
+
* contained here: a hostile getter or `Proxy` trap throws through to
|
|
3573
|
+
* {@link canonicalStringify}, which owns the single {@link attempt} boundary
|
|
3574
|
+
* for the walk.
|
|
3575
|
+
*
|
|
3576
|
+
* @param value - The value to encode
|
|
3577
|
+
* @param ancestors - Objects on the active traversal path, guarding cycles
|
|
3578
|
+
* @returns The deterministic encoding, or `undefined` when JSON cannot encode
|
|
3579
|
+
* `value`
|
|
3580
|
+
*
|
|
3581
|
+
* @example
|
|
3582
|
+
* ```ts
|
|
3583
|
+
* canonicalizeValue({ b: 1, a: 2 }, new WeakSet()) // '{"a":2,"b":1}'
|
|
3584
|
+
* canonicalizeValue(undefined, new WeakSet()) // undefined
|
|
3585
|
+
* ```
|
|
3586
|
+
*/
|
|
3587
|
+
function canonicalizeValue(value, ancestors) {
|
|
3588
|
+
if (isArray(value)) {
|
|
3589
|
+
if (ancestors.has(value)) return void 0;
|
|
3590
|
+
ancestors.add(value);
|
|
3591
|
+
const parts = [];
|
|
3592
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
3593
|
+
const part = Object.hasOwn(value, index) ? canonicalizeValue(value[index], ancestors) : void 0;
|
|
3594
|
+
if (part === void 0) {
|
|
3595
|
+
ancestors.delete(value);
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
parts.push(part);
|
|
3599
|
+
}
|
|
3600
|
+
ancestors.delete(value);
|
|
3601
|
+
return `[${parts.join(",")}]`;
|
|
3602
|
+
}
|
|
3603
|
+
if (isRecord(value)) {
|
|
3604
|
+
if (ancestors.has(value)) return void 0;
|
|
3605
|
+
ancestors.add(value);
|
|
3606
|
+
const parts = [];
|
|
3607
|
+
for (const key of Object.keys(value).sort()) {
|
|
3608
|
+
const part = canonicalizeValue(value[key], ancestors);
|
|
3609
|
+
if (part === void 0) {
|
|
3610
|
+
ancestors.delete(value);
|
|
3611
|
+
return;
|
|
3612
|
+
}
|
|
3613
|
+
parts.push(`${JSON.stringify(key)}:${part}`);
|
|
3614
|
+
}
|
|
3615
|
+
ancestors.delete(value);
|
|
3616
|
+
return `{${parts.join(",")}}`;
|
|
3617
|
+
}
|
|
3618
|
+
return JSON.stringify(value);
|
|
3619
|
+
}
|
|
3620
|
+
/**
|
|
3621
|
+
* Render a value as a deterministic, key-sorted JSON string — or `undefined`
|
|
3622
|
+
* when it has no faithful JSON encoding.
|
|
2753
3623
|
*
|
|
2754
3624
|
* @remarks
|
|
2755
3625
|
* The stable-stringify backing {@link unifySchemas}'s de-duplication and
|
|
2756
3626
|
* ordering: unlike `JSON.stringify`, object keys are sorted before encoding
|
|
2757
3627
|
* (recursively, at every nesting level), so two structurally-equal
|
|
2758
3628
|
* `JSONSchema` fragments built independently always canonicalize to the same
|
|
2759
|
-
* string. Pure ECMAScript
|
|
3629
|
+
* string. Pure host-independent ECMAScript with no environment-specific imports.
|
|
3630
|
+
*
|
|
3631
|
+
* TOTAL: it NEVER throws, for any input. It returns `undefined` — never a
|
|
3632
|
+
* partial or invalid encoding — for every value JSON cannot faithfully encode:
|
|
3633
|
+
*
|
|
3634
|
+
* - `undefined` itself, a function, a symbol, or an array hole (JSON encodes
|
|
3635
|
+
* none of them), at the top level or anywhere inside a container;
|
|
3636
|
+
* - a bigint (`JSON.stringify` throws on one);
|
|
3637
|
+
* - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline
|
|
3638
|
+
* {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic)
|
|
3639
|
+
* reference reached twice through different paths still encodes;
|
|
3640
|
+
* - hostile traversal — a throwing own-getter, a hostile `ownKeys` trap, or a
|
|
3641
|
+
* revoked `Proxy` anywhere in the value — contained via {@link attempt}.
|
|
3642
|
+
*
|
|
3643
|
+
* A caller therefore treats `undefined` as "this value has no canonical key",
|
|
3644
|
+
* never as an encoding: see {@link unifySchemas} (an un-keyed member cannot
|
|
3645
|
+
* participate in de-duplication or ordering) and {@link inferPrimitiveEnum} (an
|
|
3646
|
+
* un-keyed member makes the slot enum-ineligible).
|
|
2760
3647
|
*
|
|
2761
3648
|
* @param value - The value to canonicalize (a `JSONSchema` fragment, or any
|
|
2762
3649
|
* nested piece of one)
|
|
2763
|
-
* @returns A deterministic string encoding of `value`
|
|
3650
|
+
* @returns A deterministic string encoding of `value`, or `undefined` when JSON
|
|
3651
|
+
* cannot encode it
|
|
2764
3652
|
*
|
|
2765
3653
|
* @example
|
|
2766
3654
|
* ```ts
|
|
2767
3655
|
* canonicalStringify({ type: 'object', properties: {} }) ===
|
|
2768
3656
|
* canonicalStringify({ properties: {}, type: 'object' }) // true
|
|
3657
|
+
* canonicalStringify(Number.NaN) // 'null' — JSON.stringify semantics
|
|
3658
|
+
* canonicalStringify(undefined) // undefined
|
|
3659
|
+
* canonicalStringify(cyclicValue) // undefined
|
|
2769
3660
|
* ```
|
|
2770
3661
|
*/
|
|
2771
3662
|
function canonicalStringify(value) {
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
return JSON.stringify(value);
|
|
3663
|
+
const outcome = attempt(() => canonicalizeValue(value, /* @__PURE__ */ new WeakSet()));
|
|
3664
|
+
return outcome.success ? outcome.value : void 0;
|
|
2775
3665
|
}
|
|
2776
3666
|
/**
|
|
2777
3667
|
* Unify a list of inferred `JSONSchema` fragments into one schema.
|
|
@@ -2785,6 +3675,14 @@ function canonicalStringify(value) {
|
|
|
2785
3675
|
* `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
|
|
2786
3676
|
* An empty input list returns the empty accept-anything schema `{}`.
|
|
2787
3677
|
*
|
|
3678
|
+
* A member {@link canonicalStringify} cannot key — a cyclic, hostile, or
|
|
3679
|
+
* otherwise JSON-inexpressible fragment, which only a direct caller can supply
|
|
3680
|
+
* since the inferers always build plain encodable fragments — has NO
|
|
3681
|
+
* de-duplication key, so it can participate in neither de-duplication nor the
|
|
3682
|
+
* canonical-key ordering. It is KEPT (dropping a variant would narrow the
|
|
3683
|
+
* union, and unification only ever widens), appended in input order after the
|
|
3684
|
+
* sorted keyed members, so the result stays total and deterministic.
|
|
3685
|
+
*
|
|
2788
3686
|
* @param schemas - The schemas to unify
|
|
2789
3687
|
* @returns The unified schema
|
|
2790
3688
|
*
|
|
@@ -2798,19 +3696,24 @@ function canonicalStringify(value) {
|
|
|
2798
3696
|
function unifySchemas(schemas) {
|
|
2799
3697
|
if (schemas.length === 0) return {};
|
|
2800
3698
|
const seen = /* @__PURE__ */ new Map();
|
|
3699
|
+
const unkeyed = [];
|
|
2801
3700
|
for (const schema of schemas) {
|
|
2802
3701
|
const key = canonicalStringify(schema);
|
|
3702
|
+
if (key === void 0) {
|
|
3703
|
+
unkeyed.push(schema);
|
|
3704
|
+
continue;
|
|
3705
|
+
}
|
|
2803
3706
|
if (!seen.has(key)) seen.set(key, schema);
|
|
2804
3707
|
}
|
|
2805
3708
|
const integerKey = canonicalStringify({ type: "integer" });
|
|
2806
3709
|
const numberKey = canonicalStringify({ type: "number" });
|
|
2807
|
-
if (seen.has(integerKey) && seen.has(numberKey)) seen.delete(integerKey);
|
|
2808
|
-
const
|
|
2809
|
-
if (
|
|
2810
|
-
const [only] =
|
|
3710
|
+
if (integerKey !== void 0 && numberKey !== void 0 && seen.has(integerKey) && seen.has(numberKey)) seen.delete(integerKey);
|
|
3711
|
+
const members = [...[...seen.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, schema]) => schema), ...unkeyed];
|
|
3712
|
+
if (members.length <= 1) {
|
|
3713
|
+
const [only] = members;
|
|
2811
3714
|
return only ?? {};
|
|
2812
3715
|
}
|
|
2813
|
-
return { anyOf:
|
|
3716
|
+
return { anyOf: members };
|
|
2814
3717
|
}
|
|
2815
3718
|
/**
|
|
2816
3719
|
* Determine whether an ISO-8601-shaped string parses to a valid instant.
|
|
@@ -2918,6 +3821,12 @@ function samplesToFormat(values) {
|
|
|
2918
3821
|
* `literalShape` emission. Members are sorted by canonical key for
|
|
2919
3822
|
* deterministic output.
|
|
2920
3823
|
*
|
|
3824
|
+
* A member {@link canonicalStringify} cannot key has no identity to
|
|
3825
|
+
* de-duplicate against, so the whole slot is enum-INELIGIBLE and returns
|
|
3826
|
+
* `undefined` — widening to the caller's bare `type` rather than emitting an
|
|
3827
|
+
* `enum` that might silently omit a value. (A string or finite number always
|
|
3828
|
+
* canonicalizes, so this only guards the total contract.)
|
|
3829
|
+
*
|
|
2921
3830
|
* @param values - The collected slot values
|
|
2922
3831
|
* @param limit - The maximum distinct-value count before giving up
|
|
2923
3832
|
* @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
|
|
@@ -2935,7 +3844,12 @@ function inferPrimitiveEnum(values, limit) {
|
|
|
2935
3844
|
const allNumber = !allString && values.every((value) => isFiniteNumber(value));
|
|
2936
3845
|
if (!allString && !allNumber) return void 0;
|
|
2937
3846
|
const distinct = /* @__PURE__ */ new Map();
|
|
2938
|
-
for (const value of values)
|
|
3847
|
+
for (const value of values) {
|
|
3848
|
+
if (!isString(value) && !isFiniteNumber(value)) continue;
|
|
3849
|
+
const key = canonicalStringify(value);
|
|
3850
|
+
if (key === void 0) return void 0;
|
|
3851
|
+
distinct.set(key, value);
|
|
3852
|
+
}
|
|
2939
3853
|
if (distinct.size >= values.length || distinct.size > limit) return void 0;
|
|
2940
3854
|
return { enum: [...distinct.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, value]) => value) };
|
|
2941
3855
|
}
|
|
@@ -2947,13 +3861,21 @@ function inferPrimitiveEnum(values, limit) {
|
|
|
2947
3861
|
* @remarks
|
|
2948
3862
|
* Total: never throws, and terminates on cyclic input via `visited`. Leaf
|
|
2949
3863
|
* classification order: `null`, boolean, integer (`Number.isInteger`
|
|
2950
|
-
* semantics — `-0` counts), finite non-integer number,
|
|
2951
|
-
* (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
|
|
3864
|
+
* semantics — `-0` counts), finite non-integer number, string (gaining a
|
|
2952
3865
|
* `format` keyword when `format` is on and {@link stringToFormat} matches),
|
|
2953
3866
|
* array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
|
|
2954
|
-
* plus `format: 'date-time'` when `format` is on); everything else
|
|
2955
|
-
* (
|
|
2956
|
-
* `Map` / `Set`
|
|
3867
|
+
* plus `format: 'date-time'` when `format` is on); everything else — a
|
|
3868
|
+
* NON-FINITE number (`NaN` / `±Infinity`), a function, a symbol, a bigint,
|
|
3869
|
+
* `undefined`, and other non-plain objects such as `Map` / `Set` — is the
|
|
3870
|
+
* empty accept-anything schema `{}`.
|
|
3871
|
+
*
|
|
3872
|
+
* A non-finite number bottoms out with the other JSON-inexpressible values on
|
|
3873
|
+
* purpose: JSON carries no `NaN` / `±Infinity` (`JSON.stringify(Number.NaN)`
|
|
3874
|
+
* is `'null'`), so `{ type: 'number' }` would ASSERT something a JSON Schema
|
|
3875
|
+
* validator rejects — and the shape {@link schemaToShape} builds from it would
|
|
3876
|
+
* reject the very sample it was inferred from. `{}` is the truthful
|
|
3877
|
+
* description, and it inverts to an accept-anything shape, keeping
|
|
3878
|
+
* `compileGuard(schemaToShape(valueToSchema(v)))(v)` true.
|
|
2957
3879
|
*
|
|
2958
3880
|
* @param value - The value to classify
|
|
2959
3881
|
* @param depth - Remaining descent budget (0 halts recursion with `{}`)
|
|
@@ -2975,7 +3897,7 @@ function inferValue(value, depth, breadth, closed, format, visited, memo) {
|
|
|
2975
3897
|
if (isBoolean(value)) return { type: "boolean" };
|
|
2976
3898
|
if (isInteger(value)) return { type: "integer" };
|
|
2977
3899
|
if (isFiniteNumber(value)) return { type: "number" };
|
|
2978
|
-
if (isNumber(value)) return {
|
|
3900
|
+
if (isNumber(value)) return {};
|
|
2979
3901
|
if (isString(value)) {
|
|
2980
3902
|
if (format) {
|
|
2981
3903
|
const detected = stringToFormat(value);
|
|
@@ -3061,22 +3983,28 @@ function inferArray(value, depth, breadth, closed, format, visited, memo) {
|
|
|
3061
3983
|
* properties.
|
|
3062
3984
|
*
|
|
3063
3985
|
* @remarks
|
|
3064
|
-
* Own enumerable string keys via
|
|
3065
|
-
* deterministic output, capped at `breadth`.
|
|
3066
|
-
*
|
|
3067
|
-
*
|
|
3068
|
-
*
|
|
3069
|
-
*
|
|
3070
|
-
*
|
|
3071
|
-
*
|
|
3072
|
-
*
|
|
3073
|
-
*
|
|
3074
|
-
*
|
|
3075
|
-
*
|
|
3076
|
-
*
|
|
3077
|
-
*
|
|
3078
|
-
*
|
|
3079
|
-
*
|
|
3986
|
+
* Own enumerable string keys via {@link enumerableKeys}, sorted
|
|
3987
|
+
* lexicographically for deterministic output, capped at `breadth`. This is the
|
|
3988
|
+
* same property view compiled object guards, parsers, and reporters use. Each
|
|
3989
|
+
* property value is read through {@link attempt} so a hostile getter cannot
|
|
3990
|
+
* escape as a thrown error; a property whose value is `undefined` is DROPPED
|
|
3991
|
+
* — JSON encodes no such property (`JSON.stringify({ a: undefined })` is
|
|
3992
|
+
* `'{}'`), so it contributes neither a `properties` entry nor a `required`
|
|
3993
|
+
* entry. Every other present key is required (single-value mode).
|
|
3994
|
+
*
|
|
3995
|
+
* Emits `additionalProperties: false` when `closed`, `true` otherwise —
|
|
3996
|
+
* mirroring {@link compileSchema}'s object-emission convention — EXCEPT when
|
|
3997
|
+
* the sampled key list no longer describes every key `value` actually carries,
|
|
3998
|
+
* which happens two ways: the own-key list exceeds `breadth` (truncation), or
|
|
3999
|
+
* a key was dropped for holding `undefined`. Either way `additionalProperties`
|
|
4000
|
+
* is forced to `true` regardless of `closed`, because a CLOSED schema built
|
|
4001
|
+
* from an incomplete key list would reject the very object it was inferred
|
|
4002
|
+
* from (`recordOf` rejects any own key the shape does not declare).
|
|
4003
|
+
*
|
|
4004
|
+
* Depth exhaustion or a cyclic re-encounter of `value` both yield `{}`. A
|
|
4005
|
+
* same-object re-inference at the same remaining `depth` is served from `memo`
|
|
4006
|
+
* instead of recomputing (guards a shared-reference DAG against exponential
|
|
4007
|
+
* blowup).
|
|
3080
4008
|
*
|
|
3081
4009
|
* @param value - The record to infer from
|
|
3082
4010
|
* @param depth - Remaining descent budget
|
|
@@ -3101,31 +4029,37 @@ function inferObject(value, depth, breadth, closed, format, visited, memo) {
|
|
|
3101
4029
|
if (cached) return cached;
|
|
3102
4030
|
visited.add(value);
|
|
3103
4031
|
const outcome = attempt(() => {
|
|
3104
|
-
const
|
|
4032
|
+
const snapshot = enumerableKeys(value);
|
|
4033
|
+
if (snapshot === void 0) throw new Error("inferObject: property enumeration failed");
|
|
4034
|
+
const allKeys = [...snapshot].sort();
|
|
3105
4035
|
const keys = allKeys.slice(0, breadth);
|
|
3106
4036
|
const truncated = allKeys.length > breadth;
|
|
3107
4037
|
const properties = Object.create(null);
|
|
3108
4038
|
const required = [];
|
|
4039
|
+
let dropped = false;
|
|
3109
4040
|
for (const key of keys) {
|
|
3110
4041
|
const propertyValue = value[key];
|
|
3111
|
-
if (propertyValue === void 0)
|
|
4042
|
+
if (propertyValue === void 0) {
|
|
4043
|
+
dropped = true;
|
|
4044
|
+
continue;
|
|
4045
|
+
}
|
|
3112
4046
|
properties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo);
|
|
3113
4047
|
required.push(key);
|
|
3114
4048
|
}
|
|
3115
4049
|
return {
|
|
3116
4050
|
properties,
|
|
3117
4051
|
required,
|
|
3118
|
-
truncated
|
|
4052
|
+
partial: truncated || dropped
|
|
3119
4053
|
};
|
|
3120
4054
|
});
|
|
3121
4055
|
visited.delete(value);
|
|
3122
4056
|
if (!outcome.success) return {};
|
|
3123
|
-
const { properties, required,
|
|
4057
|
+
const { properties, required, partial } = outcome.value;
|
|
3124
4058
|
const schema = {
|
|
3125
4059
|
type: "object",
|
|
3126
4060
|
...Object.keys(properties).length > 0 ? { properties } : {},
|
|
3127
4061
|
...required.length > 0 ? { required } : {},
|
|
3128
|
-
additionalProperties:
|
|
4062
|
+
additionalProperties: partial ? true : !closed
|
|
3129
4063
|
};
|
|
3130
4064
|
let depths = memo.get(value);
|
|
3131
4065
|
if (!depths) {
|
|
@@ -3237,14 +4171,20 @@ function inferSamples(samples, depth, breadth, closed, format, enumOn) {
|
|
|
3237
4171
|
* {@link inferArray}, this path carries no `visited` `WeakSet` — a value
|
|
3238
4172
|
* shared by reference across multiple sample rows is legitimate (not a
|
|
3239
4173
|
* cycle back to an ancestor), so termination on cyclic row data relies on
|
|
3240
|
-
* the decrementing `depth` budget alone.
|
|
3241
|
-
*
|
|
3242
|
-
* forced to `true` regardless of `closed`
|
|
3243
|
-
*
|
|
3244
|
-
*
|
|
3245
|
-
*
|
|
3246
|
-
*
|
|
3247
|
-
*
|
|
4174
|
+
* the decrementing `depth` budget alone.
|
|
4175
|
+
*
|
|
4176
|
+
* `additionalProperties` is forced to `true` regardless of `closed` whenever
|
|
4177
|
+
* the declared key list stops describing every key the rows carry — the same
|
|
4178
|
+
* incomplete-sample-opens-the-schema rule {@link inferObject} applies, so a
|
|
4179
|
+
* closed schema never rejects the very rows it was inferred from. That happens
|
|
4180
|
+
* three ways: the union of sample keys exceeds `breadth` (truncation); a
|
|
4181
|
+
* hostile getter defeats a key's value walk (which drops that key for ALL
|
|
4182
|
+
* rows — a deliberate all-or-nothing scope, not a per-row partial failure);
|
|
4183
|
+
* or some row carries the key as an own property holding `undefined`, which
|
|
4184
|
+
* JSON encodes as no property at all, so the key is dropped rather than
|
|
4185
|
+
* declared with a shape that row would fail. When the KEY walk itself fails
|
|
4186
|
+
* (a hostile `ownKeys` trap on any row), nothing is known and the whole slot
|
|
4187
|
+
* widens to `{}`.
|
|
3248
4188
|
*
|
|
3249
4189
|
* @param samples - The plain-record samples
|
|
3250
4190
|
* @param depth - Remaining descent budget
|
|
@@ -3263,29 +4203,44 @@ function inferSamples(samples, depth, breadth, closed, format, enumOn) {
|
|
|
3263
4203
|
*/
|
|
3264
4204
|
function inferRecordSamples(samples, depth, breadth, closed, format, enumOn) {
|
|
3265
4205
|
if (!(depth > 0)) return {};
|
|
3266
|
-
const
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
const keys = keysOutcome.success ? keysOutcome.value.keys : [];
|
|
3276
|
-
const truncated = keysOutcome.success && keysOutcome.value.truncated;
|
|
4206
|
+
const keySet = /* @__PURE__ */ new Set();
|
|
4207
|
+
for (const sample of samples) {
|
|
4208
|
+
const sampleKeys = enumerableKeys(sample);
|
|
4209
|
+
if (sampleKeys === void 0) return {};
|
|
4210
|
+
for (const key of sampleKeys) keySet.add(key);
|
|
4211
|
+
}
|
|
4212
|
+
const allKeys = [...keySet].sort();
|
|
4213
|
+
const keys = allKeys.slice(0, breadth);
|
|
4214
|
+
const truncated = allKeys.length > breadth;
|
|
3277
4215
|
const properties = Object.create(null);
|
|
3278
4216
|
const required = [];
|
|
4217
|
+
let partial = truncated;
|
|
3279
4218
|
for (const key of keys) {
|
|
3280
4219
|
const valuesOutcome = attempt(() => {
|
|
3281
4220
|
const values = [];
|
|
4221
|
+
let dropped = false;
|
|
3282
4222
|
for (const sample of samples) {
|
|
3283
4223
|
const propertyValue = sample[key];
|
|
3284
|
-
if (propertyValue
|
|
4224
|
+
if (propertyValue === void 0) {
|
|
4225
|
+
if (Object.hasOwn(sample, key)) dropped = true;
|
|
4226
|
+
continue;
|
|
4227
|
+
}
|
|
4228
|
+
values.push(propertyValue);
|
|
3285
4229
|
}
|
|
3286
|
-
return
|
|
4230
|
+
return {
|
|
4231
|
+
values,
|
|
4232
|
+
dropped
|
|
4233
|
+
};
|
|
3287
4234
|
});
|
|
3288
|
-
|
|
4235
|
+
if (!valuesOutcome.success) {
|
|
4236
|
+
partial = true;
|
|
4237
|
+
continue;
|
|
4238
|
+
}
|
|
4239
|
+
const { values, dropped } = valuesOutcome.value;
|
|
4240
|
+
if (dropped) {
|
|
4241
|
+
partial = true;
|
|
4242
|
+
continue;
|
|
4243
|
+
}
|
|
3289
4244
|
if (values.length > 0) properties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn);
|
|
3290
4245
|
if (values.length === samples.length) required.push(key);
|
|
3291
4246
|
}
|
|
@@ -3293,7 +4248,7 @@ function inferRecordSamples(samples, depth, breadth, closed, format, enumOn) {
|
|
|
3293
4248
|
type: "object",
|
|
3294
4249
|
...Object.keys(properties).length > 0 ? { properties } : {},
|
|
3295
4250
|
...required.length > 0 ? { required } : {},
|
|
3296
|
-
additionalProperties:
|
|
4251
|
+
additionalProperties: partial ? true : !closed
|
|
3297
4252
|
};
|
|
3298
4253
|
}
|
|
3299
4254
|
/**
|
|
@@ -3335,8 +4290,14 @@ function samplesToSchema(samples, options) {
|
|
|
3335
4290
|
/**
|
|
3336
4291
|
* Build a string {@link StringShape}.
|
|
3337
4292
|
*
|
|
4293
|
+
* @remarks
|
|
4294
|
+
* A supplied pattern is captured by source and flags. The shape exposes a fresh
|
|
4295
|
+
* frozen zero-state `RegExp` on every `pattern` read, so neither the caller's
|
|
4296
|
+
* original nor a value read from the shape can drift later compiled artifacts.
|
|
4297
|
+
*
|
|
3338
4298
|
* @param options - Optional length (`min` / `max`), `pattern`, and `description`
|
|
3339
4299
|
* @returns A string shape
|
|
4300
|
+
* @throws {ContractError} When a present bound is invalid or `pattern` has flags
|
|
3340
4301
|
*
|
|
3341
4302
|
* @example
|
|
3342
4303
|
* ```ts
|
|
@@ -3344,19 +4305,44 @@ function samplesToSchema(samples, options) {
|
|
|
3344
4305
|
* ```
|
|
3345
4306
|
*/
|
|
3346
4307
|
function stringShape(options) {
|
|
3347
|
-
|
|
4308
|
+
const pattern = options?.pattern;
|
|
4309
|
+
if (options?.min !== void 0 && (!Number.isSafeInteger(options.min) || options.min < 0)) throw new ContractError("stringShape: min must be a non-negative safe integer", {
|
|
4310
|
+
code: "bound",
|
|
4311
|
+
context: {
|
|
4312
|
+
shape: "string",
|
|
4313
|
+
limit: "non-negative safe integer",
|
|
4314
|
+
received: String(options.min)
|
|
4315
|
+
}
|
|
4316
|
+
});
|
|
4317
|
+
if (options?.max !== void 0 && (!Number.isSafeInteger(options.max) || options.max < 0)) throw new ContractError("stringShape: max must be a non-negative safe integer", {
|
|
4318
|
+
code: "bound",
|
|
4319
|
+
context: {
|
|
4320
|
+
shape: "string",
|
|
4321
|
+
limit: "non-negative safe integer",
|
|
4322
|
+
received: String(options.max)
|
|
4323
|
+
}
|
|
4324
|
+
});
|
|
4325
|
+
if (pattern !== void 0 && pattern.flags.length > 0) throw new ContractError("stringShape: pattern must not use flags; use inline pattern constructs instead", {
|
|
4326
|
+
code: "pattern",
|
|
4327
|
+
context: {
|
|
4328
|
+
shape: "string",
|
|
4329
|
+
received: pattern.toString()
|
|
4330
|
+
}
|
|
4331
|
+
});
|
|
4332
|
+
return cloneShape({
|
|
3348
4333
|
type: "string",
|
|
3349
|
-
min: options
|
|
3350
|
-
max: options
|
|
3351
|
-
pattern:
|
|
3352
|
-
description: options
|
|
3353
|
-
};
|
|
4334
|
+
...options?.min === void 0 ? {} : { min: options.min },
|
|
4335
|
+
...options?.max === void 0 ? {} : { max: options.max },
|
|
4336
|
+
...pattern === void 0 ? {} : { pattern },
|
|
4337
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4338
|
+
});
|
|
3354
4339
|
}
|
|
3355
4340
|
/**
|
|
3356
4341
|
* Build a numeric {@link NumberShape}.
|
|
3357
4342
|
*
|
|
3358
4343
|
* @param options - Optional bounds (`min` / `max`), `integer`, and `description`
|
|
3359
4344
|
* @returns A number shape
|
|
4345
|
+
* @throws {ContractError} When a present bound is not finite
|
|
3360
4346
|
*
|
|
3361
4347
|
* @example
|
|
3362
4348
|
* ```ts
|
|
@@ -3364,13 +4350,30 @@ function stringShape(options) {
|
|
|
3364
4350
|
* ```
|
|
3365
4351
|
*/
|
|
3366
4352
|
function numberShape(options) {
|
|
3367
|
-
|
|
4353
|
+
const shape = options?.integer === true ? "integer" : "number";
|
|
4354
|
+
if (options?.min !== void 0 && !Number.isFinite(options.min)) throw new ContractError("numberShape: min must be finite", {
|
|
4355
|
+
code: "bound",
|
|
4356
|
+
context: {
|
|
4357
|
+
shape,
|
|
4358
|
+
limit: "finite number",
|
|
4359
|
+
received: String(options.min)
|
|
4360
|
+
}
|
|
4361
|
+
});
|
|
4362
|
+
if (options?.max !== void 0 && !Number.isFinite(options.max)) throw new ContractError("numberShape: max must be finite", {
|
|
4363
|
+
code: "bound",
|
|
4364
|
+
context: {
|
|
4365
|
+
shape,
|
|
4366
|
+
limit: "finite number",
|
|
4367
|
+
received: String(options.max)
|
|
4368
|
+
}
|
|
4369
|
+
});
|
|
4370
|
+
return Object.freeze({
|
|
3368
4371
|
type: "number",
|
|
3369
|
-
min: options
|
|
3370
|
-
max: options
|
|
3371
|
-
integer: options
|
|
3372
|
-
description: options
|
|
3373
|
-
};
|
|
4372
|
+
...options?.min === void 0 ? {} : { min: options.min },
|
|
4373
|
+
...options?.max === void 0 ? {} : { max: options.max },
|
|
4374
|
+
...options?.integer === void 0 ? {} : { integer: options.integer },
|
|
4375
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4376
|
+
});
|
|
3374
4377
|
}
|
|
3375
4378
|
/**
|
|
3376
4379
|
* Build an integer {@link NumberShape} — forces `integer: true`.
|
|
@@ -3381,15 +4384,13 @@ function numberShape(options) {
|
|
|
3381
4384
|
*
|
|
3382
4385
|
* @param options - Optional bounds and `description` (no `integer` key)
|
|
3383
4386
|
* @returns An integer number shape
|
|
4387
|
+
* @throws {ContractError} When a present bound is not finite
|
|
3384
4388
|
*/
|
|
3385
4389
|
function integerShape(options) {
|
|
3386
|
-
return {
|
|
3387
|
-
|
|
3388
|
-
integer: true
|
|
3389
|
-
|
|
3390
|
-
max: options?.max,
|
|
3391
|
-
description: options?.description
|
|
3392
|
-
};
|
|
4390
|
+
return numberShape({
|
|
4391
|
+
...options,
|
|
4392
|
+
integer: true
|
|
4393
|
+
});
|
|
3393
4394
|
}
|
|
3394
4395
|
/**
|
|
3395
4396
|
* Build a {@link BooleanShape}.
|
|
@@ -3403,10 +4404,10 @@ function integerShape(options) {
|
|
|
3403
4404
|
* ```
|
|
3404
4405
|
*/
|
|
3405
4406
|
function booleanShape(options) {
|
|
3406
|
-
return {
|
|
4407
|
+
return Object.freeze({
|
|
3407
4408
|
type: "boolean",
|
|
3408
|
-
description: options
|
|
3409
|
-
};
|
|
4409
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4410
|
+
});
|
|
3410
4411
|
}
|
|
3411
4412
|
/**
|
|
3412
4413
|
* Build a {@link NullShape}.
|
|
@@ -3420,32 +4421,18 @@ function booleanShape(options) {
|
|
|
3420
4421
|
* ```
|
|
3421
4422
|
*/
|
|
3422
4423
|
function nullShape(options) {
|
|
3423
|
-
return {
|
|
4424
|
+
return Object.freeze({
|
|
3424
4425
|
type: "null",
|
|
3425
|
-
description: options
|
|
3426
|
-
};
|
|
4426
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4427
|
+
});
|
|
3427
4428
|
}
|
|
3428
|
-
/**
|
|
3429
|
-
* Build a literal shape from a fixed set of primitive values.
|
|
3430
|
-
*
|
|
3431
|
-
* @param values - The permitted literals
|
|
3432
|
-
* @param options - Optional `description`
|
|
3433
|
-
* @returns A literal shape whose `Infer` is the union of `values`
|
|
3434
|
-
*
|
|
3435
|
-
* @example
|
|
3436
|
-
* ```ts
|
|
3437
|
-
* const role = literalShape(['admin', 'member', 'guest'])
|
|
3438
|
-
* // Infer<typeof role> = 'admin' | 'member' | 'guest'
|
|
3439
|
-
*
|
|
3440
|
-
* const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
|
|
3441
|
-
* ```
|
|
3442
|
-
*/
|
|
3443
4429
|
function literalShape(values, options) {
|
|
3444
|
-
|
|
4430
|
+
const snapshot = Object.freeze([...values]);
|
|
4431
|
+
return Object.freeze({
|
|
3445
4432
|
type: "literal",
|
|
3446
|
-
values,
|
|
3447
|
-
description: options
|
|
3448
|
-
};
|
|
4433
|
+
values: snapshot,
|
|
4434
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4435
|
+
});
|
|
3449
4436
|
}
|
|
3450
4437
|
/**
|
|
3451
4438
|
* Build an {@link ArrayShape} from an element shape.
|
|
@@ -3453,6 +4440,7 @@ function literalShape(values, options) {
|
|
|
3453
4440
|
* @param items - The element shape
|
|
3454
4441
|
* @param options - Optional length bounds and `description`
|
|
3455
4442
|
* @returns An array shape
|
|
4443
|
+
* @throws {ContractError} When a present bound is not a non-negative safe integer
|
|
3456
4444
|
*
|
|
3457
4445
|
* @example
|
|
3458
4446
|
* ```ts
|
|
@@ -3460,13 +4448,29 @@ function literalShape(values, options) {
|
|
|
3460
4448
|
* ```
|
|
3461
4449
|
*/
|
|
3462
4450
|
function arrayShape(items, options) {
|
|
3463
|
-
|
|
4451
|
+
if (options?.min !== void 0 && (!Number.isSafeInteger(options.min) || options.min < 0)) throw new ContractError("arrayShape: min must be a non-negative safe integer", {
|
|
4452
|
+
code: "bound",
|
|
4453
|
+
context: {
|
|
4454
|
+
shape: "array",
|
|
4455
|
+
limit: "non-negative safe integer",
|
|
4456
|
+
received: String(options.min)
|
|
4457
|
+
}
|
|
4458
|
+
});
|
|
4459
|
+
if (options?.max !== void 0 && (!Number.isSafeInteger(options.max) || options.max < 0)) throw new ContractError("arrayShape: max must be a non-negative safe integer", {
|
|
4460
|
+
code: "bound",
|
|
4461
|
+
context: {
|
|
4462
|
+
shape: "array",
|
|
4463
|
+
limit: "non-negative safe integer",
|
|
4464
|
+
received: String(options.max)
|
|
4465
|
+
}
|
|
4466
|
+
});
|
|
4467
|
+
return Object.freeze({
|
|
3464
4468
|
type: "array",
|
|
3465
4469
|
items,
|
|
3466
|
-
min: options
|
|
3467
|
-
max: options
|
|
3468
|
-
description: options
|
|
3469
|
-
};
|
|
4470
|
+
...options?.min === void 0 ? {} : { min: options.min },
|
|
4471
|
+
...options?.max === void 0 ? {} : { max: options.max },
|
|
4472
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4473
|
+
});
|
|
3470
4474
|
}
|
|
3471
4475
|
/**
|
|
3472
4476
|
* Build an {@link ObjectShape} from a property map.
|
|
@@ -3490,12 +4494,14 @@ function arrayShape(items, options) {
|
|
|
3490
4494
|
* ```
|
|
3491
4495
|
*/
|
|
3492
4496
|
function objectShape(properties, options) {
|
|
3493
|
-
|
|
4497
|
+
const snapshot = Object.create(null);
|
|
4498
|
+
for (const key in properties) if (Object.hasOwn(properties, key)) snapshot[key] = properties[key];
|
|
4499
|
+
return Object.freeze({
|
|
3494
4500
|
type: "object",
|
|
3495
|
-
properties,
|
|
3496
|
-
additionalProperties: options
|
|
3497
|
-
description: options
|
|
3498
|
-
};
|
|
4501
|
+
properties: Object.freeze(snapshot),
|
|
4502
|
+
...options?.additionalProperties === void 0 ? {} : { additionalProperties: options.additionalProperties },
|
|
4503
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4504
|
+
});
|
|
3499
4505
|
}
|
|
3500
4506
|
/**
|
|
3501
4507
|
* Build an open {@link ObjectShape} with no fixed properties — a dictionary.
|
|
@@ -3514,12 +4520,12 @@ function objectShape(properties, options) {
|
|
|
3514
4520
|
* ```
|
|
3515
4521
|
*/
|
|
3516
4522
|
function recordShape(values, options) {
|
|
3517
|
-
return {
|
|
4523
|
+
return Object.freeze({
|
|
3518
4524
|
type: "object",
|
|
3519
|
-
properties: {},
|
|
4525
|
+
properties: Object.freeze({}),
|
|
3520
4526
|
additionalProperties: values,
|
|
3521
|
-
description: options
|
|
3522
|
-
};
|
|
4527
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4528
|
+
});
|
|
3523
4529
|
}
|
|
3524
4530
|
/**
|
|
3525
4531
|
* Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
|
|
@@ -3534,10 +4540,10 @@ function recordShape(values, options) {
|
|
|
3534
4540
|
* ```
|
|
3535
4541
|
*/
|
|
3536
4542
|
function unionShape(...variants) {
|
|
3537
|
-
return {
|
|
4543
|
+
return Object.freeze({
|
|
3538
4544
|
type: "union",
|
|
3539
|
-
variants
|
|
3540
|
-
};
|
|
4545
|
+
variants: Object.freeze(variants)
|
|
4546
|
+
});
|
|
3541
4547
|
}
|
|
3542
4548
|
/**
|
|
3543
4549
|
* Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
|
|
@@ -3572,11 +4578,11 @@ function unionShape(...variants) {
|
|
|
3572
4578
|
* ```
|
|
3573
4579
|
*/
|
|
3574
4580
|
function oneOfShape(...variants) {
|
|
3575
|
-
return {
|
|
4581
|
+
return Object.freeze({
|
|
3576
4582
|
type: "union",
|
|
3577
|
-
variants,
|
|
4583
|
+
variants: Object.freeze(variants),
|
|
3578
4584
|
mode: "oneOf"
|
|
3579
|
-
};
|
|
4585
|
+
});
|
|
3580
4586
|
}
|
|
3581
4587
|
/**
|
|
3582
4588
|
* Wrap a shape so it may be absent (`undefined`).
|
|
@@ -3589,10 +4595,10 @@ function oneOfShape(...variants) {
|
|
|
3589
4595
|
* @returns An optional shape
|
|
3590
4596
|
*/
|
|
3591
4597
|
function optionalShape(inner) {
|
|
3592
|
-
return {
|
|
4598
|
+
return Object.freeze({
|
|
3593
4599
|
type: "optional",
|
|
3594
4600
|
inner
|
|
3595
|
-
};
|
|
4601
|
+
});
|
|
3596
4602
|
}
|
|
3597
4603
|
/**
|
|
3598
4604
|
* Wrap a shape so it may be `null`.
|
|
@@ -3607,18 +4613,18 @@ function optionalShape(inner) {
|
|
|
3607
4613
|
* ```
|
|
3608
4614
|
*/
|
|
3609
4615
|
function nullableShape(inner) {
|
|
3610
|
-
return {
|
|
4616
|
+
return Object.freeze({
|
|
3611
4617
|
type: "nullable",
|
|
3612
4618
|
inner
|
|
3613
|
-
};
|
|
4619
|
+
});
|
|
3614
4620
|
}
|
|
3615
4621
|
/**
|
|
3616
4622
|
* Build a {@link JSONShape}.
|
|
3617
4623
|
*
|
|
3618
4624
|
* @remarks
|
|
3619
4625
|
* The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
|
|
3620
|
-
* schema fragment and accepts
|
|
3621
|
-
* that a value is real JSON (via {@link isJSONValue}).
|
|
4626
|
+
* schema fragment and accepts every defined value at runtime, while `jsonShape`
|
|
4627
|
+
* validates that a value is real JSON (via {@link isJSONValue}).
|
|
3622
4628
|
*
|
|
3623
4629
|
* @param options - Optional `description`
|
|
3624
4630
|
* @returns A JSON passthrough shape
|
|
@@ -3629,20 +4635,27 @@ function nullableShape(inner) {
|
|
|
3629
4635
|
* ```
|
|
3630
4636
|
*/
|
|
3631
4637
|
function jsonShape(options) {
|
|
3632
|
-
return {
|
|
4638
|
+
return Object.freeze({
|
|
3633
4639
|
type: "json",
|
|
3634
|
-
description: options
|
|
3635
|
-
};
|
|
4640
|
+
...options?.description === void 0 ? {} : { description: options.description }
|
|
4641
|
+
});
|
|
3636
4642
|
}
|
|
3637
4643
|
/**
|
|
3638
4644
|
* Build a {@link RawShape} from a JSON Schema fragment.
|
|
3639
4645
|
*
|
|
3640
4646
|
* @remarks
|
|
3641
|
-
* For values the shape DSL can't express. The compiled guard accepts
|
|
3642
|
-
*
|
|
4647
|
+
* For values the shape DSL can't express. The compiled guard accepts every
|
|
4648
|
+
* DEFINED value — `undefined` alone fails, because it is the parser's failure
|
|
4649
|
+
* sentinel; wrap the shape in {@link optionalShape} to admit absence. The
|
|
4650
|
+
* parser passes a defined value through unchanged, and the fragment is
|
|
4651
|
+
* deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so
|
|
4652
|
+
* `rawShape(fragment).schema !== fragment` and later edits to the caller's
|
|
4653
|
+
* fragment cannot reach the shape. `compileSchema` re-emits that snapshot
|
|
4654
|
+
* structurally verbatim; `compileGenerator` throws, since an arbitrary embedded
|
|
4655
|
+
* schema has no auto-generatable sample.
|
|
3643
4656
|
*
|
|
3644
4657
|
* @param schema - The JSON Schema fragment to embed
|
|
3645
|
-
* @returns A raw shape
|
|
4658
|
+
* @returns A raw shape owning a frozen copy of the fragment
|
|
3646
4659
|
*
|
|
3647
4660
|
* @example
|
|
3648
4661
|
* ```ts
|
|
@@ -3650,10 +4663,10 @@ function jsonShape(options) {
|
|
|
3650
4663
|
* ```
|
|
3651
4664
|
*/
|
|
3652
4665
|
function rawShape(schema) {
|
|
3653
|
-
return {
|
|
4666
|
+
return Object.freeze({
|
|
3654
4667
|
type: "raw",
|
|
3655
|
-
schema
|
|
3656
|
-
};
|
|
4668
|
+
schema: cloneSchema(schema)
|
|
4669
|
+
});
|
|
3657
4670
|
}
|
|
3658
4671
|
/**
|
|
3659
4672
|
* Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
|
|
@@ -3661,10 +4674,11 @@ function rawShape(schema) {
|
|
|
3661
4674
|
*
|
|
3662
4675
|
* @remarks
|
|
3663
4676
|
* Total and pure. Either keyword is used only when it is a non-negative
|
|
3664
|
-
* integer (`
|
|
3665
|
-
* number, `NaN`, `Infinity`, a fraction
|
|
3666
|
-
* bounds are present and `min` exceeds `max`,
|
|
3667
|
-
* (an unbounded shape is always a legal widening
|
|
4677
|
+
* safe integer (`Number.isSafeInteger` + `>= 0`); a malformed value (a string,
|
|
4678
|
+
* a negative number, `NaN`, `Infinity`, a fraction, or an unsafe integer) is
|
|
4679
|
+
* dropped as if absent. When both bounds are present and `min` exceeds `max`,
|
|
4680
|
+
* the PAIR is dropped entirely (an unbounded shape is always a legal widening
|
|
4681
|
+
* of a contradictory schema).
|
|
3668
4682
|
*
|
|
3669
4683
|
* @param min - The raw `minLength` / `minItems` keyword value
|
|
3670
4684
|
* @param max - The raw `maxLength` / `maxItems` keyword value
|
|
@@ -3678,12 +4692,12 @@ function rawShape(schema) {
|
|
|
3678
4692
|
* ```
|
|
3679
4693
|
*/
|
|
3680
4694
|
function deriveLengthBounds(min, max) {
|
|
3681
|
-
const lo = isInteger(min) && min >= 0 ? min : void 0;
|
|
3682
|
-
const hi = isInteger(max) && max >= 0 ? max : void 0;
|
|
4695
|
+
const lo = isInteger(min) && Number.isSafeInteger(min) && min >= 0 ? min : void 0;
|
|
4696
|
+
const hi = isInteger(max) && Number.isSafeInteger(max) && max >= 0 ? max : void 0;
|
|
3683
4697
|
if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
|
|
3684
4698
|
return {
|
|
3685
|
-
min: lo,
|
|
3686
|
-
max: hi
|
|
4699
|
+
...lo === void 0 ? {} : { min: lo },
|
|
4700
|
+
...hi === void 0 ? {} : { max: hi }
|
|
3687
4701
|
};
|
|
3688
4702
|
}
|
|
3689
4703
|
/**
|
|
@@ -3711,8 +4725,8 @@ function deriveRangeBounds(min, max) {
|
|
|
3711
4725
|
const hi = isFiniteNumber(max) ? max : void 0;
|
|
3712
4726
|
if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
|
|
3713
4727
|
return {
|
|
3714
|
-
min: lo,
|
|
3715
|
-
max: hi
|
|
4728
|
+
...lo === void 0 ? {} : { min: lo },
|
|
4729
|
+
...hi === void 0 ? {} : { max: hi }
|
|
3716
4730
|
};
|
|
3717
4731
|
}
|
|
3718
4732
|
/**
|
|
@@ -3724,7 +4738,7 @@ function deriveRangeBounds(min, max) {
|
|
|
3724
4738
|
* `properties` (when a record) contributes one child shape per own key, capped
|
|
3725
4739
|
* at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
|
|
3726
4740
|
* unless it appears as a string entry of `required`. A property whose value is
|
|
3727
|
-
* not itself a record widens to {@link
|
|
4741
|
+
* not itself a record widens to {@link rawShape}. `additionalProperties`:
|
|
3728
4742
|
* `false` closes the object; a record value recurses into it (`objectShape`
|
|
3729
4743
|
* validates extras against that shape); anything else — `true`, absent, or
|
|
3730
4744
|
* malformed — leaves the object OPEN (`true`), matching JSON Schema's own
|
|
@@ -3734,8 +4748,8 @@ function deriveRangeBounds(min, max) {
|
|
|
3734
4748
|
* keys than {@link INFER_BREADTH_LIMIT}, the schema's own
|
|
3735
4749
|
* `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
|
|
3736
4750
|
* a dropped key's value could otherwise fail a `false` or record-valued rest
|
|
3737
|
-
* shape it was never checked against — mirroring
|
|
3738
|
-
*
|
|
4751
|
+
* shape it was never checked against — mirroring {@link inferObject}'s
|
|
4752
|
+
* partial-key handling in `inferers.ts`. The accumulator uses a
|
|
3739
4753
|
* null-prototype record so a property literally named `__proto__` becomes an
|
|
3740
4754
|
* own data key rather than mutating the prototype, mirroring
|
|
3741
4755
|
* {@link inferObject} (inferers.ts).
|
|
@@ -3776,14 +4790,14 @@ function buildObjectShape(schema, depth, visited, memo, description) {
|
|
|
3776
4790
|
const keys = allKeys.slice(0, 256);
|
|
3777
4791
|
for (const key of keys) {
|
|
3778
4792
|
const child = propertiesSource[key];
|
|
3779
|
-
const childShape = isRecord(child) ? schemaNodeToShape(child, depth - 1, visited, memo) :
|
|
4793
|
+
const childShape = isRecord(child) ? schemaNodeToShape(child, depth - 1, visited, memo) : rawShape({});
|
|
3780
4794
|
properties[key] = requiredSource.includes(key) ? childShape : optionalShape(childShape);
|
|
3781
4795
|
}
|
|
3782
4796
|
}
|
|
3783
4797
|
const extra = schema.additionalProperties;
|
|
3784
4798
|
return objectShape(properties, {
|
|
3785
4799
|
additionalProperties: truncated ? true : extra === false ? false : isRecord(extra) ? schemaNodeToShape(extra, depth - 1, visited, memo) : true,
|
|
3786
|
-
description
|
|
4800
|
+
...description === void 0 ? {} : { description }
|
|
3787
4801
|
});
|
|
3788
4802
|
}
|
|
3789
4803
|
/**
|
|
@@ -3806,7 +4820,7 @@ function buildObjectShape(schema, depth, visited, memo, description) {
|
|
|
3806
4820
|
* record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
|
|
3807
4821
|
* limit, building a subset union would be strictly narrower than the
|
|
3808
4822
|
* schema's full union (a value matching only a dropped variant would be
|
|
3809
|
-
* wrongly rejected), so the whole node widens to {@link
|
|
4823
|
+
* wrongly rejected), so the whole node widens to {@link rawShape} instead
|
|
3810
4824
|
* of sampling a subset.
|
|
3811
4825
|
* 3. `anyOf` — identically, via {@link unionShape}.
|
|
3812
4826
|
* 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
|
|
@@ -3816,14 +4830,16 @@ function buildObjectShape(schema, depth, visited, memo, description) {
|
|
|
3816
4830
|
* (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
|
|
3817
4831
|
* rejects — so the result is always a valid shape.
|
|
3818
4832
|
* 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
|
|
3819
|
-
* a record-valued `items` (widening to {@link
|
|
4833
|
+
* a record-valued `items` (widening to {@link rawShape} otherwise), with
|
|
3820
4834
|
* bounds from `minItems` / `maxItems`.
|
|
3821
4835
|
* 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
|
|
3822
4836
|
* record-valued `properties` — delegates to {@link buildObjectShape}.
|
|
3823
4837
|
* 7. Everything else — an empty schema, an unrecognized/absent `type`,
|
|
3824
4838
|
* exhausted depth/breadth, or an attempt failure — widens to
|
|
3825
|
-
* {@link
|
|
3826
|
-
*
|
|
4839
|
+
* {@link rawShape}, whose guard accepts every defined value and whose
|
|
4840
|
+
* emitted schema is the same `{}` (plus `description`) the node carried.
|
|
4841
|
+
* This is the exact inverse of `{}`, JSON Schema's accept-anything schema,
|
|
4842
|
+
* and where the inferers themselves bottom out at their own limits.
|
|
3827
4843
|
*
|
|
3828
4844
|
* `format` and `pattern` are NEVER read into the compiled shape — `format` is
|
|
3829
4845
|
* annotation-only and `pattern` compiling an attacker-supplied string into a
|
|
@@ -3831,7 +4847,7 @@ function buildObjectShape(schema, depth, visited, memo, description) {
|
|
|
3831
4847
|
* the produced shape's `description` option.
|
|
3832
4848
|
*
|
|
3833
4849
|
* @param schema - The schema node to convert
|
|
3834
|
-
* @param depth - Remaining descent budget (0 halts recursion with `
|
|
4850
|
+
* @param depth - Remaining descent budget (0 halts recursion with `rawShape({})`)
|
|
3835
4851
|
* @param visited - The ancestor set guarding against cycles — recursion
|
|
3836
4852
|
* state owned by the {@link schemaToShape} entry point; passing a shared or
|
|
3837
4853
|
* pre-populated `WeakSet` changes cycle-detection behavior and is not
|
|
@@ -3854,58 +4870,44 @@ function buildShapeFromNode(schema, depth, visited, memo) {
|
|
|
3854
4870
|
const description = isString(schema.description) ? schema.description : void 0;
|
|
3855
4871
|
if (isArray(schema.enum)) {
|
|
3856
4872
|
const literals = schema.enum.filter((entry) => isString(entry) || isFiniteNumber(entry) || isBoolean(entry));
|
|
3857
|
-
if (literals.length > 0) return literalShape(literals, { description });
|
|
4873
|
+
if (literals.length > 0) return literalShape(literals, description === void 0 ? void 0 : { description });
|
|
3858
4874
|
}
|
|
3859
4875
|
if (isArray(schema.oneOf)) {
|
|
3860
4876
|
const records = schema.oneOf.filter((entry) => isRecord(entry));
|
|
3861
|
-
if (records.length > 256) return
|
|
4877
|
+
if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
|
|
3862
4878
|
const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
|
|
3863
4879
|
if (variants.length > 0) return oneOfShape(...variants);
|
|
3864
4880
|
}
|
|
3865
4881
|
if (isArray(schema.anyOf)) {
|
|
3866
4882
|
const records = schema.anyOf.filter((entry) => isRecord(entry));
|
|
3867
|
-
if (records.length > 256) return
|
|
4883
|
+
if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
|
|
3868
4884
|
const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
|
|
3869
4885
|
if (variants.length > 0) return unionShape(...variants);
|
|
3870
4886
|
}
|
|
3871
4887
|
const type = isString(schema.type) ? schema.type : void 0;
|
|
3872
|
-
if (type === "string") {
|
|
3873
|
-
|
|
3874
|
-
|
|
3875
|
-
|
|
3876
|
-
|
|
3877
|
-
|
|
3878
|
-
}
|
|
3879
|
-
}
|
|
3880
|
-
if (type === "number") {
|
|
3881
|
-
const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
|
|
3882
|
-
return numberShape({
|
|
3883
|
-
min: bounds.min,
|
|
3884
|
-
max: bounds.max,
|
|
3885
|
-
description
|
|
3886
|
-
});
|
|
3887
|
-
}
|
|
4888
|
+
if (type === "string") return stringShape({
|
|
4889
|
+
...deriveLengthBounds(schema.minLength, schema.maxLength),
|
|
4890
|
+
...description === void 0 ? {} : { description }
|
|
4891
|
+
});
|
|
4892
|
+
if (type === "number") return numberShape({
|
|
4893
|
+
...deriveRangeBounds(schema.minimum, schema.maximum),
|
|
4894
|
+
...description === void 0 ? {} : { description }
|
|
4895
|
+
});
|
|
3888
4896
|
if (type === "integer") {
|
|
3889
4897
|
const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
|
|
3890
|
-
return integerShape(Math.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > Math.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? { description } : {
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
description
|
|
3894
|
-
});
|
|
3895
|
-
}
|
|
3896
|
-
if (type === "boolean") return booleanShape({ description });
|
|
3897
|
-
if (type === "null") return nullShape({ description });
|
|
3898
|
-
if (type === "array") {
|
|
3899
|
-
const items = isRecord(schema.items) ? schemaNodeToShape(schema.items, depth - 1, visited, memo) : jsonShape();
|
|
3900
|
-
const bounds = deriveLengthBounds(schema.minItems, schema.maxItems);
|
|
3901
|
-
return arrayShape(items, {
|
|
3902
|
-
min: bounds.min,
|
|
3903
|
-
max: bounds.max,
|
|
3904
|
-
description
|
|
4898
|
+
return integerShape(Math.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > Math.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : { description } : {
|
|
4899
|
+
...bounds,
|
|
4900
|
+
...description === void 0 ? {} : { description }
|
|
3905
4901
|
});
|
|
3906
4902
|
}
|
|
4903
|
+
if (type === "boolean") return booleanShape(description === void 0 ? void 0 : { description });
|
|
4904
|
+
if (type === "null") return nullShape(description === void 0 ? void 0 : { description });
|
|
4905
|
+
if (type === "array") return arrayShape(isRecord(schema.items) ? schemaNodeToShape(schema.items, depth - 1, visited, memo) : rawShape({}), {
|
|
4906
|
+
...deriveLengthBounds(schema.minItems, schema.maxItems),
|
|
4907
|
+
...description === void 0 ? {} : { description }
|
|
4908
|
+
});
|
|
3907
4909
|
if (type === "object" || type === void 0 && isRecord(schema.properties)) return buildObjectShape(schema, depth, visited, memo, description);
|
|
3908
|
-
return
|
|
4910
|
+
return rawShape(description === void 0 ? {} : { description });
|
|
3909
4911
|
}
|
|
3910
4912
|
/**
|
|
3911
4913
|
* Convert one JSON Schema node into a {@link ContractShape} — the recursion
|
|
@@ -3916,13 +4918,13 @@ function buildShapeFromNode(schema, depth, visited, memo) {
|
|
|
3916
4918
|
* @remarks
|
|
3917
4919
|
* Total: never throws. Guards depth exhaustion, a non-record node (the
|
|
3918
4920
|
* node's static `JSONSchema` type is not trusted at runtime), and a cyclic
|
|
3919
|
-
* re-encounter of `schema` — all three widen to {@link
|
|
4921
|
+
* re-encounter of `schema` — all three widen to {@link rawShape}. The
|
|
3920
4922
|
* ancestor set is added to and removed from around the WHOLE subtree
|
|
3921
4923
|
* conversion (not permanently), so a DAG-shaped schema reached twice via two
|
|
3922
4924
|
* different, non-cyclic paths does not false-positive as a cycle. The
|
|
3923
4925
|
* subtree conversion itself runs inside {@link attempt}, so a hostile
|
|
3924
4926
|
* throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
|
|
3925
|
-
* — it degrades to {@link
|
|
4927
|
+
* — it degrades to {@link rawShape} instead. A same-node re-conversion at
|
|
3926
4928
|
* the same remaining `depth` is served from `memo` (guards a
|
|
3927
4929
|
* shared-reference schema DAG against exponential blowup), mirroring
|
|
3928
4930
|
* {@link inferObject} / {@link inferArray} (inferers.ts).
|
|
@@ -3937,7 +4939,7 @@ function buildShapeFromNode(schema, depth, visited, memo) {
|
|
|
3937
4939
|
* recursion state owned by the {@link schemaToShape} entry point; passing
|
|
3938
4940
|
* a shared or pre-populated `WeakMap` changes caching behavior and is not
|
|
3939
4941
|
* supported usage
|
|
3940
|
-
* @returns The built shape for `schema`, or {@link
|
|
4942
|
+
* @returns The built shape for `schema`, or {@link rawShape} on any failure
|
|
3941
4943
|
*
|
|
3942
4944
|
* @example
|
|
3943
4945
|
* ```ts
|
|
@@ -3946,13 +4948,13 @@ function buildShapeFromNode(schema, depth, visited, memo) {
|
|
|
3946
4948
|
* ```
|
|
3947
4949
|
*/
|
|
3948
4950
|
function schemaNodeToShape(schema, depth, visited, memo) {
|
|
3949
|
-
if (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return
|
|
4951
|
+
if (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return rawShape({});
|
|
3950
4952
|
const cached = memo.get(schema)?.get(depth);
|
|
3951
4953
|
if (cached) return cached;
|
|
3952
4954
|
visited.add(schema);
|
|
3953
4955
|
const outcome = attempt(() => buildShapeFromNode(schema, depth, visited, memo));
|
|
3954
4956
|
visited.delete(schema);
|
|
3955
|
-
const shape = outcome.success ? outcome.value :
|
|
4957
|
+
const shape = outcome.success ? outcome.value : rawShape({});
|
|
3956
4958
|
let depths = memo.get(schema);
|
|
3957
4959
|
if (!depths) {
|
|
3958
4960
|
depths = /* @__PURE__ */ new Map();
|
|
@@ -3969,7 +4971,7 @@ function schemaNodeToShape(schema, depth, visited, memo) {
|
|
|
3969
4971
|
* @remarks
|
|
3970
4972
|
* Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
|
|
3971
4973
|
* outright hostile (throwing-getter Proxy) `schema` value all degrade to
|
|
3972
|
-
* {@link
|
|
4974
|
+
* {@link rawShape} rather than escaping as an error, so
|
|
3973
4975
|
* `createContract(schemaToShape(x))` is safe to call for any `x`. See
|
|
3974
4976
|
* {@link buildShapeFromNode} for the exact per-keyword precedence.
|
|
3975
4977
|
*
|
|
@@ -3979,9 +4981,36 @@ function schemaNodeToShape(schema, depth, visited, memo) {
|
|
|
3979
4981
|
* `RegExp` is a ReDoS vector; both keywords are read only far enough to be
|
|
3980
4982
|
* ignored. Any node the walk cannot express — an empty `{}`, an
|
|
3981
4983
|
* unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
|
|
3982
|
-
* cyclic re-encounter — widens to {@link
|
|
3983
|
-
*
|
|
3984
|
-
*
|
|
4984
|
+
* cyclic re-encounter — widens to {@link rawShape} (accept any defined
|
|
4985
|
+
* value), never narrows.
|
|
4986
|
+
*
|
|
4987
|
+
* ROUND TRIP: `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` for
|
|
4988
|
+
* every `v` — including the values no JSON Schema keyword describes (`NaN`,
|
|
4989
|
+
* `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a
|
|
4990
|
+
* bigint, a cyclic or hostile host), which infer `{}` and widen back to an
|
|
4991
|
+
* accept-anything {@link rawShape}. Widening is the only source of looseness.
|
|
4992
|
+
* The law has three explicit host limits:
|
|
4993
|
+
*
|
|
4994
|
+
* - **Absence.** `undefined` is not a value: no compiled guard accepts it
|
|
4995
|
+
* (`rawShape` reserves it as the parser failure sentinel). So `undefined`
|
|
4996
|
+
* itself, an array element holding it, and an array HOLE (`arrayOf` requires
|
|
4997
|
+
* every index to be an own property, the same rule `isJSONValue` applies)
|
|
4998
|
+
* all fall outside the law. An OBJECT property holding `undefined` does not:
|
|
4999
|
+
* `valueToSchema` drops the key and opens the object, so the source object
|
|
5000
|
+
* is still accepted.
|
|
5001
|
+
* - **`Date` serialization.** A `Date` infers the schema of its JSON form
|
|
5002
|
+
* (`{ type: 'string' }`, plus `format: 'date-time'` when `format` is on), so
|
|
5003
|
+
* the law applies to `date.toISOString()` rather than the runtime instance.
|
|
5004
|
+
* - **Stateful access.** A getter whose result changes between inference and
|
|
5005
|
+
* guard evaluation can invalidate the sampled fact. Likewise, an array that
|
|
5006
|
+
* overrides iteration behavior can present different elements to the two
|
|
5007
|
+
* phases. The law applies only while the sampled host's observable own
|
|
5008
|
+
* enumerable string properties and array iteration remain stable.
|
|
5009
|
+
*
|
|
5010
|
+
* A widened node cannot be auto-generated: `rawShape` embeds an arbitrary
|
|
5011
|
+
* schema fragment, so `createContract(schemaToShape(x)).generate()` throws
|
|
5012
|
+
* when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
|
|
5013
|
+
* stay total.
|
|
3985
5014
|
*
|
|
3986
5015
|
* @param schema - The JSON Schema value to convert
|
|
3987
5016
|
* @returns The built {@link ContractShape}
|
|
@@ -3998,9 +5027,13 @@ function schemaToShape(schema) {
|
|
|
3998
5027
|
return schemaNodeToShape(schema, 32, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap());
|
|
3999
5028
|
}
|
|
4000
5029
|
//#endregion
|
|
5030
|
+
exports.COMPILE_DEPTH_LIMIT = COMPILE_DEPTH_LIMIT;
|
|
5031
|
+
exports.ContractError = ContractError;
|
|
4001
5032
|
exports.FAULT_LIMIT = FAULT_LIMIT;
|
|
4002
5033
|
exports.FORMAT_MAX_LENGTH = FORMAT_MAX_LENGTH;
|
|
4003
5034
|
exports.FORMAT_PATTERNS = FORMAT_PATTERNS;
|
|
5035
|
+
exports.GENERATION_ATTEMPT_LIMIT = GENERATION_ATTEMPT_LIMIT;
|
|
5036
|
+
exports.GUARD_DEPTH_LIMIT = GUARD_DEPTH_LIMIT;
|
|
4004
5037
|
exports.INFER_BREADTH_LIMIT = INFER_BREADTH_LIMIT;
|
|
4005
5038
|
exports.INFER_DEPTH_LIMIT = INFER_DEPTH_LIMIT;
|
|
4006
5039
|
exports.INFER_ENUM_LIMIT = INFER_ENUM_LIMIT;
|
|
@@ -4015,6 +5048,9 @@ exports.boundsOf = boundsOf;
|
|
|
4015
5048
|
exports.buildObjectShape = buildObjectShape;
|
|
4016
5049
|
exports.buildShapeFromNode = buildShapeFromNode;
|
|
4017
5050
|
exports.canonicalStringify = canonicalStringify;
|
|
5051
|
+
exports.canonicalizeValue = canonicalizeValue;
|
|
5052
|
+
exports.cloneSchema = cloneSchema;
|
|
5053
|
+
exports.cloneShape = cloneShape;
|
|
4018
5054
|
exports.compileGenerator = compileGenerator;
|
|
4019
5055
|
exports.compileGuard = compileGuard;
|
|
4020
5056
|
exports.compileParser = compileParser;
|
|
@@ -4024,8 +5060,11 @@ exports.complementOf = complementOf;
|
|
|
4024
5060
|
exports.createContract = createContract;
|
|
4025
5061
|
exports.deriveLengthBounds = deriveLengthBounds;
|
|
4026
5062
|
exports.deriveRangeBounds = deriveRangeBounds;
|
|
5063
|
+
exports.drawRandom = drawRandom;
|
|
4027
5064
|
exports.enumOf = enumOf;
|
|
5065
|
+
exports.enumerableKeys = enumerableKeys;
|
|
4028
5066
|
exports.enumerableSymbolCount = enumerableSymbolCount;
|
|
5067
|
+
exports.holds = holds;
|
|
4029
5068
|
exports.inferArray = inferArray;
|
|
4030
5069
|
exports.inferObject = inferObject;
|
|
4031
5070
|
exports.inferPrimitiveEnum = inferPrimitiveEnum;
|
|
@@ -4046,6 +5085,7 @@ exports.isBigInt64Array = isBigInt64Array;
|
|
|
4046
5085
|
exports.isBigUint64Array = isBigUint64Array;
|
|
4047
5086
|
exports.isBoolean = isBoolean;
|
|
4048
5087
|
exports.isConstructor = isConstructor;
|
|
5088
|
+
exports.isContractError = isContractError;
|
|
4049
5089
|
exports.isDataView = isDataView;
|
|
4050
5090
|
exports.isDate = isDate;
|
|
4051
5091
|
exports.isDefined = isDefined;
|
|
@@ -4102,7 +5142,6 @@ exports.isZeroArg = isZeroArg;
|
|
|
4102
5142
|
exports.isZeroArgAsync = isZeroArgAsync;
|
|
4103
5143
|
exports.isZeroArgAsyncGenerator = isZeroArgAsyncGenerator;
|
|
4104
5144
|
exports.isZeroArgGenerator = isZeroArgGenerator;
|
|
4105
|
-
exports.iterableOf = iterableOf;
|
|
4106
5145
|
exports.jsonShape = jsonShape;
|
|
4107
5146
|
exports.keyOf = keyOf;
|
|
4108
5147
|
exports.lazyOf = lazyOf;
|
|
@@ -4110,6 +5149,7 @@ exports.literalOf = literalOf;
|
|
|
4110
5149
|
exports.literalShape = literalShape;
|
|
4111
5150
|
exports.mapOf = mapOf;
|
|
4112
5151
|
exports.matchOf = matchOf;
|
|
5152
|
+
exports.matchesJSONValue = matchesJSONValue;
|
|
4113
5153
|
exports.notOf = notOf;
|
|
4114
5154
|
exports.nullShape = nullShape;
|
|
4115
5155
|
exports.nullableOf = nullableOf;
|
|
@@ -4121,6 +5161,7 @@ exports.oneOfShape = oneOfShape;
|
|
|
4121
5161
|
exports.optionalOf = optionalOf;
|
|
4122
5162
|
exports.optionalShape = optionalShape;
|
|
4123
5163
|
exports.orOf = orOf;
|
|
5164
|
+
exports.ownShape = ownShape;
|
|
4124
5165
|
exports.parseArray = parseArray;
|
|
4125
5166
|
exports.parseArrayField = parseArrayField;
|
|
4126
5167
|
exports.parseBoolean = parseBoolean;
|
|
@@ -4166,6 +5207,7 @@ exports.unifySchemas = unifySchemas;
|
|
|
4166
5207
|
exports.unionOf = unionOf;
|
|
4167
5208
|
exports.unionShape = unionShape;
|
|
4168
5209
|
exports.validateShape = validateShape;
|
|
5210
|
+
exports.validateShapeDepth = validateShapeDepth;
|
|
4169
5211
|
exports.valueToSchema = valueToSchema;
|
|
4170
5212
|
exports.whereOf = whereOf;
|
|
4171
5213
|
|