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