@amritk/validation 0.5.0 → 0.6.1
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/AI.md +11 -0
- package/README.md +50 -3
- package/dist/parsers/generators/generate-parser-function.js +9 -9
- package/dist/parsers/generators/generate-schema-checks.js +3 -3
- package/dist/parsers/generators/generate-strict-assertion.js +5 -5
- package/dist/parsers/generators/generate-type-checks.js +2 -2
- package/dist/parsers/generators/generate-validation-expression.js +3 -3
- package/dist/parsers/generators/subschema-match.js +4 -4
- package/dist/parsers/generators/unevaluated-match.js +2 -2
- package/dist/validators/generators/build-schema.d.ts +1 -1
- package/dist/validators/generators/build-schema.js +32 -217
- package/dist/validators/generators/collect-validator-imports.d.ts +7 -0
- package/dist/validators/generators/collect-validator-imports.js +6 -3
- package/dist/validators/generators/generate-files.d.ts +6 -0
- package/dist/validators/generators/generate-files.js +34 -9
- package/dist/validators/generators/generate-repair-function.d.ts +13 -17
- package/dist/validators/generators/generate-repair-function.js +224 -118
- package/dist/validators/generators/generate-repair-walk.d.ts +24 -0
- package/dist/validators/generators/generate-repair-walk.js +335 -0
- package/dist/validators/generators/generate-validator-function.d.ts +19 -1
- package/dist/validators/generators/generate-validator-function.js +143 -47
- package/dist/validators/generators/repair-context.d.ts +39 -0
- package/dist/validators/generators/repair-context.js +35 -0
- package/dist/validators/generators/repair-runtime.d.ts +25 -0
- package/dist/validators/generators/repair-runtime.js +1071 -0
- package/dist/validators/generators/repair-walkable.d.ts +33 -0
- package/dist/validators/generators/repair-walkable.js +148 -0
- package/dist/validators/generators/unevaluated-match.js +2 -2
- package/package.json +2 -2
|
@@ -3,6 +3,8 @@ import { DEFAULT_UNKNOWN_KEYS } from "@amritk/helpers/unknown-keys-strategy";
|
|
|
3
3
|
import { walkRefGraph } from "@amritk/helpers/walk-ref-graph";
|
|
4
4
|
import { emitFormatModule, FORMAT_FRAGMENTS, formatCheckName } from "./emit-format-checks.js";
|
|
5
5
|
import { generateValidatorFile } from "./generate-files.js";
|
|
6
|
+
import { REPAIR_RUNTIME_CONTENT } from "./repair-runtime.js";
|
|
7
|
+
import { asksForRefs, repairWalkBlocker } from "./repair-walkable.js";
|
|
6
8
|
const VALIDATION_RESULT_CONTENT = `/**
|
|
7
9
|
* A single validation error: what went wrong, where, and which keyword said so.
|
|
8
10
|
*
|
|
@@ -436,222 +438,10 @@ const acceptedKinds = (
|
|
|
436
438
|
]
|
|
437
439
|
}
|
|
438
440
|
|
|
439
|
-
|
|
440
|
-
* The result of a generated repairing validator.
|
|
441
|
-
*
|
|
442
|
-
* \`repairs\` is not a second, parallel account of what went wrong \u2014 it *is* the
|
|
443
|
-
* errors \`validateX\` produced, the ones a repair was found for. So a caller that
|
|
444
|
-
* logs a repair logs the same path, keyword and params it would have been
|
|
445
|
-
* rejected with, and the two can never drift apart, because there is only one of
|
|
446
|
-
* them.
|
|
447
|
-
*
|
|
448
|
-
* A document that needed no repair comes back \`valid: true\` with an empty
|
|
449
|
-
* \`repairs\`, which is exactly what \`coerceX\` would have returned. One that was
|
|
450
|
-
* fully repaired is \`valid: true\` with a non-empty \`repairs\` \u2014 the caller
|
|
451
|
-
* decides whether that is acceptable by looking, rather than by being told. One
|
|
452
|
-
* that could not be fully repaired is \`valid: false\` and carries both: the
|
|
453
|
-
* repairs that were applied, and the \`errors\` still outstanding against the
|
|
454
|
-
* value handed back.
|
|
455
|
-
*/
|
|
456
|
-
export type RepairResult<T> =
|
|
457
|
-
| { valid: true; value: T; repairs: ValidationError[] }
|
|
458
|
-
| { valid: false; value: unknown; errors: ValidationError[]; repairs: ValidationError[] }
|
|
459
|
-
|
|
460
|
-
/**
|
|
461
|
-
* Looks up the repaired value for one position, given that position's JSON
|
|
462
|
-
* Pointer split into segments. Returns a thunk rather than a value so each
|
|
463
|
-
* repair gets its own object \u2014 a shared literal would alias every site that
|
|
464
|
-
* repaired to it \u2014 and \`null\` where the schema offers nothing to repair toward.
|
|
465
|
-
*/
|
|
466
|
-
export type RepairLookup = (segments: readonly string[]) => (() => unknown) | null
|
|
467
|
-
|
|
468
|
-
/**
|
|
469
|
-
* How many validate-and-repair rounds \`repairX\` will run. Repairing a child can
|
|
470
|
-
* expose a parent that only became checkable once the child was there, so one
|
|
471
|
-
* round is not always enough; but each round is bounded further by the rule that
|
|
472
|
-
* a position is repaired at most once, so this is a backstop rather than the
|
|
473
|
-
* thing doing the terminating.
|
|
474
|
-
*/
|
|
475
|
-
export const MAX_REPAIR_PASSES = 8
|
|
476
|
-
|
|
477
|
-
/**
|
|
478
|
-
* Splits a JSON Pointer into its segments, undoing the escaping
|
|
479
|
-
* {@link escapePointer} applied. The root pointer (\`''\`) is zero segments.
|
|
480
|
-
*/
|
|
481
|
-
export const pointerSegments = (path: string): string[] =>
|
|
482
|
-
path === ''
|
|
483
|
-
? []
|
|
484
|
-
: path
|
|
485
|
-
.slice(1)
|
|
486
|
-
.split('/')
|
|
487
|
-
.map((segment) =>
|
|
488
|
-
segment.indexOf('~') === -1 ? segment : segment.replace(/~1/g, '/').replace(/~0/g, '~'),
|
|
489
|
-
)
|
|
490
|
-
|
|
491
|
-
/**
|
|
492
|
-
* Returns \`root\` with the position at \`segments\` replaced by \`value\`, copying
|
|
493
|
-
* only the containers along the way.
|
|
494
|
-
*
|
|
495
|
-
* Copying rather than writing is not politeness, it is the same promise
|
|
496
|
-
* \`coerceX\` makes: the caller's input is never modified, so a repaired document
|
|
497
|
-
* can be compared against what was actually sent. Everything the path did not
|
|
498
|
-
* touch is shared, so repairing one field of a large document does not clone it.
|
|
499
|
-
*
|
|
500
|
-
* Returns \`root\` unchanged when the path does not lead anywhere \u2014 a segment into
|
|
501
|
-
* a missing or non-container parent. That is not a failure to handle here: the
|
|
502
|
-
* parent has an error of its own, and repairing *it* is what makes this position
|
|
503
|
-
* reachable on a later pass.
|
|
504
|
-
*/
|
|
505
|
-
export const repairAt = (root: unknown, segments: readonly string[], value: unknown): unknown => {
|
|
506
|
-
if (segments.length === 0) return value
|
|
507
|
-
const [head, ...rest] = segments as [string, ...string[]]
|
|
508
|
-
|
|
509
|
-
if (Array.isArray(root)) {
|
|
510
|
-
const index = Number(head)
|
|
511
|
-
// \`index === root.length\` is an append, which is what padding a short array
|
|
512
|
-
// to its \`minItems\` is made of. Anything past that would leave a hole, and a
|
|
513
|
-
// hole is not a repair.
|
|
514
|
-
if (!Number.isInteger(index) || index < 0 || index > root.length) return root
|
|
515
|
-
const next = repairAt(root[index], rest, value)
|
|
516
|
-
if (next === root[index]) return root
|
|
517
|
-
const copy = [...root]
|
|
518
|
-
copy[index] = next
|
|
519
|
-
return copy
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
if (typeof root !== 'object' || root === null) return root
|
|
523
|
-
const obj = root as Record<string, unknown>
|
|
524
|
-
// A missing key is reachable only when this is the last segment: that is the
|
|
525
|
-
// \`required\` repair, which is putting the key there. Deeper than that and the
|
|
526
|
-
// parent is the thing that needs repairing first.
|
|
527
|
-
if (!Object.hasOwn(obj, head) && rest.length > 0) return root
|
|
528
|
-
const next = repairAt(obj[head], rest, value)
|
|
529
|
-
if (next === obj[head] && Object.hasOwn(obj, head)) return root
|
|
530
|
-
return { ...obj, [head]: next }
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
/**
|
|
534
|
-
* The position one error is asking to have repaired, or \`null\` when the error is
|
|
535
|
-
* not about a position a value can be put at.
|
|
536
|
-
*
|
|
537
|
-
* One keyword does not point at the value that is wrong: a \`required\` error is
|
|
538
|
-
* reported against the *object* that is missing the key, and names the key in
|
|
539
|
-
* \`params.missingProperty\`, so the position to fill is one segment deeper.
|
|
540
|
-
* \`minItems\` is the other exception and is handled separately, because it is
|
|
541
|
-
* satisfied by adding several values rather than by replacing one.
|
|
542
|
-
*/
|
|
543
|
-
const repairTarget = (error: ValidationError): readonly string[] | null => {
|
|
544
|
-
const segments = pointerSegments(error.path)
|
|
545
|
-
if (error.keyword === 'required') {
|
|
546
|
-
const missing = error.params['missingProperty']
|
|
547
|
-
return typeof missing === 'string' ? [...segments, missing] : null
|
|
548
|
-
}
|
|
549
|
-
return segments
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/** The value at a pointer, or \`undefined\` when the path does not lead anywhere. */
|
|
553
|
-
const valueAt = (root: unknown, segments: readonly string[]): unknown =>
|
|
554
|
-
segments.reduce<unknown>(
|
|
555
|
-
(node, segment) =>
|
|
556
|
-
Array.isArray(node)
|
|
557
|
-
? node[Number(segment)]
|
|
558
|
-
: typeof node === 'object' && node !== null
|
|
559
|
-
? (node as Record<string, unknown>)[segment]
|
|
560
|
-
: undefined,
|
|
561
|
-
root,
|
|
562
|
-
)
|
|
563
|
-
|
|
564
|
-
/**
|
|
565
|
-
* Grows a short array to the length \`minItems\` asks for, or \`null\` when it
|
|
566
|
-
* cannot.
|
|
567
|
-
*
|
|
568
|
-
* Padding is its own operation rather than a position repair because one
|
|
569
|
-
* \`minItems\` error is satisfied by *several* values, not one. Doing it a single
|
|
570
|
-
* element per round would work, but it would spend a round per element and a
|
|
571
|
-
* \`minItems: 50\` would run out of them; filling the shortfall at once keeps the
|
|
572
|
-
* number of rounds a question about the shape of the document rather than about
|
|
573
|
-
* the size of its arrays.
|
|
574
|
-
*
|
|
575
|
-
* Every added element is a separate call to the thunk, so no two share an object.
|
|
576
|
-
*/
|
|
577
|
-
const padToMinItems = (
|
|
578
|
-
root: unknown,
|
|
579
|
-
error: ValidationError,
|
|
580
|
-
lookup: RepairLookup,
|
|
581
|
-
done: Set<string>,
|
|
582
|
-
): unknown => {
|
|
583
|
-
const segments = pointerSegments(error.path)
|
|
584
|
-
const array = valueAt(root, segments)
|
|
585
|
-
const limit = error.params['limit']
|
|
586
|
-
if (!Array.isArray(array) || typeof limit !== 'number' || array.length >= limit) return null
|
|
587
|
-
|
|
588
|
-
// Keyed apart from a position repair at the same path: replacing the whole
|
|
589
|
-
// array and padding it are different repairs, and having done one is no reason
|
|
590
|
-
// to refuse the other.
|
|
591
|
-
const key = \`\${segments.join('/')}#minItems\`
|
|
592
|
-
if (done.has(key)) return null
|
|
593
|
-
|
|
594
|
-
const element = lookup([...segments, String(array.length)])
|
|
595
|
-
if (element === null) return null
|
|
596
|
-
|
|
597
|
-
const padded = [...array]
|
|
598
|
-
while (padded.length < limit) padded.push(element())
|
|
599
|
-
const updated = repairAt(root, segments, padded)
|
|
600
|
-
if (updated === root) return null
|
|
601
|
-
done.add(key)
|
|
602
|
-
return updated
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
/**
|
|
606
|
-
* Applies one round of repairs: every error the schema offers a value for is
|
|
607
|
-
* repaired, and the rest are handed back untouched.
|
|
608
|
-
*
|
|
609
|
-
* \`done\` carries the positions already repaired on an earlier round. A position
|
|
610
|
-
* that failed again after being repaired is not repaired a second time \u2014 the
|
|
611
|
-
* value the schema offered did not satisfy the schema, which is a fact about the
|
|
612
|
-
* schema, and trying again would only produce the same value. Refusing keeps the
|
|
613
|
-
* loop finite without relying on the pass cap, and turns the position into an
|
|
614
|
-
* honest error instead of a silent spin.
|
|
615
|
-
*/
|
|
616
|
-
export const applyRepairs = (
|
|
617
|
-
value: unknown,
|
|
618
|
-
errors: readonly ValidationError[],
|
|
619
|
-
lookup: RepairLookup,
|
|
620
|
-
done: Set<string>,
|
|
621
|
-
): { value: unknown; repaired: ValidationError[] } => {
|
|
622
|
-
const repaired: ValidationError[] = []
|
|
623
|
-
let next = value
|
|
624
|
-
|
|
625
|
-
for (const error of errors) {
|
|
626
|
-
if (error.keyword === 'minItems') {
|
|
627
|
-
const padded = padToMinItems(next, error, lookup, done)
|
|
628
|
-
if (padded === null) continue
|
|
629
|
-
next = padded
|
|
630
|
-
repaired.push(error)
|
|
631
|
-
continue
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
const target = repairTarget(error)
|
|
635
|
-
if (target === null) continue
|
|
636
|
-
const key = target.join('/')
|
|
637
|
-
if (done.has(key)) continue
|
|
638
|
-
const to = lookup(target)
|
|
639
|
-
if (to === null) continue
|
|
640
|
-
|
|
641
|
-
const updated = repairAt(next, target, to())
|
|
642
|
-
// An unreachable position leaves the document exactly as it was. Not counting
|
|
643
|
-
// it as repaired is what lets the parent's own error be the thing that
|
|
644
|
-
// reports, rather than this silently claiming a fix that did not land.
|
|
645
|
-
if (updated === next) continue
|
|
646
|
-
done.add(key)
|
|
647
|
-
next = updated
|
|
648
|
-
repaired.push(error)
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
return { value: next, repaired }
|
|
652
|
-
}
|
|
653
|
-
`;
|
|
441
|
+
` + REPAIR_RUNTIME_CONTENT;
|
|
654
442
|
const RESERVED_TYPE_NAMES = /* @__PURE__ */ new Set(["ValidationResult", "ValidationError"]);
|
|
443
|
+
const COERCE_TYPE_NAMES = ["CoercionResult"];
|
|
444
|
+
const REPAIR_TYPE_NAMES = ["RepairResult", "RepairLookup", "RepairOptions", "RepairThunk", "RepairWalk", "RepairRun"];
|
|
655
445
|
const TYPE_NAME = /^[\p{ID_Start}_$][\p{ID_Continue}$]*$/u;
|
|
656
446
|
const RESERVED_WORDS = /* @__PURE__ */ new Set([
|
|
657
447
|
"await",
|
|
@@ -693,10 +483,34 @@ const RESERVED_WORDS = /* @__PURE__ */ new Set([
|
|
|
693
483
|
"with",
|
|
694
484
|
"yield"
|
|
695
485
|
]);
|
|
486
|
+
const decideRepairWalk = (nodes) => {
|
|
487
|
+
for (const node of nodes) {
|
|
488
|
+
const blocker = repairWalkBlocker(node.schema, node.isRoot);
|
|
489
|
+
if (blocker === null)
|
|
490
|
+
continue;
|
|
491
|
+
const refs = nodes.find((candidate) => asksForRefs(candidate.schema));
|
|
492
|
+
if (refs !== void 0) {
|
|
493
|
+
const owner = node.isRoot ? "the root schema" : `"${node.ref}"`;
|
|
494
|
+
throw new Error(`"x-repair": "ref" needs the single-pass repair walk, which ${owner} cannot use: ${blocker} is a keyword the walk does not repair. Remove it, or drop the "x-repair": "ref" opt-in.`);
|
|
495
|
+
}
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
return true;
|
|
499
|
+
};
|
|
696
500
|
const buildValidatorSchema = async (rootSchema, rootTypeName, typeSuffix = "", schemas, unknownKeys = DEFAULT_UNKNOWN_KEYS, formats, coerce = false, branchErrors = false, repair = false, importExt = "js", check = false) => {
|
|
697
501
|
const enforced = formats === "all" ? new Set(Object.keys(FORMAT_FRAGMENTS)) : new Set((formats ?? []).filter((name) => Object.hasOwn(FORMAT_FRAGMENTS, name)));
|
|
698
502
|
const files = [];
|
|
503
|
+
const reserved = /* @__PURE__ */ new Set([
|
|
504
|
+
...RESERVED_TYPE_NAMES,
|
|
505
|
+
...coerce || repair ? COERCE_TYPE_NAMES : [],
|
|
506
|
+
...repair ? REPAIR_TYPE_NAMES : []
|
|
507
|
+
]);
|
|
508
|
+
const nodes = [];
|
|
699
509
|
walkRefGraph(rootSchema, rootTypeName, { typeSuffix, ...schemas !== void 0 ? { schemas } : {} }, (node) => {
|
|
510
|
+
nodes.push(node);
|
|
511
|
+
});
|
|
512
|
+
const repairWalk = repair && decideRepairWalk(nodes);
|
|
513
|
+
for (const node of nodes) {
|
|
700
514
|
if (node.filename === "validation-result" || node.filename === "index") {
|
|
701
515
|
const owner = node.isRoot ? `the root type "${node.typeName}"` : `"${node.ref}"`;
|
|
702
516
|
const purpose = node.filename === "index" ? "the generated barrel" : "the generated validators' runtime contract";
|
|
@@ -707,7 +521,7 @@ const buildValidatorSchema = async (rootSchema, rootTypeName, typeSuffix = "", s
|
|
|
707
521
|
const suffixNote = typeSuffix === "" ? "" : ` (with the type suffix "${typeSuffix}")`;
|
|
708
522
|
throw new Error(`${owner}${suffixNote}, "${node.typeName}", is not a TypeScript type name, so the generated file would not parse. Pass a name that is a plain identifier \u2014 letters, digits, "_" and "$", not starting with a digit, and not a reserved word.`);
|
|
709
523
|
}
|
|
710
|
-
if (
|
|
524
|
+
if (reserved.has(node.typeName)) {
|
|
711
525
|
const owner = node.isRoot ? `the root type name "${node.typeName}"` : `"${node.ref}"`;
|
|
712
526
|
throw new Error(`${owner} generates the type "${node.typeName}", which every generated file already imports from "validation-result.ts". Rename the definition (or pass a different root type name or type suffix) so the two names do not collide.`);
|
|
713
527
|
}
|
|
@@ -720,11 +534,12 @@ const buildValidatorSchema = async (rootSchema, rootTypeName, typeSuffix = "", s
|
|
|
720
534
|
coerce,
|
|
721
535
|
branchErrors,
|
|
722
536
|
repair,
|
|
537
|
+
repairWalk,
|
|
723
538
|
importExt,
|
|
724
539
|
...node.ref !== void 0 ? { selfRef: node.ref } : {}
|
|
725
540
|
});
|
|
726
541
|
files.push({ filename: `${node.filename}.ts`, content });
|
|
727
|
-
}
|
|
542
|
+
}
|
|
728
543
|
files.push({ filename: "validation-result.ts", content: VALIDATION_RESULT_CONTENT });
|
|
729
544
|
const called = [...enforced].filter((format) => files.some((file) => file.content.includes(`${formatCheckName(format)}(`)));
|
|
730
545
|
const formatModule = emitFormatModule(called);
|
|
@@ -46,6 +46,7 @@ type CollectValidatorImportsOptions = {
|
|
|
46
46
|
readonly checkerName: string;
|
|
47
47
|
readonly coercerName: string;
|
|
48
48
|
readonly repairerName: string;
|
|
49
|
+
readonly walkerName: string;
|
|
49
50
|
}) => {
|
|
50
51
|
readonly type: boolean;
|
|
51
52
|
readonly validator: boolean;
|
|
@@ -76,6 +77,12 @@ type CollectValidatorImportsOptions = {
|
|
|
76
77
|
* without {@link coercer}, though the reverse is ordinary.
|
|
77
78
|
*/
|
|
78
79
|
readonly repairer?: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* The `$ref` target's single-pass repair walk. Only emitted when the whole
|
|
82
|
+
* schema graph is one the walk covers, and then called wherever a walk
|
|
83
|
+
* reaches the ref.
|
|
84
|
+
*/
|
|
85
|
+
readonly walker?: boolean;
|
|
79
86
|
};
|
|
80
87
|
};
|
|
81
88
|
/**
|
|
@@ -10,20 +10,23 @@ const buildImport = (ref, suffix, reads, importExt) => {
|
|
|
10
10
|
const checkerName = `check${typeName}`;
|
|
11
11
|
const coercerName = `coerce${typeName}Value`;
|
|
12
12
|
const repairerName = `repair${typeName}At`;
|
|
13
|
-
const
|
|
13
|
+
const walkerName = `walk${typeName}Repair`;
|
|
14
|
+
const { type, validator, guard = false, checker = false, coercer = false, repairer = false, walker = false } = reads({
|
|
14
15
|
typeName,
|
|
15
16
|
validatorName,
|
|
16
17
|
guardName,
|
|
17
18
|
checkerName,
|
|
18
19
|
coercerName,
|
|
19
|
-
repairerName
|
|
20
|
+
repairerName,
|
|
21
|
+
walkerName
|
|
20
22
|
});
|
|
21
23
|
const values = [
|
|
22
24
|
...validator ? [validatorName] : [],
|
|
23
25
|
...guard ? [guardName] : [],
|
|
24
26
|
...checker ? [checkerName] : [],
|
|
25
27
|
...coercer ? [coercerName] : [],
|
|
26
|
-
...repairer ? [repairerName] : []
|
|
28
|
+
...repairer ? [repairerName] : [],
|
|
29
|
+
...walker ? [walkerName] : []
|
|
27
30
|
];
|
|
28
31
|
if (type && values.length > 0)
|
|
29
32
|
return `import { type ${typeName}, ${values.join(", ")} } from './${filename}.${importExt}'`;
|
|
@@ -53,6 +53,12 @@ type GenerateValidatorFileOptions = {
|
|
|
53
53
|
* validator ever sees it, and never shows up as a repair.
|
|
54
54
|
*/
|
|
55
55
|
readonly repair?: boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Whether the repairing half also gets the single-pass walk, which `repairX`
|
|
58
|
+
* then runs instead of the validate-and-repair loop. Decided over the whole
|
|
59
|
+
* schema graph by the caller, since one walk calls another across files.
|
|
60
|
+
*/
|
|
61
|
+
readonly repairWalk?: boolean;
|
|
56
62
|
/** Extension on every emitted relative specifier: `'js'` (default) or `'ts'`. */
|
|
57
63
|
readonly importExt?: 'js' | 'ts';
|
|
58
64
|
/**
|
|
@@ -17,7 +17,7 @@ const generateValidatorFile = (schema, typeName, options) => {
|
|
|
17
17
|
const importExt = options?.importExt ?? "js";
|
|
18
18
|
const formats = options?.formats ?? NO_FORMATS;
|
|
19
19
|
const validatorFunction = generateValidatorFunction(schema, typeName, typeSuffix, options?.rootSchema, unknownKeys, formats, options?.branchErrors === true);
|
|
20
|
-
const { code: booleanGuard, standalone: standaloneGuard } = generateBooleanGuardSource(schema, typeName, unknownKeys, formats);
|
|
20
|
+
const { code: booleanGuard, standalone: standaloneGuard } = generateBooleanGuardSource(schema, typeName, unknownKeys, formats, { suffix: typeSuffix, ...options?.rootSchema !== void 0 ? { rootSchema: options.rootSchema } : {} });
|
|
21
21
|
const checker = options?.check === true ? generateCheckFunction(schema, typeName, typeSuffix, options?.rootSchema, unknownKeys, formats) : "";
|
|
22
22
|
const wantsCoerce = options?.coerce === true || options?.repair === true;
|
|
23
23
|
const coercer = wantsCoerce ? generateCoerceFunction(schema, typeName, typeSuffix, {
|
|
@@ -27,7 +27,8 @@ const generateValidatorFile = (schema, typeName, options) => {
|
|
|
27
27
|
}).code : "";
|
|
28
28
|
const repairer = options?.repair === true ? generateRepairFunction(schema, typeName, typeSuffix, {
|
|
29
29
|
...options?.rootSchema !== void 0 ? { rootSchema: options.rootSchema } : {},
|
|
30
|
-
formats
|
|
30
|
+
formats,
|
|
31
|
+
walk: options.repairWalk === true
|
|
31
32
|
}).code : "";
|
|
32
33
|
const appended = [checker, coercer, repairer].filter((part) => part !== "");
|
|
33
34
|
const body = validatorFunction + booleanGuard + (appended.length === 0 ? "" : "\n\n" + appended.join("\n\n"));
|
|
@@ -37,13 +38,14 @@ const generateValidatorFile = (schema, typeName, options) => {
|
|
|
37
38
|
rootSchema: options?.rootSchema,
|
|
38
39
|
typeSuffix,
|
|
39
40
|
importExt,
|
|
40
|
-
reads: ({ typeName: name, validatorName, guardName, checkerName, coercerName, repairerName }) => ({
|
|
41
|
+
reads: ({ typeName: name, validatorName, guardName, checkerName, coercerName, repairerName, walkerName }) => ({
|
|
41
42
|
type: mentions(name),
|
|
42
43
|
validator: mentions(validatorName),
|
|
43
44
|
guard: mentions(guardName),
|
|
44
45
|
checker: mentions(checkerName),
|
|
45
46
|
coercer: mentions(coercerName),
|
|
46
|
-
repairer: mentions(repairerName)
|
|
47
|
+
repairer: mentions(repairerName),
|
|
48
|
+
walker: mentions(walkerName)
|
|
47
49
|
})
|
|
48
50
|
});
|
|
49
51
|
const resultTypes = [
|
|
@@ -51,7 +53,7 @@ const generateValidatorFile = (schema, typeName, options) => {
|
|
|
51
53
|
.../\bValidationError\b/.test(body) ? ["ValidationError"] : [],
|
|
52
54
|
.../\bCoercionResult\b/.test(body) ? ["CoercionResult"] : [],
|
|
53
55
|
.../\bRepairResult\b/.test(body) ? ["RepairResult"] : [],
|
|
54
|
-
|
|
56
|
+
...["RepairLookup", "RepairOptions", "RepairThunk", "RepairWalk", "RepairRun"].filter((name) => new RegExp(`\\b${name}\\b`).test(body))
|
|
55
57
|
];
|
|
56
58
|
let result = `import type { ${resultTypes.join(", ")} } from './validation-result.${importExt}'
|
|
57
59
|
`;
|
|
@@ -63,10 +65,33 @@ const generateValidatorFile = (schema, typeName, options) => {
|
|
|
63
65
|
"selectBranchErrors",
|
|
64
66
|
"coerceScalar",
|
|
65
67
|
"coerceUnion",
|
|
66
|
-
"
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
"runRepairLoop",
|
|
69
|
+
"runRepairWalk",
|
|
70
|
+
"childAt",
|
|
71
|
+
"fillKey",
|
|
72
|
+
"fillInto",
|
|
73
|
+
"walkError",
|
|
74
|
+
"walkPath",
|
|
75
|
+
"walkRepair",
|
|
76
|
+
"walkVerified",
|
|
77
|
+
"walkSet",
|
|
78
|
+
"walkSetItem",
|
|
79
|
+
"walkCompact",
|
|
80
|
+
"walkMissing",
|
|
81
|
+
"walkScope",
|
|
82
|
+
"walkUnscope",
|
|
83
|
+
"fillBegin",
|
|
84
|
+
"walkExtra",
|
|
85
|
+
"walkProto",
|
|
86
|
+
"walkHalt",
|
|
87
|
+
"walkMemo",
|
|
88
|
+
"walkRef",
|
|
89
|
+
"isPlainObject"
|
|
90
|
+
].filter((name) => body.includes(`${name}(`) || body.includes(`${name}<`));
|
|
91
|
+
for (const name of ["REPAIR_DROP", "NO_SEGMENTS", "MAX_FILL_DEPTH"]) {
|
|
92
|
+
if (new RegExp(`\\b${name}\\b`).test(body))
|
|
93
|
+
runtimeHelpers.push(name);
|
|
94
|
+
}
|
|
70
95
|
if (runtimeHelpers.length > 0) {
|
|
71
96
|
result += `import { ${runtimeHelpers.join(", ")} } from './validation-result.${importExt}'
|
|
72
97
|
`;
|
|
@@ -5,28 +5,24 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
|
5
5
|
*/
|
|
6
6
|
export declare const repairLookupNameFor: (ref: string, typeSuffix: string) => string;
|
|
7
7
|
/**
|
|
8
|
-
* Generates the repairing half of a validator file: the position lookup,
|
|
9
|
-
* `repairX` that
|
|
8
|
+
* Generates the repairing half of a validator file: the position lookup, the
|
|
9
|
+
* single-pass walk when the schema is one it covers, and the `repairX` that runs
|
|
10
|
+
* one or the other.
|
|
10
11
|
*
|
|
11
|
-
* The
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* and there is no parallel set of rules about what is wrong that could disagree
|
|
18
|
-
* with it.
|
|
19
|
-
*
|
|
20
|
-
* Re-validating after a round is what catches the cases one pass cannot see: a
|
|
21
|
-
* required object that was missing entirely is repaired into existence, and only
|
|
22
|
-
* then can its own children be judged. A position is repaired at most once, so
|
|
23
|
-
* the loop terminates on progress rather than on the pass cap.
|
|
12
|
+
* The lookup answers what a position repairs to, and both engines ask it, so
|
|
13
|
+
* they cannot land on different values. The walk checks and repairs every
|
|
14
|
+
* position in one pass; the loop — validate, repair the reported positions,
|
|
15
|
+
* validate again — is what every other schema gets. Either way, what is
|
|
16
|
+
* reported is the error the validator would have produced, and nothing
|
|
17
|
+
* second-guesses it.
|
|
24
18
|
*/
|
|
25
19
|
export declare const generateRepairFunction: (schema: JSONSchema, typeName: string, typeSuffix?: string, options?: {
|
|
26
|
-
/** The whole document, for a
|
|
20
|
+
/** The whole document, for a test that reads a `$ref`'s target. */
|
|
27
21
|
readonly rootSchema?: Record<string, unknown>;
|
|
28
|
-
/** The `format` names the validator enforces, so a
|
|
22
|
+
/** The `format` names the validator enforces, so a test agrees with it. */
|
|
29
23
|
readonly formats?: ReadonlySet<string>;
|
|
24
|
+
/** Whether to emit the single-pass walk, decided over the whole schema graph. */
|
|
25
|
+
readonly walk?: boolean;
|
|
30
26
|
}) => {
|
|
31
27
|
code: string;
|
|
32
28
|
};
|