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,1798 @@
1
+ import { $ as DEFINITION_REF_PREFIXES, A as isDefinitionKeyword, B as isSchemaObject, C as hasNumericKeyword, Dt as STRING_KEYWORDS, E as isArktypeDefinition, I as isQuoted, L as isRecord, M as isNullable, Mt as WIRE_PRIMITIVE_ORDER, O as isDeepLocalPointer, Q as DEFINITION_POINTER_PATTERN, R as isRootRef, T as hasType, Tt as STRINGBOOL_TRUTHY_PATTERN, U as ALL_CODE_EXTENSION_KEYS, V as isShapelessMember, W as ANCHOR_REF_PATTERN, X as DEFAULT_ROOT_NAME, Y as DATE_PATTERN_SOURCE, _ as canBeNull, _t as OFFSET_PATTERN_SOURCE, c as normalizeTypes, d as toPascalCase, ht as NUMERIC_KEYWORDS, j as isNullTypeMember, k as isDefaultOnlyMember, kt as UNICODE_ESCAPE_PATTERN, l as resolveOpenAPIRef, lt as MISSING_DEFINITION_PREFIX, mt as NUMBER_WIRE_PATTERN, ot as INTEGER_WIRE_PATTERN, s as makeSafeKey, t as coerceDefault, tt as FORMAT_PATTERNS, u as toIdentifierPascalCase, v as canBeString, w as hasStringKeyword, wt as STRINGBOOL_PATTERN, y as hasCombinator, z as isSchemaList } from "./utils-Bky98UmP.js";
2
+ //#region src/helper/regex.ts
3
+ /**
4
+ * Build a JavaScript regular-expression literal from a JSON Schema `pattern`.
5
+ *
6
+ * Escapes unescaped `/` so the literal stays delimited, and adds the `u` flag
7
+ * when the pattern uses Unicode property escapes (`\p{...}`, `\P{...}`,
8
+ * `\u{...}`), which TypeScript requires for those constructs (TS1530). A Perl
9
+ * hex escape `\x{HHHH}` is rewritten to `\uHHHH` (or `\u{HHHHH}` above
10
+ * U+FFFF, which also sets `u`): TypeScript rejects `\x{` (TS1125) and, without
11
+ * `u`, V8 treats it as an identity escape. Returns the literal only (`/.../`
12
+ * or `/.../u`); callers append any validator-specific error argument.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * regexLiteral('^[a-z]+$') // '/^[a-z]+$/'
17
+ * regexLiteral('^\\p{L}+$') // '/^\\p{L}+$/u'
18
+ * regexLiteral('a/b') // '/a\\/b/'
19
+ * regexLiteral('\\x{FFFF}') // '/\\uFFFF/'
20
+ * ```
21
+ */
22
+ function regexLiteral(pattern) {
23
+ const rewritten = rewriteBracedHex(pattern);
24
+ return `/${rewritten.pattern.replaceAll(/(?<!\\)\//gu, "\\/")}/${rewritten.unicode || UNICODE_ESCAPE_PATTERN.test(rewritten.pattern) ? "u" : ""}`;
25
+ }
26
+ /**
27
+ * The pattern with braced hex escapes (`\x{hex}`) rewritten to JavaScript unicode
28
+ * escapes. A code point above U+FFFF needs the `u` flag (`unicode`). An
29
+ * already-escaped backslash (`\\x{FFFF}`) is left as text.
30
+ */
31
+ function patternSource(pattern) {
32
+ return rewriteBracedHex(pattern).pattern;
33
+ }
34
+ function rewriteBracedHex(pattern) {
35
+ let unicode = false;
36
+ let out = "";
37
+ for (let index = 0; index < pattern.length; index++) {
38
+ const char = pattern.charAt(index);
39
+ if (char === "\\" && pattern.charAt(index + 1) === "\\") {
40
+ out += "\\\\";
41
+ index += 1;
42
+ continue;
43
+ }
44
+ if (char === "\\" && pattern.startsWith("x{", index + 1)) {
45
+ const close = pattern.indexOf("}", index + 3);
46
+ const hex = close > index + 3 ? pattern.slice(index + 3, close) : "";
47
+ if (/^[0-9A-Fa-f]+$/u.test(hex)) {
48
+ const codePoint = Number.parseInt(hex, 16);
49
+ if (codePoint <= 1114111) {
50
+ if (codePoint > 65535) {
51
+ unicode = true;
52
+ out += `\\u{${hex}}`;
53
+ } else out += `\\u${hex.padStart(4, "0")}`;
54
+ index = close;
55
+ continue;
56
+ }
57
+ }
58
+ }
59
+ out += char;
60
+ }
61
+ return {
62
+ pattern: out,
63
+ unicode
64
+ };
65
+ }
66
+ //#endregion
67
+ //#region src/helper/all-of.ts
68
+ /**
69
+ * An `allOf` member that only carries keywords (`{ minimum: 5 }`, `{ maxLength: 10 }`).
70
+ *
71
+ * It has no type of its own. The keywords still apply to the composed value — a number
72
+ * must meet `minimum`, a string must meet `maxLength` — so dropping the member drops
73
+ * constraints that JSON Schema keeps.
74
+ */
75
+ const KEYWORD_ONLY_KEYS = /* @__PURE__ */ new Set([
76
+ ...NUMERIC_KEYWORDS,
77
+ ...STRING_KEYWORDS,
78
+ "x-error-message",
79
+ "x-minimum-message",
80
+ "x-maximum-message",
81
+ "x-exclusiveMinimum-message",
82
+ "x-exclusiveMaximum-message",
83
+ "x-multipleOf-message",
84
+ "x-minLength-message",
85
+ "x-maxLength-message",
86
+ "x-pattern-message",
87
+ "title",
88
+ "description",
89
+ "$comment",
90
+ "examples",
91
+ "example",
92
+ "deprecated",
93
+ "readOnly",
94
+ "writeOnly"
95
+ ]);
96
+ /** Whether every key of `schema` is a numeric or string keyword, its message, or an annotation. */
97
+ function isKeywordOnlyMember(schema) {
98
+ const keys = Object.keys(schema);
99
+ if (keys.length === 0) return false;
100
+ if (!keys.every((key) => KEYWORD_ONLY_KEYS.has(key))) return false;
101
+ return hasNumericKeyword(schema) || hasStringKeyword(schema);
102
+ }
103
+ /** The message a keyword-only member should report, keyword messages falling back together. */
104
+ function constraintMessage(schema) {
105
+ return schema["x-error-message"] ?? schema["x-minimum-message"] ?? schema["x-maximum-message"] ?? schema["x-exclusiveMinimum-message"] ?? schema["x-exclusiveMaximum-message"] ?? schema["x-multipleOf-message"] ?? schema["x-minLength-message"] ?? schema["x-maxLength-message"] ?? schema["x-pattern-message"];
106
+ }
107
+ /**
108
+ * The predicate that keeps a keyword-only member's constraints without forcing a type.
109
+ *
110
+ * A number that fails `minimum` is rejected; a string is not a number, so `minimum` does
111
+ * not apply to it. `param` is the value name the caller already uses.
112
+ */
113
+ function constraintPredicate(schema, param) {
114
+ const parts = [numericGuard(schema, param), stringGuard(schema, param)].filter((part) => part !== "");
115
+ if (parts.length === 0) return "true";
116
+ return parts.join(" && ");
117
+ }
118
+ /**
119
+ * Fold keyword-only `allOf` members into a sibling whose type they constrain.
120
+ *
121
+ * `{ type: 'integer' }` beside `{ minimum: 5 }` is one integer of at least 5. A keyword
122
+ * with no such sibling stays keyword-only, so the caller emits a type-guarded check. On
123
+ * the string wire a leftover is given the type its keywords imply, and one coercion
124
+ * reads the text.
125
+ */
126
+ function foldAllOfMembers(members, isWire) {
127
+ let numericAt = -1;
128
+ let stringAt = -1;
129
+ for (const [index, member] of members.entries()) {
130
+ if (numericAt === -1 && isNumericHost(member)) numericAt = index;
131
+ if (stringAt === -1 && isStringHost(member)) stringAt = index;
132
+ }
133
+ const next = [...members];
134
+ const numericLeftovers = [];
135
+ const stringLeftovers = [];
136
+ const drop = /* @__PURE__ */ new Set();
137
+ for (const [index, member] of members.entries()) {
138
+ if (!isKeywordOnlyMember(member)) continue;
139
+ drop.add(index);
140
+ const numeric = numericPart(member);
141
+ const text = stringPart(member);
142
+ if (numeric !== void 0) {
143
+ const host = numericAt === -1 ? void 0 : next[numericAt];
144
+ const absorbed = host === void 0 ? void 0 : tryAbsorbNumeric(host, numeric);
145
+ if (host !== void 0 && absorbed !== void 0) next[numericAt] = absorbed;
146
+ else numericLeftovers.push(numeric);
147
+ }
148
+ if (text !== void 0) {
149
+ const host = stringAt === -1 ? void 0 : next[stringAt];
150
+ const absorbed = host === void 0 ? void 0 : tryAbsorbString(host, text);
151
+ if (host !== void 0 && absorbed !== void 0) next[stringAt] = absorbed;
152
+ else stringLeftovers.push(text);
153
+ }
154
+ }
155
+ const kept = [];
156
+ for (const [index, member] of next.entries()) if (!drop.has(index)) kept.push(member);
157
+ return [
158
+ ...kept,
159
+ ...collapse(numericLeftovers, "number", isWire),
160
+ ...collapse(stringLeftovers, "string", isWire)
161
+ ];
162
+ }
163
+ function isNumericHost(schema) {
164
+ if (schema.type !== "number" && schema.type !== "integer") return false;
165
+ if (schema.$ref !== void 0 || hasCombinator(schema)) return false;
166
+ if (schema.properties !== void 0 || schema.enum !== void 0 || "const" in schema) return false;
167
+ return true;
168
+ }
169
+ function isStringHost(schema) {
170
+ if (schema.type !== "string") return false;
171
+ if (schema.$ref !== void 0 || hasCombinator(schema)) return false;
172
+ if (schema.properties !== void 0 || schema.enum !== void 0 || "const" in schema) return false;
173
+ return true;
174
+ }
175
+ function numericPart(schema) {
176
+ if (!hasNumericKeyword(schema)) return void 0;
177
+ return {
178
+ ...schema.minimum !== void 0 ? { minimum: schema.minimum } : {},
179
+ ...schema.maximum !== void 0 ? { maximum: schema.maximum } : {},
180
+ ...schema.exclusiveMinimum !== void 0 ? { exclusiveMinimum: schema.exclusiveMinimum } : {},
181
+ ...schema.exclusiveMaximum !== void 0 ? { exclusiveMaximum: schema.exclusiveMaximum } : {},
182
+ ...schema.multipleOf !== void 0 ? { multipleOf: schema.multipleOf } : {},
183
+ ...schema["x-minimum-message"] !== void 0 ? { "x-minimum-message": schema["x-minimum-message"] } : {},
184
+ ...schema["x-maximum-message"] !== void 0 ? { "x-maximum-message": schema["x-maximum-message"] } : {},
185
+ ...schema["x-exclusiveMinimum-message"] !== void 0 ? { "x-exclusiveMinimum-message": schema["x-exclusiveMinimum-message"] } : {},
186
+ ...schema["x-exclusiveMaximum-message"] !== void 0 ? { "x-exclusiveMaximum-message": schema["x-exclusiveMaximum-message"] } : {},
187
+ ...schema["x-multipleOf-message"] !== void 0 ? { "x-multipleOf-message": schema["x-multipleOf-message"] } : {}
188
+ };
189
+ }
190
+ function stringPart(schema) {
191
+ if (!hasStringKeyword(schema)) return void 0;
192
+ return {
193
+ ...schema.minLength !== void 0 ? { minLength: schema.minLength } : {},
194
+ ...schema.maxLength !== void 0 ? { maxLength: schema.maxLength } : {},
195
+ ...schema.pattern !== void 0 ? { pattern: schema.pattern } : {},
196
+ ...schema["x-minLength-message"] !== void 0 ? { "x-minLength-message": schema["x-minLength-message"] } : {},
197
+ ...schema["x-maxLength-message"] !== void 0 ? { "x-maxLength-message": schema["x-maxLength-message"] } : {},
198
+ ...schema["x-pattern-message"] !== void 0 ? { "x-pattern-message": schema["x-pattern-message"] } : {}
199
+ };
200
+ }
201
+ function tryAbsorbNumeric(host, extra) {
202
+ if (!canAbsorbMultipleOf(host, extra)) return void 0;
203
+ return absorbMultipleOf(absorbUpper(absorbLower(host, extra), extra), extra);
204
+ }
205
+ function tryAbsorbString(host, extra) {
206
+ if (typeof extra.pattern === "string" && typeof host.pattern === "string" && extra.pattern !== host.pattern) return;
207
+ return absorbString(host, extra);
208
+ }
209
+ function canAbsorbMultipleOf(host, extra) {
210
+ if (typeof extra.multipleOf !== "number" || typeof host.multipleOf !== "number") return true;
211
+ if (host.multipleOf === extra.multipleOf) return true;
212
+ return leastCommonMultiple(host.multipleOf, extra.multipleOf) !== void 0;
213
+ }
214
+ function absorbLower(host, extra) {
215
+ const extraBound = lowerBound(extra);
216
+ if (extraBound === void 0) return host;
217
+ const hostBound = lowerBound(host);
218
+ if (hostBound !== void 0 && !isStricter(extraBound, hostBound, "lower")) return host;
219
+ return withLower(host, extraBound, boundMessage(extra, extraBound, "lower"));
220
+ }
221
+ function absorbUpper(host, extra) {
222
+ const extraBound = upperBound(extra);
223
+ if (extraBound === void 0) return host;
224
+ const hostBound = upperBound(host);
225
+ if (hostBound !== void 0 && !isStricter(extraBound, hostBound, "upper")) return host;
226
+ return withUpper(host, extraBound, boundMessage(extra, extraBound, "upper"));
227
+ }
228
+ function absorbMultipleOf(host, extra) {
229
+ if (typeof extra.multipleOf !== "number") return host;
230
+ if (typeof host.multipleOf !== "number") return {
231
+ ...host,
232
+ multipleOf: extra.multipleOf,
233
+ ...extra["x-multipleOf-message"] !== void 0 ? { "x-multipleOf-message": extra["x-multipleOf-message"] } : {}
234
+ };
235
+ if (host.multipleOf === extra.multipleOf) return host;
236
+ const multiple = leastCommonMultiple(host.multipleOf, extra.multipleOf);
237
+ if (multiple === void 0) return host;
238
+ const { "x-multipleOf-message": message, ...rest } = host;
239
+ return {
240
+ ...rest,
241
+ multipleOf: multiple
242
+ };
243
+ }
244
+ function absorbString(host, extra) {
245
+ let next = host;
246
+ if (typeof extra.minLength === "number" && (next.minLength === void 0 || extra.minLength > next.minLength)) next = {
247
+ ...next,
248
+ minLength: extra.minLength,
249
+ ...extra["x-minLength-message"] !== void 0 ? { "x-minLength-message": extra["x-minLength-message"] } : {}
250
+ };
251
+ if (typeof extra.maxLength === "number" && (next.maxLength === void 0 || extra.maxLength < next.maxLength)) next = {
252
+ ...next,
253
+ maxLength: extra.maxLength,
254
+ ...extra["x-maxLength-message"] !== void 0 ? { "x-maxLength-message": extra["x-maxLength-message"] } : {}
255
+ };
256
+ if (typeof extra.pattern === "string" && next.pattern === void 0) next = {
257
+ ...next,
258
+ pattern: extra.pattern,
259
+ ...extra["x-pattern-message"] !== void 0 ? { "x-pattern-message": extra["x-pattern-message"] } : {}
260
+ };
261
+ return next;
262
+ }
263
+ function collapse(parts, kind, isWire) {
264
+ const groups = [];
265
+ for (const part of parts) {
266
+ const last = groups.at(-1);
267
+ const absorbed = last === void 0 ? void 0 : kind === "number" ? tryAbsorbNumeric(last, part) : tryAbsorbString(last, part);
268
+ if (last === void 0 || absorbed === void 0) {
269
+ groups.push(isWire ? {
270
+ ...part,
271
+ type: kind
272
+ } : part);
273
+ continue;
274
+ }
275
+ groups[groups.length - 1] = absorbed;
276
+ }
277
+ return groups;
278
+ }
279
+ function lowerBound(schema) {
280
+ if (typeof schema.exclusiveMinimum === "number") return {
281
+ value: schema.exclusiveMinimum,
282
+ exclusive: true
283
+ };
284
+ if (typeof schema.minimum === "number") return {
285
+ value: schema.minimum,
286
+ exclusive: schema.exclusiveMinimum === true
287
+ };
288
+ }
289
+ function upperBound(schema) {
290
+ if (typeof schema.exclusiveMaximum === "number") return {
291
+ value: schema.exclusiveMaximum,
292
+ exclusive: true
293
+ };
294
+ if (typeof schema.maximum === "number") return {
295
+ value: schema.maximum,
296
+ exclusive: schema.exclusiveMaximum === true
297
+ };
298
+ }
299
+ function isStricter(next, current, direction) {
300
+ if (next.value !== current.value) return direction === "lower" ? next.value > current.value : next.value < current.value;
301
+ return next.exclusive && !current.exclusive;
302
+ }
303
+ function boundMessage(schema, bound, direction) {
304
+ if (direction === "lower") return bound.exclusive ? schema["x-exclusiveMinimum-message"] : schema["x-minimum-message"];
305
+ return bound.exclusive ? schema["x-exclusiveMaximum-message"] : schema["x-maximum-message"];
306
+ }
307
+ function dropLower(schema) {
308
+ const { minimum, exclusiveMinimum, "x-minimum-message": minimumMessage, "x-exclusiveMinimum-message": exclusiveMinimumMessage, ...rest } = schema;
309
+ return rest;
310
+ }
311
+ function dropUpper(schema) {
312
+ const { maximum, exclusiveMaximum, "x-maximum-message": maximumMessage, "x-exclusiveMaximum-message": exclusiveMaximumMessage, ...rest } = schema;
313
+ return rest;
314
+ }
315
+ function withLower(schema, bound, message) {
316
+ const base = dropLower(schema);
317
+ if (bound.exclusive) return {
318
+ ...base,
319
+ exclusiveMinimum: bound.value,
320
+ ...message !== void 0 ? { "x-exclusiveMinimum-message": message } : {}
321
+ };
322
+ return {
323
+ ...base,
324
+ minimum: bound.value,
325
+ ...message !== void 0 ? { "x-minimum-message": message } : {}
326
+ };
327
+ }
328
+ function withUpper(schema, bound, message) {
329
+ const base = dropUpper(schema);
330
+ if (bound.exclusive) return {
331
+ ...base,
332
+ exclusiveMaximum: bound.value,
333
+ ...message !== void 0 ? { "x-exclusiveMaximum-message": message } : {}
334
+ };
335
+ return {
336
+ ...base,
337
+ maximum: bound.value,
338
+ ...message !== void 0 ? { "x-maximum-message": message } : {}
339
+ };
340
+ }
341
+ function leastCommonMultiple(left, right) {
342
+ if (!Number.isSafeInteger(left) || !Number.isSafeInteger(right) || left === 0 || right === 0) return;
343
+ const divisor = greatestCommonDivisor(Math.abs(left), Math.abs(right));
344
+ const multiple = Math.abs(left) / divisor * Math.abs(right);
345
+ if (!Number.isSafeInteger(multiple)) return void 0;
346
+ return multiple;
347
+ }
348
+ function greatestCommonDivisor(left, right) {
349
+ let x = left;
350
+ let y = right;
351
+ while (y !== 0) {
352
+ const next = x % y;
353
+ x = y;
354
+ y = next;
355
+ }
356
+ return x;
357
+ }
358
+ function numericGuard(schema, param) {
359
+ const checks = [];
360
+ if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) checks.push(`${param} >= ${schema.minimum}`);
361
+ if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") checks.push(`${param} > ${schema.minimum}`);
362
+ if (typeof schema.exclusiveMinimum === "number") checks.push(`${param} > ${schema.exclusiveMinimum}`);
363
+ if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) checks.push(`${param} <= ${schema.maximum}`);
364
+ if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") checks.push(`${param} < ${schema.maximum}`);
365
+ if (typeof schema.exclusiveMaximum === "number") checks.push(`${param} < ${schema.exclusiveMaximum}`);
366
+ if (typeof schema.multipleOf === "number") checks.push(`${param} % ${schema.multipleOf} === 0`);
367
+ if (checks.length === 0) return "";
368
+ return `(typeof ${param} !== 'number' || (${checks.join(" && ")}))`;
369
+ }
370
+ function stringGuard(schema, param) {
371
+ const checks = [];
372
+ if (typeof schema.minLength === "number") checks.push(`${param}.length >= ${schema.minLength}`);
373
+ if (typeof schema.maxLength === "number") checks.push(`${param}.length <= ${schema.maxLength}`);
374
+ if (typeof schema.pattern === "string") checks.push(`${regexLiteral(schema.pattern)}.test(${param})`);
375
+ if (checks.length === 0) return "";
376
+ return `(typeof ${param} !== 'string' || (${checks.join(" && ")}))`;
377
+ }
378
+ //#endregion
379
+ //#region src/helper/walk.ts
380
+ /**
381
+ * Every object node under `root`, depth first, the root first.
382
+ *
383
+ * Arrays are descended into but never yielded: a combinator list is a list of schemas,
384
+ * not a schema. This is the one traversal every "does the document contain ..." question
385
+ * is asked through, so the questions stay one line each and agree on what a node is.
386
+ *
387
+ * @yields each object node, parents before children
388
+ */
389
+ function* walkSchema(root, options) {
390
+ const stack = [root];
391
+ let isRoot = true;
392
+ while (stack.length > 0) {
393
+ const node = stack.pop();
394
+ if (!isRecord(node)) continue;
395
+ if (Array.isArray(node)) {
396
+ for (const item of node) stack.push(item);
397
+ continue;
398
+ }
399
+ const yielded = !(isRoot && options?.skipRoot === true);
400
+ isRoot = false;
401
+ if (yielded) {
402
+ yield node;
403
+ if (options?.prune?.(node) === true) continue;
404
+ }
405
+ for (const [key, value] of Object.entries(node)) {
406
+ if (options?.skipDefinitions === true && isDefinitionKeyword(key)) continue;
407
+ if (isRecord(value)) stack.push(value);
408
+ }
409
+ }
410
+ }
411
+ /** Whether any node under `root` carries one of `keywords`. */
412
+ function hasKeyword(root, keywords) {
413
+ for (const node of walkSchema(root)) if (keywords.some((keyword) => keyword in node)) return true;
414
+ return false;
415
+ }
416
+ /**
417
+ * Whether a schema (at any depth) uses the JSON Schema `not` keyword. The TypeBox
418
+ * generator falls back to `Type.Any()` because TypeBox v1 has no runtime `Type.Not(...)`
419
+ * and `Value.Check` does not evaluate `not`.
420
+ */
421
+ function hasNotKeyword(schema) {
422
+ return hasKeyword(schema, ["not"]);
423
+ }
424
+ //#endregion
425
+ //#region src/helper/code-extensions.ts
426
+ const CODE_EXTENSION_KEYS = new Set(ALL_CODE_EXTENSION_KEYS);
427
+ const DENYLIST_PATTERN = new RegExp([
428
+ "\\b(?:process|require|import|globalThis|eval|Function|constructor|__proto__|",
429
+ "child_process|setTimeout|setInterval|XMLHttpRequest|fetch|atob|btoa|",
430
+ "document|window|self|top|parent|location|navigator|localStorage|",
431
+ "sessionStorage|indexedDB|WebSocket|FileReader|Worker|crypto|require_|",
432
+ "arguments|callee|caller|Reflect|Proxy|Symbol)\\b",
433
+ "|String\\s*\\.\\s*fromCharCode",
434
+ "|String\\s*\\.\\s*raw",
435
+ "|\\.\\s*join\\s*\\(",
436
+ "|`",
437
+ "|\\\\[uxN]",
438
+ "|\\[\\s*['\"]"
439
+ ].join(""), "u");
440
+ /**
441
+ * Validate a raw code-extension value against a small denylist.
442
+ *
443
+ * **This is defense-in-depth only — not a primary control.** The primary
444
+ * security control is the `unsafeCodeExtensions: true` programmatic opt-in
445
+ * itself. A motivated attacker can bypass the denylist through string-
446
+ * construction (`String.fromCharCode(...)`, `['c','o','d','e'].join('')`),
447
+ * `arguments.callee.caller` chains, ES2015+ identifier characters, or any
448
+ * number of metaprogramming patterns we have not enumerated. Do not pass
449
+ * `{ unsafeCodeExtensions: true }` for JSON Schemas from outside your trust
450
+ * boundary, regardless of what this function returns.
451
+ *
452
+ * Blocks: `process` / `require` / `import` / `globalThis` / `eval` /
453
+ * `Function` / `constructor` / `__proto__` / `child_process` /
454
+ * `arguments` / `callee` / `caller` / `Reflect` / `Proxy` / `Symbol`,
455
+ * network and browser globals, `String.fromCharCode` and `String.raw`,
456
+ * any `.join(` invocation, template-literal backticks,
457
+ * unicode/hex/octal-name escape sequences, and `[ '...' ]` computed access.
458
+ */
459
+ function isSafeCodeExtension(value) {
460
+ if (typeof value !== "string") return false;
461
+ return !DENYLIST_PATTERN.test(value);
462
+ }
463
+ /**
464
+ * Returns the list of code-extension keys present on a schema (any nested
465
+ * level), so callers can emit a single warning when programmatic callers
466
+ * supply such schemas without `unsafeCodeExtensions: true`.
467
+ */
468
+ function findCodeExtensionKeysInSchema(schema) {
469
+ const found = /* @__PURE__ */ new Set();
470
+ for (const node of walkSchema(schema)) for (const key of Object.keys(node)) if (CODE_EXTENSION_KEYS.has(key)) found.add(key);
471
+ return [...found];
472
+ }
473
+ /**
474
+ * Read a code-extension value from the schema only when the flag is enabled
475
+ * AND the value passes the denylist check. Returns `undefined` otherwise.
476
+ */
477
+ function readCodeExtension(schema, key, options) {
478
+ if (options?.unsafeCodeExtensions !== true) return void 0;
479
+ const raw = schema[key];
480
+ if (typeof raw !== "string") return void 0;
481
+ if (!isSafeCodeExtension(raw)) return void 0;
482
+ return raw;
483
+ }
484
+ //#endregion
485
+ //#region src/helper/arktype-wrap.ts
486
+ /**
487
+ * `inner` read after `readers`, each a `(data) => ...` arrow over the raw value: a morph
488
+ * from `input` that pipes into `inner`, with `.to()` for a bare definition.
489
+ */
490
+ function arktypePreprocess(readers, inner, input = "unknown") {
491
+ if (readers.length === 0) return inner;
492
+ if (isArktypeDefinition(inner)) return `type("${input}").pipe(${readers.join(",")}).to(${inner})`;
493
+ return `type("${input}").pipe(${readers.join(",")},${inner})`;
494
+ }
495
+ /**
496
+ * Wraps an ArkType schema string with `.or("null")`, `.brand()` and
497
+ * `.describe()` based on the JSON Schema's `nullable` / `x-brand` fields and
498
+ * OpenAPI `description`.
499
+ *
500
+ * Metadata mapping (ArkType `.describe()`):
501
+ * - `description` → `.describe(text)`, or `[def, "@", text]` in scope mode
502
+ *
503
+ * Other OpenAPI metadata fields (`examples`, `deprecated`, `externalDocs`,
504
+ * `readOnly`, `writeOnly`) are NOT emitted because ArkType's `.configure()`
505
+ * requires `ArkEnv["meta"]` interface augmentation for non-standard keys,
506
+ * which the user must opt in to. Emitting them here could produce TypeScript
507
+ * compile errors in consumer projects.
508
+ *
509
+ * @see https://arktype.io/docs/configuration
510
+ */
511
+ function arktypeWrap(arktypeStr, schema, options) {
512
+ const inScope = options?.scopeMode === true;
513
+ const isDefinition = isArktypeDefinition;
514
+ const withNullable = isNullable(schema) ? isQuoted(arktypeStr) ? `"${arktypeStr.slice(1, -1)} | null"` : inScope && isDefinition(arktypeStr) ? `[${arktypeStr},"|","null"]` : `type(${arktypeStr}).or("null")` : arktypeStr;
515
+ const withReadonly = schema["x-readonly"] === true ? isDefinition(withNullable) ? `type(${withNullable}).readonly()` : `${withNullable}.readonly()` : withNullable;
516
+ const brand = schema["x-brand"];
517
+ const withBrand = typeof brand === "string" ? isDefinition(withReadonly) ? `type(${withReadonly}).brand("${brand}")` : `${withReadonly}.brand("${brand}")` : withReadonly;
518
+ const codeChain = [
519
+ readCodeExtension(schema, "x-narrow", options),
520
+ readCodeExtension(schema, "x-morph", options),
521
+ readCodeExtension(schema, "x-pipe", options)
522
+ ].filter((v) => v !== void 0).join("");
523
+ const withCodeExts = codeChain ? isDefinition(withBrand) ? `type(${withBrand})${codeChain}` : `${withBrand}${codeChain}` : withBrand;
524
+ if (schema.description === void 0) return withCodeExts;
525
+ const text = JSON.stringify(schema.description);
526
+ if (inScope && isDefinition(withCodeExts)) return `[${withCodeExts},"@",${text}]`;
527
+ return `${isDefinition(withCodeExts) ? `type(${withCodeExts})` : withCodeExts}.describe(${text})`;
528
+ }
529
+ //#endregion
530
+ //#region src/helper/schema.ts
531
+ /** `definitions` and `$defs` read as one map, `$defs` winning on a shared name. */
532
+ function collectDefinitions(schema) {
533
+ return {
534
+ ...schema.definitions,
535
+ ...schema.$defs
536
+ };
537
+ }
538
+ /**
539
+ * The schema every array element is validated against: `items` itself, or the first
540
+ * member of a Draft-04 tuple. `undefined` for a boolean `items`, or none.
541
+ */
542
+ function itemsSchemaOf(items) {
543
+ if (isSchemaObject(items)) return items;
544
+ if (isSchemaList(items)) return items[0];
545
+ }
546
+ /**
547
+ * The example values of a node: `examples` as given, or the single OpenAPI `example`
548
+ * lifted into a list. `undefined` when the node carries neither.
549
+ */
550
+ function examplesOf(schema) {
551
+ if (schema.examples !== void 0) return schema.examples;
552
+ return schema.example === void 0 ? void 0 : [schema.example];
553
+ }
554
+ /**
555
+ * Whether a node carries a `default` the generators keep, so a property holding it may be
556
+ * left out of the input.
557
+ */
558
+ function hasKeptDefault(schema, definitions) {
559
+ return schema.default !== void 0 && coerceDefault(schema, schema.default, definitions).keep;
560
+ }
561
+ /**
562
+ * Whether a node's own emitter already makes it optional with a default: a kept `default`,
563
+ * or an `allOf` member that only carries one. An object wrapping such a property again
564
+ * would hide the default behind the outer wrapper.
565
+ */
566
+ function isOptionalByDefault(schema, definitions) {
567
+ return hasKeptDefault(schema, definitions) || schema.allOf?.some(isDefaultOnlyMember) === true;
568
+ }
569
+ //#endregion
570
+ //#region src/helper/cyclic.ts
571
+ /**
572
+ * The definition a local `$ref` names, in any form the generators understand:
573
+ * `#/definitions/X`, `#/$defs/X` and the bare `#X` shorthand. `undefined` for the
574
+ * whole-document reference and for a pointer into a sub-schema.
575
+ */
576
+ function localDefinitionName(ref) {
577
+ return DEFINITION_POINTER_PATTERN.exec(ref)?.groups?.name ?? ANCHOR_REF_PATTERN.exec(ref)?.groups?.name;
578
+ }
579
+ /**
580
+ * Collect the local definition names a schema refers to. Nested `definitions`/`$defs`
581
+ * are not traversed: only references reachable from the schema body count as edges.
582
+ */
583
+ function collectLocalRefs(schema) {
584
+ const refs = /* @__PURE__ */ new Set();
585
+ for (const node of walkSchema(schema, { skipDefinitions: true })) {
586
+ if (typeof node.$ref !== "string") continue;
587
+ const name = localDefinitionName(node.$ref);
588
+ if (name !== void 0) refs.add(name);
589
+ }
590
+ return [...refs];
591
+ }
592
+ /**
593
+ * True when a schema body refers back to itself, ignoring anything nested
594
+ * under `definitions`/`$defs`.
595
+ *
596
+ * By default only a whole-document reference (`$ref: "#"` or `""`) counts.
597
+ * Pass `isSelfRef` to also recognise a named reference that resolves back to
598
+ * the schema being emitted — an OpenAPI component referencing its own
599
+ * `#/components/schemas/...` entry, for instance.
600
+ */
601
+ function hasRootSelfReference(schema, isSelfRef = isRootRef) {
602
+ for (const node of walkSchema(schema, {
603
+ skipDefinitions: true,
604
+ skipRoot: true
605
+ })) if (typeof node.$ref === "string" && isSelfRef(node.$ref)) return true;
606
+ return false;
607
+ }
608
+ /**
609
+ * Names of the local definitions that take part in a `$ref` cycle — either a
610
+ * self loop (`A -> A`) or a mutual one (`A -> B -> A`).
611
+ *
612
+ * Generators that cannot express a cycle with plain `const` declarations (a
613
+ * later definition would be referenced before initialisation) use this to
614
+ * switch those definitions over to a by-name construct instead.
615
+ *
616
+ * @example
617
+ * ```ts
618
+ * cyclicDefinitionNames({
619
+ * $defs: {
620
+ * A: { properties: { b: { $ref: '#/$defs/B' } } },
621
+ * B: { properties: { a: { $ref: '#/$defs/A' } } },
622
+ * },
623
+ * }) // Set { 'A', 'B' }
624
+ * ```
625
+ */
626
+ function cyclicDefinitionNames(schema) {
627
+ const definitions = collectDefinitions(schema);
628
+ const edges = /* @__PURE__ */ new Map();
629
+ for (const [name, def] of Object.entries(definitions)) edges.set(name, collectLocalRefs(def).filter((ref) => ref in definitions));
630
+ const cyclic = /* @__PURE__ */ new Set();
631
+ const state = /* @__PURE__ */ new Map();
632
+ const path = [];
633
+ const visit = (start) => {
634
+ const work = [[start, false]];
635
+ while (work.length > 0) {
636
+ const entry = work.pop();
637
+ if (entry === void 0) continue;
638
+ const [name, leaving] = entry;
639
+ if (leaving) {
640
+ path.pop();
641
+ state.set(name, "done");
642
+ continue;
643
+ }
644
+ if (state.get(name) === "done") continue;
645
+ if (state.get(name) === "visiting") {
646
+ for (let i = path.lastIndexOf(name); i >= 0 && i < path.length; i++) {
647
+ const onCycle = path[i];
648
+ if (onCycle !== void 0) cyclic.add(onCycle);
649
+ }
650
+ continue;
651
+ }
652
+ state.set(name, "visiting");
653
+ path.push(name);
654
+ work.push([name, true]);
655
+ for (const next of edges.get(name) ?? []) work.push([next, false]);
656
+ }
657
+ };
658
+ for (const name of Object.keys(definitions).toSorted()) visit(name);
659
+ return cyclic;
660
+ }
661
+ //#endregion
662
+ //#region src/helper/resolve-schema-dependencies-from-schema.ts
663
+ /** The definition name the fragment of an external `$ref` points at, if it names one. */
664
+ function fragmentDefinitionName(fragment) {
665
+ return /^\/(?:definitions|\$defs)\/(?<name>[^/]+)$/u.exec(fragment)?.groups?.name ?? /^\/(?<name>[^/]+)$/u.exec(fragment)?.groups?.name;
666
+ }
667
+ /** A node that is a reference into a document: what it points at is the whole of what it says. */
668
+ function isPointerNode(node) {
669
+ return typeof node.$ref === "string" && node.$ref.includes("#");
670
+ }
671
+ /**
672
+ * The definition names a definition refers to, sorted. A reference node is not descended
673
+ * into, so a sibling keyword beside a `$ref` adds no edge.
674
+ */
675
+ function collectRefs(definition) {
676
+ const refs = /* @__PURE__ */ new Set();
677
+ for (const node of walkSchema(definition, { prune: isPointerNode })) {
678
+ const ref = node.$ref;
679
+ if (typeof ref !== "string" || ref === "#") continue;
680
+ const local = localDefinitionName(ref);
681
+ if (local !== void 0) refs.add(local);
682
+ if (!ref.includes("#")) continue;
683
+ const [, fragment] = ref.split("#");
684
+ if (!fragment) continue;
685
+ const external = fragmentDefinitionName(fragment);
686
+ if (external !== void 0) refs.add(external);
687
+ }
688
+ return [...refs].toSorted();
689
+ }
690
+ /**
691
+ * Resolve schema dependencies and return them in topological order
692
+ *
693
+ * @param schema - JSON Schema object containing definitions or $defs
694
+ * @returns Array of schema names in dependency order
695
+ * @example
696
+ * ```ts
697
+ * const schema = {
698
+ * $defs: {
699
+ * animal: { type: 'object', properties: { name: { type: 'string' } } },
700
+ * zoo: { type: 'object', properties: { animals: { $ref: '#/$defs/animal' } } }
701
+ * }
702
+ * }
703
+ * resolveSchemaDependenciesFromSchema(schema) // ['animal', 'zoo']
704
+ * ```
705
+ */
706
+ function resolveSchemaDependenciesFromSchema(schema) {
707
+ const definitions = collectDefinitions(schema);
708
+ const sorted = [];
709
+ const done = /* @__PURE__ */ new Set();
710
+ const visiting = /* @__PURE__ */ new Set();
711
+ const visit = (name) => {
712
+ if (done.has(name) || visiting.has(name)) return;
713
+ const definition = definitions[name];
714
+ if (!definition) return;
715
+ visiting.add(name);
716
+ for (const ref of collectRefs(definition)) if (ref in definitions) visit(ref);
717
+ visiting.delete(name);
718
+ done.add(name);
719
+ sorted.push(name);
720
+ };
721
+ for (const name of Object.keys(definitions).toSorted()) visit(name);
722
+ return sorted;
723
+ }
724
+ //#endregion
725
+ //#region src/helper/document.ts
726
+ /** The node options of a document generation, with the unset parameter options left out. */
727
+ function emitOptionsOf(options) {
728
+ return {
729
+ openapi: options?.openapi ?? false,
730
+ readonly: options?.readonly ?? false,
731
+ unsafeCodeExtensions: options?.unsafeCodeExtensions ?? false,
732
+ ...options?.paramIn !== void 0 && { paramIn: options.paramIn },
733
+ ...options?.style !== void 0 && { style: options.style },
734
+ ...options?.explode !== void 0 && { explode: options.explode },
735
+ ...options?.allowEmptyValue !== void 0 && { allowEmptyValue: options.allowEmptyValue },
736
+ ...options?.contentType !== void 0 && { contentType: options.contentType },
737
+ ...options?.properties !== void 0 && { properties: options.properties },
738
+ ...options?.definitions !== void 0 && { definitions: options.definitions }
739
+ };
740
+ }
741
+ /**
742
+ * `options.definitions` plus the document's own `$defs` / `definitions`. The document
743
+ * wins on a shared name. `undefined` when neither holds a schema.
744
+ */
745
+ function definitionsOf(options, document) {
746
+ if (Object.keys(document).length === 0 && options?.definitions === void 0) return void 0;
747
+ return {
748
+ ...options?.definitions,
749
+ ...document
750
+ };
751
+ }
752
+ /**
753
+ * How a document names its schemas. An OpenAPI component name is always made a valid
754
+ * identifier; a plain JSON Schema title keeps its hyphens and underscores for back-compat.
755
+ */
756
+ function schemaNamer(openapi) {
757
+ return openapi === true ? toIdentifierPascalCase : toPascalCase;
758
+ }
759
+ /** The name the root schema is exported under: its `title`, or `fallback`. */
760
+ function rootNameOf(schema, toName, fallback = DEFAULT_ROOT_NAME) {
761
+ return schema.title ? toName(schema.title) : fallback;
762
+ }
763
+ /** The comment left where a `$ref` names a definition the document does not hold. */
764
+ function missingDefinitionComment(name) {
765
+ return `${MISSING_DEFINITION_PREFIX}${name}`;
766
+ }
767
+ /**
768
+ * The plan of a document: its definitions in dependency order, and which of them, if
769
+ * any, is the root under another name.
770
+ */
771
+ function planDocument(schema, rootName) {
772
+ const definitions = collectDefinitions(schema);
773
+ const hasDefinitions = Object.keys(definitions).length > 0;
774
+ const orderedNames = hasDefinitions ? resolveSchemaDependenciesFromSchema(schema) : [];
775
+ const rootDefinition = definitions[rootName];
776
+ return {
777
+ rootName,
778
+ definitions,
779
+ hasDefinitions,
780
+ orderedNames,
781
+ rootDefinition,
782
+ nonRootNames: rootDefinition === void 0 ? orderedNames : orderedNames.filter((name) => name !== rootName),
783
+ root: rootDefinition ?? schema
784
+ };
785
+ }
786
+ /**
787
+ * Every non-root definition rendered through `render` and joined as paragraphs, with a
788
+ * comment standing in for a definition the document names but does not hold.
789
+ */
790
+ function renderDefinitions(plan, toName, render) {
791
+ return plan.nonRootNames.map((name) => {
792
+ const definition = plan.definitions[name];
793
+ return definition === void 0 ? missingDefinitionComment(name) : render(definition, toName(name));
794
+ }).join("\n\n");
795
+ }
796
+ //#endregion
797
+ //#region src/helper/meta.ts
798
+ /**
799
+ * Host `$ref` name for OpenAPI component registration (hono-openapi
800
+ * `components.schemas`). TypeBox stores this on the schema at construction
801
+ * time — there is no post-construction `.meta()` — so it must land in the
802
+ * factory options object. Empty when the caller omitted `ref`.
803
+ */
804
+ function typeboxRefOpt(ref) {
805
+ return ref === void 0 ? [] : [`ref:${JSON.stringify(ref)}`];
806
+ }
807
+ /**
808
+ * Returns OpenAPI/JSON Schema metadata fields as a list of TypeBox option
809
+ * entries (`'key:value'` strings) ready to be joined into a `{...}` literal.
810
+ *
811
+ * Used by TypeBox type-level generators to embed metadata directly into the
812
+ * `Type.X(payload, options)` constructor call. A host `ref` is emitted first
813
+ * when supplied, in the same object as description / examples / deprecated.
814
+ */
815
+ function typeboxMetaOpts(schema, ref) {
816
+ const examples = examplesOf(schema);
817
+ return [
818
+ ...typeboxRefOpt(ref),
819
+ schema.description !== void 0 ? `description:${JSON.stringify(schema.description)}` : void 0,
820
+ examples !== void 0 ? `examples:${serializeJSValue(examples)}` : void 0,
821
+ schema.deprecated !== void 0 ? `deprecated:${schema.deprecated}` : void 0,
822
+ schema.externalDocs !== void 0 ? `externalDocs:${serializeJSValue(schema.externalDocs)}` : void 0,
823
+ schema.readOnly !== void 0 ? `readOnly:${schema.readOnly}` : void 0,
824
+ schema.writeOnly !== void 0 ? `writeOnly:${schema.writeOnly}` : void 0
825
+ ].filter((v) => v !== void 0);
826
+ }
827
+ /**
828
+ * Returns the TypeBox `default` option entry (`['default:1']`) for a schema, or
829
+ * `[]` when absent/droppable. TypeBox v1's `Type.Optional(type)` takes one arg —
830
+ * defaults must live on the inner type's options object, so every factory emits
831
+ * its own default here rather than the wrapper passing a 2nd `Type.Optional` arg.
832
+ * `stringWire` (for `query`/`path` coercion) emits the default in its string-wire
833
+ * form (`'1'` / `'true'`), since the coerced `Type.String(...)` input is a string.
834
+ */
835
+ function typeboxDefaultOpt(schema, stringWire = false, definitions) {
836
+ if (schema.default === void 0) return [];
837
+ const result = coerceDefault(schema, schema.default, definitions);
838
+ if (!result.keep) return [];
839
+ const value = stringWire ? String(result.value) : result.value;
840
+ return [`default:${typeof value === "boolean" || typeof value === "number" ? `${value}` : JSON.stringify(value)}`];
841
+ }
842
+ /**
843
+ * Serializes a value into a JavaScript expression string.
844
+ *
845
+ * - Strings, numbers, booleans, null: via `JSON.stringify`
846
+ * - Arrays: `[elem1,elem2,...]`
847
+ * - Plain objects: `{key1:value1,...}` with bare identifiers when possible
848
+ * - Undefined values inside objects are skipped
849
+ */
850
+ function serializeJSValue(value) {
851
+ if (value === void 0) return "undefined";
852
+ if (value === null) return "null";
853
+ if (typeof value !== "object") return JSON.stringify(value);
854
+ if (Array.isArray(value)) return `[${value.map(serializeJSValue).join(",")}]`;
855
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
856
+ if (entries.length === 0) return "{}";
857
+ return `{${entries.map(([k, v]) => `${makeSafeKey(k)}:${serializeJSValue(v)}`).join(",")}}`;
858
+ }
859
+ //#endregion
860
+ //#region src/helper/value.ts
861
+ /**
862
+ * A JSON value as the TypeScript literal that reproduces it.
863
+ *
864
+ * `JSON.stringify` already answers for strings, arrays and objects; booleans and numbers
865
+ * go through template interpolation so `-0`, `1e21` and friends keep the spelling the
866
+ * source had rather than picking up quotes.
867
+ */
868
+ function jsLiteral(value) {
869
+ if (typeof value === "boolean") return `${value}`;
870
+ if (typeof value === "number") return `${value}`;
871
+ return JSON.stringify(value);
872
+ }
873
+ //#endregion
874
+ //#region src/helper/format.ts
875
+ /** A regular expression as the literal that reproduces it in generated source. */
876
+ function regexSource(pattern) {
877
+ return `/${pattern.source}/${pattern.flags}`;
878
+ }
879
+ /**
880
+ * The source of an RFC 3339 `partial-time`. `precision` follows Zod's `z.iso.time`: `-1`
881
+ * minutes only, `0` whole seconds, `n` exactly `n` fraction digits, and `undefined` any
882
+ * number of them — with the seconds themselves optional unless `seconds` says otherwise.
883
+ */
884
+ function timeSource(precision, seconds) {
885
+ const hhmm = String.raw`(?:[01]\d|2[0-3]):[0-5]\d`;
886
+ if (precision === void 0) return seconds ? String.raw`${hhmm}:[0-5]\d(?:\.\d+)?` : String.raw`${hhmm}(?::[0-5]\d(?:\.\d+)?)?`;
887
+ if (precision === -1) return hhmm;
888
+ if (precision === 0) return String.raw`${hhmm}:[0-5]\d`;
889
+ return String.raw`${hhmm}:[0-5]\d\.\d{${precision}}`;
890
+ }
891
+ /** The regex literal of an RFC 3339 `full-date` that is a real calendar date. */
892
+ function datePattern() {
893
+ return `/^${DATE_PATTERN_SOURCE}$/`;
894
+ }
895
+ /**
896
+ * The regex literal of an RFC 3339 time: a `partial-time`, with the offset optional
897
+ * unless `offset` is `false`, in which case none is accepted.
898
+ */
899
+ function timePattern(precision, offset) {
900
+ const tail = offset ? `${OFFSET_PATTERN_SOURCE}?` : "";
901
+ return `/^${timeSource(precision, false)}${tail}$/`;
902
+ }
903
+ /**
904
+ * The regex literal of an RFC 3339 `date-time`, built as Zod's `z.iso.datetime()` builds
905
+ * its own: a `Z` always, a numeric offset when `offset` is set, and an offset-less local
906
+ * time when `local` is set.
907
+ */
908
+ function datetimePattern(options) {
909
+ const suffixes = ["Z", ...options.offset ? [String.raw`([+-](?:[01]\d|2[0-3]):[0-5]\d)`] : []];
910
+ const qualified = `${timeSource(options.precision, true)}(?:${suffixes.join("|")})`;
911
+ const time = options.local ? `${qualified}|${timeSource(options.precision, false)}` : qualified;
912
+ return `/^${DATE_PATTERN_SOURCE}T(?:${time})$/`;
913
+ }
914
+ /**
915
+ * The regex literal of an RFC 9562 UUID of `version`, or of any version — the nil and
916
+ * max UUIDs included — when none is given.
917
+ */
918
+ function uuidPattern(version) {
919
+ if (version === void 0) return "/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/";
920
+ return `/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$/`;
921
+ }
922
+ /** The UUID version a format or an `x-uuidVersion` pins, or `undefined` for any. */
923
+ function uuidVersionOf(schema, format) {
924
+ const named = /^uuidv(?<version>[1-8])$/u.exec(format)?.groups?.version;
925
+ if (named !== void 0) return Number(named);
926
+ const extension = /^v(?<version>[1-8])$/u.exec(schema["x-uuidVersion"] ?? "")?.groups?.version;
927
+ return extension === void 0 ? void 0 : Number(extension);
928
+ }
929
+ /** The precision an `x-isoPrecision` pins, or `undefined` for any. */
930
+ function isoPrecisionOf(schema) {
931
+ const precision = schema["x-isoPrecision"];
932
+ return typeof precision === "number" ? precision : void 0;
933
+ }
934
+ /**
935
+ * The regex literal that checks a string `format` for a target without a validator of
936
+ * its own for it, honouring `x-isoPrecision` / `x-isoOffset` / `x-isoLocal` on the ISO
937
+ * formats and `x-uuidVersion` on `uuid`. `undefined` for a format with no pattern here.
938
+ */
939
+ function formatPattern(schema, format) {
940
+ if (format === "date") return datePattern();
941
+ if (format === "time") return timePattern(isoPrecisionOf(schema), schema["x-isoOffset"] !== false);
942
+ if (format === "date-time") return datetimePattern({
943
+ precision: isoPrecisionOf(schema),
944
+ offset: schema["x-isoOffset"] !== false,
945
+ local: schema["x-isoLocal"] === true
946
+ });
947
+ if (format === "uuid" || /^uuidv[1-8]$/u.test(format)) return uuidPattern(uuidVersionOf(schema, format));
948
+ const pattern = FORMAT_PATTERNS[format];
949
+ return pattern === void 0 ? void 0 : regexSource(pattern);
950
+ }
951
+ //#endregion
952
+ //#region src/helper/wire.ts
953
+ /**
954
+ * What the generators share about a value read off the string wire — a query, path,
955
+ * header, cookie or form field — beyond the coercion each library spells its own way.
956
+ */
957
+ /** The `type` a typeless wire node reads its text as, from the constraints it carries. */
958
+ function impliedWireType(schema) {
959
+ if (schema.type !== void 0 || hasCombinator(schema) || schema.const !== void 0 || schema.enum !== void 0 || schema.properties !== void 0) return;
960
+ const isNumeric = hasNumericKeyword(schema);
961
+ const isString = hasStringKeyword(schema);
962
+ if (isNumeric && !isString) return "number";
963
+ if (isString && !isNumeric) return "string";
964
+ }
965
+ /**
966
+ * The primitive members of a `type` list as a union would list them: `number` already
967
+ * takes every integer, so the two together are one member, and on the wire every member
968
+ * reads text, so the string member is tried last.
969
+ */
970
+ function unionPrimitiveTypes(types, isWire) {
971
+ return (isWire ? WIRE_PRIMITIVE_ORDER.filter((t) => types.includes(t)) : types).filter((t) => (t === "string" || t === "number" || t === "boolean" || t === "integer") && !(t === "integer" && types.includes("number")));
972
+ }
973
+ /** Whether a `type` list is a union of primitives alone: more than one, and no array or object. */
974
+ function isPrimitiveUnion(types, isWire) {
975
+ return unionPrimitiveTypes(types, isWire).length > 1 && !types.includes("array") && !types.includes("object");
976
+ }
977
+ /**
978
+ * Whether the text `null` has to be read ahead of a wire node: it takes `null`, and no
979
+ * string, so `null` can only be the value and never the text.
980
+ */
981
+ function isNullTextRead(schema) {
982
+ return canBeNull(schema) && !canBeString(schema);
983
+ }
984
+ /**
985
+ * Whether a node matches `null` before its members coerce it: a nullable type, or a
986
+ * `null` among its literals. A combinator coerces `null` to `0` or `false` before a
987
+ * `null` member is tried, so the null has to be matched ahead of it instead.
988
+ */
989
+ function isNullMatchedFirst(schema) {
990
+ return isNullable(schema) || schema.const === null || schema.enum?.includes(null) === true;
991
+ }
992
+ /** A wire array sent once arrives as its one element: wrapped, it is an array of one. */
993
+ function wireArrayOnce(param) {
994
+ return `(${param})=>(${param}===undefined||Array.isArray(${param})?${param}:[${param}])`;
995
+ }
996
+ /** The text `null` on the wire, read as the `null` a nullable non-string schema takes. */
997
+ function wireNullText(param) {
998
+ return `(${param})=>(${param}==='null'?null:${param})`;
999
+ }
1000
+ /**
1001
+ * A parameter object answers an `Object.prototype` name it was not sent with the inherited
1002
+ * member. Copied onto a null-prototype object, it holds only what the request carried.
1003
+ */
1004
+ function ownProperties(param) {
1005
+ return `(${param})=>(typeof ${param}==="object"&&${param}!==null&&!Array.isArray(${param})?Object.assign(Object.create(null),${param}):${param})`;
1006
+ }
1007
+ /** The regex literal of integer text on the wire. */
1008
+ function integerWirePattern() {
1009
+ return regexSource(INTEGER_WIRE_PATTERN);
1010
+ }
1011
+ /** The regex literal of JSON number text on the wire. */
1012
+ function numberWirePattern() {
1013
+ return regexSource(NUMBER_WIRE_PATTERN);
1014
+ }
1015
+ /**
1016
+ * Whether wire text for these literals is an integer or a number. An integer rejects
1017
+ * exponents and fractions; a number follows the JSON number grammar.
1018
+ */
1019
+ function wireNumericKind(schema, values) {
1020
+ const types = schema.type;
1021
+ if (types === "number") return "number";
1022
+ if (types === "integer") return "integer";
1023
+ if (Array.isArray(types) && types.includes("number")) return "number";
1024
+ if (Array.isArray(types) && types.includes("integer")) return "integer";
1025
+ if (values.every((value) => typeof value === "number" && Number.isInteger(value))) return "integer";
1026
+ return "number";
1027
+ }
1028
+ /** The regex literal of every spelling of a boolean on the wire. */
1029
+ function stringboolPattern() {
1030
+ return regexSource(STRINGBOOL_PATTERN);
1031
+ }
1032
+ /** The regex literal of the spellings that read as `true`. */
1033
+ function stringboolTruthyPattern() {
1034
+ return regexSource(STRINGBOOL_TRUTHY_PATTERN);
1035
+ }
1036
+ /**
1037
+ * A default value as it is spelled on the string wire, where a coerced schema's input
1038
+ * is text: a scalar as its text, an array element by element, `null` and objects as
1039
+ * they are.
1040
+ */
1041
+ function wireDefaultValue(value) {
1042
+ if (Array.isArray(value)) return value.map(wireDefaultValue);
1043
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
1044
+ return value;
1045
+ }
1046
+ //#endregion
1047
+ //#region src/helper/effect-wrap.ts
1048
+ /** `inner` read after `reader`, a `(input) => ...` arrow over the raw value. */
1049
+ function effectPreprocess(readers, inner) {
1050
+ if (readers.length === 0) return inner;
1051
+ return `Schema.Unknown.pipe(${readers.map((reader) => `Schema.decodeTo(Schema.Unknown,SchemaTransformation.transform<unknown,unknown>({decode:${reader},encode:(output)=>output}))`).join(",")},Schema.decodeTo(${inner}))`;
1052
+ }
1053
+ /** A default as the Effect literal of the schema's decoded type: a bigint for a 64-bit integer. */
1054
+ function defaultLiteral$1(schema, value) {
1055
+ if (typeof value === "number") {
1056
+ if (schema.format === "int64" || schema.format === "uint64") return `${value}n`;
1057
+ if (schema.format === "bigint") return `BigInt(${value})`;
1058
+ }
1059
+ return jsLiteral(value);
1060
+ }
1061
+ /**
1062
+ * Wraps an Effect Schema v4 schema string with `Schema.withDecodingDefault()`,
1063
+ * `Schema.NullOr()`, `Schema.brand()` and `.annotate({...})` based on
1064
+ * `default` / `nullable` / `x-brand` and OpenAPI metadata fields.
1065
+ *
1066
+ * Metadata mapping (v4 `.annotate`):
1067
+ * - `description` → `description`
1068
+ * - `readOnly` / `writeOnly` → same-named annotations (v4 promoted both to
1069
+ * first-class fields on `Annotations.Augment`)
1070
+ * - `examples` (or `[example]` when only singular present), `deprecated` and
1071
+ * `externalDocs` → carried as loose annotation keys, since v4 types the
1072
+ * native `examples` annotation as `ReadonlyArray<T>` and OpenAPI specs may
1073
+ * carry incomplete examples that would fail to type-check.
1074
+ *
1075
+ * @see https://effect.website/docs/schema/annotations/
1076
+ */
1077
+ function effectWrap(effectStr, schema, options) {
1078
+ const nullText = options?.nullText === true;
1079
+ const withNullable = isNullable(schema) || nullText && !isNullMatchedFirst(schema) ? `Schema.NullOr(${effectStr})` : effectStr;
1080
+ const withNullText = nullText ? effectPreprocess([wireNullText("input")], withNullable) : withNullable;
1081
+ const brand = schema["x-brand"];
1082
+ const withBrand = typeof brand === "string" ? `${withNullText}.pipe(Schema.brand("${brand}"))` : withNullText;
1083
+ const codeChain = [
1084
+ readCodeExtension(schema, "x-filter", options),
1085
+ readCodeExtension(schema, "x-transform", options),
1086
+ readCodeExtension(schema, "x-pipe", options)
1087
+ ].filter((v) => v !== void 0);
1088
+ const withCodeExts = codeChain.length === 0 ? withBrand : `${withBrand}${codeChain.join("")}`;
1089
+ const defaultResult = schema.default !== void 0 ? coerceDefault(schema, schema.default, options?.definitions) : void 0;
1090
+ const decodingDefault = options?.stringWire === true ? "Schema.withDecodingDefaultType" : "Schema.withDecodingDefault";
1091
+ const withDefault = defaultResult?.keep ? `${withCodeExts}.pipe(${decodingDefault}(Effect.succeed(${defaultLiteral$1(schema, defaultResult.value)})))` : withCodeExts;
1092
+ const examples = examplesOf(schema);
1093
+ const ann = {};
1094
+ if (schema.description !== void 0) ann.description = schema.description;
1095
+ if (examples !== void 0) ann.jsonSchemaExamples = examples;
1096
+ if (schema.deprecated !== void 0) ann.jsonSchemaDeprecated = schema.deprecated;
1097
+ if (schema.externalDocs !== void 0) ann.jsonSchemaExternalDocs = schema.externalDocs;
1098
+ if (schema.readOnly !== void 0) ann.readOnly = schema.readOnly;
1099
+ if (schema.writeOnly !== void 0) ann.writeOnly = schema.writeOnly;
1100
+ if (Object.keys(ann).length === 0) return withDefault;
1101
+ return `${withDefault}.annotate(${serializeJSValue(ann)})`;
1102
+ }
1103
+ //#endregion
1104
+ //#region src/helper/hoist-refs.ts
1105
+ /** Keywords whose values are data, not schemas: a `$ref` string there is not a reference. */
1106
+ const DATA_KEYWORDS = /* @__PURE__ */ new Set([
1107
+ "const",
1108
+ "default",
1109
+ "enum",
1110
+ "example",
1111
+ "examples"
1112
+ ]);
1113
+ /** Whether a `$ref` already names a definition directly (`#/$defs/X`). */
1114
+ function isDefinitionRef(ref) {
1115
+ return DEFINITION_REF_PREFIXES.some((prefix) => {
1116
+ if (!ref.startsWith(prefix)) return false;
1117
+ const rest = ref.slice(prefix.length);
1118
+ return rest !== "" && !rest.includes("/");
1119
+ });
1120
+ }
1121
+ /** A local JSON Pointer `$ref` deeper than a definition: `#/$defs/A/properties/b`. */
1122
+ function isNestedPointer(ref) {
1123
+ return ref.startsWith("#/") && !isDefinitionRef(ref);
1124
+ }
1125
+ function decodeToken(token) {
1126
+ return decodeURIComponent(token).replaceAll("~1", "/").replaceAll("~0", "~");
1127
+ }
1128
+ function resolvePointer(document, ref) {
1129
+ let node = document;
1130
+ for (const token of ref.slice(2).split("/").map(decodeToken)) {
1131
+ if (typeof node !== "object" || node === null || !Object.hasOwn(node, token)) return void 0;
1132
+ node = Reflect.get(node, token);
1133
+ }
1134
+ return node;
1135
+ }
1136
+ function collectNestedPointers(node, found) {
1137
+ if (Array.isArray(node)) {
1138
+ for (const item of node) collectNestedPointers(item, found);
1139
+ return;
1140
+ }
1141
+ if (typeof node !== "object" || node === null) return;
1142
+ for (const [key, value] of Object.entries(node)) if (key === "$ref" && typeof value === "string" && isNestedPointer(value)) found.add(value);
1143
+ else if (!DATA_KEYWORDS.has(key)) collectNestedPointers(value, found);
1144
+ }
1145
+ /** A JSON object read as a schema node: what a pointer reaches or a rewrite returns. */
1146
+ function isSchemaNode(value) {
1147
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1148
+ }
1149
+ function rewriteRefs(node, refs) {
1150
+ if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, refs));
1151
+ if (typeof node !== "object" || node === null) return node;
1152
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => {
1153
+ if (key === "$ref" && typeof value === "string") return [key, refs.get(value) ?? value];
1154
+ return [key, DATA_KEYWORDS.has(key) ? value : rewriteRefs(value, refs)];
1155
+ }));
1156
+ }
1157
+ /**
1158
+ * Hoist every schema a `$ref` reaches through a nested JSON Pointer into a definition of
1159
+ * its own, and point the references at it.
1160
+ *
1161
+ * Bundling an external file leaves its `definitions` where the file was referenced, so a
1162
+ * reference inside it reads `#/$defs/Root/properties/root/definitions/Node`. The
1163
+ * generators name and declare top-level definitions only; a recursive schema reached that
1164
+ * way would otherwise be referenced by a name nothing declares. A hoisted definition is
1165
+ * named after the pointer's last token, numbered when the name is taken.
1166
+ *
1167
+ * Returns the document as given when it has no such reference.
1168
+ */
1169
+ function hoistNestedRefs(schema) {
1170
+ const pointers = /* @__PURE__ */ new Set();
1171
+ collectNestedPointers(schema, pointers);
1172
+ if (pointers.size === 0) return schema;
1173
+ const container = schema.$defs === void 0 && schema.definitions !== void 0 ? "definitions" : "$defs";
1174
+ const taken = /* @__PURE__ */ new Set([...Object.keys(schema.$defs ?? {}), ...Object.keys(schema.definitions ?? {})]);
1175
+ const refs = /* @__PURE__ */ new Map();
1176
+ const hoisted = [];
1177
+ for (const pointer of pointers) {
1178
+ const target = resolvePointer(schema, pointer);
1179
+ if (!isSchemaNode(target)) continue;
1180
+ const base = pointer.slice(2).split("/").map(decodeToken).at(-1) ?? "Definition";
1181
+ let name = base;
1182
+ for (let index = 2; taken.has(name); index += 1) name = `${base}${index}`;
1183
+ taken.add(name);
1184
+ refs.set(pointer, `#/${container}/${encodeURIComponent(name)}`);
1185
+ hoisted.push([name, target]);
1186
+ }
1187
+ const rewritten = rewriteRefs(schema, refs);
1188
+ if (refs.size === 0 || !isSchemaNode(rewritten)) return schema;
1189
+ const added = {};
1190
+ for (const [name, target] of hoisted) {
1191
+ const node = rewriteRefs(target, refs);
1192
+ if (isSchemaNode(node)) added[name] = node;
1193
+ }
1194
+ return {
1195
+ ...rewritten,
1196
+ [container]: {
1197
+ ...rewritten[container],
1198
+ ...added
1199
+ }
1200
+ };
1201
+ }
1202
+ //#endregion
1203
+ //#region src/helper/not.ts
1204
+ /** Whether the schema's values are bigints (`int64`, `uint64`, `bigint`). */
1205
+ function isBigintFormat(schema) {
1206
+ return schema.format === "int64" || schema.format === "uint64" || schema.format === "bigint";
1207
+ }
1208
+ /** A value as a TypeScript literal. Numbers of a bigint schema are `0n`, not `0`. */
1209
+ function literal(value, bigint) {
1210
+ if (bigint && typeof value === "number" && Number.isFinite(value)) return `${value}n`;
1211
+ return JSON.stringify(value);
1212
+ }
1213
+ /**
1214
+ * An `enum` as an array literal. A bigint schema's numbers are bigint literals, so
1215
+ * `[0n].includes(val)` type-checks and rejects `0n`; `[0].includes(0n)` is both a
1216
+ * type error and always false.
1217
+ */
1218
+ function valueListLiteral(values, bigint) {
1219
+ if (!bigint) return JSON.stringify(values);
1220
+ return `[${values.map((value) => literal(value, true)).join(",")}]`;
1221
+ }
1222
+ /** The `not` predicate bodies by `type`, over a value bound to `param`. */
1223
+ function notTypeBody(type, param) {
1224
+ switch (type) {
1225
+ case "string":
1226
+ case "number":
1227
+ case "boolean": return `typeof ${param} !== '${type}'`;
1228
+ case "integer": return `typeof ${param} !== 'number' || !Number.isInteger(${param})`;
1229
+ case "array": return `!Array.isArray(${param})`;
1230
+ case "object": return `typeof ${param} !== 'object' || ${param} === null || Array.isArray(${param})`;
1231
+ case "null": return `${param} !== null`;
1232
+ default: return;
1233
+ }
1234
+ }
1235
+ /**
1236
+ * The predicate refusing what a `not` schema describes, as the source of an arrow over
1237
+ * `param` (declared as `parameter`, which may carry a type annotation): a `const` is
1238
+ * refused by value, a `type` by its runtime check, a list of types by every check at
1239
+ * once. `bigint` spells a numeric `const` as a bigint literal. `undefined` for a `not`
1240
+ * these shared cases do not cover — an `enum` or a combinator, which each generator
1241
+ * spells with its own parser.
1242
+ */
1243
+ function notPredicate(inner, param, parameter = param, bigint = false) {
1244
+ if ("const" in inner) return `(${parameter}) => ${param} !== ${literal(inner.const, bigint)}`;
1245
+ if (typeof inner.type === "string") {
1246
+ const body = notTypeBody(inner.type, param);
1247
+ return body === void 0 ? void 0 : `(${parameter}) => ${body}`;
1248
+ }
1249
+ if (Array.isArray(inner.type)) {
1250
+ const bodies = normalizeTypes(inner.type).map((t) => notTypeBody(t, param)).filter((body) => body !== void 0).map((body) => `(${body})`);
1251
+ if (bodies.length > 0) return `(${parameter}) => ${bodies.join(" && ")}`;
1252
+ }
1253
+ }
1254
+ //#endregion
1255
+ //#region src/helper/parameter.ts
1256
+ /**
1257
+ * How an OpenAPI Parameter Object's text is read into the value its schema describes:
1258
+ * `allowEmptyValue`, a JSON `content`, or its `style` / `explode`. Every reader is the
1259
+ * source of a `(param) => ...` arrow, which each generator wraps in its own
1260
+ * preprocessing form.
1261
+ *
1262
+ * @see https://spec.openapis.org/oas/v3.2.0.html#style-examples
1263
+ */
1264
+ /** A media type that holds a JSON document: `application/json` or any `+json` suffix. */
1265
+ const JSON_MEDIA_TYPE_PATTERN = /^[^/]+\/(?:[^;]+\+)?json\s*(?:;|$)/iu;
1266
+ /** The leading `.` of a `label` value, as a regex literal. */
1267
+ const LABEL_PREFIX = String.raw`/^\./u`;
1268
+ /** The leading `;name=` of a non-exploded `matrix` value, as a regex literal. */
1269
+ const MATRIX_PREFIX = "/^;[^=]*=?/u";
1270
+ /** Whether the options carry any of a parameter's serialization fields. */
1271
+ function hasParameterSerialization(options) {
1272
+ return options?.style !== void 0 || options?.explode !== void 0 || options?.allowEmptyValue === true || options?.contentType !== void 0;
1273
+ }
1274
+ /**
1275
+ * The options the nodes under a parameter's root are emitted with: no serialization, and
1276
+ * no string wire either when the parameter's text is a JSON document.
1277
+ */
1278
+ function withoutParameterSerialization(options) {
1279
+ const isJson = isJsonMediaType(options?.contentType);
1280
+ return {
1281
+ ...options?.openapi !== void 0 && { openapi: options.openapi },
1282
+ ...options?.readonly !== void 0 && { readonly: options.readonly },
1283
+ ...options?.unsafeCodeExtensions !== void 0 && { unsafeCodeExtensions: options.unsafeCodeExtensions },
1284
+ ...options?.paramIn !== void 0 && !isJson && { paramIn: options.paramIn },
1285
+ ...options?.definitions !== void 0 && { definitions: options.definitions },
1286
+ ...options?.properties !== void 0 && { properties: options.properties }
1287
+ };
1288
+ }
1289
+ /**
1290
+ * The emit options of one property, when that property carries its own serialization
1291
+ * (`x-style` / `x-explode` / `x-allowEmptyValue`, or `options.properties`). `undefined`
1292
+ * when it does not, so the caller keeps the object's options. Requires `paramIn`: the
1293
+ * keywords describe wire text.
1294
+ */
1295
+ function propertyEmitOptions(key, property, options) {
1296
+ if (options?.paramIn === void 0) return void 0;
1297
+ const named = options.properties?.[key];
1298
+ const style = named?.style ?? property["x-style"];
1299
+ const explode = named?.explode ?? property["x-explode"];
1300
+ const allowEmptyValue = named?.allowEmptyValue === true || property["x-allowEmptyValue"] === true;
1301
+ if (style === void 0 && explode === void 0 && !allowEmptyValue) return void 0;
1302
+ return {
1303
+ ...options.openapi !== void 0 && { openapi: options.openapi },
1304
+ ...options.readonly !== void 0 && { readonly: options.readonly },
1305
+ ...options.unsafeCodeExtensions !== void 0 && { unsafeCodeExtensions: options.unsafeCodeExtensions },
1306
+ ...options.definitions !== void 0 && { definitions: options.definitions },
1307
+ paramIn: options.paramIn,
1308
+ ...style !== void 0 && { style },
1309
+ ...explode !== void 0 && { explode },
1310
+ ...allowEmptyValue && { allowEmptyValue: true }
1311
+ };
1312
+ }
1313
+ function isJsonMediaType(contentType) {
1314
+ return contentType !== void 0 && JSON_MEDIA_TYPE_PATTERN.test(contentType);
1315
+ }
1316
+ /** The `style` a parameter has when its Parameter Object names none. */
1317
+ function defaultStyle(paramIn) {
1318
+ if (paramIn === "path" || paramIn === "header") return "simple";
1319
+ if (paramIn === void 0) return void 0;
1320
+ return "form";
1321
+ }
1322
+ /** `text`, a string expression, split on `separator` — none for an empty text. */
1323
+ function split(text, separator) {
1324
+ return `(${text}===''?[]:${text}.split(${JSON.stringify(separator)}))`;
1325
+ }
1326
+ /** An array of `[name, value, name, value, ...]` read into an object. */
1327
+ function pairs(parts) {
1328
+ return `${parts}.reduce<{[k:string]:string}>((acc,part,i,all)=>i%2===1?{...acc,[all[i-1]??'']:part}:acc,{})`;
1329
+ }
1330
+ /** An array of `name=value` read into an object. */
1331
+ function entries(parts) {
1332
+ return `${parts}.reduce<{[k:string]:string}>((acc,part)=>{const i=part.indexOf('=');return i<0?{...acc,[part]:''}:{...acc,[part.slice(0,i)]:part.slice(i+1)}},{})`;
1333
+ }
1334
+ /** An empty value stands for an absent parameter, so its default applies. */
1335
+ function emptyValueReader(param) {
1336
+ return `(${param})=>(${param}===''?undefined:${param})`;
1337
+ }
1338
+ /** The text of a `content: application/json` parameter, read as the JSON document it holds. */
1339
+ function jsonReader(param) {
1340
+ return `(${param})=>{if(typeof ${param}!=='string')return ${param};try{return JSON.parse(${param})}catch{return ${param}}}`;
1341
+ }
1342
+ /** `deep[age]=5&deep[name]=bob`, gathered into the one object `{ age, name }`. */
1343
+ function deepObjectReader(param) {
1344
+ return String.raw`(${param})=>{if(typeof ${param}!=='object'||${param}===null||Array.isArray(${param}))return ${param};const out=Object.entries(${param}).reduce<{[k:string]:unknown}>((acc,[key,value])=>{const name=/^[^[\]]+\[([^\]]+)\]$/u.exec(key)?.[1];return name===undefined?acc:{...acc,[name]:value}},{});return Object.keys(out).length>0?out:${param}}`;
1345
+ }
1346
+ /** A reader of a string value: `body` maps `text`, the value with `prefix` removed. */
1347
+ function textReader(param, body, prefix) {
1348
+ return `(${param})=>{if(typeof ${param}!=='string')return ${param};const text=${prefix === void 0 ? param : `${param}.replace(${prefix},'')`};return ${body}}`;
1349
+ }
1350
+ function arrayReader(param, style, explode) {
1351
+ if (style === "simple") return textReader(param, split("text", ","));
1352
+ if (style === "label") return textReader(param, split("text", explode ? "." : ","), LABEL_PREFIX);
1353
+ if (style === "matrix") return explode ? textReader(param, `text.split(';').filter((part)=>part!=='').map((part)=>part.slice(part.indexOf('=')+1))`) : textReader(param, split("text", ","), MATRIX_PREFIX);
1354
+ if (explode || style === "deepObject") return void 0;
1355
+ return textReader(param, split("text", style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ","));
1356
+ }
1357
+ function objectReader(param, style, explode) {
1358
+ if (style === "deepObject") return deepObjectReader(param);
1359
+ if (style === "simple") return textReader(param, (explode ? entries : pairs)(split("text", ",")));
1360
+ if (style === "label") return textReader(param, explode ? entries(split("text", ".")) : pairs(split("text", ",")), LABEL_PREFIX);
1361
+ if (style === "matrix") return explode ? textReader(param, entries(`text.split(';').filter((part)=>part!=='')`)) : textReader(param, pairs(split("text", ",")), MATRIX_PREFIX);
1362
+ if (explode) return void 0;
1363
+ return textReader(param, pairs(split("text", style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ",")));
1364
+ }
1365
+ function primitiveReader(param, style) {
1366
+ if (style === "label") return textReader(param, "text", LABEL_PREFIX);
1367
+ if (style === "matrix") return textReader(param, "text", MATRIX_PREFIX);
1368
+ }
1369
+ /** What reads a parameter's text in `style` into the value its schema describes. */
1370
+ function styleReader(param, schema, style, explode) {
1371
+ if (hasType(schema, "array") || schema.items !== void 0 || schema.prefixItems !== void 0) return arrayReader(param, style, explode);
1372
+ if (hasType(schema, "object") || schema.properties !== void 0) return objectReader(param, style, explode);
1373
+ return primitiveReader(param, style);
1374
+ }
1375
+ /**
1376
+ * The readers of a parameter's serialization, outermost first: the `allowEmptyValue`
1377
+ * reader, then the one for a JSON `content` or the parameter's `style` / `explode`. Each
1378
+ * is the source of an arrow over `param`, the name the target library gives a predicate's
1379
+ * input.
1380
+ */
1381
+ function parameterReaders(schema, options, param) {
1382
+ const style = options?.style ?? defaultStyle(options?.paramIn);
1383
+ const reader = isJsonMediaType(options?.contentType) ? jsonReader(param) : style === void 0 ? void 0 : styleReader(param, schema, style, options?.explode ?? style === "form");
1384
+ return [options?.allowEmptyValue === true ? emptyValueReader(param) : void 0, reader].filter((step) => step !== void 0);
1385
+ }
1386
+ //#endregion
1387
+ //#region src/helper/polymorphic-base.ts
1388
+ /** The definition name a `$ref` names and the prefix it is written with. */
1389
+ function refParts(ref) {
1390
+ for (const prefix of DEFINITION_REF_PREFIXES) {
1391
+ if (!ref.startsWith(prefix)) continue;
1392
+ const rest = ref.slice(prefix.length);
1393
+ if (rest === "" || rest.includes("/")) return void 0;
1394
+ return {
1395
+ prefix,
1396
+ name: decodeURIComponent(rest)
1397
+ };
1398
+ }
1399
+ }
1400
+ /** A definition's own shape: the definition without the union that lists its subtypes. */
1401
+ function baseOf(schema) {
1402
+ const { oneOf: _oneOf, anyOf: _anyOf, discriminator: _discriminator, ...base } = schema;
1403
+ return base;
1404
+ }
1405
+ /**
1406
+ * Break the cycle of a polymorphic base: a definition whose `oneOf` / `anyOf` lists its
1407
+ * subtypes while each subtype extends it through `allOf: [{ $ref: base }, ...]` (the
1408
+ * OpenAPI discriminator inheritance pattern). Read literally the base is a union of its
1409
+ * subtypes and each subtype contains the base, which loops forever.
1410
+ *
1411
+ * In a subtype's `allOf` the base stands for its own shape only, so that member is
1412
+ * pointed at a new `<Base>Base` definition holding the base without its union. The base
1413
+ * itself stays the union of its subtypes.
1414
+ *
1415
+ * Returns `definitions` unchanged when no definition has that shape.
1416
+ */
1417
+ function separatePolymorphicBases(definitions) {
1418
+ const result = { ...definitions };
1419
+ let changed = false;
1420
+ for (const [name, schema] of Object.entries(definitions)) {
1421
+ const members = schema.oneOf ?? schema.anyOf;
1422
+ if (members === void 0 || members.length === 0) continue;
1423
+ const extending = members.flatMap((member) => {
1424
+ const parts = member.$ref === void 0 ? void 0 : refParts(member.$ref);
1425
+ return parts === void 0 ? [] : [parts.name];
1426
+ }).filter((subtype) => definitions[subtype]?.allOf?.some((member) => member.$ref !== void 0 && refParts(member.$ref)?.name === name));
1427
+ if (extending.length === 0) continue;
1428
+ changed = true;
1429
+ const baseName = unusedName(`${name}Base`, result);
1430
+ result[baseName] = baseOf(schema);
1431
+ for (const subtype of extending) {
1432
+ const subtypeSchema = result[subtype];
1433
+ if (subtypeSchema?.allOf === void 0) continue;
1434
+ result[subtype] = {
1435
+ ...subtypeSchema,
1436
+ allOf: subtypeSchema.allOf.map((member) => {
1437
+ const parts = member.$ref === void 0 ? void 0 : refParts(member.$ref);
1438
+ return parts?.name === name ? withRef(member, `${parts.prefix}${encodeURIComponent(baseName)}`) : member;
1439
+ })
1440
+ };
1441
+ }
1442
+ }
1443
+ return changed ? result : definitions;
1444
+ }
1445
+ function withRef(schema, $ref) {
1446
+ return {
1447
+ ...schema,
1448
+ $ref
1449
+ };
1450
+ }
1451
+ function unusedName(name, taken) {
1452
+ if (!Object.hasOwn(taken, name)) return name;
1453
+ let index = 2;
1454
+ while (Object.hasOwn(taken, `${name}${index}`)) index += 1;
1455
+ return `${name}${index}`;
1456
+ }
1457
+ /**
1458
+ * A document with {@link separatePolymorphicBases} applied to its `$defs` and
1459
+ * `definitions`; the document itself when neither changes.
1460
+ */
1461
+ function withPolymorphicBases(schema) {
1462
+ const $defs = schema.$defs === void 0 ? void 0 : separatePolymorphicBases(schema.$defs);
1463
+ const definitions = schema.definitions === void 0 ? void 0 : separatePolymorphicBases(schema.definitions);
1464
+ if ($defs === schema.$defs && definitions === schema.definitions) return schema;
1465
+ return {
1466
+ ...schema,
1467
+ ...$defs !== void 0 && { $defs },
1468
+ ...definitions !== void 0 && { definitions }
1469
+ };
1470
+ }
1471
+ //#endregion
1472
+ //#region src/helper/ref.ts
1473
+ /**
1474
+ * Resolves a `$ref` for the Zod, Valibot and Effect generators, which name declarations
1475
+ * alike: a definition is `Name` inside a document (`isDocument`), `NameSchema` when a
1476
+ * single schema is emitted under the default root name, and a thunk everywhere else.
1477
+ */
1478
+ function refTarget(ref, rootName, isDocument, openapi) {
1479
+ if (isRootRef(ref)) return {
1480
+ kind: "lazy",
1481
+ name: rootName
1482
+ };
1483
+ if (isDeepLocalPointer(ref)) return { kind: "unknown" };
1484
+ if (openapi) {
1485
+ const resolved = resolveOpenAPIRef(ref);
1486
+ if (resolved) return resolved === rootName || isDocument ? {
1487
+ kind: "lazy",
1488
+ name: resolved
1489
+ } : {
1490
+ kind: "value",
1491
+ name: resolved
1492
+ };
1493
+ }
1494
+ const toName = schemaNamer(openapi);
1495
+ const declared = (name) => {
1496
+ if (name === rootName || isDocument) return {
1497
+ kind: "lazy",
1498
+ name
1499
+ };
1500
+ if (rootName === "Schema") return {
1501
+ kind: "value",
1502
+ name: `${name}Schema`
1503
+ };
1504
+ return {
1505
+ kind: "lazy",
1506
+ name
1507
+ };
1508
+ };
1509
+ for (const prefix of DEFINITION_REF_PREFIXES) if (ref.startsWith(prefix)) return declared(toName(ref.slice(prefix.length)));
1510
+ if (ref.startsWith("#")) {
1511
+ const refName = ref.slice(1);
1512
+ return refName === "" ? {
1513
+ kind: "lazy",
1514
+ name: rootName
1515
+ } : declared(toName(refName));
1516
+ }
1517
+ if (ref.includes("#")) return { kind: "unknown" };
1518
+ if (ref.startsWith("http")) {
1519
+ const last = ref.split("/").at(-1);
1520
+ if (last) return {
1521
+ kind: "value",
1522
+ name: last.replace(/\.json$/, "")
1523
+ };
1524
+ }
1525
+ return { kind: "any" };
1526
+ }
1527
+ //#endregion
1528
+ //#region src/helper/type.ts
1529
+ /** Whether a node is a 64-bit integer, whose number is a bigint. */
1530
+ function isInt64(schema) {
1531
+ return schema.format === "int64" || schema.format === "uint64";
1532
+ }
1533
+ /**
1534
+ * The TypeScript type of a schema, as the declaration that accompanies a recursive
1535
+ * schema (`type _Category = ...`) spells it. A `$ref` names a sibling declaration
1536
+ * (`_Name`), the root refers to itself through `inferRoot`, and anything the type cannot
1537
+ * say is `unknown`.
1538
+ */
1539
+ function typeDeclaration(schema, flavour, rootName = DEFAULT_ROOT_NAME) {
1540
+ if (schema === void 0) return "";
1541
+ const base = nonNullType(schema, flavour, rootName);
1542
+ if (!(isNullable(schema) || schema.allOf?.some(isNullTypeMember) === true) || base === "null" || base === "unknown") return base;
1543
+ return `(${base} | null)`;
1544
+ }
1545
+ function nonNullType(schema, flavour, rootName) {
1546
+ const type = (s) => typeDeclaration(s, flavour, rootName);
1547
+ if (schema.$ref) {
1548
+ if (isRootRef(schema.$ref)) return flavour.inferRoot(rootName);
1549
+ for (const prefix of DEFINITION_REF_PREFIXES) if (schema.$ref.startsWith(prefix)) return `_${toPascalCase(schema.$ref.slice(prefix.length))}`;
1550
+ if (schema.$ref.startsWith("#")) {
1551
+ const refName = schema.$ref.slice(1);
1552
+ if (refName === "") return flavour.inferRoot(rootName);
1553
+ if (!refName.includes("/")) return `_${toPascalCase(refName)}`;
1554
+ }
1555
+ return "unknown";
1556
+ }
1557
+ if (schema.oneOf || schema.anyOf) return `(${(schema.oneOf ?? schema.anyOf ?? []).map(type).join(" | ")})`;
1558
+ if (schema.allOf) {
1559
+ const members = schema.allOf.filter((s) => !isShapelessMember(s)).map(type);
1560
+ if (members.length === 0) return "unknown";
1561
+ if (members.length === 1) return members[0];
1562
+ return `(${members.join(" & ")})`;
1563
+ }
1564
+ if (schema.not) return "unknown";
1565
+ const literal = (value) => typeof value === "number" && isInt64(schema) ? `${value}n` : jsLiteral(value);
1566
+ if (schema.const !== void 0) return literal(schema.const);
1567
+ if (schema.enum) {
1568
+ if (schema.enum.length === 1) return literal(schema.enum[0]);
1569
+ return `(${schema.enum.map(literal).join(" | ")})`;
1570
+ }
1571
+ const readonly = flavour.readonly ? "readonly " : "";
1572
+ const object = () => {
1573
+ if (!schema.properties) {
1574
+ if (schema.additionalProperties) {
1575
+ if (typeof schema.additionalProperties === "boolean") return schema.additionalProperties ? "{ [key: string]: unknown }" : "{ [key: string]: never }";
1576
+ return `{ [key: string]: ${type(schema.additionalProperties)} }`;
1577
+ }
1578
+ return "{ [key: string]: unknown }";
1579
+ }
1580
+ const required = new Set(schema.required);
1581
+ return `{${Object.entries(schema.properties).map(([key, propSchema]) => {
1582
+ const safeKey = makeSafeKey(key);
1583
+ const marker = required.has(key) ? "" : "?";
1584
+ return `${readonly}${safeKey}${marker}: ${type(propSchema)}`;
1585
+ }).join("; ")}}`;
1586
+ };
1587
+ if (schema.properties) return object();
1588
+ const t = normalizeTypes(schema.type);
1589
+ const integerType = isInt64(schema) || schema.format === "bigint" ? "bigint" : "number";
1590
+ const primitives = [
1591
+ t.includes("string") ? "string" : void 0,
1592
+ t.includes("number") ? "number" : t.includes("integer") ? integerType : void 0,
1593
+ t.includes("boolean") ? "boolean" : void 0
1594
+ ].filter((p) => p !== void 0);
1595
+ if (primitives.length > 1 && !t.includes("array") && !t.includes("object")) return `(${primitives.join(" | ")})`;
1596
+ if (primitives.length > 0) return primitives[0];
1597
+ if (t.includes("array")) {
1598
+ const items = itemsSchemaOf(schema.items);
1599
+ return items ? `${readonly}${type(items)}[]` : `${readonly}unknown[]`;
1600
+ }
1601
+ if (t.includes("object")) return object();
1602
+ if (t.includes("date")) return "Date";
1603
+ if (t.length === 1 && t[0] === "null") return "null";
1604
+ return "unknown";
1605
+ }
1606
+ //#endregion
1607
+ //#region src/helper/typebox-wrap.ts
1608
+ /**
1609
+ * Wraps a TypeBox schema string with `Type.Union([..., Type.Null()])` (when nullable),
1610
+ * `Type.Readonly()` (on `x-readonly`) and, outermost, `Type.Optional()` when a `default`
1611
+ * is present: the modifier has to sit on the property schema itself for `Type.Object` to
1612
+ * read the key as optional, so it goes outside the union.
1613
+ *
1614
+ * Metadata (`description`, `examples`, `deprecated`, `externalDocs`,
1615
+ * `readOnly`, `writeOnly`) is NOT handled here. Each TypeBox factory call
1616
+ * (`Type.String`, `Type.Object`, `Type.Array`, etc.) embeds metadata directly
1617
+ * into its own options argument via {@link typeboxMetaOpts} at construction
1618
+ * time, because TypeBox stores metadata on the schema object during
1619
+ * construction and exposes no post-construction `.meta()` method.
1620
+ */
1621
+ function typeboxWrap(typeboxStr, schema) {
1622
+ const withNullable = isNullable(schema) ? `Type.Union([${typeboxStr},Type.Null()])` : typeboxStr;
1623
+ const withReadonly = schema["x-readonly"] === true ? `Type.Readonly(${withNullable})` : withNullable;
1624
+ return hasKeptDefault(schema) ? `Type.Optional(${withReadonly})` : withReadonly;
1625
+ }
1626
+ //#endregion
1627
+ //#region src/helper/unevaluated.ts
1628
+ function definitionOf(ref, definitions) {
1629
+ if (definitions === void 0) return void 0;
1630
+ for (const prefix of DEFINITION_REF_PREFIXES) {
1631
+ if (!ref.startsWith(prefix)) continue;
1632
+ const rest = ref.slice(prefix.length);
1633
+ if (rest === "" || rest.includes("/")) return void 0;
1634
+ const name = decodeURIComponent(rest);
1635
+ return Object.hasOwn(definitions, name) ? definitions[name] : void 0;
1636
+ }
1637
+ }
1638
+ /**
1639
+ * The properties a node evaluates for `unevaluatedProperties` (JSON Schema 2020-12 §11.3):
1640
+ * its own `properties` and `patternProperties`, and those of every `allOf` / `oneOf` /
1641
+ * `anyOf` / `then` / `else` / `dependentSchemas` member, a `$ref` read as the
1642
+ * definition it names. A branch that may not apply counts as evaluated, so a valid value
1643
+ * is never refused.
1644
+ *
1645
+ * `undefined` when every property is evaluated (an `additionalProperties` anywhere) or
1646
+ * when that cannot be told (a `$ref` `definitions` does not hold).
1647
+ */
1648
+ function evaluatedProperties(schema, definitions, reading = /* @__PURE__ */ new Set()) {
1649
+ if (schema.additionalProperties !== void 0) return void 0;
1650
+ const members = [
1651
+ ...schema.allOf ?? [],
1652
+ ...schema.oneOf ?? [],
1653
+ ...schema.anyOf ?? [],
1654
+ ...schema.then === void 0 ? [] : [schema.then],
1655
+ ...schema.else === void 0 ? [] : [schema.else],
1656
+ ...Object.values(schema.dependentSchemas ?? {})
1657
+ ];
1658
+ const names = new Set(Object.keys(schema.properties ?? {}));
1659
+ const patterns = new Set(Object.keys(schema.patternProperties ?? {}));
1660
+ if (schema.$ref !== void 0 && !reading.has(schema.$ref)) {
1661
+ const target = definitionOf(schema.$ref, definitions);
1662
+ if (target === void 0) return void 0;
1663
+ members.push(target);
1664
+ }
1665
+ const next = schema.$ref === void 0 ? reading : /* @__PURE__ */ new Set([...reading, schema.$ref]);
1666
+ for (const member of members) {
1667
+ if (typeof member !== "object" || member === null) continue;
1668
+ const evaluated = evaluatedProperties(member, definitions, next);
1669
+ if (evaluated === void 0) return void 0;
1670
+ for (const name of evaluated.names) names.add(name);
1671
+ for (const pattern of evaluated.patterns) patterns.add(pattern);
1672
+ }
1673
+ return {
1674
+ names: [...names],
1675
+ patterns: [...patterns]
1676
+ };
1677
+ }
1678
+ /**
1679
+ * The emitted expression that tells whether `key` is evaluated: a lookup in the names
1680
+ * plus one `RegExp` test per pattern.
1681
+ */
1682
+ function isEvaluatedKeyExpression(evaluated, key) {
1683
+ return [`${JSON.stringify(evaluated.names)}.includes(${key})`, ...evaluated.patterns.map((pattern) => `new RegExp(${JSON.stringify(pattern)}).test(${key})`)].join("||");
1684
+ }
1685
+ //#endregion
1686
+ //#region src/helper/valibot-wrap.ts
1687
+ /** A default as the Valibot literal of the schema's input: a bigint for a 64-bit integer. */
1688
+ function defaultLiteral(schema, value, stringWire) {
1689
+ if (stringWire) return jsLiteral(wireDefaultValue(value));
1690
+ if (typeof value === "number") {
1691
+ if (schema.format === "int64" || schema.format === "uint64") return `${value}n`;
1692
+ if (schema.format === "bigint") return `BigInt(${value})`;
1693
+ }
1694
+ return jsLiteral(value);
1695
+ }
1696
+ /**
1697
+ * Wraps a Valibot schema string with `v.nullable()`, `v.optional(..., default)`,
1698
+ * metadata actions (`v.description()` / `v.metadata()`) and `v.brand()` based on the
1699
+ * JSON Schema's `default` / `nullable` / `x-brand` and OpenAPI metadata fields. All
1700
+ * actions are consolidated into a single outer `v.pipe(...)`.
1701
+ *
1702
+ * `v.optional(schema, default)` is the outermost of the three so that an object never
1703
+ * has to wrap the property again: the key is optional and its default applies whatever
1704
+ * the schema inside.
1705
+ *
1706
+ * Metadata mapping (Valibot v1 actions):
1707
+ * - `description` → `v.description(text)`
1708
+ * - `examples` (or `[example]`), `deprecated`, `externalDocs`, `readOnly`,
1709
+ * `writeOnly` → `v.metadata({ ... })`
1710
+ *
1711
+ * @see https://valibot.dev/api/metadata/
1712
+ * @see https://valibot.dev/api/description/
1713
+ */
1714
+ function valibotWrap(valibotStr, schema, options) {
1715
+ const nullText = options?.nullText === true;
1716
+ const withNullable = isNullable(schema) || nullText && !isNullMatchedFirst(schema) ? `v.nullable(${valibotStr})` : valibotStr;
1717
+ const withNullText = nullText ? `v.pipe(v.unknown(),v.transform(${wireNullText("input")}),${withNullable})` : withNullable;
1718
+ const defaultResult = schema.default !== void 0 ? coerceDefault(schema, schema.default, options?.definitions) : void 0;
1719
+ const withDefault = defaultResult?.keep ? `v.optional(${withNullText},${defaultLiteral(schema, defaultResult.value, options?.stringWire === true)})` : withNullText;
1720
+ const examples = examplesOf(schema);
1721
+ const actions = [];
1722
+ if (schema.description !== void 0) actions.push(`v.description(${JSON.stringify(schema.description)})`);
1723
+ const metaObj = {};
1724
+ if (examples !== void 0) metaObj.examples = examples;
1725
+ if (schema.deprecated !== void 0) metaObj.deprecated = schema.deprecated;
1726
+ if (schema.externalDocs !== void 0) metaObj.externalDocs = schema.externalDocs;
1727
+ if (schema.readOnly !== void 0) metaObj.readOnly = schema.readOnly;
1728
+ if (schema.writeOnly !== void 0) metaObj.writeOnly = schema.writeOnly;
1729
+ if (Object.keys(metaObj).length > 0) actions.push(`v.metadata(${serializeJSValue(metaObj)})`);
1730
+ if (schema["x-readonly"] === true) actions.push("v.readonly()");
1731
+ const brand = schema["x-brand"];
1732
+ if (typeof brand === "string") actions.push(`v.brand("${brand}")`);
1733
+ const check = readCodeExtension(schema, "x-check", options);
1734
+ if (check) actions.push(check);
1735
+ const transform = readCodeExtension(schema, "x-transform", options);
1736
+ if (transform) actions.push(transform);
1737
+ const pipeExt = readCodeExtension(schema, "x-pipe", options);
1738
+ if (pipeExt) actions.push(pipeExt);
1739
+ const piped = actions.length === 0 ? withDefault : `v.pipe(${withDefault},${actions.join(",")})`;
1740
+ if (schema["x-fallback"] !== void 0) return `v.fallback(${piped},${jsLiteral(schema["x-fallback"])})`;
1741
+ return piped;
1742
+ }
1743
+ //#endregion
1744
+ //#region src/helper/zod-wrap.ts
1745
+ /**
1746
+ * Wraps a Zod schema string with `.default()`, `.nullable()`, `.brand<...>()`
1747
+ * and a single Zod v4 metadata chain (`.meta({ ... })`) based on the JSON
1748
+ * Schema's `default` / `nullable` / `x-brand` and OpenAPI metadata fields.
1749
+ *
1750
+ * When `options.unsafeCodeExtensions` is true, chain-term extensions
1751
+ * (`x-refine` / `x-transform` / `x-pipe`) are appended between brand and
1752
+ * meta, and the outermost extensions (`x-codec` / `x-preprocess`) replace
1753
+ * the final result with their raw expression value.
1754
+ *
1755
+ * @see https://zod.dev/metadata
1756
+ */
1757
+ function zodWrap(zodStr, schema, options) {
1758
+ const formatLiteral = (value) => {
1759
+ if (typeof value === "boolean") return `${value}`;
1760
+ if (typeof value === "number") {
1761
+ if (schema.format === "int64" || schema.format === "uint64") return `${value}n`;
1762
+ if (schema.format === "bigint") return `BigInt(${value})`;
1763
+ return `${value}`;
1764
+ }
1765
+ if (schema.type === "date" && typeof value === "string") return `new Date(${JSON.stringify(value)})`;
1766
+ return JSON.stringify(value);
1767
+ };
1768
+ const defaultResult = schema.default !== void 0 ? coerceDefault(schema, schema.default, options?.definitions) : void 0;
1769
+ const withNullable = isNullable(schema) ? `${zodStr}.nullable()` : zodStr;
1770
+ const withDefault = defaultResult?.keep ? `${withNullable}.default(${formatLiteral(defaultResult.value)})` : withNullable;
1771
+ const withReadonly = schema["x-readonly"] === true ? `${withDefault}.readonly()` : withDefault;
1772
+ const withPrefault = schema["x-prefault"] !== void 0 ? `${withReadonly}.prefault(${formatLiteral(schema["x-prefault"])})` : withReadonly;
1773
+ const withCatch = schema["x-catch"] !== void 0 ? `${withPrefault}.catch(${formatLiteral(schema["x-catch"])})` : withPrefault;
1774
+ const brand = schema["x-brand"];
1775
+ const withBrand = typeof brand === "string" ? `${withCatch}.brand<"${brand}">()` : withCatch;
1776
+ const refine = readCodeExtension(schema, "x-refine", options);
1777
+ const transform = readCodeExtension(schema, "x-transform", options);
1778
+ const pipe = readCodeExtension(schema, "x-pipe", options);
1779
+ const withRefine = refine ? `${withBrand}${refine}` : withBrand;
1780
+ const withTransform = transform ? `${withRefine}${transform}` : withRefine;
1781
+ const withPipe = pipe ? `${withTransform}${pipe}` : withTransform;
1782
+ const examples = examplesOf(schema);
1783
+ const metaObj = {};
1784
+ if (schema.description !== void 0) metaObj.description = schema.description;
1785
+ if (examples !== void 0) metaObj.examples = examples;
1786
+ if (schema.deprecated !== void 0) metaObj.deprecated = schema.deprecated;
1787
+ if (schema.externalDocs !== void 0) metaObj.externalDocs = schema.externalDocs;
1788
+ if (schema.readOnly !== void 0) metaObj.readOnly = schema.readOnly;
1789
+ if (schema.writeOnly !== void 0) metaObj.writeOnly = schema.writeOnly;
1790
+ const withMeta = Object.keys(metaObj).length === 0 ? withPipe : `${withPipe}.meta(${serializeJSValue(metaObj)})`;
1791
+ const codec = readCodeExtension(schema, "x-codec", options);
1792
+ const preprocess = readCodeExtension(schema, "x-preprocess", options);
1793
+ if (codec) return codec;
1794
+ if (preprocess) return preprocess;
1795
+ return withMeta;
1796
+ }
1797
+ //#endregion
1798
+ export { hasNotKeyword as $, wireNullText as A, emitOptionsOf as B, isPrimitiveUnion as C, stringboolTruthyPattern as D, stringboolPattern as E, jsLiteral as F, schemaNamer as G, planDocument as H, typeboxDefaultOpt as I, isOptionalByDefault as J, cyclicDefinitionNames as K, typeboxMetaOpts as L, formatPattern as M, regexSource as N, unionPrimitiveTypes as O, timePattern as P, findCodeExtensionKeysInSchema as Q, typeboxRefOpt as R, isNullTextRead as S, ownProperties as T, renderDefinitions as U, missingDefinitionComment as V, rootNameOf as W, arktypePreprocess as X, itemsSchemaOf as Y, arktypeWrap as Z, effectPreprocess as _, typeboxWrap as a, regexLiteral as at, integerWirePattern as b, withPolymorphicBases as c, propertyEmitOptions as d, constraintMessage as et, withoutParameterSerialization as f, hoistNestedRefs as g, valueListLiteral as h, isEvaluatedKeyExpression as i, patternSource as it, wireNumericKind as j, wireArrayOnce as k, hasParameterSerialization as l, notPredicate as m, valibotWrap as n, foldAllOfMembers as nt, typeDeclaration as o, isBigintFormat as p, hasRootSelfReference as q, evaluatedProperties as r, isKeywordOnlyMember as rt, refTarget as s, zodWrap as t, constraintPredicate as tt, parameterReaders as u, effectWrap as v, numberWirePattern as w, isNullMatchedFirst as x, impliedWireType as y, definitionsOf as z };