@amritk/validation 0.5.0 → 0.6.0
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/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 +53 -18
- 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/package.json +1 -1
package/AI.md
CHANGED
|
@@ -107,4 +107,15 @@ any of them without one of those two flags.
|
|
|
107
107
|
barrel — a leading `_` marks a name for sibling files only). Strict and
|
|
108
108
|
`stripUnknown` parsers are unchanged.
|
|
109
109
|
|
|
110
|
+
11. **`repairX(input, options?)` takes options, and is one pass when it can be.**
|
|
111
|
+
`inPlace`, `coerce: false` and `path` work for every schema; `refs`,
|
|
112
|
+
`skipRefs`, `onRef`, `maxDepth`, `maxWork`, `memo`, `finite` and
|
|
113
|
+
`plainObjects` only for a schema the single-pass walk covers (the
|
|
114
|
+
`if`/`then`/`else` + `allOf` + `properties` family; see the README) — on any
|
|
115
|
+
other schema `repairX` throws if they are set. Do not
|
|
116
|
+
promise a user instance `$ref` following without `"x-repair": "ref"` on their
|
|
117
|
+
Reference schema — generation refuses that opt-in on a schema the walk cannot
|
|
118
|
+
serve rather than ignoring it. `"x-repair": "drop"` and `false` schemas remove
|
|
119
|
+
a failing position rather than defaulting it.
|
|
120
|
+
|
|
110
121
|
Only the `.` entry. Install: `bun add @amritk/validation`.
|
package/README.md
CHANGED
|
@@ -103,6 +103,51 @@ not enough: a document nothing could repair comes back with none either, and
|
|
|
103
103
|
`valid: false`. To reject a bad config, use `coerceX`. To hand back a fixed one,
|
|
104
104
|
use `repairX`.
|
|
105
105
|
|
|
106
|
+
**Repairing large documents.** `repairX(input, options?)` takes an options
|
|
107
|
+
object (a bare string is still read as the base path):
|
|
108
|
+
|
|
109
|
+
| option | default | what it does |
|
|
110
|
+
| --- | --- | --- |
|
|
111
|
+
| `path` | `''` | JSON Pointer every reported path is rooted at |
|
|
112
|
+
| `inPlace` | `false` | assign and delete on the input instead of copying the containers a repair touches |
|
|
113
|
+
| `coerce` | `true` | move a scalar written in the wrong type (`"5"` under `integer`) before repairing; off, it is repaired to the schema's value and reported |
|
|
114
|
+
| `refs` | `true` | follow instance `$ref`s at positions whose Reference schema opts in (below) |
|
|
115
|
+
| `skipRefs` | `[]` | pointer prefixes (`'#/components/'`) whose targets the root schema already walks; still resolved, not walked again |
|
|
116
|
+
| `onRef` | — | `(value, path, typeId) => boolean \| void`, called for every opted-in `$ref`; `false` leaves it alone |
|
|
117
|
+
| `maxDepth` | `512` | depth past which a position is reported (`maxDepth`) instead of walked |
|
|
118
|
+
| `maxWork` | `10_000_000` | containers visited before the walk stops (`maxWork`) |
|
|
119
|
+
| `memo` | `false` | walk each object once per schema — for in-memory graphs with shared or cyclic subtrees |
|
|
120
|
+
| `finite` | `false` | reject `NaN` and the infinities where a number is declared |
|
|
121
|
+
| `plainObjects` | `false` | accept only plain objects, and remove an own `__proto__` key |
|
|
122
|
+
|
|
123
|
+
When every definition in the schema is built from `type`, `enum`, `const`,
|
|
124
|
+
`properties`, `required`, `additionalProperties`, `patternProperties`, `items`,
|
|
125
|
+
`$ref`, `if`/`then`/`else` and `allOf` — plus annotations, and scalar
|
|
126
|
+
assertions such as `minLength`, `pattern`, `minimum`, `anyOf`, `oneOf` or `not`,
|
|
127
|
+
which are asked of the validator's own test of the position — `repairX` is a
|
|
128
|
+
single pass: each position is checked and repaired where it stands, an `if` is
|
|
129
|
+
evaluated against the value actually there, a missing required object is built
|
|
130
|
+
with its required children (to a bounded depth on a recursive definition), and
|
|
131
|
+
errors go straight into one array with their paths built only when something is
|
|
132
|
+
reported. A valid document comes back as itself with nothing copied. On a 24 MB
|
|
133
|
+
bundled OpenAPI document that is well under a hundred milliseconds (`bun
|
|
134
|
+
--conditions development scripts/bench-repair-walk.ts`). Any other keyword keeps
|
|
135
|
+
the validate-and-repair loop, which honours `path`, `inPlace` and `coerce` and
|
|
136
|
+
throws on the walk-only options (`skipRefs`, `onRef`, `maxDepth`, `maxWork`,
|
|
137
|
+
`memo`, `finite`, `plainObjects`) rather than quietly dropping a guard.
|
|
138
|
+
|
|
139
|
+
Two schema annotations steer it. `"x-repair": "drop"` — and a `false` schema —
|
|
140
|
+
removes a failing position instead of writing a default: an unknown key under
|
|
141
|
+
`additionalProperties: false`, an array element under `items: false`, a
|
|
142
|
+
drop-marked property. `"x-repair": "ref"` on a Reference schema turns on
|
|
143
|
+
instance `$ref` following: at a position written
|
|
144
|
+
`{ if: { type: object, required: [$ref] }, then: Reference, else: T }`, the
|
|
145
|
+
`$ref` is resolved as a JSON Pointer against the root document (own properties
|
|
146
|
+
only), and its target is checked and repaired as that position's type, with
|
|
147
|
+
errors at the target's own path. Each target is walked once per type, chains
|
|
148
|
+
and cycles included; one that does not resolve is reported as `unresolvedRef`
|
|
149
|
+
and never created.
|
|
150
|
+
|
|
106
151
|
**`parseX` agrees with `coerceX`.** Wherever `coerceX` accepts a document, the
|
|
107
152
|
coercing `parseX` returns the very same value — through a union, an `allOf`, an
|
|
108
153
|
`if`, a `$ref`, recursion included — and it only repairs what `coerceX` would
|
|
@@ -182,9 +227,11 @@ both leave the caller's document alone (`bun run bench:validators:coerce`, or
|
|
|
182
227
|
|
|
183
228
|
<sub>Each cell is how many times faster `coerceX` is than Ajv on the same input,
|
|
184
229
|
each engine timed in its own process (Bun 1.3.11, Node 22.22, Linux x64). A
|
|
185
|
-
valid document is the common case and the widest gap:
|
|
186
|
-
|
|
187
|
-
|
|
230
|
+
valid document is the common case and the widest gap: `coerceX` answers it with
|
|
231
|
+
`isX` and hands the input straight back, without walking it. `isX` builds
|
|
232
|
+
nothing — no error, no path — and stops at the first failure, answering a
|
|
233
|
+
`$ref` with the target's own `isX`; it calls `validateX` only for a schema that
|
|
234
|
+
folds to a constant. On valid input Ajv rewrites nothing, so it can
|
|
188
235
|
also be timed without the clone; `coerceX` is still ahead there on these
|
|
189
236
|
schemas, by 1.2–3.3×, but not on every one: on a large, union-heavy document
|
|
190
237
|
that the caller lets Ajv coerce in place, Ajv can come out modestly ahead. The
|
|
@@ -12,7 +12,7 @@ export type GeneratedFile = {
|
|
|
12
12
|
* types plus the helpers emitted code calls as free identifiers. Exported so tests
|
|
13
13
|
* can evaluate the very source that ships instead of reimplementing it.
|
|
14
14
|
*/
|
|
15
|
-
export declare const VALIDATION_RESULT_CONTENT = "/**\n * A single validation error: what went wrong, where, and which keyword said so.\n *\n * The shape matches `@amritk/runtime-validators`, so an error from a generated\n * validator and one from the runtime interpreter can be handled by the same\n * code \u2014 grouped, translated, or branched on \u2014 without knowing which produced it.\n */\nexport type ValidationError = {\n /** Human-readable description of what went wrong. */\n message: string\n /** JSON Pointer to the offending value inside the instance. */\n path: string\n /** The JSON Schema keyword that rejected the value \u2014 `type`, `required`, `minimum`, \u2026 */\n keyword: string\n /**\n * The keyword's own values, as far as they explain the failure: the bound that\n * was exceeded, the property that was missing, the allowed values that were not\n * matched. Empty for a keyword with nothing to add beyond its name.\n */\n params: Record<string, unknown>\n}\n\n/**\n * The result of a generated validator function.\n * Returns `true` when the input is valid, or an object with `valid: false`\n * and a list of errors when it is not.\n */\nexport type ValidationResult = true | { valid: false; errors: ValidationError[] }\n\n/**\n * The result of a generated coercing validator.\n *\n * Unlike `ValidationResult` there is no bare `true`: a caller that coerces wants\n * the value back, and the whole point is that it may differ from what went in.\n * The input is never modified \u2014 `value` is the input itself when nothing needed\n * coercing, and otherwise a copy that shares everything the coercion did not\n * touch. So a caller does not have to clone defensively the way an in-place\n * coercer forces them to.\n */\nexport type CoercionResult<T> = { valid: true; value: T } | { valid: false; errors: ValidationError[] }\n\n/**\n * A string this will read as a number: an optional sign, digits with an optional\n * fractional part, an optional exponent. Nothing else.\n *\n * Deliberately narrower than what `Number()` accepts, which is where Ajv gets\n * its surprises \u2014 `Number(\" \")` is `0`, `Number(\"0x10\")` is `16` and\n * `Number(\"Infinity\")` is a value JSON cannot even represent. A config that says\n * `retries: \" \"` has a mistake in it, and answering `0` is the one thing worse\n * than rejecting it. Leading zeros (`\"007\"`) and exponents (`\"1e3\"`) stay: both\n * are ordinary ways to write a number in a YAML file, and neither is ambiguous.\n */\nconst isNumericString = (text: string): boolean => {\n // `/^[+-]?(?:\\d+|\\d*\\.\\d+)(?:[eE][+-]?\\d+)?$/`, walked by hand. The regex\n // cost more than the rest of a number coercion put together \u2014 a string past\n // its end reads `NaN` from `charCodeAt`, which fails every test below, so\n // the scan needs no bounds checks of its own.\n let i = 0\n let c = text.charCodeAt(0)\n if (c === 43 || c === 45) c = text.charCodeAt(++i)\n let digits = 0\n while (c >= 48 && c <= 57) {\n digits++\n c = text.charCodeAt(++i)\n }\n if (c === 46) {\n c = text.charCodeAt(++i)\n let fraction = 0\n while (c >= 48 && c <= 57) {\n fraction++\n c = text.charCodeAt(++i)\n }\n if (fraction === 0) return false\n } else if (digits === 0) return false\n if (c === 101 || c === 69) {\n c = text.charCodeAt(++i)\n if (c === 43 || c === 45) c = text.charCodeAt(++i)\n let exponent = 0\n while (c >= 48 && c <= 57) {\n exponent++\n c = text.charCodeAt(++i)\n }\n if (exponent === 0) return false\n }\n return i === text.length\n}\n\n/**\n * One scalar, coerced toward `type`, or returned untouched when that is not\n * possible.\n *\n * Returning the original on failure is what keeps the error honest: nothing is\n * substituted, so the validator that runs next rejects the value the caller\n * actually wrote, with the keyword and params that rejected it. That is the\n * difference between this and a parser's repair, which repairs toward a default\n * and leaves nothing to report.\n *\n * The table is Ajv's `coerceTypes` minus the cells where Ajv guesses. Every\n * value this coerces, Ajv coerces to the same value \u2014 `coerced-vs-ajv` pins that\n * as a property, so moving off Ajv never changes a value, it only turns some of\n * Ajv's silent repairs into errors. What is deliberately *not* coerced:\n *\n * - **Anything to or from `null`.** Ajv reads `null` as `\"\"`, `0` and\n * `false`, and reads `\"\"`, `0` and `false` back as `null`. `null` is a\n * JSON value in its own right and usually means \"not set\"; turning it into an\n * empty string, or an empty string into it, loses the distinction the document\n * drew.\n * - **Strings that are not cleanly numeric** ({@link isNumericString}) \u2014 no\n * whitespace padding, no `0x`/`0o`/`0b`, no `Infinity`, no trailing `.`.\n */\nexport const coerceScalar = (value: unknown, type: string): unknown => {\n switch (type) {\n case 'string':\n return typeof value === 'number' || typeof value === 'boolean' ? String(value) : value\n case 'number':\n case 'integer': {\n if (typeof value === 'boolean') return value ? 1 : 0\n if (typeof value !== 'string' || !isNumericString(value)) return value\n const asNumber = Number(value)\n if (!Number.isFinite(asNumber)) return value\n return type === 'integer' && asNumber % 1 !== 0 ? value : asNumber\n }\n case 'boolean':\n if (value === 'true' || value === 1) return true\n if (value === 'false' || value === 0) return false\n return value\n default:\n return value\n }\n}\n\n/**\n * One scalar at a position that offers several types \u2014 a `type` array, or a\n * union of scalar branches \u2014 coerced only when every type that can take it\n * agrees on the result.\n *\n * A value whose type is already one of the offered types is left alone: it is\n * what the schema asked for, and the question of coercion does not arise. That\n * one rule is where this parts company with Ajv, which walks its own coercion\n * list in order and so turns `\"1\"` into `1` under `[\"number\", \"string\"]` while\n * leaving it a string under `[\"string\", \"number\"]`. The answer should not depend\n * on the order someone wrote the union in.\n *\n * Otherwise every offered type is tried, and the coercion is taken only if the\n * types that succeed all agree on it. `true` against `number | string` could be\n * `1` or `\"true\"` with equal justification, so it stays `true` and the\n * validator says what is wrong with it. `\"1\"` against `number | integer` is `1`\n * either way, so it is `1`.\n */\nexport const coerceUnion = (value: unknown, types: readonly string[]): unknown => {\n const actual = value === null ? 'null' : typeof value\n for (const type of types) {\n // `integer` is satisfied by a number, so a non-integral number is not a\n // *type* mismatch here \u2014 the validator is what holds it to being whole.\n if (actual === type || (actual === 'number' && type === 'integer')) return value\n }\n\n let coerced: unknown = value\n for (const type of types) {\n const candidate = coerceScalar(value, type)\n if (candidate === value) continue\n if (coerced === value) coerced = candidate\n else if (candidate !== coerced) return value\n }\n return coerced\n}\n\n/**\n * How deep a structural comparison walks before it gives up and answers \"not\n * equal\".\n *\n * JSON data is acyclic, but a generated validator is a plain function applied to\n * whatever in-memory value a caller hands it \u2014 and a self-referential object\n * reaching a `const` / `enum` / `uniqueItems` check used to recurse until the\n * stack overflowed, so `validateFoo` threw a `RangeError` instead of returning\n * the `ValidationResult` its signature promises. The cap turns that into an\n * ordinary \"these are different\" without ever coming near real data;\n * `@amritk/runtime-validators` guards its own `deepEqual` at the same depth.\n */\nconst MAX_EQUAL_DEPTH = 512\n\n/**\n * Structural deep equality used by generated `const` checks. Objects compare by\n * their key sets rather than serialization, so `{ a: 1, b: 2 }` and\n * `{ b: 2, a: 1 }` are equal \u2014 unlike `JSON.stringify`, which is key-order\n * sensitive and would reject a reordered-but-equal value.\n */\nexport const valuesEqual = (a: unknown, b: unknown, depth = 0): boolean => {\n // SameValueZero: `===` settles every primitive except `NaN`, which counts as\n // equal to itself here. That is what the native `Set` in {@link allUnique} does,\n // what Ajv does, and what the interpreter's `deepEqual` does \u2014 leaving it out\n // made a `NaN` nested inside an object compare unequal to itself, so the same\n // array was \"unique\" here and \"duplicated\" everywhere else.\n if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n if (depth >= MAX_EQUAL_DEPTH) return false\n const aArray = Array.isArray(a)\n const bArray = Array.isArray(b)\n if (aArray !== bArray) return false\n if (aArray) {\n const aa = a as unknown[]\n const bb = b as unknown[]\n if (aa.length !== bb.length) return false\n for (let i = 0; i < aa.length; i++) if (!valuesEqual(aa[i], bb[i], depth + 1)) return false\n return true\n }\n const ao = a as Record<string, unknown>\n const bo = b as Record<string, unknown>\n const keys = Object.keys(ao)\n if (keys.length !== Object.keys(bo).length) return false\n for (const key of keys) {\n if (!Object.hasOwn(bo, key) || !valuesEqual(ao[key], bo[key], depth + 1)) return false\n }\n return true\n}\n\n/**\n * A cheap, order-independent structural hash consistent with {@link valuesEqual}:\n * equal values always hash the same. It buckets candidate-equal elements in\n * {@link allUnique} so the exact comparison only ever runs inside a bucket.\n *\n * Object keys are folded commutatively (XOR) so key order does not change the\n * hash, and `NaN` / `-0` collapse the way SameValueZero does. Depth-capped like\n * {@link valuesEqual}: an over-deep value simply shares a bucket and is settled by\n * the (also capped) comparison, so the cap can cost a little time and never a\n * wrong answer. This is the same hash `@amritk/runtime-validators` uses.\n */\nconst structuralHash = (value: unknown, depth = 0): number => {\n if (value === null) return 0x1a2b3c\n const t = typeof value\n if (t === 'number') {\n const n = value as number\n return Number.isNaN(n) ? 0x7ff8 : n === 0 ? 0 : Math.trunc(n * 2654435761) | 0\n }\n if (t === 'string') {\n const s = value as string\n let h = 0x811c9dc5\n for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)\n return h | 0\n }\n if (t === 'boolean') return value ? 1 : 2\n if (t !== 'object') return 0x5eed\n if (depth >= MAX_EQUAL_DEPTH) return 0xdee9\n if (Array.isArray(value)) {\n let h = 0x12345 ^ value.length\n for (let i = 0; i < value.length; i++) h = (Math.imul(h, 31) + structuralHash(value[i], depth + 1)) | 0\n return h | 0\n }\n const obj = value as Record<string, unknown>\n const keys = Object.keys(obj)\n let h = 0xabcde ^ keys.length\n for (const k of keys) {\n let kh = 0x811c9dc5\n for (let i = 0; i < k.length; i++) kh = Math.imul(kh ^ k.charCodeAt(i), 0x01000193)\n h = (h ^ (Math.imul(kh, 0x9e3779b1) + structuralHash(obj[k], depth + 1))) | 0\n }\n return h | 0\n}\n\n/**\n * True when every element of `arr` is distinct under structural equality\n * ({@link valuesEqual}). Backs generated `uniqueItems` checks whose items may be\n * objects or arrays, where a `JSON.stringify` dedupe key would be key-order\n * sensitive and let a reordered-but-equal duplicate (`{ a: 1, b: 2 }` vs\n * `{ b: 2, a: 1 }`) slip through.\n *\n * A native `Set` dedupes the all-primitive case in one linear pass. Object and\n * array elements are bucketed by {@link structuralHash} first, so the exact\n * comparison runs only against elements that could actually be equal: an array of\n * distinct objects costs ~O(n) instead of the O(n\u00B2) an exhaustive pairwise sweep\n * charged \u2014 4 000 rows took over half a second of pure comparison before, which\n * is a lot to hand an unauthenticated caller.\n */\nexport const allUnique = (arr: readonly unknown[]): boolean => {\n const len = arr.length\n if (len < 2) return true\n let allPrimitive = true\n for (let i = 0; i < len; i++) {\n const v = arr[i]\n if (v !== null && typeof v === 'object') {\n allPrimitive = false\n break\n }\n }\n if (allPrimitive) return new Set(arr).size === len\n const buckets = new Map<number, unknown[]>()\n for (let i = 0; i < len; i++) {\n const item = arr[i]\n const hash = structuralHash(item)\n const bucket = buckets.get(hash)\n if (bucket === undefined) {\n buckets.set(hash, [item])\n continue\n }\n for (const seen of bucket) if (valuesEqual(seen, item)) return false\n bucket.push(item)\n }\n return true\n}\n\n/**\n * True when `test` holds for every element of `arr`, holes included. Backs the\n * item check inside a generated boolean guard.\n *\n * Not `Array.prototype.every`, because that *skips holes* in a sparse array\n * (`[, 'x']`), whereas the validator's index-based loop reads a hole as\n * `undefined` and rejects it \u2014 and the guard must never accept what the validator\n * rejects. The guard used to get that by materialising `Array.from(arr)` first,\n * which copied every array it looked at; an index loop reads a hole the same way\n * and copies nothing.\n */\nexport const everyItem = (arr: readonly unknown[], test: (item: unknown) => boolean): boolean => {\n for (let i = 0; i < arr.length; i++) if (!test(arr[i])) return false\n return true\n}\n\n/**\n * Escapes one JSON Pointer segment (RFC 6901): `~` \u2192 `~0`, `/` \u2192 `~1`, in that\n * order. Generated error paths are built from *runtime* keys wherever the schema\n * did not name them \u2014 a `patternProperties` match, an `additionalProperties`\n * sweep, a `propertyNames` loop \u2014 and a key containing a `/` would otherwise read\n * back as two segments, so an error on `{\"a/b\": \u2026}` pointed at `/a/b`, which is\n * the child `b` of a property `a`. Keys the schema *does* name are escaped at\n * generation time instead, and `@amritk/runtime-validators` escapes the same way,\n * so all three agree.\n *\n * The `indexOf` pre-test keeps the common key \u2014 no `/`, no `~` \u2014 off the replace\n * path entirely, which is what the interpreter does for the same reason.\n */\nexport const escapePointer = (key: string): string =>\n key.indexOf('/') !== -1 || key.indexOf('~') !== -1 ? key.replace(/~/g, '~0').replace(/\\//g, '~1') : key\n\n/**\n * The errors of the branch that was plainly the one meant, out of every branch a\n * failing `anyOf` / `oneOf` rejected. Empty when no branch stands out.\n *\n * A failing combinator on its own says almost nothing: \"must match a schema in\n * anyOf\" names no field and no reason, and on the shape this is most often used\n * for \u2014 a union where the value plainly *is* one of the variants and one field of\n * it is wrong \u2014 that is the least useful thing a validator can say. The branch\n * errors are computed anyway to answer the yes/no question, so the only question\n * is which of them are worth reporting.\n *\n * Branches that rejected the value's *kind* go first: a branch wanting a string\n * has nothing to say about an object, so a `string | { \u2026 }` union is left with\n * the one branch that was even talking about this value. When more than one\n * survives they all describe the same kind of value, and the tie is broken the\n * way a discriminated union reads from the outside \u2014 if every survivor but one\n * was rejected on the value's *identity* (a `const` or `enum` on the value or\n * one of its own properties), the remaining one is the variant the author meant.\n *\n * When every branch rejected the value's kind, no branch was meant, but the\n * kinds they wanted together are what the union accepts, so that is reported as\n * one `type` error: \"must be object or boolean\" for a `true` written as the\n * string `'true'`. `total` is how many branches the combinator has, and the kinds\n * are only named when all of them were heard from. A branch that could not\n * explain itself might have accepted this kind, and then the list would be wrong.\n *\n * Otherwise nothing is reported when no branch stands out, which is as much as\n * can be said honestly: \"the branch with the fewest errors\" would answer here\n * too, and answers wrongly on `oneOf: [aReference, theActualThing]`, where \"you\n * did not write a $ref\" is one complaint and the real mistake is two.\n *\n * `path` is where the combinator was applied, so a segment below it is a direct\n * property of the value being judged. `@amritk/runtime-validators` selects the\n * same branch by the same rule, so a generated validator and the interpreter\n * explain a failing union the same way.\n */\nexport const selectBranchErrors = (\n branches: readonly (readonly ValidationError[])[],\n path: string,\n total?: number,\n): readonly ValidationError[] => {\n const candidates: (readonly ValidationError[])[] = []\n for (const errors of branches) {\n // The value itself is `path`, so a `type` error there is a rejected kind.\n if (!errors.some((error) => error.keyword === 'type' && error.path === path)) candidates.push(errors)\n }\n if (candidates.length === 1) return candidates[0] as readonly ValidationError[]\n if (candidates.length === 0) return branches.length === total ? acceptedKinds(branches, path) : []\n\n let selected: readonly ValidationError[] | null = null\n let rejectedOnIdentity = 0\n for (const errors of candidates) {\n // One segment below `path` and no deeper: a discriminator is conventionally a\n // direct field, and a `const` buried further down is far more likely to be an\n // ordinary payload constraint.\n const identity = errors.some(\n (error) =>\n (error.keyword === 'const' || error.keyword === 'enum') && error.path.indexOf('/', path.length + 1) === -1,\n )\n if (identity) {\n rejectedOnIdentity++\n continue\n }\n // Two branches survive the discriminator, so it did not discriminate.\n if (selected !== null) return []\n selected = errors\n }\n\n return selected !== null && rejectedOnIdentity === candidates.length - 1 ? selected : []\n}\n\n/**\n * One `type` error naming every kind the branches asked for, in branch order and\n * once each. A branch's own `type` may be a list, and a nested union reports its\n * kinds as a list too, so both are read flat.\n */\nconst acceptedKinds = (\n branches: readonly (readonly ValidationError[])[],\n path: string,\n): readonly ValidationError[] => {\n const kinds: string[] = []\n for (const errors of branches) {\n for (const error of errors) {\n if (error.keyword !== 'type' || error.path !== path) continue\n const type = error.params['type']\n for (const kind of Array.isArray(type) ? type : [type]) {\n if (typeof kind === 'string' && !kinds.includes(kind)) kinds.push(kind)\n }\n }\n }\n if (kinds.length === 0) return []\n return [\n {\n message: 'must be ' + kinds.join(' or '),\n path,\n keyword: 'type',\n params: { type: kinds.length === 1 ? kinds[0] : kinds },\n },\n ]\n}\n\n/**\n * The result of a generated repairing validator.\n *\n * `repairs` is not a second, parallel account of what went wrong \u2014 it *is* the\n * errors `validateX` produced, the ones a repair was found for. So a caller that\n * logs a repair logs the same path, keyword and params it would have been\n * rejected with, and the two can never drift apart, because there is only one of\n * them.\n *\n * A document that needed no repair comes back `valid: true` with an empty\n * `repairs`, which is exactly what `coerceX` would have returned. One that was\n * fully repaired is `valid: true` with a non-empty `repairs` \u2014 the caller\n * decides whether that is acceptable by looking, rather than by being told. One\n * that could not be fully repaired is `valid: false` and carries both: the\n * repairs that were applied, and the `errors` still outstanding against the\n * value handed back.\n */\nexport type RepairResult<T> =\n | { valid: true; value: T; repairs: ValidationError[] }\n | { valid: false; value: unknown; errors: ValidationError[]; repairs: ValidationError[] }\n\n/**\n * Looks up the repaired value for one position, given that position's JSON\n * Pointer split into segments. Returns a thunk rather than a value so each\n * repair gets its own object \u2014 a shared literal would alias every site that\n * repaired to it \u2014 and `null` where the schema offers nothing to repair toward.\n */\nexport type RepairLookup = (segments: readonly string[]) => (() => unknown) | null\n\n/**\n * How many validate-and-repair rounds `repairX` will run. Repairing a child can\n * expose a parent that only became checkable once the child was there, so one\n * round is not always enough; but each round is bounded further by the rule that\n * a position is repaired at most once, so this is a backstop rather than the\n * thing doing the terminating.\n */\nexport const MAX_REPAIR_PASSES = 8\n\n/**\n * Splits a JSON Pointer into its segments, undoing the escaping\n * {@link escapePointer} applied. The root pointer (`''`) is zero segments.\n */\nexport const pointerSegments = (path: string): string[] =>\n path === ''\n ? []\n : path\n .slice(1)\n .split('/')\n .map((segment) =>\n segment.indexOf('~') === -1 ? segment : segment.replace(/~1/g, '/').replace(/~0/g, '~'),\n )\n\n/**\n * Returns `root` with the position at `segments` replaced by `value`, copying\n * only the containers along the way.\n *\n * Copying rather than writing is not politeness, it is the same promise\n * `coerceX` makes: the caller's input is never modified, so a repaired document\n * can be compared against what was actually sent. Everything the path did not\n * touch is shared, so repairing one field of a large document does not clone it.\n *\n * Returns `root` unchanged when the path does not lead anywhere \u2014 a segment into\n * a missing or non-container parent. That is not a failure to handle here: the\n * parent has an error of its own, and repairing *it* is what makes this position\n * reachable on a later pass.\n */\nexport const repairAt = (root: unknown, segments: readonly string[], value: unknown): unknown => {\n if (segments.length === 0) return value\n const [head, ...rest] = segments as [string, ...string[]]\n\n if (Array.isArray(root)) {\n const index = Number(head)\n // `index === root.length` is an append, which is what padding a short array\n // to its `minItems` is made of. Anything past that would leave a hole, and a\n // hole is not a repair.\n if (!Number.isInteger(index) || index < 0 || index > root.length) return root\n const next = repairAt(root[index], rest, value)\n if (next === root[index]) return root\n const copy = [...root]\n copy[index] = next\n return copy\n }\n\n if (typeof root !== 'object' || root === null) return root\n const obj = root as Record<string, unknown>\n // A missing key is reachable only when this is the last segment: that is the\n // `required` repair, which is putting the key there. Deeper than that and the\n // parent is the thing that needs repairing first.\n if (!Object.hasOwn(obj, head) && rest.length > 0) return root\n const next = repairAt(obj[head], rest, value)\n if (next === obj[head] && Object.hasOwn(obj, head)) return root\n return { ...obj, [head]: next }\n}\n\n/**\n * The position one error is asking to have repaired, or `null` when the error is\n * not about a position a value can be put at.\n *\n * One keyword does not point at the value that is wrong: a `required` error is\n * reported against the *object* that is missing the key, and names the key in\n * `params.missingProperty`, so the position to fill is one segment deeper.\n * `minItems` is the other exception and is handled separately, because it is\n * satisfied by adding several values rather than by replacing one.\n */\nconst repairTarget = (error: ValidationError): readonly string[] | null => {\n const segments = pointerSegments(error.path)\n if (error.keyword === 'required') {\n const missing = error.params['missingProperty']\n return typeof missing === 'string' ? [...segments, missing] : null\n }\n return segments\n}\n\n/** The value at a pointer, or `undefined` when the path does not lead anywhere. */\nconst valueAt = (root: unknown, segments: readonly string[]): unknown =>\n segments.reduce<unknown>(\n (node, segment) =>\n Array.isArray(node)\n ? node[Number(segment)]\n : typeof node === 'object' && node !== null\n ? (node as Record<string, unknown>)[segment]\n : undefined,\n root,\n )\n\n/**\n * Grows a short array to the length `minItems` asks for, or `null` when it\n * cannot.\n *\n * Padding is its own operation rather than a position repair because one\n * `minItems` error is satisfied by *several* values, not one. Doing it a single\n * element per round would work, but it would spend a round per element and a\n * `minItems: 50` would run out of them; filling the shortfall at once keeps the\n * number of rounds a question about the shape of the document rather than about\n * the size of its arrays.\n *\n * Every added element is a separate call to the thunk, so no two share an object.\n */\nconst padToMinItems = (\n root: unknown,\n error: ValidationError,\n lookup: RepairLookup,\n done: Set<string>,\n): unknown => {\n const segments = pointerSegments(error.path)\n const array = valueAt(root, segments)\n const limit = error.params['limit']\n if (!Array.isArray(array) || typeof limit !== 'number' || array.length >= limit) return null\n\n // Keyed apart from a position repair at the same path: replacing the whole\n // array and padding it are different repairs, and having done one is no reason\n // to refuse the other.\n const key = `${segments.join('/')}#minItems`\n if (done.has(key)) return null\n\n const element = lookup([...segments, String(array.length)])\n if (element === null) return null\n\n const padded = [...array]\n while (padded.length < limit) padded.push(element())\n const updated = repairAt(root, segments, padded)\n if (updated === root) return null\n done.add(key)\n return updated\n}\n\n/**\n * Applies one round of repairs: every error the schema offers a value for is\n * repaired, and the rest are handed back untouched.\n *\n * `done` carries the positions already repaired on an earlier round. A position\n * that failed again after being repaired is not repaired a second time \u2014 the\n * value the schema offered did not satisfy the schema, which is a fact about the\n * schema, and trying again would only produce the same value. Refusing keeps the\n * loop finite without relying on the pass cap, and turns the position into an\n * honest error instead of a silent spin.\n */\nexport const applyRepairs = (\n value: unknown,\n errors: readonly ValidationError[],\n lookup: RepairLookup,\n done: Set<string>,\n): { value: unknown; repaired: ValidationError[] } => {\n const repaired: ValidationError[] = []\n let next = value\n\n for (const error of errors) {\n if (error.keyword === 'minItems') {\n const padded = padToMinItems(next, error, lookup, done)\n if (padded === null) continue\n next = padded\n repaired.push(error)\n continue\n }\n\n const target = repairTarget(error)\n if (target === null) continue\n const key = target.join('/')\n if (done.has(key)) continue\n const to = lookup(target)\n if (to === null) continue\n\n const updated = repairAt(next, target, to())\n // An unreachable position leaves the document exactly as it was. Not counting\n // it as repaired is what lets the parent's own error be the thing that\n // reports, rather than this silently claiming a fix that did not land.\n if (updated === next) continue\n done.add(key)\n next = updated\n repaired.push(error)\n }\n\n return { value: next, repaired }\n}\n";
|
|
15
|
+
export declare const VALIDATION_RESULT_CONTENT: string;
|
|
16
16
|
/**
|
|
17
17
|
* Builds all TypeScript validator files from a JSON Schema by traversing all
|
|
18
18
|
* `$ref` / `$dynamicRef` references recursively (via the shared
|
|
@@ -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
|
};
|