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