@amritk/generate-parsers 0.24.0 → 0.25.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/README.md +37 -463
- package/dist/index.d.ts +22 -2
- package/dist/index.js +18 -1
- package/package.json +15 -40
- package/AI.md +0 -52
- package/dist/generators/assert-supported-keywords.d.ts +0 -30
- package/dist/generators/assert-supported-keywords.js +0 -87
- package/dist/generators/build-schema.d.ts +0 -111
- package/dist/generators/build-schema.js +0 -74
- package/dist/generators/generate-deep-equal-check.d.ts +0 -24
- package/dist/generators/generate-deep-equal-check.js +0 -35
- package/dist/generators/generate-default-from-pattern.d.ts +0 -26
- package/dist/generators/generate-default-from-pattern.js +0 -223
- package/dist/generators/generate-discriminated-union-validation.d.ts +0 -15
- package/dist/generators/generate-discriminated-union-validation.js +0 -28
- package/dist/generators/generate-enum-check.d.ts +0 -35
- package/dist/generators/generate-enum-check.js +0 -31
- package/dist/generators/generate-files.d.ts +0 -138
- package/dist/generators/generate-files.js +0 -89
- package/dist/generators/generate-non-discriminated-union-validation.d.ts +0 -6
- package/dist/generators/generate-non-discriminated-union-validation.js +0 -26
- package/dist/generators/generate-parser-function.d.ts +0 -120
- package/dist/generators/generate-parser-function.js +0 -1973
- package/dist/generators/generate-schema-checks.d.ts +0 -5
- package/dist/generators/generate-schema-checks.js +0 -260
- package/dist/generators/generate-strict-assertion.d.ts +0 -155
- package/dist/generators/generate-strict-assertion.js +0 -759
- package/dist/generators/generate-type-checks.d.ts +0 -148
- package/dist/generators/generate-type-checks.js +0 -454
- package/dist/generators/generate-unique-items-check.d.ts +0 -16
- package/dist/generators/generate-unique-items-check.js +0 -32
- package/dist/generators/generate-validation-expression.d.ts +0 -79
- package/dist/generators/generate-validation-expression.js +0 -416
- package/dist/generators/subschema-match.d.ts +0 -48
- package/dist/generators/subschema-match.js +0 -485
- package/dist/generators/unevaluated-match.d.ts +0 -19
- package/dist/generators/unevaluated-match.js +0 -206
- package/dist/helpers/apply-schema-extensions.d.ts +0 -35
- package/dist/helpers/apply-schema-extensions.js +0 -20
- package/dist/helpers/collect-helpers.d.ts +0 -15
- package/dist/helpers/collect-helpers.js +0 -64
- package/dist/helpers/collect-imports.d.ts +0 -104
- package/dist/helpers/collect-imports.js +0 -227
- package/dist/helpers/find-discriminator.d.ts +0 -6
- package/dist/helpers/find-discriminator.js +0 -27
- package/dist/helpers/get-default-value.d.ts +0 -7
- package/dist/helpers/get-default-value.js +0 -155
- package/dist/helpers/get-discriminator-value.d.ts +0 -6
- package/dist/helpers/get-discriminator-value.js +0 -18
- package/dist/types/schema-extensions.d.ts +0 -34
- package/dist/types/schema-extensions.js +0 -0
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
-
/**
|
|
3
|
-
* Generates a discriminated union validation expression.
|
|
4
|
-
* Uses a discriminator property to efficiently choose the correct schema.
|
|
5
|
-
*
|
|
6
|
-
* The emitted expression is a single *nested* ternary in schema order — for
|
|
7
|
-
* branches `dog`, `cat` it reads `disc === "dog" ? v : disc === "cat" ? v :
|
|
8
|
-
* <fallback>`. Each branch tests its discriminant (plus any per-branch shape
|
|
9
|
-
* checks) and, on a match, passes the value through; the innermost `else` is the
|
|
10
|
-
* shared fallback taken when no discriminant matches. The previous
|
|
11
|
-
* `cases[i] + ' : ' + result` folding spliced complete ternaries together
|
|
12
|
-
* (`c1 ? v : d1 : c0 ? v : d0`), which is a parse error for >=2 branches and
|
|
13
|
-
* also evaluated branches in reverse with the wrong per-case default.
|
|
14
|
-
*/
|
|
15
|
-
export declare const generateDiscriminatedUnionValidation: (accessor: string, schemas: readonly JSONSchema[], discriminatorKey: string, defaultValue: string, isRequired: boolean) => string;
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { getDiscriminatorValue } from "../helpers/get-discriminator-value.js";
|
|
2
|
-
import { generateSchemaChecks } from "./generate-schema-checks.js";
|
|
3
|
-
const generateDiscriminatedUnionValidation = (accessor, schemas, discriminatorKey, defaultValue, isRequired) => {
|
|
4
|
-
const discAccessor = `(${accessor} as Record<string, unknown> | null | undefined)?.[${JSON.stringify(discriminatorKey)}]`;
|
|
5
|
-
const branches = [];
|
|
6
|
-
for (const schema of schemas) {
|
|
7
|
-
const discriminatorValue = getDiscriminatorValue(schema, discriminatorKey);
|
|
8
|
-
if (discriminatorValue === null)
|
|
9
|
-
continue;
|
|
10
|
-
let condition = `${discAccessor} === ${JSON.stringify(discriminatorValue)}`;
|
|
11
|
-
const checks = generateSchemaChecks(accessor, schema);
|
|
12
|
-
for (const check of checks) {
|
|
13
|
-
condition += " && " + check;
|
|
14
|
-
}
|
|
15
|
-
branches.push(condition);
|
|
16
|
-
}
|
|
17
|
-
if (branches.length === 0) {
|
|
18
|
-
return isRequired ? `${accessor} ?? ${defaultValue}` : accessor;
|
|
19
|
-
}
|
|
20
|
-
let result = isRequired ? defaultValue : accessor;
|
|
21
|
-
for (let i = branches.length - 1; i >= 0; i--) {
|
|
22
|
-
result = `${branches[i]} ? ${accessor} : ${result}`;
|
|
23
|
-
}
|
|
24
|
-
return result;
|
|
25
|
-
};
|
|
26
|
-
export {
|
|
27
|
-
generateDiscriminatedUnionValidation
|
|
28
|
-
};
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Generates an enum validation check expression.
|
|
3
|
-
* Returns a string that checks if the value is in the allowed enum values.
|
|
4
|
-
*
|
|
5
|
-
* For the common all-primitive case this emits a parenthesized `x === a || x ===
|
|
6
|
-
* b` chain rather than `[a, b].includes(x)`. The `.includes` form allocates a
|
|
7
|
-
* fresh array on every call (this expression runs on the parser hot path); the
|
|
8
|
-
* `===` chain is allocation-free and matches the validators package's
|
|
9
|
-
* `enumMembershipExpr`.
|
|
10
|
-
*
|
|
11
|
-
* An object or array member is compared *structurally* via
|
|
12
|
-
* {@link generateDeepEqualCheck}. `.includes` was SameValueZero — reference
|
|
13
|
-
* equality — so `{ enum: [{ a: 1 }] }` could never match a freshly parsed
|
|
14
|
-
* `{ a: 1 }`: the fast path never fired and the strict parser threw on a document
|
|
15
|
-
* Ajv accepts. `NaN` keeps its own `Number.isNaN` test, the one case `===` cannot
|
|
16
|
-
* express.
|
|
17
|
-
*/
|
|
18
|
-
export declare const generateEnumCheck: (accessor: string, enumValues: readonly unknown[]) => string;
|
|
19
|
-
/**
|
|
20
|
-
* Builds a case-insensitive coercion expression for a string `enum`/`const`
|
|
21
|
-
* value whose exact-match check has already failed. Only the *string* members
|
|
22
|
-
* participate (a number/boolean/null member has no case to fold): a value that
|
|
23
|
-
* matches one case-insensitively normalizes to that member's exact casing, and
|
|
24
|
-
* everything else yields `fallback`.
|
|
25
|
-
*
|
|
26
|
-
* This is emitted ONLY on the already-invalid branch of the coercion ternary, so
|
|
27
|
-
* a correctly-cased value never reaches it — the exact `===` fast path (and the
|
|
28
|
-
* shape validators / deep guards built on it) is unchanged, so the hot path pays
|
|
29
|
-
* nothing. Only a mis-cased value, which today coerces straight to the default,
|
|
30
|
-
* now takes a single `toLowerCase()` and an O(1) map lookup instead.
|
|
31
|
-
*
|
|
32
|
-
* Returns `null` when no member is a string (nothing to fold), so the caller
|
|
33
|
-
* keeps its plain fallback and emits no extra code.
|
|
34
|
-
*/
|
|
35
|
-
export declare const generateEnumCaseInsensitiveCoercion: (accessor: string, enumValues: readonly unknown[], fallback: string) => string | null;
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { generateDeepEqualCheck } from "./generate-deep-equal-check.js";
|
|
2
|
-
const generateEnumCheck = (accessor, enumValues) => {
|
|
3
|
-
if (enumValues.length === 0)
|
|
4
|
-
return "false";
|
|
5
|
-
const members = enumValues.map((value) => {
|
|
6
|
-
const check = generateDeepEqualCheck(accessor, value);
|
|
7
|
-
return value !== null && typeof value === "object" ? `(${check})` : check;
|
|
8
|
-
});
|
|
9
|
-
return `(${members.join(" || ")})`;
|
|
10
|
-
};
|
|
11
|
-
const generateEnumCaseInsensitiveCoercion = (accessor, enumValues, fallback) => {
|
|
12
|
-
const entries = [];
|
|
13
|
-
const seen = /* @__PURE__ */ new Set();
|
|
14
|
-
for (const value of enumValues) {
|
|
15
|
-
if (typeof value !== "string")
|
|
16
|
-
continue;
|
|
17
|
-
const lower = value.toLowerCase();
|
|
18
|
-
if (seen.has(lower))
|
|
19
|
-
continue;
|
|
20
|
-
seen.add(lower);
|
|
21
|
-
entries.push([lower, value]);
|
|
22
|
-
}
|
|
23
|
-
if (entries.length === 0)
|
|
24
|
-
return null;
|
|
25
|
-
const map = `new Map(${JSON.stringify(entries)})`;
|
|
26
|
-
return `(typeof ${accessor} === "string" ? (${map}.get((${accessor} as string).toLowerCase()) ?? ${fallback}) : ${fallback})`;
|
|
27
|
-
};
|
|
28
|
-
export {
|
|
29
|
-
generateEnumCaseInsensitiveCoercion,
|
|
30
|
-
generateEnumCheck
|
|
31
|
-
};
|
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
import { type UnknownKeysStrategy } from '@amritk/helpers/unknown-keys-strategy';
|
|
2
|
-
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
3
|
-
import { type HelpersMode, type RuntimeHelperName } from '../helpers/collect-helpers.js';
|
|
4
|
-
import { type ImportExtension } from '../helpers/collect-imports.js';
|
|
5
|
-
/**
|
|
6
|
-
* Options for controlling what gets generated in a file.
|
|
7
|
-
*/
|
|
8
|
-
type GenerateFileOptions = {
|
|
9
|
-
/**
|
|
10
|
-
* When true, only emit the TypeScript type definition and skip the parser function.
|
|
11
|
-
* Imports will be type-only as well, since there are no parsers to call.
|
|
12
|
-
*/
|
|
13
|
-
readonly typesOnly?: boolean;
|
|
14
|
-
/**
|
|
15
|
-
* The $ref path of the schema being generated (e.g. `#/$defs/encoding`).
|
|
16
|
-
* When provided, any $ref that resolves to the same filename is excluded from
|
|
17
|
-
* the import list, preventing a file from importing itself.
|
|
18
|
-
*/
|
|
19
|
-
readonly selfRef?: string;
|
|
20
|
-
/**
|
|
21
|
-
* The filename this file is written as, without extension. Used for
|
|
22
|
-
* self-import detection when the schema has no `$ref` of its own — the root
|
|
23
|
-
* document — so a `$defs` entry that collides with the root type name cannot
|
|
24
|
-
* make the root file import itself.
|
|
25
|
-
*/
|
|
26
|
-
readonly selfFilename?: string;
|
|
27
|
-
/**
|
|
28
|
-
* The root schema document. When provided, URI refs that cannot be resolved
|
|
29
|
-
* within the root schema's $defs are excluded from the import list.
|
|
30
|
-
*/
|
|
31
|
-
readonly rootSchema?: Record<string, unknown>;
|
|
32
|
-
/**
|
|
33
|
-
* When true, the generated parser emits a console.warn for every input key
|
|
34
|
-
* that is not declared in the schema's properties.
|
|
35
|
-
*/
|
|
36
|
-
readonly logWarnings?: boolean;
|
|
37
|
-
/**
|
|
38
|
-
* When true, the generated parser throws on type/shape mismatches instead
|
|
39
|
-
* of coercing invalid input to default values.
|
|
40
|
-
*/
|
|
41
|
-
readonly strict?: boolean;
|
|
42
|
-
/**
|
|
43
|
-
* When true, the generated parser builds its result from declared properties
|
|
44
|
-
* only, silently dropping undeclared input keys at every nesting level (zod's
|
|
45
|
-
* `.strip()`), without treating extras as a validation error. Composes with
|
|
46
|
-
* `strict` (still throws on wrong types / missing required properties) and
|
|
47
|
-
* yields to `additionalProperties: false` (which rejects rather than strips in
|
|
48
|
-
* strict mode).
|
|
49
|
-
*/
|
|
50
|
-
readonly stripUnknown?: boolean;
|
|
51
|
-
/**
|
|
52
|
-
* Controls how runtime helpers are referenced.
|
|
53
|
-
* - `'package'` (default): emit imports from `@amritk/helpers/...`.
|
|
54
|
-
* - `'embedded'`: emit imports from `./_helpers/...` so the helper sources can
|
|
55
|
-
* be shipped alongside the generated files.
|
|
56
|
-
*/
|
|
57
|
-
readonly helpersMode?: HelpersMode;
|
|
58
|
-
/**
|
|
59
|
-
* Relative path prefix to the shared `_helpers/` directory in embedded mode.
|
|
60
|
-
* Defaults to `'./'`. The recursive multi-schema build passes `'../'`,
|
|
61
|
-
* `'../../'`, etc. so a nested parser can reach a single `_helpers/` directory
|
|
62
|
-
* at the output root.
|
|
63
|
-
*/
|
|
64
|
-
readonly helpersImportPrefix?: string;
|
|
65
|
-
/**
|
|
66
|
-
* When true, every property, array, and record in the generated type
|
|
67
|
-
* definitions is emitted as `readonly`.
|
|
68
|
-
*/
|
|
69
|
-
readonly readonly?: boolean;
|
|
70
|
-
/**
|
|
71
|
-
* Suffix appended to every type/parser name derived from a `$ref`.
|
|
72
|
-
* Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
|
|
73
|
-
*/
|
|
74
|
-
readonly typeSuffix?: string;
|
|
75
|
-
/**
|
|
76
|
-
* Extension used on every relative import specifier (cross-file `$ref`
|
|
77
|
-
* imports and embedded-helper imports). Defaults to `'js'` (the TS NodeNext
|
|
78
|
-
* form); `'ts'` makes the generated sources runnable under Node's type
|
|
79
|
-
* stripping.
|
|
80
|
-
*/
|
|
81
|
-
readonly importExt?: ImportExtension;
|
|
82
|
-
/**
|
|
83
|
-
* True when this file is the root document rather than a `$ref`-reached
|
|
84
|
-
* definition. Forwarded to the parser generator so the JSON Schema
|
|
85
|
-
* meta-schema special case (type name `Schema`) never applies to a
|
|
86
|
-
* user-named root.
|
|
87
|
-
*/
|
|
88
|
-
readonly isRoot?: boolean;
|
|
89
|
-
/**
|
|
90
|
-
* When true, a mis-cased string that matches a declared `enum`/`const` member
|
|
91
|
-
* case-insensitively is normalized to that member's exact casing (coerce mode
|
|
92
|
-
* only). The normalization is emitted on the coercion failure branch, so
|
|
93
|
-
* already-valid input keeps the exact-match fast path.
|
|
94
|
-
*/
|
|
95
|
-
readonly caseInsensitive?: boolean;
|
|
96
|
-
/**
|
|
97
|
-
* How the generated fast paths prove a closed object carries no undeclared
|
|
98
|
-
* key — `Object.keys` (the default) or a `for…in` count. See
|
|
99
|
-
* {@link UnknownKeysStrategy} for the trade-off between the two.
|
|
100
|
-
*/
|
|
101
|
-
readonly unknownKeys?: UnknownKeysStrategy;
|
|
102
|
-
};
|
|
103
|
-
/** Result of generating a single parser file. */
|
|
104
|
-
export type GeneratedFileContent = {
|
|
105
|
-
readonly content: string;
|
|
106
|
-
readonly usedHelpers: ReadonlySet<RuntimeHelperName>;
|
|
107
|
-
};
|
|
108
|
-
/**
|
|
109
|
-
* Generates a complete TypeScript file from a JSON Schema.
|
|
110
|
-
*
|
|
111
|
-
* The generated file contains imports, type definition, and parser function.
|
|
112
|
-
* When typesOnly is true, only the type definition is emitted without any parser.
|
|
113
|
-
*
|
|
114
|
-
* @param schema - The JSON Schema to generate code from
|
|
115
|
-
* @param typeName - The name to use for the generated TypeScript type
|
|
116
|
-
* @param options - Optional settings to control what gets generated
|
|
117
|
-
* @returns The generated file content and the set of runtime helpers it references
|
|
118
|
-
*
|
|
119
|
-
* @example
|
|
120
|
-
* ```typescript
|
|
121
|
-
* const schema = {
|
|
122
|
-
* type: "object",
|
|
123
|
-
* properties: {
|
|
124
|
-
* name: { type: "string" },
|
|
125
|
-
* age: { type: "number" }
|
|
126
|
-
* },
|
|
127
|
-
* required: ["name"]
|
|
128
|
-
* };
|
|
129
|
-
*
|
|
130
|
-
* const result = generateFile(schema, "User");
|
|
131
|
-
* // result contains imports, type User, and parseUser function
|
|
132
|
-
*
|
|
133
|
-
* const typesOnly = generateFile(schema, "User", { typesOnly: true });
|
|
134
|
-
* // typesOnly contains only type-only imports and type User (no parser)
|
|
135
|
-
* ```
|
|
136
|
-
*/
|
|
137
|
-
export declare const generateFile: (schema: JSONSchema, typeName: string, options?: GenerateFileOptions) => GeneratedFileContent;
|
|
138
|
-
export {};
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { generateTypeDefinition } from "@amritk/helpers/generate-type-definition";
|
|
2
|
-
import { DEFAULT_UNKNOWN_KEYS } from "@amritk/helpers/unknown-keys-strategy";
|
|
3
|
-
import { collectHelpers } from "../helpers/collect-helpers.js";
|
|
4
|
-
import { collectImports, collectImportTypeNames } from "../helpers/collect-imports.js";
|
|
5
|
-
import { generateParserFunction, generateShapeValidator } from "./generate-parser-function.js";
|
|
6
|
-
const generateFile = (schema, typeName, options) => {
|
|
7
|
-
const typesOnly = options?.typesOnly === true;
|
|
8
|
-
const selfRef = options?.selfRef;
|
|
9
|
-
const rootSchema = options?.rootSchema;
|
|
10
|
-
const helpersMode = options?.helpersMode ?? "package";
|
|
11
|
-
const typeSuffix = options?.typeSuffix ?? "";
|
|
12
|
-
const importExt = options?.importExt ?? "js";
|
|
13
|
-
const typeDefinition = generateTypeDefinition(schema, typeName, {
|
|
14
|
-
readonly: options?.readonly ?? false,
|
|
15
|
-
typeSuffix,
|
|
16
|
-
...rootSchema !== void 0 ? { rootSchema } : {}
|
|
17
|
-
});
|
|
18
|
-
if (typesOnly) {
|
|
19
|
-
const imports2 = collectImports(schema, {
|
|
20
|
-
typesOnly: true,
|
|
21
|
-
selfRef,
|
|
22
|
-
selfFilename: options?.selfFilename,
|
|
23
|
-
rootSchema,
|
|
24
|
-
typeSuffix,
|
|
25
|
-
importExt,
|
|
26
|
-
usedIn: typeDefinition
|
|
27
|
-
});
|
|
28
|
-
let result2 = "";
|
|
29
|
-
if (imports2.length > 0) {
|
|
30
|
-
result2 += imports2[0];
|
|
31
|
-
for (let i = 1; i < imports2.length; i++) {
|
|
32
|
-
result2 += "\n" + imports2[i];
|
|
33
|
-
}
|
|
34
|
-
result2 += "\n\n";
|
|
35
|
-
}
|
|
36
|
-
return { content: result2 + typeDefinition, usedHelpers: /* @__PURE__ */ new Set() };
|
|
37
|
-
}
|
|
38
|
-
const stripUnknown = options?.stripUnknown ?? false;
|
|
39
|
-
const reservedNames = collectImportTypeNames(schema, {
|
|
40
|
-
selfRef,
|
|
41
|
-
selfFilename: options?.selfFilename,
|
|
42
|
-
rootSchema,
|
|
43
|
-
typeSuffix
|
|
44
|
-
});
|
|
45
|
-
const unknownKeys = options?.unknownKeys ?? DEFAULT_UNKNOWN_KEYS;
|
|
46
|
-
const shapeValidator = generateShapeValidator(schema, typeName, true, typeSuffix, true, stripUnknown, reservedNames, unknownKeys);
|
|
47
|
-
const parserFunction = generateParserFunction(schema, typeName, {
|
|
48
|
-
useRefImports: true,
|
|
49
|
-
typeSuffix,
|
|
50
|
-
reservedNames,
|
|
51
|
-
shapeValidatorSource: shapeValidator,
|
|
52
|
-
unknownKeys,
|
|
53
|
-
...options?.isRoot !== void 0 ? { isRoot: options.isRoot } : {},
|
|
54
|
-
...rootSchema !== void 0 ? { rootSchema } : {},
|
|
55
|
-
...options?.logWarnings !== void 0 ? { logWarnings: options.logWarnings } : {},
|
|
56
|
-
...options?.strict !== void 0 ? { strict: options.strict } : {},
|
|
57
|
-
...options?.stripUnknown !== void 0 ? { stripUnknown: options.stripUnknown } : {},
|
|
58
|
-
...options?.caseInsensitive !== void 0 ? { caseInsensitive: options.caseInsensitive } : {}
|
|
59
|
-
});
|
|
60
|
-
const combinedFunctions = `${shapeValidator}
|
|
61
|
-
|
|
62
|
-
${parserFunction}`;
|
|
63
|
-
const helpers = collectHelpers(combinedFunctions, helpersMode, options?.helpersImportPrefix, importExt);
|
|
64
|
-
const imports = [
|
|
65
|
-
...collectImports(schema, {
|
|
66
|
-
selfRef,
|
|
67
|
-
selfFilename: options?.selfFilename,
|
|
68
|
-
rootSchema,
|
|
69
|
-
typeSuffix,
|
|
70
|
-
importExt,
|
|
71
|
-
// Both halves of the file: the type names the type definition spells and
|
|
72
|
-
// the functions the emitted code calls are one question about one text.
|
|
73
|
-
usedIn: typeDefinition + "\n\n" + combinedFunctions
|
|
74
|
-
}),
|
|
75
|
-
...helpers.imports
|
|
76
|
-
];
|
|
77
|
-
let result = "";
|
|
78
|
-
if (imports.length > 0) {
|
|
79
|
-
result += imports[0];
|
|
80
|
-
for (let i = 1; i < imports.length; i++) {
|
|
81
|
-
result += "\n" + imports[i];
|
|
82
|
-
}
|
|
83
|
-
result += "\n\n";
|
|
84
|
-
}
|
|
85
|
-
return { content: result + typeDefinition + "\n\n" + combinedFunctions, usedHelpers: helpers.used };
|
|
86
|
-
};
|
|
87
|
-
export {
|
|
88
|
-
generateFile
|
|
89
|
-
};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
-
/**
|
|
3
|
-
* Generates a non-discriminated union validation expression.
|
|
4
|
-
* Tries each schema in order until one matches.
|
|
5
|
-
*/
|
|
6
|
-
export declare const generateNonDiscriminatedUnionValidation: (accessor: string, schemas: readonly JSONSchema[], defaultValue: string, isRequired: boolean) => string;
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { generateSchemaChecks } from "./generate-schema-checks.js";
|
|
2
|
-
const generateNonDiscriminatedUnionValidation = (accessor, schemas, defaultValue, isRequired) => {
|
|
3
|
-
const cases = [];
|
|
4
|
-
for (const schema of schemas) {
|
|
5
|
-
const checks = generateSchemaChecks(accessor, schema);
|
|
6
|
-
if (checks.length > 0) {
|
|
7
|
-
let combinedChecks = checks[0];
|
|
8
|
-
for (let i = 1; i < checks.length; i++) {
|
|
9
|
-
combinedChecks += " && " + checks[i];
|
|
10
|
-
}
|
|
11
|
-
cases.push("(" + combinedChecks + ")");
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
if (cases.length === 0) {
|
|
15
|
-
return isRequired ? `${accessor} ?? ${defaultValue}` : accessor;
|
|
16
|
-
}
|
|
17
|
-
let combinedCheck = cases[0];
|
|
18
|
-
for (let i = 1; i < cases.length; i++) {
|
|
19
|
-
combinedCheck += " || " + cases[i];
|
|
20
|
-
}
|
|
21
|
-
const finalDefault = isRequired ? defaultValue : "undefined";
|
|
22
|
-
return `(${combinedCheck}) ? ${accessor} : ${finalDefault}`;
|
|
23
|
-
};
|
|
24
|
-
export {
|
|
25
|
-
generateNonDiscriminatedUnionValidation
|
|
26
|
-
};
|
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
import { type UnknownKeysStrategy } from '@amritk/helpers/unknown-keys-strategy';
|
|
2
|
-
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
3
|
-
/**
|
|
4
|
-
* Options for controlling parser function generation behavior.
|
|
5
|
-
*/
|
|
6
|
-
type GenerateParserOptions = {
|
|
7
|
-
/**
|
|
8
|
-
* When true, properties with $ref will call the imported parser function
|
|
9
|
-
* instead of inlining the validation logic. This is used when generating
|
|
10
|
-
* files where each ref has its own separate file with a parser.
|
|
11
|
-
*/
|
|
12
|
-
readonly useRefImports?: boolean;
|
|
13
|
-
/**
|
|
14
|
-
* When true, the generated parser emits a console.warn for every input key
|
|
15
|
-
* that is not declared in the schema's properties.
|
|
16
|
-
*/
|
|
17
|
-
readonly logWarnings?: boolean;
|
|
18
|
-
/**
|
|
19
|
-
* When true, the generated parser throws on type/shape mismatches instead
|
|
20
|
-
* of coercing invalid input to default values. Throws on the first violation
|
|
21
|
-
* with a path-aware Error. When the schema sets `additionalProperties: false`,
|
|
22
|
-
* undeclared keys throw too; otherwise they are still allowed.
|
|
23
|
-
*/
|
|
24
|
-
readonly strict?: boolean;
|
|
25
|
-
/**
|
|
26
|
-
* When true, the generated parser builds its result from the schema's declared
|
|
27
|
-
* properties only, silently dropping any undeclared input key at every nesting
|
|
28
|
-
* level (zod's `.strip()`). Unlike `additionalProperties: false`, extras are
|
|
29
|
-
* never a validation error — this composes with `strict`: `strict + stripUnknown`
|
|
30
|
-
* still throws on wrong types and missing required properties but strips extras
|
|
31
|
-
* instead of throwing on them. When the schema *also* sets
|
|
32
|
-
* `additionalProperties: false`, rejecting wins over stripping in strict mode.
|
|
33
|
-
*/
|
|
34
|
-
readonly stripUnknown?: boolean;
|
|
35
|
-
/**
|
|
36
|
-
* Suffix appended to every type/parser name derived from a `$ref`. Must match
|
|
37
|
-
* the suffix used when generating the referenced files. Defaults to `''`.
|
|
38
|
-
*/
|
|
39
|
-
readonly typeSuffix?: string;
|
|
40
|
-
/**
|
|
41
|
-
* The root schema document. When present, a top-level `oneOf`/`anyOf` whose
|
|
42
|
-
* branches are `$ref`s can be resolved to find a shared discriminator and emit a
|
|
43
|
-
* dispatch to the branch parsers, instead of falling back to a passthrough cast.
|
|
44
|
-
*/
|
|
45
|
-
readonly rootSchema?: Record<string, unknown>;
|
|
46
|
-
/**
|
|
47
|
-
* Type names the generated file imports for its `$ref`s. Synthesized private
|
|
48
|
-
* sub-type names (nested objects, array items, the root array's `{Type}Item`)
|
|
49
|
-
* dedup against this set so they can never shadow an imported identifier —
|
|
50
|
-
* which would both fail to compile (duplicate declaration) and silently
|
|
51
|
-
* validate against the wrong schema.
|
|
52
|
-
*/
|
|
53
|
-
readonly reservedNames?: ReadonlySet<string>;
|
|
54
|
-
/**
|
|
55
|
-
* True when this schema is the root document (not a `$ref`-reached definition).
|
|
56
|
-
* The root type name is user-derived (schema `title`, filename, or `--root-type`),
|
|
57
|
-
* so the JSON Schema meta-schema special case — keyed on the literal name
|
|
58
|
-
* `Schema` — must not apply to it, or a common `schema.json` root would silently
|
|
59
|
-
* generate a validation-free pass-through parser.
|
|
60
|
-
*/
|
|
61
|
-
readonly isRoot?: boolean;
|
|
62
|
-
/**
|
|
63
|
-
* When true, a mis-cased string that matches a declared `enum`/`const` member
|
|
64
|
-
* case-insensitively is normalized to that member's exact casing (e.g. `hElLo`
|
|
65
|
-
* → `hello`) instead of coercing to the default. Coerce mode only — strict
|
|
66
|
-
* parsers still reject a casing mismatch. The normalization lives on the
|
|
67
|
-
* failure branch of the coercion ternary, so a correctly-cased value keeps the
|
|
68
|
-
* exact `===` fast path and the hot path is unaffected.
|
|
69
|
-
*/
|
|
70
|
-
readonly caseInsensitive?: boolean;
|
|
71
|
-
/**
|
|
72
|
-
* How the fast paths prove a closed object carries no undeclared key —
|
|
73
|
-
* `Object.getPrototypeOf(input) === Object.prototype && Object.keys(input).length`
|
|
74
|
-
* (the default) or a `for…in` count. See {@link UnknownKeysStrategy} for the
|
|
75
|
-
* trade-off, and {@link keyCountCheck} for what each form emits.
|
|
76
|
-
*/
|
|
77
|
-
readonly unknownKeys?: UnknownKeysStrategy;
|
|
78
|
-
/**
|
|
79
|
-
* The exact source of the `validate{TypeName}Shape` predicate emitted into
|
|
80
|
-
* the same file as this parser (generate-files produces it for the root
|
|
81
|
-
* type). When the parser can prove — by rendering the predicate it would
|
|
82
|
-
* need and comparing byte-for-byte — that this emitted predicate tests
|
|
83
|
-
* exactly its own fast-path guard, it emits `validate{TypeName}Shape(input)`
|
|
84
|
-
* instead of a second inline copy of the whole check chain, which roughly
|
|
85
|
-
* halves the emitted checks per object type. Any mismatch (composition
|
|
86
|
-
* keywords, conditional flattening, alias/union predicates, stubs) keeps
|
|
87
|
-
* the inline guard, so a wrong substitution is impossible by construction.
|
|
88
|
-
*/
|
|
89
|
-
readonly shapeValidatorSource?: string;
|
|
90
|
-
};
|
|
91
|
-
/**
|
|
92
|
-
* Generates a safe parser as an arrow function that never throws.
|
|
93
|
-
* The parser provides default values for all missing or invalid fields.
|
|
94
|
-
*
|
|
95
|
-
* When useRefImports is enabled, properties with $ref will call the imported
|
|
96
|
-
* parser function (e.g., parseContact(input?.contact)) instead of inlining
|
|
97
|
-
* the resolved schema's validation logic. Array properties whose items are a
|
|
98
|
-
* $ref will map each element through the imported parser.
|
|
99
|
-
*/
|
|
100
|
-
export declare const generateParserFunction: (schema: JSONSchema, typeName: string, rawOptions?: GenerateParserOptions) => string;
|
|
101
|
-
/**
|
|
102
|
-
* Returns the predicate function name for a generated shape validator.
|
|
103
|
-
* @example shapeValidatorFunctionName('CustomerObject') // 'validateCustomerObjectShape'
|
|
104
|
-
*/
|
|
105
|
-
export declare const shapeValidatorFunctionName: (typeName: string) => string;
|
|
106
|
-
/**
|
|
107
|
-
* Generates a `validate{TypeName}Shape(input)` predicate that returns true
|
|
108
|
-
* iff `input` already matches the shape produced by the parser's fast path —
|
|
109
|
-
* i.e. the parser would return `{ ...input } as TypeName` without coercion.
|
|
110
|
-
*
|
|
111
|
-
* Parents call this predicate to fast-path through nested ref properties
|
|
112
|
-
* (and arrays of refs) without recursing into their parser.
|
|
113
|
-
*
|
|
114
|
-
* Returns a stub that always returns `false` for schemas that cannot be
|
|
115
|
-
* predicated (composition, conditionals, pattern properties, complex refs
|
|
116
|
-
* in additionalProperties). The stub is safe: parents calling it will fall
|
|
117
|
-
* through to the slow path, matching the pre-deep-fast-path behavior.
|
|
118
|
-
*/
|
|
119
|
-
export declare const generateShapeValidator: (schema: JSONSchema, typeName: string, useRefImports: boolean, suffix?: string, exported?: boolean, stripUnknown?: boolean, reservedNames?: ReadonlySet<string>, unknownKeys?: UnknownKeysStrategy) => string;
|
|
120
|
-
export {};
|