schema-truth 0.0.0-stage → 0.7.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/README.md +143 -2
- package/dist/ajv-DTP2FXRr.js +105 -0
- package/dist/ajv.d.ts +24 -0
- package/dist/ajv.js +1 -0
- package/dist/arktype-BdvvaBQX.js +746 -0
- package/dist/arktype.d.ts +10 -0
- package/dist/arktype.js +1 -0
- package/dist/cli/ajv.d.ts +1 -0
- package/dist/cli/ajv.js +15 -0
- package/dist/cli/arktype.d.ts +1 -0
- package/dist/cli/arktype.js +15 -0
- package/dist/cli/effect.d.ts +1 -0
- package/dist/cli/effect.js +15 -0
- package/dist/cli/typebox.d.ts +1 -0
- package/dist/cli/typebox.js +15 -0
- package/dist/cli/valibot.d.ts +1 -0
- package/dist/cli/valibot.js +15 -0
- package/dist/cli/yup.d.ts +1 -0
- package/dist/cli/yup.js +15 -0
- package/dist/cli/zod.d.ts +1 -0
- package/dist/cli/zod.js +15 -0
- package/dist/cli-CL2mSark.js +124 -0
- package/dist/effect-mUknRPv_.js +645 -0
- package/dist/effect.d.ts +12 -0
- package/dist/effect.js +1 -0
- package/dist/helper-Cfvb5UDq.js +1115 -0
- package/dist/index-C2L8Ty0-.d.ts +65 -0
- package/dist/index-DbV3dEmN.d.ts +551 -0
- package/dist/index.d.ts +303 -0
- package/dist/index.js +10 -0
- package/dist/parser-CyJ2auea.js +36 -0
- package/dist/typebox-BdWJv3ND.js +544 -0
- package/dist/typebox.d.ts +21 -0
- package/dist/typebox.js +1 -0
- package/dist/utils-WNBq1HR0.js +1017 -0
- package/dist/valibot-CaJIynCH.js +664 -0
- package/dist/valibot.d.ts +9 -0
- package/dist/valibot.js +1 -0
- package/dist/yup-CM2TSFig.js +92 -0
- package/dist/yup.d.ts +17 -0
- package/dist/yup.js +1 -0
- package/dist/zod-BsXLZfwK.js +777 -0
- package/dist/zod.d.ts +9 -0
- package/dist/zod.js +1 -0
- package/package.json +112 -4
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
import { B as isSchemaObject, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, Ot as UNSAFE_GENERATED_MARKER, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, b as hasConditional, c as normalizeTypes, ft as NUMBER_RANGES, i as effectMessage, j as isNullTypeMember, k as isDefaultOnlyMember, n as effectError, r as effectErrorPart, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-WNBq1HR0.js";
|
|
2
|
+
import { A as emitOptionsOf, C as formatPattern, E as jsLiteral, F as schemaNamer, H as findCodeExtensionKeysInSchema, L as hasRootSelfReference, M as planDocument, N as renderDefinitions, P as rootNameOf, _ as ownProperties, a as regexLiteral, b as unionPrimitiveTypes, c as parameterReaders, d as effectPreprocess, f as effectWrap, g as isPrimitiveUnion, h as isNullTextRead, i as typeDeclaration, l as withoutParameterSerialization, o as refTarget, p as impliedWireType, s as hasParameterSerialization, u as notPredicate, v as stringboolPattern, w as regexSource, x as wireArrayOnce, y as stringboolTruthyPattern, z as itemsSchemaOf } from "./helper-Cfvb5UDq.js";
|
|
3
|
+
//#region src/generator/effect/number.ts
|
|
4
|
+
/** The bound and `multipleOf` checks of a numeric node. */
|
|
5
|
+
function numberChecks(schema, lit = (n) => `${n}`, suffix = "") {
|
|
6
|
+
const minimumMessage = schema["x-minimum-message"];
|
|
7
|
+
const minErrorPart = effectErrorPart(minimumMessage);
|
|
8
|
+
const maximumMessage = schema["x-maximum-message"];
|
|
9
|
+
const maxErrorPart = effectErrorPart(maximumMessage);
|
|
10
|
+
const exMinMessage = schema["x-exclusiveMinimum-message"];
|
|
11
|
+
const exMinErrorPart = effectErrorPart(exMinMessage);
|
|
12
|
+
const exMaxMessage = schema["x-exclusiveMaximum-message"];
|
|
13
|
+
const exMaxErrorPart = effectErrorPart(exMaxMessage);
|
|
14
|
+
const multipleOfMessage = schema["x-multipleOf-message"];
|
|
15
|
+
const multipleOfErrorPart = effectErrorPart(multipleOfMessage);
|
|
16
|
+
return [
|
|
17
|
+
(() => {
|
|
18
|
+
if (schema.minimum !== void 0) return schema.exclusiveMinimum === true ? `Schema.isGreaterThan${suffix}(${lit(schema.minimum)}${exMinErrorPart})` : `Schema.isGreaterThanOrEqualTo${suffix}(${lit(schema.minimum)}${minErrorPart})`;
|
|
19
|
+
if (typeof schema.exclusiveMinimum === "number") return `Schema.isGreaterThan${suffix}(${lit(schema.exclusiveMinimum)}${exMinErrorPart})`;
|
|
20
|
+
})(),
|
|
21
|
+
(() => {
|
|
22
|
+
if (schema.maximum !== void 0) return schema.exclusiveMaximum === true ? `Schema.isLessThan${suffix}(${lit(schema.maximum)}${exMaxErrorPart})` : `Schema.isLessThanOrEqualTo${suffix}(${lit(schema.maximum)}${maxErrorPart})`;
|
|
23
|
+
if (typeof schema.exclusiveMaximum === "number") return `Schema.isLessThan${suffix}(${lit(schema.exclusiveMaximum)}${exMaxErrorPart})`;
|
|
24
|
+
})(),
|
|
25
|
+
schema.multipleOf === void 0 ? void 0 : suffix === "BigInt" ? `Schema.makeFilter((input)=>input%${lit(schema.multipleOf)}===0n${multipleOfErrorPart})` : `Schema.isMultipleOf(${lit(schema.multipleOf)}${multipleOfErrorPart})`
|
|
26
|
+
].filter((v) => v !== void 0);
|
|
27
|
+
}
|
|
28
|
+
/** The range check of a fixed-width numeric `format` that has one and no filter of its own. */
|
|
29
|
+
function rangeCheck(format, suffix = "") {
|
|
30
|
+
const range = format === void 0 ? void 0 : NUMBER_RANGES[format];
|
|
31
|
+
if (range === void 0) return [];
|
|
32
|
+
return [`Schema.isBetween${suffix}({minimum:${range.minimum},maximum:${range.maximum}})`];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The Effect schema of a number node. On the string wire the text is read with
|
|
36
|
+
* `Schema.FiniteFromString`, which refuses `NaN` and the infinities as `z.coerce.number()`
|
|
37
|
+
* does; `float` / `float32` carries its range.
|
|
38
|
+
*/
|
|
39
|
+
function number(schema, options) {
|
|
40
|
+
const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
|
|
41
|
+
const checks = [...rangeCheck(schema.format === "float" || schema.format === "float32" ? "float32" : void 0), ...numberChecks(schema)];
|
|
42
|
+
const input = options?.wire === true ? "Schema.FiniteFromString" : "Schema.Number";
|
|
43
|
+
const base = checks.length > 0 ? `${input}.check(${checks.join(",")})` : input;
|
|
44
|
+
return errorMessage ? `${base}.annotate(${effectError(errorMessage)})` : base;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/generator/effect/integer.ts
|
|
48
|
+
/** Whether a node is a 64-bit integer: a value beyond 2^53 that is read as a bigint. */
|
|
49
|
+
function isInt64(schema) {
|
|
50
|
+
return schema.format === "int64" || schema.format === "uint64";
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The schema that reads a 64-bit integer into a bigint ahead of its checks. On the
|
|
54
|
+
* string wire the text is a sign and digits; in a JSON body the value is a bigint, a
|
|
55
|
+
* safe-integer number, or the string of digits that is the only lossless way to carry a
|
|
56
|
+
* larger one.
|
|
57
|
+
*/
|
|
58
|
+
function int64Input(isWire) {
|
|
59
|
+
if (isWire) return "Schema.BigIntFromString";
|
|
60
|
+
return `Schema.Union([Schema.BigInt,Schema.Number.check(Schema.isInt()),Schema.String.check(Schema.isPattern(${regexSource(INTEGER_TEXT_PATTERN)}))]).pipe(Schema.decodeTo(Schema.BigInt,SchemaTransformation.transform({decode:(input)=>BigInt(input),encode:(output)=>output})))`;
|
|
61
|
+
}
|
|
62
|
+
/** The range check of `int64` / `uint64`, over bigints. */
|
|
63
|
+
function int64Range(format) {
|
|
64
|
+
const range = NUMBER_RANGES[format];
|
|
65
|
+
if (range === void 0) return "";
|
|
66
|
+
return `Schema.isBetweenBigInt({minimum:${range.minimum},maximum:${range.maximum}})`;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The Effect schema of an integer node. `int64` / `uint64` are bigints wherever they come
|
|
70
|
+
* from, `bigint` is one too, `int32` / `uint32` are their own filters, and on the string
|
|
71
|
+
* wire the text is read with `Schema.FiniteFromString`.
|
|
72
|
+
*/
|
|
73
|
+
function integer(schema, options) {
|
|
74
|
+
const isWire = options?.wire === true;
|
|
75
|
+
const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
|
|
76
|
+
const annotate = (base) => errorMessage ? `${base}.annotate(${effectError(errorMessage)})` : base;
|
|
77
|
+
if (schema.format === "bigint" || isInt64(schema)) {
|
|
78
|
+
const lit = (n) => schema.format === "bigint" ? `BigInt(${n})` : `${n}n`;
|
|
79
|
+
const checks = [...schema.format === "bigint" ? [] : [int64Range(schema.format ?? "")], ...numberChecks(schema, lit, "BigInt")].filter((check) => check !== "");
|
|
80
|
+
const input = schema.format === "bigint" ? isWire ? "Schema.BigIntFromString" : "Schema.BigInt" : int64Input(isWire);
|
|
81
|
+
return annotate(checks.length > 0 ? `${input}.check(${checks.join(",")})` : input);
|
|
82
|
+
}
|
|
83
|
+
const checks = [schema.format === "int32" || schema.format === "uint32" ? `Schema.${schema.format === "uint32" ? "isUint32" : "isInt32"}(${errorMessage ? effectError(errorMessage) : ""})` : errorMessage ? `Schema.isInt(${effectError(errorMessage)})` : "Schema.isInt()", ...numberChecks(schema)];
|
|
84
|
+
return `${isWire ? "Schema.FiniteFromString" : "Schema.Number"}.check(${checks.join(",")})`;
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/generator/effect/enum.ts
|
|
88
|
+
function literal(v, isBigint) {
|
|
89
|
+
if (v === null) return "null";
|
|
90
|
+
if (typeof v === "string") return `"${v}"`;
|
|
91
|
+
if (typeof v === "number" && isBigint) return `${v}n`;
|
|
92
|
+
if (typeof v === "number" || typeof v === "boolean") return String(v);
|
|
93
|
+
return JSON.stringify(v) ?? "null";
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Generates an Effect Schema enum. Multi-value scalar enums map to
|
|
97
|
+
* `Schema.Literals([...])` (v4 dropped the variadic `Schema.Literal(a, b)`
|
|
98
|
+
* overload), array enums to `Schema.Tuple` or `Schema.Union`, single values to
|
|
99
|
+
* `Schema.Literal`. The members of an int64 / uint64 enum are bigint literals, as the
|
|
100
|
+
* value they match is.
|
|
101
|
+
*
|
|
102
|
+
* `x-error-message` (whole-enum) is applied **only to the outermost
|
|
103
|
+
* expression** via `.annotate(...)`. Inner Schema.Literal entries
|
|
104
|
+
* inside a Union/Tuple never receive their own annotations — the outer
|
|
105
|
+
* annotation already covers them.
|
|
106
|
+
*
|
|
107
|
+
* Per-literal `x-enum-error-messages` was removed entirely: a rejected
|
|
108
|
+
* value by definition isn't in the enum, so a per-literal branch can
|
|
109
|
+
* never match. Whole-enum messages come from `x-error-message`;
|
|
110
|
+
* finer-grained business rules belong in handler code, not the schema.
|
|
111
|
+
*/
|
|
112
|
+
function _enum(schema) {
|
|
113
|
+
if (!schema.enum || schema.enum.length === 0) return "Schema.Unknown";
|
|
114
|
+
const isBigint = isInt64(schema);
|
|
115
|
+
const lit = (v) => literal(v, isBigint);
|
|
116
|
+
const errorMessage = schema["x-enum-message"] ?? schema["x-error-message"];
|
|
117
|
+
const annotate = (code) => errorMessage ? `${code}.annotate(${effectError(errorMessage)})` : code;
|
|
118
|
+
const tuple = (arr) => `Schema.Tuple([${arr.map((i) => `Schema.Literal(${lit(i)})`).join(",")}])`;
|
|
119
|
+
const literals = (values) => values.length > 1 ? `Schema.Literals([${values.map(lit).join(",")}])` : `Schema.Literal(${lit(values[0])})`;
|
|
120
|
+
if (hasType(schema, "number") || hasType(schema, "integer") || hasType(schema, "boolean")) return annotate(literals(schema.enum));
|
|
121
|
+
if (hasType(schema, "array")) {
|
|
122
|
+
if (schema.enum.length === 1 && Array.isArray(schema.enum[0])) return annotate(tuple(schema.enum[0]));
|
|
123
|
+
return annotate(`Schema.Union([${schema.enum.map((v) => Array.isArray(v) ? tuple(v) : `Schema.Literal(${lit(v)})`).join(",")}])`);
|
|
124
|
+
}
|
|
125
|
+
return annotate(literals(schema.enum));
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/generator/effect/object.ts
|
|
129
|
+
/**
|
|
130
|
+
* Generate an Effect Schema object node.
|
|
131
|
+
*
|
|
132
|
+
* Dispatches `additionalProperties` to `Schema.Record` (Schema), `Schema.Struct`
|
|
133
|
+
* (otherwise). Combinators (oneOf/anyOf/allOf/not) delegate to the main
|
|
134
|
+
* `effect` entry. JSON Schema 2020-12 keywords (`minProperties`,
|
|
135
|
+
* `maxProperties`, `propertyNames`, `patternProperties`, `dependentRequired`)
|
|
136
|
+
* become `Schema.makeFilter(...)` filters passed to the schema's `.check(...)`.
|
|
137
|
+
*/
|
|
138
|
+
function object(schema, rootName, isEffect, options) {
|
|
139
|
+
if (hasCombinator(schema)) return effect(schema, rootName, isEffect, options);
|
|
140
|
+
const errorMessage = schema["x-error-message"];
|
|
141
|
+
const errorArg = effectErrorPart(errorMessage);
|
|
142
|
+
const minimumMessage = schema["x-minProperties-message"];
|
|
143
|
+
const minErrorArg = effectErrorPart(minimumMessage);
|
|
144
|
+
const maximumMessage = schema["x-maxProperties-message"];
|
|
145
|
+
const maxErrorArg = effectErrorPart(maximumMessage);
|
|
146
|
+
const patternPropsMessage = schema["x-patternProperties-message"];
|
|
147
|
+
const patternErrorArg = effectErrorPart(patternPropsMessage);
|
|
148
|
+
const propNamesMessage = schema["x-propertyNames-message"];
|
|
149
|
+
const propNamesErrorArg = effectErrorPart(propNamesMessage);
|
|
150
|
+
const depReqMessage = schema["x-dependentRequired-message"];
|
|
151
|
+
const depReqErrorArg = depReqMessage ? `,${effectError(depReqMessage)}` : errorArg;
|
|
152
|
+
const depSchMessage = schema["x-dependentSchemas-message"];
|
|
153
|
+
const depSchErrorArg = depSchMessage ? `,${effectError(depSchMessage)}` : errorArg;
|
|
154
|
+
const addlPropsMessage = schema["x-additionalProperties-message"];
|
|
155
|
+
const unevalPropsMessage = schema.unevaluatedProperties === false ? schema["x-unevaluatedProperties-message"] : void 0;
|
|
156
|
+
const strictExtrasMessage = addlPropsMessage ?? unevalPropsMessage;
|
|
157
|
+
const propertyNamesFilter = () => {
|
|
158
|
+
if (schema.propertyNames?.pattern) return `Schema.makeFilter((input)=>Object.keys(input).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})`;
|
|
159
|
+
if (schema.propertyNames?.enum) return `Schema.makeFilter((input)=>Object.keys(input).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})`;
|
|
160
|
+
return "";
|
|
161
|
+
};
|
|
162
|
+
const patternPropertiesFilters = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
|
|
163
|
+
const s = effect(propSchema, rootName, isEffect, options);
|
|
164
|
+
return `Schema.makeFilter((input)=>Object.entries(input).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||Schema.is(${s})(value))${patternErrorArg})`;
|
|
165
|
+
}) : [];
|
|
166
|
+
if (typeof schema.additionalProperties === "object") {
|
|
167
|
+
const record = `Schema.Record(Schema.String,${effect(schema.additionalProperties, rootName, isEffect, options)})`;
|
|
168
|
+
const checks = [propertyNamesFilter(), ...patternPropertiesFilters()].filter((a) => a !== "");
|
|
169
|
+
return checks.length > 0 ? `${record}.check(${checks.join(",")})` : record;
|
|
170
|
+
}
|
|
171
|
+
if (!schema.properties) {
|
|
172
|
+
if (schema.patternProperties) {
|
|
173
|
+
const record = "Schema.Record(Schema.String,Schema.Unknown)";
|
|
174
|
+
const checks = [propertyNamesFilter(), ...patternPropertiesFilters()].filter((a) => a !== "");
|
|
175
|
+
return checks.length > 0 ? `${record}.check(${checks.join(",")})` : record;
|
|
176
|
+
}
|
|
177
|
+
if (schema.additionalProperties === true) return "Schema.Unknown";
|
|
178
|
+
return "Schema.Struct({})";
|
|
179
|
+
}
|
|
180
|
+
const required = new Set(schema.required);
|
|
181
|
+
const props = Object.entries(schema.properties).map(([key, propSchema]) => {
|
|
182
|
+
const parsed = effect(propSchema, rootName, isEffect, options);
|
|
183
|
+
if (!parsed) return null;
|
|
184
|
+
const safeKey = makeSafeKey(key);
|
|
185
|
+
const isRequired = required.has(key);
|
|
186
|
+
const hasDecodingDefault = parsed.includes("Schema.withDecodingDefault");
|
|
187
|
+
return isRequired || hasDecodingDefault ? `${safeKey}:${parsed}` : `${safeKey}:Schema.optional(${parsed})`;
|
|
188
|
+
}).filter((p) => p !== null);
|
|
189
|
+
const conditionalKeysReferenced = hasConditional(schema);
|
|
190
|
+
const struct = `Schema.Struct({${props.join(",")}})`;
|
|
191
|
+
const rawBase = conditionalKeysReferenced ? `Schema.StructWithRest(${struct},[Schema.Record(Schema.String,Schema.Unknown)])` : struct;
|
|
192
|
+
const propsMessage = schema["x-properties-message"];
|
|
193
|
+
const partialBase = propsMessage ? wholeValueMessage(rawBase, propsMessage) : rawBase;
|
|
194
|
+
const minPropertiesFilter = typeof schema.minProperties === "number" ? `Schema.makeFilter((input)=>Object.keys(input).length>=${schema.minProperties}${minErrorArg})` : "";
|
|
195
|
+
const maxPropertiesFilter = typeof schema.maxProperties === "number" ? `Schema.makeFilter((input)=>Object.keys(input).length<=${schema.maxProperties}${maxErrorArg})` : "";
|
|
196
|
+
const dependentRequiredFilters = schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
|
|
197
|
+
return `Schema.makeFilter((input)=>!('${key}' in input)||(${deps.map((d) => `'${d}' in input`).join("&&")})${depReqErrorArg})`;
|
|
198
|
+
}) : [];
|
|
199
|
+
const dependentSchemasFilters = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
|
|
200
|
+
return `Schema.makeFilter((input)=>!('${key}' in input)||Schema.is(${effect(subSchema, rootName, isEffect, options)})(input)${depSchErrorArg})`;
|
|
201
|
+
}) : [];
|
|
202
|
+
const strictExtrasAnnotation = schema.additionalProperties === false || schema.unevaluatedProperties === false ? strictExtrasMessage ? `.annotate({parseOptions:{onExcessProperty:"error"},messageUnexpectedKey:${JSON.stringify(strictExtrasMessage)}})` : `.annotate({parseOptions:{onExcessProperty:"error"}})` : "";
|
|
203
|
+
const ifThenElseFilters = (() => {
|
|
204
|
+
if (!schema.if) return [];
|
|
205
|
+
const ifSchema = effect(schema.if, rootName, isEffect, options);
|
|
206
|
+
const thenSchema = schema.then ? effect(schema.then, rootName, isEffect, options) : "";
|
|
207
|
+
const elseSchema = schema.else ? effect(schema.else, rootName, isEffect, options) : "";
|
|
208
|
+
if (!thenSchema && !elseSchema) return [];
|
|
209
|
+
const ifMessage = schema["x-if-message"];
|
|
210
|
+
const thenMessage = schema["x-then-message"] ?? ifMessage;
|
|
211
|
+
const elseMessage = schema["x-else-message"] ?? ifMessage;
|
|
212
|
+
const parts = [];
|
|
213
|
+
if (thenSchema) {
|
|
214
|
+
const arg = thenMessage ? `,${effectError(thenMessage)}` : errorArg;
|
|
215
|
+
parts.push(`Schema.makeFilter((input)=>!Schema.is(${ifSchema})(input)||Schema.is(${thenSchema})(input)${arg})`);
|
|
216
|
+
}
|
|
217
|
+
if (elseSchema) {
|
|
218
|
+
const arg = elseMessage ? `,${effectError(elseMessage)}` : errorArg;
|
|
219
|
+
parts.push(`Schema.makeFilter((input)=>Schema.is(${ifSchema})(input)||Schema.is(${elseSchema})(input)${arg})`);
|
|
220
|
+
}
|
|
221
|
+
return parts;
|
|
222
|
+
})();
|
|
223
|
+
const checks = [
|
|
224
|
+
minPropertiesFilter,
|
|
225
|
+
maxPropertiesFilter,
|
|
226
|
+
propertyNamesFilter(),
|
|
227
|
+
...patternPropertiesFilters(),
|
|
228
|
+
...dependentRequiredFilters,
|
|
229
|
+
...dependentSchemasFilters,
|
|
230
|
+
...ifThenElseFilters
|
|
231
|
+
].filter((a) => a !== "");
|
|
232
|
+
const objectExpr = `${checks.length > 0 ? `${partialBase}.check(${checks.join(",")})` : partialBase}${strictExtrasAnnotation}`;
|
|
233
|
+
const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
|
|
234
|
+
return isStringWireLocation(options?.paramIn) && hasInheritedName ? effectPreprocess([ownProperties("input")], objectExpr) : objectExpr;
|
|
235
|
+
}
|
|
236
|
+
//#endregion
|
|
237
|
+
//#region src/generator/effect/string.ts
|
|
238
|
+
/**
|
|
239
|
+
* Formats whose Effect Schema v4 equivalent is a check on `Schema.String`.
|
|
240
|
+
* v3 shipped `Schema.UUID` / `Schema.ULID` schemas; v4 expresses both as
|
|
241
|
+
* filters instead.
|
|
242
|
+
*/
|
|
243
|
+
const FORMAT_CHECK = {
|
|
244
|
+
uuid: "Schema.isUUID()",
|
|
245
|
+
uuidv4: "Schema.isUUID(4)",
|
|
246
|
+
uuidv6: "Schema.isUUID(6)",
|
|
247
|
+
uuidv7: "Schema.isUUID(7)",
|
|
248
|
+
ulid: "Schema.isULID()",
|
|
249
|
+
base64: "Schema.isBase64()",
|
|
250
|
+
base64url: "Schema.isBase64Url()",
|
|
251
|
+
uri: "Schema.makeFilter((input)=>URL.canParse(input))",
|
|
252
|
+
url: "Schema.makeFilter((input)=>URL.canParse(input))",
|
|
253
|
+
httpurl: String.raw`Schema.makeFilter((input)=>URL.canParse(input)&&/^https?:\/\//.test(input))`
|
|
254
|
+
};
|
|
255
|
+
/** The formats checked with a pattern of this generator's own. */
|
|
256
|
+
const FORMAT_PATTERN = { email: "Schema.isPattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/)" };
|
|
257
|
+
/** The formats that normalise the value rather than check it, keyed by the lower-cased format. */
|
|
258
|
+
const TRANSFORM_FORMATS = {
|
|
259
|
+
trim: "trim",
|
|
260
|
+
tolowercase: "toLowerCase",
|
|
261
|
+
touppercase: "toUpperCase"
|
|
262
|
+
};
|
|
263
|
+
/** The checks that verify a string `format`, or `[]` for a format with none here. */
|
|
264
|
+
function formatChecks(schema, format, patternMessage) {
|
|
265
|
+
const withMessage = (check) => patternMessage ? check.replace(/\)$/u, `,${effectError(patternMessage)})`) : check;
|
|
266
|
+
const check = FORMAT_CHECK[format];
|
|
267
|
+
if (check !== void 0) return [check];
|
|
268
|
+
if (format === "uuid" && typeof schema["x-uuidVersion"] === "string") return [`Schema.isUUID(${schema["x-uuidVersion"].slice(1)})`];
|
|
269
|
+
const own = FORMAT_PATTERN[format];
|
|
270
|
+
if (own !== void 0) return [withMessage(own)];
|
|
271
|
+
const pattern = formatPattern(schema, format);
|
|
272
|
+
return pattern === void 0 ? [] : [withMessage(`Schema.isPattern(${pattern})`)];
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The base string schema, applying any normalisation: `x-trim` / `x-toLowerCase` /
|
|
276
|
+
* `x-toUpperCase` / `x-normalize` and the `trim` / `toLowerCase` / `toUpperCase`
|
|
277
|
+
* formats. v4 keeps `Schema.Trim` but replaced the `Schema.Lowercase` /
|
|
278
|
+
* `Schema.Uppercase` schemas with transformations that `Schema.decodeTo` applies to
|
|
279
|
+
* `Schema.String`; a combination of them, or a Unicode normalisation, is one
|
|
280
|
+
* transformation over the string.
|
|
281
|
+
*/
|
|
282
|
+
function stringBase(schema, transformFormat) {
|
|
283
|
+
const steps = [
|
|
284
|
+
schema["x-trim"] === true || transformFormat === "trim" ? "trim" : void 0,
|
|
285
|
+
schema["x-toLowerCase"] === true || transformFormat === "toLowerCase" ? "toLowerCase" : void 0,
|
|
286
|
+
schema["x-toUpperCase"] === true || transformFormat === "toUpperCase" ? "toUpperCase" : void 0,
|
|
287
|
+
typeof schema["x-normalize"] === "string" ? `normalize(${JSON.stringify(schema["x-normalize"])})` : void 0
|
|
288
|
+
].filter((step) => step !== void 0);
|
|
289
|
+
if (steps.length === 0) return "Schema.String";
|
|
290
|
+
if (steps.length === 1) {
|
|
291
|
+
if (steps[0] === "trim") return "Schema.Trim";
|
|
292
|
+
if (steps[0] === "toLowerCase" || steps[0] === "toUpperCase") return `Schema.String.pipe(Schema.decodeTo(Schema.String,SchemaTransformation.${steps[0]}()))`;
|
|
293
|
+
}
|
|
294
|
+
return `Schema.String.pipe(Schema.decodeTo(Schema.String,SchemaTransformation.transform({decode:(input)=>input${steps.map((step) => step.endsWith(")") ? `.${step}` : `.${step}()`).join("")},encode:(output)=>output})))`;
|
|
295
|
+
}
|
|
296
|
+
/** A count of characters, as the filter annotations spell it. */
|
|
297
|
+
function characters(count) {
|
|
298
|
+
return `${count} ${count === 1 ? "character" : "characters"}`;
|
|
299
|
+
}
|
|
300
|
+
/** The annotations of a length filter: what it expects, and the message it reports. */
|
|
301
|
+
function lengthAnnotations(expected, message) {
|
|
302
|
+
const messagePart = message === void 0 ? "" : `,message:${effectMessage(message)}`;
|
|
303
|
+
return `{expected:${JSON.stringify(expected)}${messagePart}}`;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The Effect schema of a string node. `minLength` / `maxLength` count code points, as
|
|
307
|
+
* JSON Schema does, so a filter over `[...input]` stands in for `Schema.isMinLength`,
|
|
308
|
+
* which counts UTF-16 units.
|
|
309
|
+
*/
|
|
310
|
+
function string(schema) {
|
|
311
|
+
const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
|
|
312
|
+
const annotate = (code) => errorMessage ? `${code}.annotate(${effectError(errorMessage)})` : code;
|
|
313
|
+
const formatName = schema.format?.toLowerCase();
|
|
314
|
+
if (formatName === "binary") return annotate("Schema.instanceOf(File)");
|
|
315
|
+
const patternMessage = schema["x-pattern-message"];
|
|
316
|
+
const patternErrorPart = effectErrorPart(patternMessage);
|
|
317
|
+
const lengthMessage = schema["x-minLength-message"] ?? schema["x-maxLength-message"];
|
|
318
|
+
const minimumMessage = schema["x-minLength-message"];
|
|
319
|
+
const maximumMessage = schema["x-maxLength-message"];
|
|
320
|
+
const isFixedLength = hasFixedLength(schema);
|
|
321
|
+
const lengthChecks = [
|
|
322
|
+
typeof schema["x-startsWith"] === "string" ? `Schema.isStartsWith(${JSON.stringify(schema["x-startsWith"])})` : void 0,
|
|
323
|
+
typeof schema["x-endsWith"] === "string" ? `Schema.isEndsWith(${JSON.stringify(schema["x-endsWith"])})` : void 0,
|
|
324
|
+
typeof schema["x-includes"] === "string" ? `Schema.isIncludes(${JSON.stringify(schema["x-includes"])})` : void 0,
|
|
325
|
+
schema.pattern ? `Schema.isPattern(${regexLiteral(schema.pattern)}${patternErrorPart})` : void 0,
|
|
326
|
+
isFixedLength ? `Schema.makeFilter((input)=>[...input].length===${schema.minLength},${lengthAnnotations(`a string of ${characters(schema.minLength)}`, lengthMessage)})` : void 0,
|
|
327
|
+
!isFixedLength && schema.minLength !== void 0 ? `Schema.makeFilter((input)=>[...input].length>=${schema.minLength},${lengthAnnotations(`a string of at least ${characters(schema.minLength)}`, minimumMessage)})` : void 0,
|
|
328
|
+
!isFixedLength && schema.maxLength !== void 0 ? `Schema.makeFilter((input)=>[...input].length<=${schema.maxLength},${lengthAnnotations(`a string of at most ${characters(schema.maxLength)}`, maximumMessage)})` : void 0
|
|
329
|
+
].filter((v) => v !== void 0);
|
|
330
|
+
const checks = [...formatName === void 0 ? [] : formatChecks(schema, formatName, patternMessage), ...lengthChecks];
|
|
331
|
+
const base = stringBase(schema, formatName === void 0 ? void 0 : TRANSFORM_FORMATS[formatName]);
|
|
332
|
+
return annotate(checks.length > 0 ? `${base}.check(${checks.join(",")})` : base);
|
|
333
|
+
}
|
|
334
|
+
//#endregion
|
|
335
|
+
//#region src/generator/effect/effect.ts
|
|
336
|
+
/**
|
|
337
|
+
* The boolean spellings of the wire, read into a boolean as `z.stringbool()` reads them:
|
|
338
|
+
* `true` / `1` / `yes` / `on` / `y` / `enabled` and their opposites, in any case. v3
|
|
339
|
+
* shipped a `Schema.BooleanFromString` for `true` / `false`; v4 has no such schema, so
|
|
340
|
+
* the transformation is spelled out.
|
|
341
|
+
*/
|
|
342
|
+
function stringbool() {
|
|
343
|
+
return `Schema.String.check(Schema.isPattern(${stringboolPattern()})).pipe(Schema.decodeTo(Schema.Boolean,SchemaTransformation.transform({decode:(input)=>${stringboolTruthyPattern()}.test(input),encode:(output)=>output?"true":"false"})))`;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* True when a generated expression is a `Schema.Struct({...})`, optionally
|
|
347
|
+
* followed by `.check(...)` / `.annotate(...)` chains — the shapes whose
|
|
348
|
+
* `.fields` property survives (v4 rebuilds a struct as a struct).
|
|
349
|
+
*/
|
|
350
|
+
function isStructExpr(code) {
|
|
351
|
+
return code.startsWith("Schema.Struct({");
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The Effect Schema v4 spelling of an `allOf` intersection.
|
|
355
|
+
*
|
|
356
|
+
* v4 has no general `Schema.extend`. Structs intersect by spreading `.fields`,
|
|
357
|
+
* which is the documented replacement and keeps the full combined type. For
|
|
358
|
+
* anything else — a refined string, a union, a record — the first member
|
|
359
|
+
* becomes the base and each remaining member is enforced as a filter, which
|
|
360
|
+
* validates correctly but types the result as the base member alone.
|
|
361
|
+
*/
|
|
362
|
+
function intersect(schemas) {
|
|
363
|
+
const [first, ...rest] = schemas;
|
|
364
|
+
if (first === void 0) return "Schema.Unknown";
|
|
365
|
+
if (schemas.every(isStructExpr)) return `Schema.Struct({${schemas.map((s) => `...${s}.fields`).join(",")}})`;
|
|
366
|
+
return `${first}.check(${rest.map((s) => `Schema.makeFilter((input)=>Schema.is(${s})(input))`).join(",")})`;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Replace every decoding failure of `inner` with a single message.
|
|
370
|
+
*
|
|
371
|
+
* v4 annotates a node with a plain `message` string, but that only covers
|
|
372
|
+
* issues the node itself reports — a missing or mistyped key is reported
|
|
373
|
+
* deeper and keeps its own message. Validating the whole value through one
|
|
374
|
+
* filter and then decoding restores the v3 `transformOrFail` behaviour of
|
|
375
|
+
* collapsing any failure into the given message, and `decodeTo` carries the
|
|
376
|
+
* inner schema's type through.
|
|
377
|
+
*/
|
|
378
|
+
function wholeValueMessage(inner, message) {
|
|
379
|
+
return `Schema.Unknown.check(Schema.makeFilter((input)=>Schema.is(${inner})(input),${effectError(message)})).pipe(Schema.decodeTo(${inner}))`;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Generate Effect Schema code from a JSON Schema.
|
|
383
|
+
*
|
|
384
|
+
* The `options.readonly` flag is accepted for API symmetry with the other
|
|
385
|
+
* generators but is a no-op for Effect Schema: fields produced by
|
|
386
|
+
* `Schema.Struct({...})` are already `readonly` at the TypeScript type level,
|
|
387
|
+
* and `Schema.Array(...)` returns `ReadonlyArray<T>` by default. Effect Schema
|
|
388
|
+
* has no separate runtime "readonly" wrapper.
|
|
389
|
+
*/
|
|
390
|
+
function effect(schema, rootName = DEFAULT_ROOT_NAME, isEffect = false, options) {
|
|
391
|
+
if (hasParameterSerialization(options)) {
|
|
392
|
+
const inner = effect(schema, rootName, isEffect, withoutParameterSerialization(options));
|
|
393
|
+
return effectPreprocess(parameterReaders(schema, options, "input"), inner);
|
|
394
|
+
}
|
|
395
|
+
return node(schema, rootName, isEffect, options);
|
|
396
|
+
}
|
|
397
|
+
function node(schema, rootName, isEffect, options) {
|
|
398
|
+
const isStringWireParam = isStringWireLocation(options?.paramIn);
|
|
399
|
+
const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
|
|
400
|
+
const codeExtOpts = options?.unsafeCodeExtensions === true ? { unsafeCodeExtensions: true } : {};
|
|
401
|
+
const wireOptions = (s) => {
|
|
402
|
+
if (!isStringWireParam || s["x-coerce"] === false) return {};
|
|
403
|
+
return {
|
|
404
|
+
stringWire: true,
|
|
405
|
+
...isNullTextRead(s) && { nullText: true }
|
|
406
|
+
};
|
|
407
|
+
};
|
|
408
|
+
const effectWrap$1 = (effectStr, s) => effectWrap(effectStr, s, {
|
|
409
|
+
...codeExtOpts,
|
|
410
|
+
...wireOptions(s)
|
|
411
|
+
});
|
|
412
|
+
const wireArray = (v) => isStringWireParam ? effectPreprocess([wireArrayOnce("input")], v) : v;
|
|
413
|
+
const literalInput = (values) => {
|
|
414
|
+
if (values.every((v) => typeof v === "number")) {
|
|
415
|
+
if (isInt64(schema)) return int64Input(isWireCoerced);
|
|
416
|
+
if (isWireCoerced) return "Schema.FiniteFromString";
|
|
417
|
+
}
|
|
418
|
+
if (isWireCoerced && values.every((v) => typeof v === "boolean")) return stringbool();
|
|
419
|
+
};
|
|
420
|
+
if (schema.$ref) {
|
|
421
|
+
const ref = (s) => {
|
|
422
|
+
if (s.$ref === void 0) return "Schema.Unknown";
|
|
423
|
+
const target = refTarget(s.$ref, rootName, isEffect, options?.openapi);
|
|
424
|
+
if (target.kind === "lazy") return `Schema.suspend(() => ${target.name})`;
|
|
425
|
+
return target.kind === "value" ? target.name : "Schema.Unknown";
|
|
426
|
+
};
|
|
427
|
+
const items = itemsSchemaOf(schema.items);
|
|
428
|
+
if (schema.type === "array" && items?.$ref) return `Schema.Array(${effectWrap$1(ref(items), items)})`;
|
|
429
|
+
return effectWrap$1(ref(schema), schema);
|
|
430
|
+
}
|
|
431
|
+
const impliedType = isWireCoerced ? impliedWireType(schema) : void 0;
|
|
432
|
+
if (impliedType !== void 0) return node({
|
|
433
|
+
...schema,
|
|
434
|
+
type: impliedType
|
|
435
|
+
}, rootName, isEffect, options);
|
|
436
|
+
if (schema.oneOf) {
|
|
437
|
+
if (schema.oneOf.length === 0) return effectWrap$1("Schema.Unknown", schema);
|
|
438
|
+
const schemas = schema.oneOf.map((s) => effect(s, rootName, isEffect, options));
|
|
439
|
+
const oneOfMessage = schema["x-oneOf-message"];
|
|
440
|
+
const expr = `Schema.Union([${schemas.join(",")}])`;
|
|
441
|
+
return effectWrap$1(oneOfMessage ? `${expr}.annotate(${effectError(oneOfMessage)})` : expr, schema);
|
|
442
|
+
}
|
|
443
|
+
if (schema.anyOf) {
|
|
444
|
+
if (schema.anyOf.length === 0) return effectWrap$1("Schema.Unknown", schema);
|
|
445
|
+
const schemas = schema.anyOf.map((s) => effect(s, rootName, isEffect, options));
|
|
446
|
+
const anyOfMessage = schema["x-implication-message"] ?? schema["x-anyOf-message"];
|
|
447
|
+
const expr = `Schema.Union([${schemas.join(",")}])`;
|
|
448
|
+
return effectWrap$1(anyOfMessage ? `${expr}.annotate(${effectError(anyOfMessage)})` : expr, schema);
|
|
449
|
+
}
|
|
450
|
+
if (schema.allOf) {
|
|
451
|
+
if (schema.allOf.length === 0) return effectWrap$1("Schema.Unknown", schema);
|
|
452
|
+
const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
|
|
453
|
+
const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
|
|
454
|
+
const schemas = schema.allOf.filter((s) => !isShapelessMember(s)).map((s) => effect(s, rootName, isEffect, options));
|
|
455
|
+
if (schemas.length === 0) return effectWrap$1("Schema.Unknown", {
|
|
456
|
+
...schema,
|
|
457
|
+
nullable
|
|
458
|
+
});
|
|
459
|
+
const intersected = schemas.length === 1 ? schemas[0] : intersect(schemas);
|
|
460
|
+
const allOfMessage = schema["x-allOf-message"];
|
|
461
|
+
const baseResult = allOfMessage ? wholeValueMessage(intersected, allOfMessage) : intersected;
|
|
462
|
+
if (defaultValue !== void 0) return `${nullable ? `Schema.NullOr(${baseResult})` : baseResult}.pipe(${isWireCoerced ? "Schema.withDecodingDefaultType" : "Schema.withDecodingDefault"}(Effect.succeed(${jsLiteral(defaultValue)})))`;
|
|
463
|
+
return effectWrap$1(baseResult, {
|
|
464
|
+
...schema,
|
|
465
|
+
nullable
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
if (schema.not) {
|
|
469
|
+
const { not: inner, ...withoutNot } = schema;
|
|
470
|
+
if (typeof inner !== "object" || inner === null) return effectWrap$1("Schema.Unknown", schema);
|
|
471
|
+
const notMessage = schema["x-not-message"];
|
|
472
|
+
const filterOpts = effectErrorPart(notMessage);
|
|
473
|
+
const predicate = (() => {
|
|
474
|
+
const shared = notPredicate(inner, "input");
|
|
475
|
+
if (shared !== void 0) return shared;
|
|
476
|
+
if (Array.isArray(inner.enum)) return `(input) => !${JSON.stringify(inner.enum)}.some((item) => item === input)`;
|
|
477
|
+
})();
|
|
478
|
+
if (withoutNot.type !== void 0) {
|
|
479
|
+
const base = effect(withoutNot, rootName, isEffect, options);
|
|
480
|
+
return predicate ? `${base}.check(Schema.makeFilter(${predicate}${filterOpts}))` : base;
|
|
481
|
+
}
|
|
482
|
+
if (predicate) return effectWrap$1(`Schema.Unknown.check(Schema.makeFilter(${predicate}${filterOpts}))`, schema);
|
|
483
|
+
return effectWrap$1("Schema.Unknown", schema);
|
|
484
|
+
}
|
|
485
|
+
if (schema.const !== void 0) {
|
|
486
|
+
const constMessage = schema["x-const-message"] ?? schema["x-error-message"];
|
|
487
|
+
const literalCode = typeof schema.const === "number" && isInt64(schema) ? `Schema.Literal(${schema.const}n)` : `Schema.Literal(${JSON.stringify(schema.const)})`;
|
|
488
|
+
const withMessage = constMessage ? `${literalCode}.annotate(${effectError(constMessage)})` : literalCode;
|
|
489
|
+
const input = literalInput([schema.const]);
|
|
490
|
+
return effectWrap$1(input ? `${input}.pipe(Schema.decodeTo(${withMessage}))` : withMessage, schema);
|
|
491
|
+
}
|
|
492
|
+
if (schema.enum) {
|
|
493
|
+
const values = schema.enum.filter((value) => value !== null);
|
|
494
|
+
const input = values.length > 0 ? literalInput(values) : void 0;
|
|
495
|
+
if (input === void 0) return effectWrap$1(_enum(schema), schema);
|
|
496
|
+
const hasNull = values.length < schema.enum.length;
|
|
497
|
+
const piped = `${input}.pipe(Schema.decodeTo(${_enum({
|
|
498
|
+
...schema,
|
|
499
|
+
enum: values
|
|
500
|
+
})}))`;
|
|
501
|
+
return effectWrap$1(hasNull && !isNullable(schema) ? `Schema.NullOr(${piped})` : piped, schema);
|
|
502
|
+
}
|
|
503
|
+
if (schema.properties) return effectWrap$1(object(schema, rootName, isEffect, options), schema);
|
|
504
|
+
const types = normalizeTypes(schema.type);
|
|
505
|
+
const primitive = (t) => {
|
|
506
|
+
if (t === "string") return string(schema);
|
|
507
|
+
if (t === "number") return number(schema, { wire: isWireCoerced });
|
|
508
|
+
if (t === "integer") return integer(schema, { wire: isWireCoerced });
|
|
509
|
+
if (t !== "boolean") return void 0;
|
|
510
|
+
const errorMessage = schema["x-error-message"];
|
|
511
|
+
const base = isWireCoerced ? stringbool() : "Schema.Boolean";
|
|
512
|
+
return errorMessage ? `${base}.annotate(${effectError(errorMessage)})` : base;
|
|
513
|
+
};
|
|
514
|
+
if (isPrimitiveUnion(types, isWireCoerced)) return effectWrap$1(`Schema.Union([${unionPrimitiveTypes(types, isWireCoerced).map(primitive).filter((m) => m !== void 0).join(",")}])`, schema);
|
|
515
|
+
for (const t of [
|
|
516
|
+
"string",
|
|
517
|
+
"number",
|
|
518
|
+
"integer",
|
|
519
|
+
"boolean"
|
|
520
|
+
]) {
|
|
521
|
+
if (!types.includes(t)) continue;
|
|
522
|
+
const expression = primitive(t);
|
|
523
|
+
if (expression !== void 0) return effectWrap$1(expression, schema);
|
|
524
|
+
}
|
|
525
|
+
if (types.includes("array")) {
|
|
526
|
+
const elementMessageWrap = wholeValueMessage;
|
|
527
|
+
if (schema.prefixItems?.length) {
|
|
528
|
+
const items = schema.prefixItems.map((s) => effect(s, rootName, isEffect, options));
|
|
529
|
+
const u = schema.unevaluatedItems;
|
|
530
|
+
const tuple = `Schema.Tuple([${items.join(",")}])`;
|
|
531
|
+
const tupleExpr = isSchemaObject(u) ? `Schema.TupleWithRest(${tuple},[${effect(u, rootName, isEffect, options)}])` : tuple;
|
|
532
|
+
const prefixItemsMessage = schema["x-prefixItems-message"];
|
|
533
|
+
return effectWrap$1(wireArray(prefixItemsMessage ? elementMessageWrap(tupleExpr, prefixItemsMessage) : tupleExpr), schema);
|
|
534
|
+
}
|
|
535
|
+
const itemSchema = itemsSchemaOf(schema.items);
|
|
536
|
+
const items = itemSchema ? effect(itemSchema, rootName, isEffect, options) : "Schema.Unknown";
|
|
537
|
+
const itemsMessage = schema["x-items-message"];
|
|
538
|
+
const arrayBase = `Schema.Array(${items})`;
|
|
539
|
+
const base = itemsMessage ? elementMessageWrap(arrayBase, itemsMessage) : arrayBase;
|
|
540
|
+
const isFixedLength = hasFixedItemCount(schema);
|
|
541
|
+
const lengthMessage = schema["x-length-message"];
|
|
542
|
+
const minItemsMessage = schema["x-minItems-message"] ?? lengthMessage;
|
|
543
|
+
const minArg = effectErrorPart(minItemsMessage);
|
|
544
|
+
const maxItemsMessage = schema["x-maxItems-message"] ?? lengthMessage;
|
|
545
|
+
const maxArg = effectErrorPart(maxItemsMessage);
|
|
546
|
+
const sizeArg = effectErrorPart(minItemsMessage ?? maxItemsMessage);
|
|
547
|
+
const uniqueItemsMessage = schema["x-uniqueItems-message"];
|
|
548
|
+
const uniqueArg = effectErrorPart(uniqueItemsMessage);
|
|
549
|
+
const containsChecks = (() => {
|
|
550
|
+
const c = schema.contains;
|
|
551
|
+
if (!c) return [];
|
|
552
|
+
const containsSchema = effect(c, rootName, isEffect, options);
|
|
553
|
+
const minC = schema.minContains;
|
|
554
|
+
const maxC = schema.maxContains;
|
|
555
|
+
const errorMessage = schema["x-error-message"];
|
|
556
|
+
const fallback = schema["x-contains-message"] ?? errorMessage;
|
|
557
|
+
const out = [];
|
|
558
|
+
if (minC === void 0 && maxC === void 0) {
|
|
559
|
+
const containsArg = effectErrorPart(fallback);
|
|
560
|
+
out.push(`Schema.makeFilter((input)=>input.some((item)=>Schema.is(${containsSchema})(item))${containsArg})`);
|
|
561
|
+
} else {
|
|
562
|
+
const effectiveMin = minC ?? 1;
|
|
563
|
+
if (effectiveMin > 0) {
|
|
564
|
+
const minContainsMessage = schema["x-minContains-message"] ?? fallback;
|
|
565
|
+
const minContainsArg = effectErrorPart(minContainsMessage);
|
|
566
|
+
out.push(`Schema.makeFilter((input)=>input.filter((item)=>Schema.is(${containsSchema})(item)).length>=${effectiveMin}${minContainsArg})`);
|
|
567
|
+
}
|
|
568
|
+
if (maxC !== void 0) {
|
|
569
|
+
const maxContainsMessage = schema["x-maxContains-message"] ?? fallback;
|
|
570
|
+
const maxContainsArg = effectErrorPart(maxContainsMessage);
|
|
571
|
+
out.push(`Schema.makeFilter((input)=>input.filter((item)=>Schema.is(${containsSchema})(item)).length<=${maxC}${maxContainsArg})`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return out;
|
|
575
|
+
})();
|
|
576
|
+
const checks = [
|
|
577
|
+
isFixedLength ? `Schema.isLengthBetween(${schema.minItems},${schema.minItems}${sizeArg})` : void 0,
|
|
578
|
+
!isFixedLength && typeof schema.minItems === "number" ? `Schema.isMinLength(${schema.minItems}${minArg})` : void 0,
|
|
579
|
+
!isFixedLength && typeof schema.maxItems === "number" ? `Schema.isMaxLength(${schema.maxItems}${maxArg})` : void 0,
|
|
580
|
+
schema.uniqueItems === true ? `Schema.isUnique(${uniqueArg.slice(1)})` : void 0,
|
|
581
|
+
...containsChecks
|
|
582
|
+
].filter((v) => v !== void 0);
|
|
583
|
+
return effectWrap$1(wireArray(checks.length > 0 ? `${base}.check(${checks.join(",")})` : base), schema);
|
|
584
|
+
}
|
|
585
|
+
if (types.includes("object")) return effectWrap$1(object(schema, rootName, isEffect, options), schema);
|
|
586
|
+
if (types.includes("date")) {
|
|
587
|
+
if (isWireCoerced) return effectWrap$1("Schema.DateFromString", schema);
|
|
588
|
+
return effectWrap$1("Schema.Date", schema);
|
|
589
|
+
}
|
|
590
|
+
if (types.length === 1 && types[0] === "null") return effectWrap$1("Schema.Null", schema);
|
|
591
|
+
return effectWrap$1("Schema.Unknown", schema);
|
|
592
|
+
}
|
|
593
|
+
//#endregion
|
|
594
|
+
//#region src/generator/effect/type.ts
|
|
595
|
+
/**
|
|
596
|
+
* The TypeScript type declared beside a recursive Effect schema: its decoded `Type`, whose
|
|
597
|
+
* arrays and properties are `readonly` as `Schema.Struct` and `Schema.Array` decode them.
|
|
598
|
+
*/
|
|
599
|
+
function type(schema, rootName = DEFAULT_ROOT_NAME) {
|
|
600
|
+
return typeDeclaration(schema, {
|
|
601
|
+
inferRoot: (name) => `typeof ${name}.Type`,
|
|
602
|
+
readonly: true
|
|
603
|
+
}, rootName);
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region src/generator/effect/index.ts
|
|
607
|
+
/** The root name when the document has none, or when its title would shadow the import. */
|
|
608
|
+
const EFFECT_ROOT_FALLBACK = `${DEFAULT_ROOT_NAME}_`;
|
|
609
|
+
/**
|
|
610
|
+
* A whole JSON Schema document as an Effect Schema module: imports, `$defs` in
|
|
611
|
+
* dependency order, the root export, and the inferred type.
|
|
612
|
+
*
|
|
613
|
+
* `options.readonly` is accepted for API symmetry and is a no-op: `Schema.Struct` and
|
|
614
|
+
* `Schema.Array` are already readonly at the type level.
|
|
615
|
+
*/
|
|
616
|
+
function schemaToEffect(schema, options) {
|
|
617
|
+
const exportType = options?.exportType ?? true;
|
|
618
|
+
const emitOptions = emitOptionsOf(options);
|
|
619
|
+
const codeExtensionsPresent = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
|
|
620
|
+
const toName = schemaNamer(emitOptions.openapi);
|
|
621
|
+
const pascalTitle = rootNameOf(schema, toName, EFFECT_ROOT_FALLBACK);
|
|
622
|
+
const plan = planDocument(schema, pascalTitle === "Schema" ? EFFECT_ROOT_FALLBACK : pascalTitle);
|
|
623
|
+
const { rootName } = plan;
|
|
624
|
+
const needsTypeDef = plan.hasDefinitions || hasRootSelfReference(schema);
|
|
625
|
+
const typeDefsCode = needsTypeDef ? [`type _${rootName} = ${type(plan.root, rootName)}`, renderDefinitions(plan, toName, (def, name) => `type _${name} = ${type(def, name)}`)].filter(Boolean).join("\n\n") : "";
|
|
626
|
+
const schemaDefsCode = renderDefinitions(plan, toName, (def, name) => `const ${name}: Schema.Schema<_${name}> = ${effect(def, name, true, emitOptions)}`);
|
|
627
|
+
const rootSchema = effect(plan.root, rootName, true, emitOptions);
|
|
628
|
+
const rootExport = needsTypeDef ? `export const ${rootName}: Schema.Schema<_${rootName}> = ${rootSchema}` : `export const ${rootName} = ${rootSchema}`;
|
|
629
|
+
const emitted = `${schemaDefsCode}\n${rootExport}`;
|
|
630
|
+
const importLine = `import { ${[
|
|
631
|
+
...emitted.includes("Effect.succeed(") ? ["Effect"] : [],
|
|
632
|
+
"Schema",
|
|
633
|
+
...emitted.includes("SchemaTransformation.") ? ["SchemaTransformation"] : []
|
|
634
|
+
].join(", ")} } from "effect"`;
|
|
635
|
+
return [
|
|
636
|
+
...codeExtensionsPresent ? [UNSAFE_GENERATED_MARKER] : [],
|
|
637
|
+
importLine,
|
|
638
|
+
typeDefsCode,
|
|
639
|
+
schemaDefsCode,
|
|
640
|
+
rootExport,
|
|
641
|
+
...exportType ? [`export type ${rootName} = typeof ${rootName}.Type`] : []
|
|
642
|
+
].filter(Boolean).join("\n\n");
|
|
643
|
+
}
|
|
644
|
+
//#endregion
|
|
645
|
+
export { effect as n, wholeValueMessage as r, schemaToEffect as t };
|
package/dist/effect.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { r as JSONSchema } from "./index-DbV3dEmN.js";
|
|
2
|
+
import { n as GenerateOptions } from "./index-C2L8Ty0-.js";
|
|
3
|
+
//#region src/generator/effect/index.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A whole JSON Schema document as an Effect Schema module: imports, `$defs` in
|
|
6
|
+
* dependency order, the root export, and the inferred type.
|
|
7
|
+
*
|
|
8
|
+
* `options.readonly` is accepted for API symmetry and is a no-op: `Schema.Struct` and
|
|
9
|
+
* `Schema.Array` are already readonly at the type level.
|
|
10
|
+
*/
|
|
11
|
+
export declare function schemaToEffect(schema: JSONSchema, options?: GenerateOptions): string;
|
|
12
|
+
//#endregion
|
package/dist/effect.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as schemaToEffect } from "./effect-mUknRPv_.js";
|