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