Repository navigation
Expand file tree
/
Copy pathschema.js
More file actions
3247 lines (3052 loc) · 117 KB
/
Copy pathschema.js
File metadata and controls
3247 lines (3052 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module schema
* @description Zero-dependency composable schema builder (`s`), duck-typed `zod` adapter,
* JSON Schema Draft-7/2020-12 compiler, prototype-pollution & cycle-guarded payload validator,
* and HTTP request validation middleware (`INV-LEGO-01`, `INV-LEGO-17`).
* Pure ECMAScript & Web Standards (zero host-specific imports; runs unmodified in modern
* server runtimes, browsers, and Cloudflare Workers).
*/
const SCHEMA_BRAND = Symbol.for('krusch.toolkit.schema');
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const ALLOWED_FORMATS = new Set([
'email',
'uuid',
'url',
'iso-date',
'iso-datetime',
'ipv4',
'slug',
]);
const ALLOWED_JSON_SCHEMA_TYPES = new Set([
'object',
'array',
'string',
'number',
'integer',
'boolean',
'null',
]);
const ALLOWED_MIDDLEWARE_SOURCES = new Set(['body', 'query', 'params', 'headers']);
const MAX_FORMAT_INPUT_LENGTH = 2048;
const MAX_SCHEMA_RECURSION_DEPTH = 64;
const hasOwn =
typeof Object.hasOwn === 'function'
? Object.hasOwn
: (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
/**
* Build a deterministic `INV-LEGO-01` success envelope for schema operations.
*
* @param {string} tool - Originating tool identifier
* @param {string} summary - Human-readable validation summary
* @param {unknown} data - Validated output payload
* @returns {{ ok: true, tool: string, summary: string, data: unknown }}
*/
function schemaOkEnvelope(tool, summary, data) {
return {
ok: true,
tool: String(tool || 'schema.validate'),
summary: String(summary || 'Schema validation passed'),
data,
};
}
/**
* Build a deterministic `INV-LEGO-01` error envelope for schema operations.
*
* @param {string} code - Machine-readable error code
* @param {string} message - Human-readable error message
* @param {unknown} [details=null] - Optional structured diagnostic details
* @param {string} [tool='schema.validate'] - Originating tool identifier
* @returns {{ ok: false, tool: string, summary: string, error: { code: string, message: string, details?: unknown } }}
*/
function schemaErrorEnvelope(code, message, details = null, tool = 'schema.validate') {
return {
ok: false,
tool: String(tool || 'schema.validate'),
summary: String(message || code || 'Schema validation failed'),
error: {
code: String(code || 'VALIDATION_ERROR'),
message: String(message || 'Schema validation failed'),
...(details !== null && details !== undefined ? { details } : {}),
},
};
}
/**
* Define an enumerable data property without triggering `Object.prototype` setters.
*
* @param {Record<string, unknown>} target - Destination plain object
* @param {string} key - Property key
* @param {unknown} value - Property value
*/
function defineSafeProperty(target, key, value) {
if (FORBIDDEN_KEYS.has(key)) return;
Object.defineProperty(target, key, {
value,
enumerable: true,
writable: true,
configurable: true,
});
}
/**
* Check whether a value is a plain JSON-style object (`Object.prototype` or `null` prototype).
*
* @param {unknown} val - Value to inspect
* @returns {boolean}
*/
function isPlainObject(val) {
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
return false;
}
const proto = Object.getPrototypeOf(val);
return proto === null || proto === Object.prototype;
}
/**
* Check whether an object's enumerable own properties should be traversed by `inspectPayloadGraph`
* to catch circular references and excessive nesting even on custom class instances.
*
* @param {unknown} val - Value to inspect
* @returns {boolean}
*/
function isTraversableObject(val) {
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
return false;
}
if (
val instanceof Date ||
val instanceof RegExp ||
val instanceof Map ||
val instanceof Set ||
val instanceof WeakMap ||
val instanceof WeakSet ||
val instanceof Promise ||
val instanceof Error ||
val instanceof ArrayBuffer ||
ArrayBuffer.isView(val)
) {
return false;
}
return true;
}
/**
* Check whether a value is an `@krusch/toolkit/schema` builder node.
*
* @param {unknown} candidate - Value to inspect
* @returns {boolean}
*/
function isKruschSchema(candidate) {
return Boolean(
candidate &&
typeof candidate === 'object' &&
candidate[SCHEMA_BRAND] === true &&
candidate._kruschSchema &&
typeof candidate._kruschSchema === 'object'
);
}
/**
* Deep-clone plain JSON-compatible structures while stripping forbidden prototype keys.
*
* @param {unknown} value - Value to clone safely
* @param {WeakSet<object>} [ancestors] - Active ancestor tracker
* @returns {unknown}
*/
function cloneSafeValue(value, ancestors = new WeakSet()) {
if (value === null || typeof value !== 'object') {
return value;
}
if (value instanceof Date) {
return new Date(value.getTime());
}
if (value instanceof RegExp) {
return new RegExp(value.source, value.flags);
}
if (value instanceof ArrayBuffer) {
return value.slice(0);
}
if (typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer) {
return value.slice(0);
}
if (ArrayBuffer.isView(value)) {
if (
typeof Buffer !== 'undefined' &&
typeof Buffer.isBuffer === 'function' &&
Buffer.isBuffer(value)
) {
return Buffer.from(value);
}
const slicedBuf = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
if (value instanceof DataView) {
return new DataView(slicedBuf);
}
const TypedCtor = Object.getPrototypeOf(value)?.constructor;
if (typeof TypedCtor === 'function') {
try {
const clonedView = new TypedCtor(slicedBuf);
if (ArrayBuffer.isView(clonedView) && clonedView.byteLength === value.byteLength) {
return clonedView;
}
} catch {
// Fall back to clean Uint8Array view over cloned ArrayBuffer
}
}
return new Uint8Array(slicedBuf);
}
if (ancestors.has(value)) {
throw new TypeError('Circular reference encountered while cloning value');
}
ancestors.add(value);
try {
if (Array.isArray(value)) {
const copy = [];
for (let i = 0; i < value.length; i += 1) {
copy.push(cloneSafeValue(value[i], ancestors));
}
return copy;
}
if (value instanceof Map) {
const copy = new Map();
for (const [k, v] of value.entries()) {
copy.set(cloneSafeValue(k, ancestors), cloneSafeValue(v, ancestors));
}
return copy;
}
if (value instanceof Set) {
const copy = new Set();
for (const item of value.values()) {
copy.add(cloneSafeValue(item, ancestors));
}
return copy;
}
if (isPlainObject(value)) {
const copy = {};
for (const key of Object.keys(value)) {
if (FORBIDDEN_KEYS.has(key)) continue;
defineSafeProperty(copy, key, cloneSafeValue(value[key], ancestors));
}
return copy;
}
return value;
} finally {
ancestors.delete(value);
}
}
/**
* Clone a schema-declared `default` value, tagging cyclic-default errors as `INVALID_SCHEMA`.
*
* @param {unknown} defaultValue - Schema default value
* @returns {unknown}
*/
function cloneSchemaDefault(defaultValue) {
try {
return cloneSafeValue(defaultValue);
} catch (err) {
const schemaErr = new TypeError(
err instanceof Error ? err.message : 'Invalid schema default value'
);
schemaErr.code = 'INVALID_SCHEMA';
throw schemaErr;
}
}
/**
* Format an array of property/index segments (such as `zod` issue paths) into canonical dot/bracket notation.
*
* @param {ReadonlyArray<PropertyKey>} segments - Path segments
* @returns {string}
*/
function formatPathSegments(segments) {
let out = '';
for (const seg of segments) {
if (typeof seg === 'number') {
out += `[${seg}]`;
} else {
const str = String(seg);
out = out ? `${out}.${str}` : str;
}
}
return out;
}
/**
* Deterministic canonical serializer used for `uniqueItems` structural equality checks.
*
* @param {unknown} val - Validated element value
* @returns {string}
*/
function canonicalSerialize(val) {
if (val === null) return 'null';
const t = typeof val;
if (t === 'undefined') return 'undef';
if (t === 'boolean') return `b:${val}`;
if (t === 'number') {
if (Number.isNaN(val)) return 'n:NaN';
if (Object.is(val, -0)) return 'n:0';
return `n:${val}`;
}
if (t === 'string') return `s:${JSON.stringify(val)}`;
if (Array.isArray(val)) {
return `a:[${val.map((item) => canonicalSerialize(item)).join(',')}]`;
}
if (isPlainObject(val)) {
const sortedKeys = Object.keys(val)
.filter((k) => !FORBIDDEN_KEYS.has(k))
.sort();
const entries = sortedKeys.map(
(k) => `${JSON.stringify(k)}:${canonicalSerialize(val[k])}`
);
return `o:{${entries.join(',')}}`;
}
return `x:${String(val)}`;
}
// ============================================================================
// Deterministic ReDoS-Safe Format Validators
// ============================================================================
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const ISO_DATETIME_RE =
/^(\d{4}-\d{2}-\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/;
const IPV4_RE = /^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/;
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
/**
* Check whether an ASCII codepoint is permitted inside an unquoted email local-part atom.
*
* @param {number} code - UTF-16 code unit
* @returns {boolean}
*/
function isEmailLocalChar(code) {
if (
(code >= 0x30 && code <= 0x39) || // 0-9
(code >= 0x41 && code <= 0x5a) || // A-Z
(code >= 0x61 && code <= 0x7a) // a-z
) {
return true;
}
// Printable RFC 5322 atom specials: ! # $ % & ' * + - / = ? ^ _ ` { | } ~ .
switch (code) {
case 0x21:
case 0x23:
case 0x24:
case 0x25:
case 0x26:
case 0x27:
case 0x2a:
case 0x2b:
case 0x2d:
case 0x2e:
case 0x2f:
case 0x3d:
case 0x3f:
case 0x5e:
case 0x5f:
case 0x60:
case 0x7b:
case 0x7c:
case 0x7d:
case 0x7e:
return true;
default:
return false;
}
}
/**
* Validate a domain label in linear time without backtracking.
*
* @param {string} label - Single DNS label
* @returns {boolean}
*/
function isValidDomainLabel(label) {
if (label.length < 1 || label.length > 63) return false;
for (let i = 0; i < label.length; i += 1) {
const c = label.charCodeAt(i);
const isAlphaNum =
(c >= 0x30 && c <= 0x39) ||
(c >= 0x41 && c <= 0x5a) ||
(c >= 0x61 && c <= 0x7a);
if (i === 0 || i === label.length - 1) {
if (!isAlphaNum) return false;
} else if (!isAlphaNum && c !== 0x2d) {
return false;
}
}
return true;
}
/**
* Linear-time email validator with zero regex backtracking.
*
* @param {string} val - Candidate email string
* @returns {boolean}
*/
function isValidEmail(val) {
if (val.length < 3 || val.length > 320) return false;
for (let i = 0; i < val.length; i += 1) {
const code = val.charCodeAt(i);
if (code <= 0x20 || code >= 0x7f) return false;
}
const atIdx = val.indexOf('@');
if (atIdx <= 0 || atIdx !== val.lastIndexOf('@')) return false;
const local = val.slice(0, atIdx);
const domain = val.slice(atIdx + 1);
if (local.length < 1 || local.length > 64) return false;
if (domain.length < 3 || domain.length > 255) return false;
if (local.startsWith('.') || local.endsWith('.') || local.includes('..')) {
return false;
}
for (let i = 0; i < local.length; i += 1) {
if (!isEmailLocalChar(local.charCodeAt(i))) return false;
}
const labels = domain.split('.');
if (labels.length < 2) return false;
for (const label of labels) {
if (!isValidDomainLabel(label)) return false;
}
const tld = labels[labels.length - 1];
if (tld.length < 2) return false;
return true;
}
/**
* Validate a `YYYY-MM-DD` calendar date including exact month lengths and leap years.
*
* @param {string} val - Candidate date string
* @returns {boolean}
*/
function isValidIsoDate(val) {
const match = ISO_DATE_RE.exec(val);
if (!match) return false;
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (month < 1 || month > 12 || day < 1) return false;
let maxDays = 31;
if (month === 4 || month === 6 || month === 9 || month === 11) {
maxDays = 30;
} else if (month === 2) {
const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
maxDays = isLeap ? 29 : 28;
}
return day <= maxDays;
}
/**
* Validate an ISO-8601 timestamp (`YYYY-MM-DDTHH:mm:ss(.sss)?(Z|[+-]HH:mm)`).
*
* @param {string} val - Candidate datetime string
* @returns {boolean}
*/
function isValidIsoDateTime(val) {
const match = ISO_DATETIME_RE.exec(val);
if (!match) return false;
if (!isValidIsoDate(match[1])) return false;
const hour = Number(match[2]);
const minute = Number(match[3]);
const second = Number(match[4]);
if (hour > 23 || minute > 59 || second > 59) return false;
if (match[6]) {
const tzHour = Number(match[7]);
const tzMinute = Number(match[8]);
if (tzHour > 23 || tzMinute > 59) return false;
}
return Number.isFinite(Date.parse(val));
}
/**
* Validate a canonical dotted-quad IPv4 literal (`0..255` per octet, rejecting leading zeros).
*
* @param {string} val - Candidate IPv4 string
* @returns {boolean}
*/
function isValidIpv4(val) {
if (!IPV4_RE.test(val)) return false;
const parts = val.split('.');
if (parts.length !== 4) return false;
for (const part of parts) {
const octet = Number(part);
if (!Number.isInteger(octet) || octet < 0 || octet > 255) return false;
}
return true;
}
/**
* Validate an `http:` or `https:` URL with non-empty hostname and zero raw whitespace.
*
* @param {string} val - Candidate URL string
* @returns {boolean}
*/
function isValidHttpUrl(val) {
if (/\s/.test(val)) return false;
try {
const parsed = new URL(val);
return (
(parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
parsed.hostname.length > 0
);
} catch {
return false;
}
}
/**
* Evaluate a string against a named deterministic format validator.
* Enforces `<= 2048` byte/char bound BEFORE evaluating any format rule.
*
* @param {string} format - Format identifier
* @param {string} val - Input string
* @returns {boolean}
*/
function isValidStringFormat(format, val) {
if (typeof val !== 'string' || val.length === 0 || val.length > MAX_FORMAT_INPUT_LENGTH) {
return false;
}
switch (format) {
case 'email':
return isValidEmail(val);
case 'uuid':
return UUID_RE.test(val);
case 'url':
return isValidHttpUrl(val);
case 'iso-date':
return isValidIsoDate(val);
case 'iso-datetime':
return isValidIsoDateTime(val);
case 'ipv4':
return isValidIpv4(val);
case 'slug':
return SLUG_RE.test(val);
default:
return true;
}
}
// ============================================================================
// Payload Cycle & Nesting Depth Pre-Validator
// ============================================================================
/**
* Traverse a payload graph iteratively/recursively using an active-ancestor `WeakSet`
* to detect circular references (`SCHEMA_CIRCULAR_REF`) and excessive nesting (`SCHEMA_MAX_DEPTH`)
* without falsely flagging shared non-circular DAG references.
*
* @param {unknown} payload - Root untrusted payload
* @param {number} safeMaxDepth - Maximum allowed container nesting depth (`>= 1`)
* @returns {{ code: 'SCHEMA_CIRCULAR_REF' | 'SCHEMA_MAX_DEPTH', path: string } | null}
*/
function isContainerGraphNode(val) {
return (
Array.isArray(val) ||
val instanceof Map ||
val instanceof Set ||
isTraversableObject(val)
);
}
function getInspectableOwnKeys(obj) {
if (ArrayBuffer.isView(obj) && !(obj instanceof DataView)) {
const len = typeof obj.length === 'number' ? obj.length : 0;
if (len > 65536) {
return [];
}
return Object.keys(obj).filter((k) => {
const idx = Number(k);
return !(Number.isInteger(idx) && idx >= 0 && idx < len && String(idx) === k);
});
}
return Object.keys(obj);
}
function inspectPayloadGraph(payload, safeMaxDepth) {
if (payload === null || typeof payload !== 'object') {
return null;
}
if (!isContainerGraphNode(payload) && getInspectableOwnKeys(payload).length === 0) {
return null;
}
const ancestors = new WeakSet();
/**
* Explicit DFS stack frames:
* `{ node, path, depth, exiting }`
*/
const stack = [{ node: payload, path: '', depth: 1, exiting: false }];
while (stack.length > 0) {
const frame = stack.pop();
if (frame.exiting) {
ancestors.delete(frame.node);
continue;
}
if (ancestors.has(frame.node)) {
return { code: 'SCHEMA_CIRCULAR_REF', path: frame.path };
}
if (frame.depth > safeMaxDepth) {
return { code: 'SCHEMA_MAX_DEPTH', path: frame.path };
}
ancestors.add(frame.node);
stack.push({ node: frame.node, path: frame.path, depth: frame.depth, exiting: true });
const pushChild = (child, childPath) => {
if (child === null || typeof child !== 'object') {
return null;
}
if (ancestors.has(child)) {
return { code: 'SCHEMA_CIRCULAR_REF', path: childPath };
}
if (isContainerGraphNode(child) || getInspectableOwnKeys(child).length > 0) {
stack.push({
node: child,
path: childPath,
depth: frame.depth + 1,
exiting: false,
});
}
return null;
};
if (Array.isArray(frame.node)) {
const allKeys = Object.keys(frame.node);
if (allKeys.length > frame.node.length) {
for (let i = allKeys.length - 1; i >= 0; i -= 1) {
const key = allKeys[i];
const idx = Number(key);
if (
Number.isInteger(idx) &&
idx >= 0 &&
idx < frame.node.length &&
String(idx) === key
) {
continue;
}
const child = FORBIDDEN_KEYS.has(key)
? Object.getOwnPropertyDescriptor(frame.node, key)?.value
: frame.node[key];
const childPath = frame.path ? `${frame.path}.${key}` : key;
const err = pushChild(child, childPath);
if (err) return err;
}
}
for (let i = frame.node.length - 1; i >= 0; i -= 1) {
const err = pushChild(frame.node[i], `${frame.path}[${i}]`);
if (err) return err;
}
} else {
const keys = getInspectableOwnKeys(frame.node);
for (let i = keys.length - 1; i >= 0; i -= 1) {
const key = keys[i];
const child = FORBIDDEN_KEYS.has(key)
? Object.getOwnPropertyDescriptor(frame.node, key)?.value
: frame.node[key];
const childPath = frame.path ? `${frame.path}.${key}` : key;
const err = pushChild(child, childPath);
if (err) return err;
}
if (frame.node instanceof Map) {
const entries = [...frame.node.entries()];
for (let i = entries.length - 1; i >= 0; i -= 1) {
const [entryKey, entryVal] = entries[i];
const valErr = pushChild(entryVal, `${frame.path}.$mapValue[${i}]`);
if (valErr) return valErr;
const keyErr = pushChild(entryKey, `${frame.path}.$mapKey[${i}]`);
if (keyErr) return keyErr;
}
} else if (frame.node instanceof Set) {
const values = [...frame.node.values()];
for (let i = values.length - 1; i >= 0; i -= 1) {
const itemErr = pushChild(values[i], `${frame.path}[${i}]`);
if (itemErr) return itemErr;
}
}
}
}
return null;
}
/**
* Normalize `maxDepth` option into a safe positive integer (`>= 1`, default `16`).
*
* @param {unknown} maxDepth - Caller-supplied depth option
* @returns {number}
*/
function normalizeMaxDepth(maxDepth) {
const raw = maxDepth === undefined || maxDepth === null ? 16 : Number(maxDepth);
return Number.isFinite(raw) ? Math.max(1, Math.trunc(raw)) : 16;
}
// ============================================================================
// Composable Schema Node Factory (`s.*`)
// ============================================================================
/**
* Determine whether a schema node allows omission from parent `s.object` `required` list.
*
* @param {unknown} node - Schema node
* @param {number} [depth=0] - Recursion guard
* @returns {boolean}
*/
function isOptionalSchemaNode(node, depth = 0) {
if (depth > 32 || !node || typeof node !== 'object') return false;
if (isKruschSchema(node)) {
const meta = node._kruschSchema;
if (meta.kind === 'optional' || meta.hasDefault) return true;
if (meta.kind === 'nullable') return isOptionalSchemaNode(meta.inner, depth + 1);
if (meta.kind === 'union' && Array.isArray(meta.branches)) {
return meta.branches.some((b) => isOptionalSchemaNode(b, depth + 1));
}
return false;
}
if (typeof node.safeParse === 'function') {
const def = node._def || node.def;
if (def && typeof def === 'object') {
const typeName = def.typeName || def.type;
if (
typeName === 'ZodOptional' ||
typeName === 'ZodDefault' ||
typeName === 'optional' ||
typeName === 'default'
) {
return true;
}
if (
(typeName === 'ZodNullable' || typeName === 'nullable') &&
def.innerType
) {
return isOptionalSchemaNode(def.innerType, depth + 1);
}
}
if (typeof node.isOptional === 'function') {
try {
return Boolean(node.isOptional());
} catch {
return false;
}
}
return false;
}
if (
isPlainObject(node) &&
hasOwn(node, 'default') &&
node.default !== undefined &&
typeof node.default !== 'function'
) {
return true;
}
return false;
}
/**
* Validate that a definition-time argument is a usable schema descriptor.
*
* @param {unknown} candidate - Schema argument
* @param {string} callerName - Builder function name for diagnostics
*/
function assertValidSchemaInput(candidate, callerName) {
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
throw new TypeError(`${callerName} requires a valid schema object`);
}
if (
!isKruschSchema(candidate) &&
typeof candidate.safeParse !== 'function' &&
!isValidRawJsonSchemaObject(candidate)
) {
throw new TypeError(
`${callerName} requires an s.* node, safeParse schema, or valid plain JSON Schema`
);
}
}
/**
* Construct a frozen composable schema node with `.optional()`, `.nullable()`, `.safeParse()`, and `.toJsonSchema()`.
*
* @param {object} descriptor - Internal node metadata
* @param {(val: unknown, path: string, ctx: object, issues: Array<object>) => { valid: boolean, value: unknown }} evaluateFn
* @param {() => Record<string, unknown>} jsonSchemaFn
* @returns {Readonly<object>}
*/
function createSchemaNode(descriptor, evaluateFn, jsonSchemaFn) {
const frozenDescriptor = Object.freeze({ ...descriptor });
const node = {
[SCHEMA_BRAND]: true,
_kruschSchema: frozenDescriptor,
optional() {
return createOptionalNode(node);
},
nullable() {
return createNullableNode(node);
},
toJsonSchema() {
return jsonSchemaFn();
},
safeParse(input, options = {}) {
const safeOpts = options && typeof options === 'object' ? options : {};
const safeMaxDepth = normalizeMaxDepth(safeOpts.maxDepth);
let graphErr = null;
try {
graphErr = inspectPayloadGraph(input, safeMaxDepth);
} catch (err) {
const msg = err instanceof Error ? err.message : 'Payload inspection failed';
return {
success: false,
error: {
message: msg,
issues: [{ path: '', code: 'VALIDATION_ERROR', message: msg }],
},
};
}
if (graphErr) {
const isCycle = graphErr.code === 'SCHEMA_CIRCULAR_REF';
const issueMessage = isCycle
? 'Circular reference detected'
: `Maximum depth ${safeMaxDepth} exceeded`;
const topMessage = isCycle
? 'Payload contains circular reference'
: `Payload exceeds maximum nesting depth of ${safeMaxDepth}`;
return {
success: false,
error: {
message: topMessage,
issues: [
{
path: graphErr.path,
code: graphErr.code,
message: issueMessage,
},
],
},
};
}
const ctx = {
coerce: Boolean(safeOpts.coerce),
stripUnknown: safeOpts.stripUnknown !== undefined ? Boolean(safeOpts.stripUnknown) : true,
maxDepth: safeMaxDepth,
};
const issues = [];
let res;
try {
res = evaluateFn(input, '', ctx, issues);
} catch (err) {
const isSchemaErr = Boolean(err && typeof err === 'object' && err.code === 'INVALID_SCHEMA');
const code = isSchemaErr ? 'INVALID_SCHEMA' : 'VALIDATION_ERROR';
const msg = err instanceof Error ? err.message : 'Schema validation failed';
return {
success: false,
error: {
message: msg,
issues: [{ path: '', code, message: msg }],
},
};
}
if (!res.valid || issues.length > 0) {
const fallbackIssues =
issues.length > 0
? issues
: [{ path: '', code: 'VALIDATION_ERROR', message: 'Schema validation failed' }];
return {
success: false,
error: {
message: fallbackIssues[0].message,
issues: fallbackIssues,
},
};
}
return {
success: true,
data: res.value,
};
},
};
Object.defineProperty(node, '_evaluate', {
value: evaluateFn,
enumerable: false,
writable: false,
configurable: false,
});
return Object.freeze(node);
}
/**
* Recursively inspect a validated value (and optional raw input for external `safeParse` schemas)
* to fail closed on `NaN` / `±Infinity` numbers and `boolean -> number` coercions (`INV-LEGO-17`).
*
* @param {unknown} rawVal - Original caller input at the corresponding path
* @param {unknown} outVal - Parsed/cloned candidate output value
* @param {string} [basePath=''] - Current dot/bracket path
* @param {boolean} [checkBoolCoercion=false] - Reject `typeof rawVal === 'boolean'` coerced to `number`
* @param {WeakSet<object>} [seen] - Visited output object guard
* @returns {Array<{ path: string, code: string, message: string }>}
*/
function collectNumericAndCoercionIssues(
rawVal,
outVal,
basePath = '',
checkBoolCoercion = false,
seen = new WeakSet()
) {
const found = [];
function walk(rawNode, outNode, curPath) {
if (typeof outNode === 'number') {
if (!Number.isFinite(outNode)) {
found.push({
path: curPath,
code: 'INVALID_TYPE',
message: 'Expected finite number (not NaN or Infinity)',
});
return;
}
if (checkBoolCoercion && typeof rawNode === 'boolean') {
found.push({
path: curPath,
code: 'INVALID_TYPE',
message: 'Boolean cannot be coerced to number',
});
}
return;
}
if (outNode === null || typeof outNode !== 'object') {
return;
}
if (
outNode instanceof ArrayBuffer ||
(typeof SharedArrayBuffer !== 'undefined' && outNode instanceof SharedArrayBuffer) ||
ArrayBuffer.isView(outNode) ||
outNode instanceof Date ||
outNode instanceof RegExp
) {
return;
}
if (seen.has(outNode)) {
return;
}
seen.add(outNode);
if (Array.isArray(outNode)) {
const rawArr = Array.isArray(rawNode) ? rawNode : null;
for (let i = 0; i < outNode.length; i += 1) {
walk(rawArr ? rawArr[i] : undefined, outNode[i], `${curPath}[${i}]`);
}
return;
}
if (outNode instanceof Set) {
const rawSeq = Array.isArray(rawNode)
? rawNode
: rawNode instanceof Set
? Array.from(rawNode)
: null;
if (checkBoolCoercion && rawSeq) {
const coercedTrue = rawSeq.includes(true) && !outNode.has(true) && outNode.has(1);
const coercedFalse = rawSeq.includes(false) && !outNode.has(false) && outNode.has(0);
if (coercedTrue || coercedFalse) {
found.push({
path: curPath,
code: 'INVALID_TYPE',
message: 'Boolean cannot be coerced to number',
});
}
}
let idx = 0;
for (const entry of outNode) {
walk(undefined, entry, `${curPath}[${idx}]`);
idx += 1;
}
return;
}
if (outNode instanceof Map) {
const rawMap = rawNode instanceof Map ? rawNode : null;
let idx = 0;
for (const [k, v] of outNode.entries()) {
walk(undefined, k, `${curPath}[key:${idx}]`);
walk(rawMap && rawMap.has(k) ? rawMap.get(k) : undefined, v, `${curPath}[${String(k)}]`);
idx += 1;
}
return;
}
const rawObj =
rawNode !== null && typeof rawNode === 'object' && !Array.isArray(rawNode)
? rawNode
: null;
for (const key of Object.keys(outNode)) {
if (FORBIDDEN_KEYS.has(key)) continue;
const childPath = curPath ? `${curPath}.${key}` : key;
const rawChild = rawObj && hasOwn(rawObj, key) ? rawObj[key] : undefined;
walk(rawChild, outNode[key], childPath);
}
}