schema-truth 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +143 -2
- package/dist/ajv-DTP2FXRr.js +105 -0
- package/dist/ajv.d.ts +24 -0
- package/dist/ajv.js +1 -0
- package/dist/arktype-BdvvaBQX.js +746 -0
- package/dist/arktype.d.ts +10 -0
- package/dist/arktype.js +1 -0
- package/dist/cli/ajv.d.ts +1 -0
- package/dist/cli/ajv.js +15 -0
- package/dist/cli/arktype.d.ts +1 -0
- package/dist/cli/arktype.js +15 -0
- package/dist/cli/effect.d.ts +1 -0
- package/dist/cli/effect.js +15 -0
- package/dist/cli/typebox.d.ts +1 -0
- package/dist/cli/typebox.js +15 -0
- package/dist/cli/valibot.d.ts +1 -0
- package/dist/cli/valibot.js +15 -0
- package/dist/cli/yup.d.ts +1 -0
- package/dist/cli/yup.js +15 -0
- package/dist/cli/zod.d.ts +1 -0
- package/dist/cli/zod.js +15 -0
- package/dist/cli-CL2mSark.js +124 -0
- package/dist/effect-mUknRPv_.js +645 -0
- package/dist/effect.d.ts +12 -0
- package/dist/effect.js +1 -0
- package/dist/helper-Cfvb5UDq.js +1115 -0
- package/dist/index-C2L8Ty0-.d.ts +65 -0
- package/dist/index-DbV3dEmN.d.ts +551 -0
- package/dist/index.d.ts +303 -0
- package/dist/index.js +10 -0
- package/dist/parser-CyJ2auea.js +36 -0
- package/dist/typebox-BdWJv3ND.js +544 -0
- package/dist/typebox.d.ts +21 -0
- package/dist/typebox.js +1 -0
- package/dist/utils-WNBq1HR0.js +1017 -0
- package/dist/valibot-CaJIynCH.js +664 -0
- package/dist/valibot.d.ts +9 -0
- package/dist/valibot.js +1 -0
- package/dist/yup-CM2TSFig.js +92 -0
- package/dist/yup.d.ts +17 -0
- package/dist/yup.js +1 -0
- package/dist/zod-BsXLZfwK.js +777 -0
- package/dist/zod.d.ts +9 -0
- package/dist/zod.js +1 -0
- package/package.json +112 -4
|
@@ -0,0 +1,1115 @@
|
|
|
1
|
+
import { $ as DEFINITION_REF_PREFIXES, A as isDefinitionKeyword, At as WIRE_PRIMITIVE_ORDER, B as isSchemaObject, C as hasNumericKeyword, Ct as STRINGBOOL_TRUTHY_PATTERN, Dt as UNICODE_ESCAPE_PATTERN, E as isArktypeDefinition, I as isQuoted, L as isRecord, M as isNullable, O as isDeepLocalPointer, Q as DEFINITION_POINTER_PATTERN, R as isRootRef, St as STRINGBOOL_PATTERN, T as hasType, 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, c as normalizeTypes, ct as MISSING_DEFINITION_PREFIX, d as toPascalCase, ht as OFFSET_PATTERN_SOURCE, k as isDefaultOnlyMember, l as resolveOpenAPIRef, s as makeSafeKey, t as coerceDefault, tt as FORMAT_PATTERNS, u as toIdentifierPascalCase, v as canBeString, w as hasStringKeyword, y as hasCombinator, z as isSchemaList } from "./utils-WNBq1HR0.js";
|
|
2
|
+
//#region src/helper/walk.ts
|
|
3
|
+
/**
|
|
4
|
+
* Every object node under `root`, depth first, the root first.
|
|
5
|
+
*
|
|
6
|
+
* Arrays are descended into but never yielded: a combinator list is a list of schemas,
|
|
7
|
+
* not a schema. This is the one traversal every "does the document contain ..." question
|
|
8
|
+
* is asked through, so the questions stay one line each and agree on what a node is.
|
|
9
|
+
*
|
|
10
|
+
* @yields each object node, parents before children
|
|
11
|
+
*/
|
|
12
|
+
function* walkSchema(root, options) {
|
|
13
|
+
const stack = [root];
|
|
14
|
+
let isRoot = true;
|
|
15
|
+
while (stack.length > 0) {
|
|
16
|
+
const node = stack.pop();
|
|
17
|
+
if (!isRecord(node)) continue;
|
|
18
|
+
if (Array.isArray(node)) {
|
|
19
|
+
for (const item of node) stack.push(item);
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const yielded = !(isRoot && options?.skipRoot === true);
|
|
23
|
+
isRoot = false;
|
|
24
|
+
if (yielded) {
|
|
25
|
+
yield node;
|
|
26
|
+
if (options?.prune?.(node) === true) continue;
|
|
27
|
+
}
|
|
28
|
+
for (const [key, value] of Object.entries(node)) {
|
|
29
|
+
if (options?.skipDefinitions === true && isDefinitionKeyword(key)) continue;
|
|
30
|
+
if (isRecord(value)) stack.push(value);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Whether any node under `root` carries one of `keywords`. */
|
|
35
|
+
function hasKeyword(root, keywords) {
|
|
36
|
+
for (const node of walkSchema(root)) if (keywords.some((keyword) => keyword in node)) return true;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Whether a schema (at any depth) uses the JSON Schema `not` keyword. The TypeBox
|
|
41
|
+
* generator falls back to `Type.Any()` because TypeBox v1 has no runtime `Type.Not(...)`
|
|
42
|
+
* and `Value.Check` does not evaluate `not`.
|
|
43
|
+
*/
|
|
44
|
+
function hasNotKeyword(schema) {
|
|
45
|
+
return hasKeyword(schema, ["not"]);
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/helper/code-extensions.ts
|
|
49
|
+
const CODE_EXTENSION_KEYS = new Set(ALL_CODE_EXTENSION_KEYS);
|
|
50
|
+
const DENYLIST_PATTERN = new RegExp([
|
|
51
|
+
"\\b(?:process|require|import|globalThis|eval|Function|constructor|__proto__|",
|
|
52
|
+
"child_process|setTimeout|setInterval|XMLHttpRequest|fetch|atob|btoa|",
|
|
53
|
+
"document|window|self|top|parent|location|navigator|localStorage|",
|
|
54
|
+
"sessionStorage|indexedDB|WebSocket|FileReader|Worker|crypto|require_|",
|
|
55
|
+
"arguments|callee|caller|Reflect|Proxy|Symbol)\\b",
|
|
56
|
+
"|String\\s*\\.\\s*fromCharCode",
|
|
57
|
+
"|String\\s*\\.\\s*raw",
|
|
58
|
+
"|\\.\\s*join\\s*\\(",
|
|
59
|
+
"|`",
|
|
60
|
+
"|\\\\[uxN]",
|
|
61
|
+
"|\\[\\s*['\"]"
|
|
62
|
+
].join(""), "u");
|
|
63
|
+
/**
|
|
64
|
+
* Validate a raw code-extension value against a small denylist.
|
|
65
|
+
*
|
|
66
|
+
* **This is defense-in-depth only — not a primary control.** The primary
|
|
67
|
+
* security control is the `unsafeCodeExtensions: true` programmatic opt-in
|
|
68
|
+
* itself. A motivated attacker can bypass the denylist through string-
|
|
69
|
+
* construction (`String.fromCharCode(...)`, `['c','o','d','e'].join('')`),
|
|
70
|
+
* `arguments.callee.caller` chains, ES2015+ identifier characters, or any
|
|
71
|
+
* number of metaprogramming patterns we have not enumerated. Do not pass
|
|
72
|
+
* `{ unsafeCodeExtensions: true }` for JSON Schemas from outside your trust
|
|
73
|
+
* boundary, regardless of what this function returns.
|
|
74
|
+
*
|
|
75
|
+
* Blocks: `process` / `require` / `import` / `globalThis` / `eval` /
|
|
76
|
+
* `Function` / `constructor` / `__proto__` / `child_process` /
|
|
77
|
+
* `arguments` / `callee` / `caller` / `Reflect` / `Proxy` / `Symbol`,
|
|
78
|
+
* network and browser globals, `String.fromCharCode` and `String.raw`,
|
|
79
|
+
* any `.join(` invocation, template-literal backticks,
|
|
80
|
+
* unicode/hex/octal-name escape sequences, and `[ '...' ]` computed access.
|
|
81
|
+
*/
|
|
82
|
+
function isSafeCodeExtension(value) {
|
|
83
|
+
if (typeof value !== "string") return false;
|
|
84
|
+
return !DENYLIST_PATTERN.test(value);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Returns the list of code-extension keys present on a schema (any nested
|
|
88
|
+
* level), so callers can emit a single warning when programmatic callers
|
|
89
|
+
* supply such schemas without `unsafeCodeExtensions: true`.
|
|
90
|
+
*/
|
|
91
|
+
function findCodeExtensionKeysInSchema(schema) {
|
|
92
|
+
const found = /* @__PURE__ */ new Set();
|
|
93
|
+
for (const node of walkSchema(schema)) for (const key of Object.keys(node)) if (CODE_EXTENSION_KEYS.has(key)) found.add(key);
|
|
94
|
+
return [...found];
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Read a code-extension value from the schema only when the flag is enabled
|
|
98
|
+
* AND the value passes the denylist check. Returns `undefined` otherwise.
|
|
99
|
+
*/
|
|
100
|
+
function readCodeExtension(schema, key, options) {
|
|
101
|
+
if (options?.unsafeCodeExtensions !== true) return void 0;
|
|
102
|
+
const raw = schema[key];
|
|
103
|
+
if (typeof raw !== "string") return void 0;
|
|
104
|
+
if (!isSafeCodeExtension(raw)) return void 0;
|
|
105
|
+
return raw;
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/helper/arktype-wrap.ts
|
|
109
|
+
/**
|
|
110
|
+
* `inner` read after `readers`, each a `(data) => ...` arrow over the raw value: a morph
|
|
111
|
+
* from `input` that pipes into `inner`, with `.to()` for a bare definition.
|
|
112
|
+
*/
|
|
113
|
+
function arktypePreprocess(readers, inner, input = "unknown") {
|
|
114
|
+
if (readers.length === 0) return inner;
|
|
115
|
+
if (isArktypeDefinition(inner)) return `type("${input}").pipe(${readers.join(",")}).to(${inner})`;
|
|
116
|
+
return `type("${input}").pipe(${readers.join(",")},${inner})`;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Wraps an ArkType schema string with `.or("null")`, `.brand()` and
|
|
120
|
+
* `.describe()` based on the JSON Schema's `nullable` / `x-brand` fields and
|
|
121
|
+
* OpenAPI `description`.
|
|
122
|
+
*
|
|
123
|
+
* Metadata mapping (ArkType `.describe()`):
|
|
124
|
+
* - `description` → `.describe(text)`, or `[def, "@", text]` in scope mode
|
|
125
|
+
*
|
|
126
|
+
* Other OpenAPI metadata fields (`examples`, `deprecated`, `externalDocs`,
|
|
127
|
+
* `readOnly`, `writeOnly`) are NOT emitted because ArkType's `.configure()`
|
|
128
|
+
* requires `ArkEnv["meta"]` interface augmentation for non-standard keys,
|
|
129
|
+
* which the user must opt in to. Emitting them here could produce TypeScript
|
|
130
|
+
* compile errors in consumer projects.
|
|
131
|
+
*
|
|
132
|
+
* @see https://arktype.io/docs/configuration
|
|
133
|
+
*/
|
|
134
|
+
function arktypeWrap(arktypeStr, schema, options) {
|
|
135
|
+
const inScope = options?.scopeMode === true;
|
|
136
|
+
const isDefinition = isArktypeDefinition;
|
|
137
|
+
const withNullable = isNullable(schema) ? isQuoted(arktypeStr) ? `"${arktypeStr.slice(1, -1)} | null"` : inScope && isDefinition(arktypeStr) ? `[${arktypeStr},"|","null"]` : `type(${arktypeStr}).or("null")` : arktypeStr;
|
|
138
|
+
const withReadonly = schema["x-readonly"] === true ? isDefinition(withNullable) ? `type(${withNullable}).readonly()` : `${withNullable}.readonly()` : withNullable;
|
|
139
|
+
const brand = schema["x-brand"];
|
|
140
|
+
const withBrand = typeof brand === "string" ? isDefinition(withReadonly) ? `type(${withReadonly}).brand("${brand}")` : `${withReadonly}.brand("${brand}")` : withReadonly;
|
|
141
|
+
const codeChain = [
|
|
142
|
+
readCodeExtension(schema, "x-narrow", options),
|
|
143
|
+
readCodeExtension(schema, "x-morph", options),
|
|
144
|
+
readCodeExtension(schema, "x-pipe", options)
|
|
145
|
+
].filter((v) => v !== void 0).join("");
|
|
146
|
+
const withCodeExts = codeChain ? isDefinition(withBrand) ? `type(${withBrand})${codeChain}` : `${withBrand}${codeChain}` : withBrand;
|
|
147
|
+
if (schema.description === void 0) return withCodeExts;
|
|
148
|
+
const text = JSON.stringify(schema.description);
|
|
149
|
+
if (inScope && isDefinition(withCodeExts)) return `[${withCodeExts},"@",${text}]`;
|
|
150
|
+
return `${isDefinition(withCodeExts) ? `type(${withCodeExts})` : withCodeExts}.describe(${text})`;
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/helper/schema.ts
|
|
154
|
+
/** `definitions` and `$defs` read as one map, `$defs` winning on a shared name. */
|
|
155
|
+
function collectDefinitions(schema) {
|
|
156
|
+
return {
|
|
157
|
+
...schema.definitions,
|
|
158
|
+
...schema.$defs
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The schema every array element is validated against: `items` itself, or the first
|
|
163
|
+
* member of a Draft-04 tuple. `undefined` for a boolean `items`, or none.
|
|
164
|
+
*/
|
|
165
|
+
function itemsSchemaOf(items) {
|
|
166
|
+
if (isSchemaObject(items)) return items;
|
|
167
|
+
if (isSchemaList(items)) return items[0];
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The example values of a node: `examples` as given, or the single OpenAPI `example`
|
|
171
|
+
* lifted into a list. `undefined` when the node carries neither.
|
|
172
|
+
*/
|
|
173
|
+
function examplesOf(schema) {
|
|
174
|
+
if (schema.examples !== void 0) return schema.examples;
|
|
175
|
+
return schema.example === void 0 ? void 0 : [schema.example];
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Whether a node carries a `default` the generators keep, so a property holding it may be
|
|
179
|
+
* left out of the input.
|
|
180
|
+
*/
|
|
181
|
+
function hasKeptDefault(schema) {
|
|
182
|
+
return schema.default !== void 0 && coerceDefault(schema, schema.default).keep;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Whether a node's own emitter already makes it optional with a default: a kept `default`,
|
|
186
|
+
* or an `allOf` member that only carries one. An object wrapping such a property again
|
|
187
|
+
* would hide the default behind the outer wrapper.
|
|
188
|
+
*/
|
|
189
|
+
function isOptionalByDefault(schema) {
|
|
190
|
+
return hasKeptDefault(schema) || schema.allOf?.some(isDefaultOnlyMember) === true;
|
|
191
|
+
}
|
|
192
|
+
//#endregion
|
|
193
|
+
//#region src/helper/cyclic.ts
|
|
194
|
+
/**
|
|
195
|
+
* The definition a local `$ref` names, in any form the generators understand:
|
|
196
|
+
* `#/definitions/X`, `#/$defs/X` and the bare `#X` shorthand. `undefined` for the
|
|
197
|
+
* whole-document reference and for a pointer into a sub-schema.
|
|
198
|
+
*/
|
|
199
|
+
function localDefinitionName(ref) {
|
|
200
|
+
return DEFINITION_POINTER_PATTERN.exec(ref)?.groups?.name ?? ANCHOR_REF_PATTERN.exec(ref)?.groups?.name;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Collect the local definition names a schema refers to. Nested `definitions`/`$defs`
|
|
204
|
+
* are not traversed: only references reachable from the schema body count as edges.
|
|
205
|
+
*/
|
|
206
|
+
function collectLocalRefs(schema) {
|
|
207
|
+
const refs = /* @__PURE__ */ new Set();
|
|
208
|
+
for (const node of walkSchema(schema, { skipDefinitions: true })) {
|
|
209
|
+
if (typeof node.$ref !== "string") continue;
|
|
210
|
+
const name = localDefinitionName(node.$ref);
|
|
211
|
+
if (name !== void 0) refs.add(name);
|
|
212
|
+
}
|
|
213
|
+
return [...refs];
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* True when a schema body refers back to itself, ignoring anything nested
|
|
217
|
+
* under `definitions`/`$defs`.
|
|
218
|
+
*
|
|
219
|
+
* By default only a whole-document reference (`$ref: "#"` or `""`) counts.
|
|
220
|
+
* Pass `isSelfRef` to also recognise a named reference that resolves back to
|
|
221
|
+
* the schema being emitted — an OpenAPI component referencing its own
|
|
222
|
+
* `#/components/schemas/...` entry, for instance.
|
|
223
|
+
*/
|
|
224
|
+
function hasRootSelfReference(schema, isSelfRef = isRootRef) {
|
|
225
|
+
for (const node of walkSchema(schema, {
|
|
226
|
+
skipDefinitions: true,
|
|
227
|
+
skipRoot: true
|
|
228
|
+
})) if (typeof node.$ref === "string" && isSelfRef(node.$ref)) return true;
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Names of the local definitions that take part in a `$ref` cycle — either a
|
|
233
|
+
* self loop (`A -> A`) or a mutual one (`A -> B -> A`).
|
|
234
|
+
*
|
|
235
|
+
* Generators that cannot express a cycle with plain `const` declarations (a
|
|
236
|
+
* later definition would be referenced before initialisation) use this to
|
|
237
|
+
* switch those definitions over to a by-name construct instead.
|
|
238
|
+
*
|
|
239
|
+
* @example
|
|
240
|
+
* ```ts
|
|
241
|
+
* cyclicDefinitionNames({
|
|
242
|
+
* $defs: {
|
|
243
|
+
* A: { properties: { b: { $ref: '#/$defs/B' } } },
|
|
244
|
+
* B: { properties: { a: { $ref: '#/$defs/A' } } },
|
|
245
|
+
* },
|
|
246
|
+
* }) // Set { 'A', 'B' }
|
|
247
|
+
* ```
|
|
248
|
+
*/
|
|
249
|
+
function cyclicDefinitionNames(schema) {
|
|
250
|
+
const definitions = collectDefinitions(schema);
|
|
251
|
+
const edges = /* @__PURE__ */ new Map();
|
|
252
|
+
for (const [name, def] of Object.entries(definitions)) edges.set(name, collectLocalRefs(def).filter((ref) => ref in definitions));
|
|
253
|
+
const cyclic = /* @__PURE__ */ new Set();
|
|
254
|
+
const state = /* @__PURE__ */ new Map();
|
|
255
|
+
const path = [];
|
|
256
|
+
const visit = (start) => {
|
|
257
|
+
const work = [[start, false]];
|
|
258
|
+
while (work.length > 0) {
|
|
259
|
+
const entry = work.pop();
|
|
260
|
+
if (entry === void 0) continue;
|
|
261
|
+
const [name, leaving] = entry;
|
|
262
|
+
if (leaving) {
|
|
263
|
+
path.pop();
|
|
264
|
+
state.set(name, "done");
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
if (state.get(name) === "done") continue;
|
|
268
|
+
if (state.get(name) === "visiting") {
|
|
269
|
+
for (let i = path.lastIndexOf(name); i >= 0 && i < path.length; i++) {
|
|
270
|
+
const onCycle = path[i];
|
|
271
|
+
if (onCycle !== void 0) cyclic.add(onCycle);
|
|
272
|
+
}
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
state.set(name, "visiting");
|
|
276
|
+
path.push(name);
|
|
277
|
+
work.push([name, true]);
|
|
278
|
+
for (const next of edges.get(name) ?? []) work.push([next, false]);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
for (const name of Object.keys(definitions).toSorted()) visit(name);
|
|
282
|
+
return cyclic;
|
|
283
|
+
}
|
|
284
|
+
//#endregion
|
|
285
|
+
//#region src/helper/resolve-schema-dependencies-from-schema.ts
|
|
286
|
+
/** The definition name the fragment of an external `$ref` points at, if it names one. */
|
|
287
|
+
function fragmentDefinitionName(fragment) {
|
|
288
|
+
return /^\/(?:definitions|\$defs)\/(?<name>[^/]+)$/u.exec(fragment)?.groups?.name ?? /^\/(?<name>[^/]+)$/u.exec(fragment)?.groups?.name;
|
|
289
|
+
}
|
|
290
|
+
/** A node that is a reference into a document: what it points at is the whole of what it says. */
|
|
291
|
+
function isPointerNode(node) {
|
|
292
|
+
return typeof node.$ref === "string" && node.$ref.includes("#");
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The definition names a definition refers to, sorted. A reference node is not descended
|
|
296
|
+
* into, so a sibling keyword beside a `$ref` adds no edge.
|
|
297
|
+
*/
|
|
298
|
+
function collectRefs(definition) {
|
|
299
|
+
const refs = /* @__PURE__ */ new Set();
|
|
300
|
+
for (const node of walkSchema(definition, { prune: isPointerNode })) {
|
|
301
|
+
const ref = node.$ref;
|
|
302
|
+
if (typeof ref !== "string" || ref === "#") continue;
|
|
303
|
+
const local = localDefinitionName(ref);
|
|
304
|
+
if (local !== void 0) refs.add(local);
|
|
305
|
+
if (!ref.includes("#")) continue;
|
|
306
|
+
const [, fragment] = ref.split("#");
|
|
307
|
+
if (!fragment) continue;
|
|
308
|
+
const external = fragmentDefinitionName(fragment);
|
|
309
|
+
if (external !== void 0) refs.add(external);
|
|
310
|
+
}
|
|
311
|
+
return [...refs].toSorted();
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Resolve schema dependencies and return them in topological order
|
|
315
|
+
*
|
|
316
|
+
* @param schema - JSON Schema object containing definitions or $defs
|
|
317
|
+
* @returns Array of schema names in dependency order
|
|
318
|
+
* @example
|
|
319
|
+
* ```ts
|
|
320
|
+
* const schema = {
|
|
321
|
+
* $defs: {
|
|
322
|
+
* animal: { type: 'object', properties: { name: { type: 'string' } } },
|
|
323
|
+
* zoo: { type: 'object', properties: { animals: { $ref: '#/$defs/animal' } } }
|
|
324
|
+
* }
|
|
325
|
+
* }
|
|
326
|
+
* resolveSchemaDependenciesFromSchema(schema) // ['animal', 'zoo']
|
|
327
|
+
* ```
|
|
328
|
+
*/
|
|
329
|
+
function resolveSchemaDependenciesFromSchema(schema) {
|
|
330
|
+
const definitions = collectDefinitions(schema);
|
|
331
|
+
const sorted = [];
|
|
332
|
+
const done = /* @__PURE__ */ new Set();
|
|
333
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
334
|
+
const visit = (name) => {
|
|
335
|
+
if (done.has(name) || visiting.has(name)) return;
|
|
336
|
+
const definition = definitions[name];
|
|
337
|
+
if (!definition) return;
|
|
338
|
+
visiting.add(name);
|
|
339
|
+
for (const ref of collectRefs(definition)) if (ref in definitions) visit(ref);
|
|
340
|
+
visiting.delete(name);
|
|
341
|
+
done.add(name);
|
|
342
|
+
sorted.push(name);
|
|
343
|
+
};
|
|
344
|
+
for (const name of Object.keys(definitions).toSorted()) visit(name);
|
|
345
|
+
return sorted;
|
|
346
|
+
}
|
|
347
|
+
//#endregion
|
|
348
|
+
//#region src/helper/document.ts
|
|
349
|
+
/** The node options of a document generation, with the unset parameter options left out. */
|
|
350
|
+
function emitOptionsOf(options) {
|
|
351
|
+
return {
|
|
352
|
+
openapi: options?.openapi ?? false,
|
|
353
|
+
readonly: options?.readonly ?? false,
|
|
354
|
+
unsafeCodeExtensions: options?.unsafeCodeExtensions ?? false,
|
|
355
|
+
...options?.paramIn !== void 0 && { paramIn: options.paramIn },
|
|
356
|
+
...options?.style !== void 0 && { style: options.style },
|
|
357
|
+
...options?.explode !== void 0 && { explode: options.explode },
|
|
358
|
+
...options?.allowEmptyValue !== void 0 && { allowEmptyValue: options.allowEmptyValue },
|
|
359
|
+
...options?.contentType !== void 0 && { contentType: options.contentType }
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* How a document names its schemas. An OpenAPI component name is always made a valid
|
|
364
|
+
* identifier; a plain JSON Schema title keeps its hyphens and underscores for back-compat.
|
|
365
|
+
*/
|
|
366
|
+
function schemaNamer(openapi) {
|
|
367
|
+
return openapi === true ? toIdentifierPascalCase : toPascalCase;
|
|
368
|
+
}
|
|
369
|
+
/** The name the root schema is exported under: its `title`, or `fallback`. */
|
|
370
|
+
function rootNameOf(schema, toName, fallback = DEFAULT_ROOT_NAME) {
|
|
371
|
+
return schema.title ? toName(schema.title) : fallback;
|
|
372
|
+
}
|
|
373
|
+
/** The comment left where a `$ref` names a definition the document does not hold. */
|
|
374
|
+
function missingDefinitionComment(name) {
|
|
375
|
+
return `${MISSING_DEFINITION_PREFIX}${name}`;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* The plan of a document: its definitions in dependency order, and which of them, if
|
|
379
|
+
* any, is the root under another name.
|
|
380
|
+
*/
|
|
381
|
+
function planDocument(schema, rootName) {
|
|
382
|
+
const definitions = collectDefinitions(schema);
|
|
383
|
+
const hasDefinitions = Object.keys(definitions).length > 0;
|
|
384
|
+
const orderedNames = hasDefinitions ? resolveSchemaDependenciesFromSchema(schema) : [];
|
|
385
|
+
const rootDefinition = definitions[rootName];
|
|
386
|
+
return {
|
|
387
|
+
rootName,
|
|
388
|
+
definitions,
|
|
389
|
+
hasDefinitions,
|
|
390
|
+
orderedNames,
|
|
391
|
+
rootDefinition,
|
|
392
|
+
nonRootNames: rootDefinition === void 0 ? orderedNames : orderedNames.filter((name) => name !== rootName),
|
|
393
|
+
root: rootDefinition ?? schema
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Every non-root definition rendered through `render` and joined as paragraphs, with a
|
|
398
|
+
* comment standing in for a definition the document names but does not hold.
|
|
399
|
+
*/
|
|
400
|
+
function renderDefinitions(plan, toName, render) {
|
|
401
|
+
return plan.nonRootNames.map((name) => {
|
|
402
|
+
const definition = plan.definitions[name];
|
|
403
|
+
return definition === void 0 ? missingDefinitionComment(name) : render(definition, toName(name));
|
|
404
|
+
}).join("\n\n");
|
|
405
|
+
}
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/helper/meta.ts
|
|
408
|
+
/**
|
|
409
|
+
* Host `$ref` name for OpenAPI component registration (hono-openapi
|
|
410
|
+
* `components.schemas`). TypeBox stores this on the schema at construction
|
|
411
|
+
* time — there is no post-construction `.meta()` — so it must land in the
|
|
412
|
+
* factory options object. Empty when the caller omitted `ref`.
|
|
413
|
+
*/
|
|
414
|
+
function typeboxRefOpt(ref) {
|
|
415
|
+
return ref === void 0 ? [] : [`ref:${JSON.stringify(ref)}`];
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Returns OpenAPI/JSON Schema metadata fields as a list of TypeBox option
|
|
419
|
+
* entries (`'key:value'` strings) ready to be joined into a `{...}` literal.
|
|
420
|
+
*
|
|
421
|
+
* Used by TypeBox type-level generators to embed metadata directly into the
|
|
422
|
+
* `Type.X(payload, options)` constructor call. A host `ref` is emitted first
|
|
423
|
+
* when supplied, in the same object as description / examples / deprecated.
|
|
424
|
+
*/
|
|
425
|
+
function typeboxMetaOpts(schema, ref) {
|
|
426
|
+
const examples = examplesOf(schema);
|
|
427
|
+
return [
|
|
428
|
+
...typeboxRefOpt(ref),
|
|
429
|
+
schema.description !== void 0 ? `description:${JSON.stringify(schema.description)}` : void 0,
|
|
430
|
+
examples !== void 0 ? `examples:${serializeJSValue(examples)}` : void 0,
|
|
431
|
+
schema.deprecated !== void 0 ? `deprecated:${schema.deprecated}` : void 0,
|
|
432
|
+
schema.externalDocs !== void 0 ? `externalDocs:${serializeJSValue(schema.externalDocs)}` : void 0,
|
|
433
|
+
schema.readOnly !== void 0 ? `readOnly:${schema.readOnly}` : void 0,
|
|
434
|
+
schema.writeOnly !== void 0 ? `writeOnly:${schema.writeOnly}` : void 0
|
|
435
|
+
].filter((v) => v !== void 0);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Returns the TypeBox `default` option entry (`['default:1']`) for a schema, or
|
|
439
|
+
* `[]` when absent/droppable. TypeBox v1's `Type.Optional(type)` takes one arg —
|
|
440
|
+
* defaults must live on the inner type's options object, so every factory emits
|
|
441
|
+
* its own default here rather than the wrapper passing a 2nd `Type.Optional` arg.
|
|
442
|
+
* `stringWire` (for `query`/`path` coercion) emits the default in its string-wire
|
|
443
|
+
* form (`'1'` / `'true'`), since the coerced `Type.String(...)` input is a string.
|
|
444
|
+
*/
|
|
445
|
+
function typeboxDefaultOpt(schema, stringWire = false) {
|
|
446
|
+
if (schema.default === void 0) return [];
|
|
447
|
+
const result = coerceDefault(schema, schema.default);
|
|
448
|
+
if (!result.keep) return [];
|
|
449
|
+
const value = stringWire ? String(result.value) : result.value;
|
|
450
|
+
return [`default:${typeof value === "boolean" || typeof value === "number" ? `${value}` : JSON.stringify(value)}`];
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Serializes a value into a JavaScript expression string.
|
|
454
|
+
*
|
|
455
|
+
* - Strings, numbers, booleans, null: via `JSON.stringify`
|
|
456
|
+
* - Arrays: `[elem1,elem2,...]`
|
|
457
|
+
* - Plain objects: `{key1:value1,...}` with bare identifiers when possible
|
|
458
|
+
* - Undefined values inside objects are skipped
|
|
459
|
+
*/
|
|
460
|
+
function serializeJSValue(value) {
|
|
461
|
+
if (value === void 0) return "undefined";
|
|
462
|
+
if (value === null) return "null";
|
|
463
|
+
if (typeof value !== "object") return JSON.stringify(value);
|
|
464
|
+
if (Array.isArray(value)) return `[${value.map(serializeJSValue).join(",")}]`;
|
|
465
|
+
const entries = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
466
|
+
if (entries.length === 0) return "{}";
|
|
467
|
+
return `{${entries.map(([k, v]) => `${makeSafeKey(k)}:${serializeJSValue(v)}`).join(",")}}`;
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
//#region src/helper/value.ts
|
|
471
|
+
/**
|
|
472
|
+
* A JSON value as the TypeScript literal that reproduces it.
|
|
473
|
+
*
|
|
474
|
+
* `JSON.stringify` already answers for strings, arrays and objects; booleans and numbers
|
|
475
|
+
* go through template interpolation so `-0`, `1e21` and friends keep the spelling the
|
|
476
|
+
* source had rather than picking up quotes.
|
|
477
|
+
*/
|
|
478
|
+
function jsLiteral(value) {
|
|
479
|
+
if (typeof value === "boolean") return `${value}`;
|
|
480
|
+
if (typeof value === "number") return `${value}`;
|
|
481
|
+
return JSON.stringify(value);
|
|
482
|
+
}
|
|
483
|
+
//#endregion
|
|
484
|
+
//#region src/helper/format.ts
|
|
485
|
+
/** A regular expression as the literal that reproduces it in generated source. */
|
|
486
|
+
function regexSource(pattern) {
|
|
487
|
+
return `/${pattern.source}/${pattern.flags}`;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* The source of an RFC 3339 `partial-time`. `precision` follows Zod's `z.iso.time`: `-1`
|
|
491
|
+
* minutes only, `0` whole seconds, `n` exactly `n` fraction digits, and `undefined` any
|
|
492
|
+
* number of them — with the seconds themselves optional unless `seconds` says otherwise.
|
|
493
|
+
*/
|
|
494
|
+
function timeSource(precision, seconds) {
|
|
495
|
+
const hhmm = String.raw`(?:[01]\d|2[0-3]):[0-5]\d`;
|
|
496
|
+
if (precision === void 0) return seconds ? String.raw`${hhmm}:[0-5]\d(?:\.\d+)?` : String.raw`${hhmm}(?::[0-5]\d(?:\.\d+)?)?`;
|
|
497
|
+
if (precision === -1) return hhmm;
|
|
498
|
+
if (precision === 0) return String.raw`${hhmm}:[0-5]\d`;
|
|
499
|
+
return String.raw`${hhmm}:[0-5]\d\.\d{${precision}}`;
|
|
500
|
+
}
|
|
501
|
+
/** The regex literal of an RFC 3339 `full-date` that is a real calendar date. */
|
|
502
|
+
function datePattern() {
|
|
503
|
+
return `/^${DATE_PATTERN_SOURCE}$/`;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* The regex literal of an RFC 3339 time: a `partial-time`, with the offset optional
|
|
507
|
+
* unless `offset` is `false`, in which case none is accepted.
|
|
508
|
+
*/
|
|
509
|
+
function timePattern(precision, offset) {
|
|
510
|
+
const tail = offset ? `${OFFSET_PATTERN_SOURCE}?` : "";
|
|
511
|
+
return `/^${timeSource(precision, false)}${tail}$/`;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* The regex literal of an RFC 3339 `date-time`, built as Zod's `z.iso.datetime()` builds
|
|
515
|
+
* its own: a `Z` always, a numeric offset when `offset` is set, and an offset-less local
|
|
516
|
+
* time when `local` is set.
|
|
517
|
+
*/
|
|
518
|
+
function datetimePattern(options) {
|
|
519
|
+
const suffixes = ["Z", ...options.offset ? [String.raw`([+-](?:[01]\d|2[0-3]):[0-5]\d)`] : []];
|
|
520
|
+
const qualified = `${timeSource(options.precision, true)}(?:${suffixes.join("|")})`;
|
|
521
|
+
const time = options.local ? `${qualified}|${timeSource(options.precision, false)}` : qualified;
|
|
522
|
+
return `/^${DATE_PATTERN_SOURCE}T(?:${time})$/`;
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* The regex literal of an RFC 9562 UUID of `version`, or of any version — the nil and
|
|
526
|
+
* max UUIDs included — when none is given.
|
|
527
|
+
*/
|
|
528
|
+
function uuidPattern(version) {
|
|
529
|
+
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)$/";
|
|
530
|
+
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})$/`;
|
|
531
|
+
}
|
|
532
|
+
/** The UUID version a format or an `x-uuidVersion` pins, or `undefined` for any. */
|
|
533
|
+
function uuidVersionOf(schema, format) {
|
|
534
|
+
const named = /^uuidv(?<version>[1-8])$/u.exec(format)?.groups?.version;
|
|
535
|
+
if (named !== void 0) return Number(named);
|
|
536
|
+
const extension = /^v(?<version>[1-8])$/u.exec(schema["x-uuidVersion"] ?? "")?.groups?.version;
|
|
537
|
+
return extension === void 0 ? void 0 : Number(extension);
|
|
538
|
+
}
|
|
539
|
+
/** The precision an `x-isoPrecision` pins, or `undefined` for any. */
|
|
540
|
+
function isoPrecisionOf(schema) {
|
|
541
|
+
const precision = schema["x-isoPrecision"];
|
|
542
|
+
return typeof precision === "number" ? precision : void 0;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* The regex literal that checks a string `format` for a target without a validator of
|
|
546
|
+
* its own for it, honouring `x-isoPrecision` / `x-isoOffset` / `x-isoLocal` on the ISO
|
|
547
|
+
* formats and `x-uuidVersion` on `uuid`. `undefined` for a format with no pattern here.
|
|
548
|
+
*/
|
|
549
|
+
function formatPattern(schema, format) {
|
|
550
|
+
if (format === "date") return datePattern();
|
|
551
|
+
if (format === "time") return timePattern(isoPrecisionOf(schema), schema["x-isoOffset"] !== false);
|
|
552
|
+
if (format === "date-time") return datetimePattern({
|
|
553
|
+
precision: isoPrecisionOf(schema),
|
|
554
|
+
offset: schema["x-isoOffset"] !== false,
|
|
555
|
+
local: schema["x-isoLocal"] === true
|
|
556
|
+
});
|
|
557
|
+
if (format === "uuid" || /^uuidv[1-8]$/u.test(format)) return uuidPattern(uuidVersionOf(schema, format));
|
|
558
|
+
const pattern = FORMAT_PATTERNS[format];
|
|
559
|
+
return pattern === void 0 ? void 0 : regexSource(pattern);
|
|
560
|
+
}
|
|
561
|
+
//#endregion
|
|
562
|
+
//#region src/helper/wire.ts
|
|
563
|
+
/**
|
|
564
|
+
* What the generators share about a value read off the string wire — a query, path,
|
|
565
|
+
* header, cookie or form field — beyond the coercion each library spells its own way.
|
|
566
|
+
*/
|
|
567
|
+
/** The `type` a typeless wire node reads its text as, from the constraints it carries. */
|
|
568
|
+
function impliedWireType(schema) {
|
|
569
|
+
if (schema.type !== void 0 || hasCombinator(schema) || schema.const !== void 0 || schema.enum !== void 0 || schema.properties !== void 0) return;
|
|
570
|
+
const isNumeric = hasNumericKeyword(schema);
|
|
571
|
+
const isString = hasStringKeyword(schema);
|
|
572
|
+
if (isNumeric && !isString) return "number";
|
|
573
|
+
if (isString && !isNumeric) return "string";
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* The primitive members of a `type` list as a union would list them: `number` already
|
|
577
|
+
* takes every integer, so the two together are one member, and on the wire every member
|
|
578
|
+
* reads text, so the string member is tried last.
|
|
579
|
+
*/
|
|
580
|
+
function unionPrimitiveTypes(types, isWire) {
|
|
581
|
+
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")));
|
|
582
|
+
}
|
|
583
|
+
/** Whether a `type` list is a union of primitives alone: more than one, and no array or object. */
|
|
584
|
+
function isPrimitiveUnion(types, isWire) {
|
|
585
|
+
return unionPrimitiveTypes(types, isWire).length > 1 && !types.includes("array") && !types.includes("object");
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Whether the text `null` has to be read ahead of a wire node: it takes `null`, and no
|
|
589
|
+
* string, so `null` can only be the value and never the text.
|
|
590
|
+
*/
|
|
591
|
+
function isNullTextRead(schema) {
|
|
592
|
+
return canBeNull(schema) && !canBeString(schema);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Whether a node matches `null` before its members coerce it: a nullable type, or a
|
|
596
|
+
* `null` among its literals. A combinator coerces `null` to `0` or `false` before a
|
|
597
|
+
* `null` member is tried, so the null has to be matched ahead of it instead.
|
|
598
|
+
*/
|
|
599
|
+
function isNullMatchedFirst(schema) {
|
|
600
|
+
return isNullable(schema) || schema.const === null || schema.enum?.includes(null) === true;
|
|
601
|
+
}
|
|
602
|
+
/** A wire array sent once arrives as its one element: wrapped, it is an array of one. */
|
|
603
|
+
function wireArrayOnce(param) {
|
|
604
|
+
return `(${param})=>(${param}===undefined||Array.isArray(${param})?${param}:[${param}])`;
|
|
605
|
+
}
|
|
606
|
+
/** The text `null` on the wire, read as the `null` a nullable non-string schema takes. */
|
|
607
|
+
function wireNullText(param) {
|
|
608
|
+
return `(${param})=>(${param}==='null'?null:${param})`;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* A parameter object answers an `Object.prototype` name it was not sent with the inherited
|
|
612
|
+
* member. Copied onto a null-prototype object, it holds only what the request carried.
|
|
613
|
+
*/
|
|
614
|
+
function ownProperties(param) {
|
|
615
|
+
return `(${param})=>(typeof ${param}==="object"&&${param}!==null&&!Array.isArray(${param})?Object.assign(Object.create(null),${param}):${param})`;
|
|
616
|
+
}
|
|
617
|
+
/** The regex literal of every spelling of a boolean on the wire. */
|
|
618
|
+
function stringboolPattern() {
|
|
619
|
+
return regexSource(STRINGBOOL_PATTERN);
|
|
620
|
+
}
|
|
621
|
+
/** The regex literal of the spellings that read as `true`. */
|
|
622
|
+
function stringboolTruthyPattern() {
|
|
623
|
+
return regexSource(STRINGBOOL_TRUTHY_PATTERN);
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* A default value as it is spelled on the string wire, where a coerced schema's input
|
|
627
|
+
* is text: a scalar as its text, an array element by element, `null` and objects as
|
|
628
|
+
* they are.
|
|
629
|
+
*/
|
|
630
|
+
function wireDefaultValue(value) {
|
|
631
|
+
if (Array.isArray(value)) return value.map(wireDefaultValue);
|
|
632
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
633
|
+
return value;
|
|
634
|
+
}
|
|
635
|
+
//#endregion
|
|
636
|
+
//#region src/helper/effect-wrap.ts
|
|
637
|
+
/** `inner` read after `reader`, a `(input) => ...` arrow over the raw value. */
|
|
638
|
+
function effectPreprocess(readers, inner) {
|
|
639
|
+
if (readers.length === 0) return inner;
|
|
640
|
+
return `Schema.Unknown.pipe(${readers.map((reader) => `Schema.decodeTo(Schema.Unknown,SchemaTransformation.transform<unknown,unknown>({decode:${reader},encode:(output)=>output}))`).join(",")},Schema.decodeTo(${inner}))`;
|
|
641
|
+
}
|
|
642
|
+
/** A default as the Effect literal of the schema's decoded type: a bigint for a 64-bit integer. */
|
|
643
|
+
function defaultLiteral$1(schema, value) {
|
|
644
|
+
if (typeof value === "number") {
|
|
645
|
+
if (schema.format === "int64" || schema.format === "uint64") return `${value}n`;
|
|
646
|
+
if (schema.format === "bigint") return `BigInt(${value})`;
|
|
647
|
+
}
|
|
648
|
+
return jsLiteral(value);
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Wraps an Effect Schema v4 schema string with `Schema.withDecodingDefault()`,
|
|
652
|
+
* `Schema.NullOr()`, `Schema.brand()` and `.annotate({...})` based on
|
|
653
|
+
* `default` / `nullable` / `x-brand` and OpenAPI metadata fields.
|
|
654
|
+
*
|
|
655
|
+
* Metadata mapping (v4 `.annotate`):
|
|
656
|
+
* - `description` → `description`
|
|
657
|
+
* - `readOnly` / `writeOnly` → same-named annotations (v4 promoted both to
|
|
658
|
+
* first-class fields on `Annotations.Augment`)
|
|
659
|
+
* - `examples` (or `[example]` when only singular present), `deprecated` and
|
|
660
|
+
* `externalDocs` → carried as loose annotation keys, since v4 types the
|
|
661
|
+
* native `examples` annotation as `ReadonlyArray<T>` and OpenAPI specs may
|
|
662
|
+
* carry incomplete examples that would fail to type-check.
|
|
663
|
+
*
|
|
664
|
+
* @see https://effect.website/docs/schema/annotations/
|
|
665
|
+
*/
|
|
666
|
+
function effectWrap(effectStr, schema, options) {
|
|
667
|
+
const nullText = options?.nullText === true;
|
|
668
|
+
const withNullable = isNullable(schema) || nullText && !isNullMatchedFirst(schema) ? `Schema.NullOr(${effectStr})` : effectStr;
|
|
669
|
+
const withNullText = nullText ? effectPreprocess([wireNullText("input")], withNullable) : withNullable;
|
|
670
|
+
const brand = schema["x-brand"];
|
|
671
|
+
const withBrand = typeof brand === "string" ? `${withNullText}.pipe(Schema.brand("${brand}"))` : withNullText;
|
|
672
|
+
const codeChain = [
|
|
673
|
+
readCodeExtension(schema, "x-filter", options),
|
|
674
|
+
readCodeExtension(schema, "x-transform", options),
|
|
675
|
+
readCodeExtension(schema, "x-pipe", options)
|
|
676
|
+
].filter((v) => v !== void 0);
|
|
677
|
+
const withCodeExts = codeChain.length === 0 ? withBrand : `${withBrand}${codeChain.join("")}`;
|
|
678
|
+
const defaultResult = schema.default !== void 0 ? coerceDefault(schema, schema.default) : void 0;
|
|
679
|
+
const decodingDefault = options?.stringWire === true ? "Schema.withDecodingDefaultType" : "Schema.withDecodingDefault";
|
|
680
|
+
const withDefault = defaultResult?.keep ? `${withCodeExts}.pipe(${decodingDefault}(Effect.succeed(${defaultLiteral$1(schema, defaultResult.value)})))` : withCodeExts;
|
|
681
|
+
const examples = examplesOf(schema);
|
|
682
|
+
const ann = {};
|
|
683
|
+
if (schema.description !== void 0) ann.description = schema.description;
|
|
684
|
+
if (examples !== void 0) ann.jsonSchemaExamples = examples;
|
|
685
|
+
if (schema.deprecated !== void 0) ann.jsonSchemaDeprecated = schema.deprecated;
|
|
686
|
+
if (schema.externalDocs !== void 0) ann.jsonSchemaExternalDocs = schema.externalDocs;
|
|
687
|
+
if (schema.readOnly !== void 0) ann.readOnly = schema.readOnly;
|
|
688
|
+
if (schema.writeOnly !== void 0) ann.writeOnly = schema.writeOnly;
|
|
689
|
+
if (Object.keys(ann).length === 0) return withDefault;
|
|
690
|
+
return `${withDefault}.annotate(${serializeJSValue(ann)})`;
|
|
691
|
+
}
|
|
692
|
+
//#endregion
|
|
693
|
+
//#region src/helper/not.ts
|
|
694
|
+
/** The `not` predicate bodies by `type`, over a value bound to `param`. */
|
|
695
|
+
function notTypeBody(type, param) {
|
|
696
|
+
switch (type) {
|
|
697
|
+
case "string":
|
|
698
|
+
case "number":
|
|
699
|
+
case "boolean": return `typeof ${param} !== '${type}'`;
|
|
700
|
+
case "integer": return `typeof ${param} !== 'number' || !Number.isInteger(${param})`;
|
|
701
|
+
case "array": return `!Array.isArray(${param})`;
|
|
702
|
+
case "object": return `typeof ${param} !== 'object' || ${param} === null || Array.isArray(${param})`;
|
|
703
|
+
case "null": return `${param} !== null`;
|
|
704
|
+
default: return;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* The predicate refusing what a `not` schema describes, as the source of an arrow over
|
|
709
|
+
* `param` (declared as `parameter`, which may carry a type annotation): a `const` is
|
|
710
|
+
* refused by value, a `type` by its runtime check, a list of types by every check at
|
|
711
|
+
* once. `undefined` for a `not` these shared cases do not cover — an `enum` or a
|
|
712
|
+
* combinator, which each generator spells with its own parser.
|
|
713
|
+
*/
|
|
714
|
+
function notPredicate(inner, param, parameter = param) {
|
|
715
|
+
if ("const" in inner) return `(${parameter}) => ${param} !== ${JSON.stringify(inner.const)}`;
|
|
716
|
+
if (typeof inner.type === "string") {
|
|
717
|
+
const body = notTypeBody(inner.type, param);
|
|
718
|
+
return body === void 0 ? void 0 : `(${parameter}) => ${body}`;
|
|
719
|
+
}
|
|
720
|
+
if (Array.isArray(inner.type)) {
|
|
721
|
+
const bodies = normalizeTypes(inner.type).map((t) => notTypeBody(t, param)).filter((body) => body !== void 0).map((body) => `(${body})`);
|
|
722
|
+
if (bodies.length > 0) return `(${parameter}) => ${bodies.join(" && ")}`;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
//#endregion
|
|
726
|
+
//#region src/helper/parameter.ts
|
|
727
|
+
/**
|
|
728
|
+
* How an OpenAPI Parameter Object's text is read into the value its schema describes:
|
|
729
|
+
* `allowEmptyValue`, a JSON `content`, or its `style` / `explode`. Every reader is the
|
|
730
|
+
* source of a `(param) => ...` arrow, which each generator wraps in its own
|
|
731
|
+
* preprocessing form.
|
|
732
|
+
*
|
|
733
|
+
* @see https://spec.openapis.org/oas/v3.2.0.html#style-examples
|
|
734
|
+
*/
|
|
735
|
+
/** A media type that holds a JSON document: `application/json` or any `+json` suffix. */
|
|
736
|
+
const JSON_MEDIA_TYPE_PATTERN = /^[^/]+\/(?:[^;]+\+)?json\s*(?:;|$)/iu;
|
|
737
|
+
/** The leading `.` of a `label` value, as a regex literal. */
|
|
738
|
+
const LABEL_PREFIX = String.raw`/^\./u`;
|
|
739
|
+
/** The leading `;name=` of a non-exploded `matrix` value, as a regex literal. */
|
|
740
|
+
const MATRIX_PREFIX = "/^;[^=]*=?/u";
|
|
741
|
+
/** Whether the options carry any of a parameter's serialization fields. */
|
|
742
|
+
function hasParameterSerialization(options) {
|
|
743
|
+
return options?.style !== void 0 || options?.explode !== void 0 || options?.allowEmptyValue === true || options?.contentType !== void 0;
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* The options the nodes under a parameter's root are emitted with: no serialization, and
|
|
747
|
+
* no string wire either when the parameter's text is a JSON document.
|
|
748
|
+
*/
|
|
749
|
+
function withoutParameterSerialization(options) {
|
|
750
|
+
const isJson = isJsonMediaType(options?.contentType);
|
|
751
|
+
return {
|
|
752
|
+
...options?.openapi !== void 0 && { openapi: options.openapi },
|
|
753
|
+
...options?.readonly !== void 0 && { readonly: options.readonly },
|
|
754
|
+
...options?.unsafeCodeExtensions !== void 0 && { unsafeCodeExtensions: options.unsafeCodeExtensions },
|
|
755
|
+
...options?.paramIn !== void 0 && !isJson && { paramIn: options.paramIn }
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
function isJsonMediaType(contentType) {
|
|
759
|
+
return contentType !== void 0 && JSON_MEDIA_TYPE_PATTERN.test(contentType);
|
|
760
|
+
}
|
|
761
|
+
/** The `style` a parameter has when its Parameter Object names none. */
|
|
762
|
+
function defaultStyle(paramIn) {
|
|
763
|
+
if (paramIn === "path" || paramIn === "header") return "simple";
|
|
764
|
+
if (paramIn === void 0) return void 0;
|
|
765
|
+
return "form";
|
|
766
|
+
}
|
|
767
|
+
/** `text`, a string expression, split on `separator` — none for an empty text. */
|
|
768
|
+
function split(text, separator) {
|
|
769
|
+
return `(${text}===''?[]:${text}.split(${JSON.stringify(separator)}))`;
|
|
770
|
+
}
|
|
771
|
+
/** An array of `[name, value, name, value, ...]` read into an object. */
|
|
772
|
+
function pairs(parts) {
|
|
773
|
+
return `${parts}.reduce<{[k:string]:string}>((acc,part,i,all)=>i%2===1?{...acc,[all[i-1]??'']:part}:acc,{})`;
|
|
774
|
+
}
|
|
775
|
+
/** An array of `name=value` read into an object. */
|
|
776
|
+
function entries(parts) {
|
|
777
|
+
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)}},{})`;
|
|
778
|
+
}
|
|
779
|
+
/** An empty value stands for an absent parameter, so its default applies. */
|
|
780
|
+
function emptyValueReader(param) {
|
|
781
|
+
return `(${param})=>(${param}===''?undefined:${param})`;
|
|
782
|
+
}
|
|
783
|
+
/** The text of a `content: application/json` parameter, read as the JSON document it holds. */
|
|
784
|
+
function jsonReader(param) {
|
|
785
|
+
return `(${param})=>{if(typeof ${param}!=='string')return ${param};try{return JSON.parse(${param})}catch{return ${param}}}`;
|
|
786
|
+
}
|
|
787
|
+
/** `deep[age]=5&deep[name]=bob`, gathered into the one object `{ age, name }`. */
|
|
788
|
+
function deepObjectReader(param) {
|
|
789
|
+
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}}`;
|
|
790
|
+
}
|
|
791
|
+
/** A reader of a string value: `body` maps `text`, the value with `prefix` removed. */
|
|
792
|
+
function textReader(param, body, prefix) {
|
|
793
|
+
return `(${param})=>{if(typeof ${param}!=='string')return ${param};const text=${prefix === void 0 ? param : `${param}.replace(${prefix},'')`};return ${body}}`;
|
|
794
|
+
}
|
|
795
|
+
function arrayReader(param, style, explode) {
|
|
796
|
+
if (style === "simple") return textReader(param, split("text", ","));
|
|
797
|
+
if (style === "label") return textReader(param, split("text", explode ? "." : ","), LABEL_PREFIX);
|
|
798
|
+
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);
|
|
799
|
+
if (explode || style === "deepObject") return void 0;
|
|
800
|
+
return textReader(param, split("text", style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ","));
|
|
801
|
+
}
|
|
802
|
+
function objectReader(param, style, explode) {
|
|
803
|
+
if (style === "deepObject") return deepObjectReader(param);
|
|
804
|
+
if (style === "simple") return textReader(param, (explode ? entries : pairs)(split("text", ",")));
|
|
805
|
+
if (style === "label") return textReader(param, explode ? entries(split("text", ".")) : pairs(split("text", ",")), LABEL_PREFIX);
|
|
806
|
+
if (style === "matrix") return explode ? textReader(param, entries(`text.split(';').filter((part)=>part!=='')`)) : textReader(param, pairs(split("text", ",")), MATRIX_PREFIX);
|
|
807
|
+
if (explode) return void 0;
|
|
808
|
+
return textReader(param, pairs(split("text", style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ",")));
|
|
809
|
+
}
|
|
810
|
+
function primitiveReader(param, style) {
|
|
811
|
+
if (style === "label") return textReader(param, "text", LABEL_PREFIX);
|
|
812
|
+
if (style === "matrix") return textReader(param, "text", MATRIX_PREFIX);
|
|
813
|
+
}
|
|
814
|
+
/** What reads a parameter's text in `style` into the value its schema describes. */
|
|
815
|
+
function styleReader(param, schema, style, explode) {
|
|
816
|
+
if (hasType(schema, "array") || schema.items !== void 0 || schema.prefixItems !== void 0) return arrayReader(param, style, explode);
|
|
817
|
+
if (hasType(schema, "object") || schema.properties !== void 0) return objectReader(param, style, explode);
|
|
818
|
+
return primitiveReader(param, style);
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* The readers of a parameter's serialization, outermost first: the `allowEmptyValue`
|
|
822
|
+
* reader, then the one for a JSON `content` or the parameter's `style` / `explode`. Each
|
|
823
|
+
* is the source of an arrow over `param`, the name the target library gives a predicate's
|
|
824
|
+
* input.
|
|
825
|
+
*/
|
|
826
|
+
function parameterReaders(schema, options, param) {
|
|
827
|
+
const style = options?.style ?? defaultStyle(options?.paramIn);
|
|
828
|
+
const reader = isJsonMediaType(options?.contentType) ? jsonReader(param) : style === void 0 ? void 0 : styleReader(param, schema, style, options?.explode ?? style === "form");
|
|
829
|
+
return [options?.allowEmptyValue === true ? emptyValueReader(param) : void 0, reader].filter((step) => step !== void 0);
|
|
830
|
+
}
|
|
831
|
+
//#endregion
|
|
832
|
+
//#region src/helper/ref.ts
|
|
833
|
+
/**
|
|
834
|
+
* Resolves a `$ref` for the Zod, Valibot and Effect generators, which name declarations
|
|
835
|
+
* alike: a definition is `Name` inside a document (`isDocument`), `NameSchema` when a
|
|
836
|
+
* single schema is emitted under the default root name, and a thunk everywhere else.
|
|
837
|
+
*/
|
|
838
|
+
function refTarget(ref, rootName, isDocument, openapi) {
|
|
839
|
+
if (isRootRef(ref)) return {
|
|
840
|
+
kind: "lazy",
|
|
841
|
+
name: rootName
|
|
842
|
+
};
|
|
843
|
+
if (isDeepLocalPointer(ref)) return { kind: "unknown" };
|
|
844
|
+
if (openapi) {
|
|
845
|
+
const resolved = resolveOpenAPIRef(ref);
|
|
846
|
+
if (resolved) return resolved === rootName || isDocument ? {
|
|
847
|
+
kind: "lazy",
|
|
848
|
+
name: resolved
|
|
849
|
+
} : {
|
|
850
|
+
kind: "value",
|
|
851
|
+
name: resolved
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
const toName = schemaNamer(openapi);
|
|
855
|
+
const declared = (name) => {
|
|
856
|
+
if (name === rootName || isDocument) return {
|
|
857
|
+
kind: "lazy",
|
|
858
|
+
name
|
|
859
|
+
};
|
|
860
|
+
if (rootName === "Schema") return {
|
|
861
|
+
kind: "value",
|
|
862
|
+
name: `${name}Schema`
|
|
863
|
+
};
|
|
864
|
+
return {
|
|
865
|
+
kind: "lazy",
|
|
866
|
+
name
|
|
867
|
+
};
|
|
868
|
+
};
|
|
869
|
+
for (const prefix of DEFINITION_REF_PREFIXES) if (ref.startsWith(prefix)) return declared(toName(ref.slice(prefix.length)));
|
|
870
|
+
if (ref.startsWith("#")) {
|
|
871
|
+
const refName = ref.slice(1);
|
|
872
|
+
return refName === "" ? {
|
|
873
|
+
kind: "lazy",
|
|
874
|
+
name: rootName
|
|
875
|
+
} : declared(toName(refName));
|
|
876
|
+
}
|
|
877
|
+
if (ref.includes("#")) return { kind: "unknown" };
|
|
878
|
+
if (ref.startsWith("http")) {
|
|
879
|
+
const last = ref.split("/").at(-1);
|
|
880
|
+
if (last) return {
|
|
881
|
+
kind: "value",
|
|
882
|
+
name: last.replace(/\.json$/, "")
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
return { kind: "any" };
|
|
886
|
+
}
|
|
887
|
+
//#endregion
|
|
888
|
+
//#region src/helper/regex.ts
|
|
889
|
+
/**
|
|
890
|
+
* Build a JavaScript regular-expression literal from a JSON Schema `pattern`.
|
|
891
|
+
*
|
|
892
|
+
* Escapes unescaped `/` so the literal stays delimited, and adds the `u` flag
|
|
893
|
+
* when the pattern uses Unicode property escapes (`\p{...}`, `\P{...}`,
|
|
894
|
+
* `\u{...}`), which TypeScript requires for those constructs (TS1530). Returns
|
|
895
|
+
* the literal only (`/.../` or `/.../u`); callers append any validator-specific
|
|
896
|
+
* error argument.
|
|
897
|
+
*
|
|
898
|
+
* @example
|
|
899
|
+
* ```ts
|
|
900
|
+
* regexLiteral('^[a-z]+$') // '/^[a-z]+$/'
|
|
901
|
+
* regexLiteral('^\\p{L}+$') // '/^\\p{L}+$/u'
|
|
902
|
+
* regexLiteral('a/b') // '/a\\/b/'
|
|
903
|
+
* ```
|
|
904
|
+
*/
|
|
905
|
+
function regexLiteral(pattern) {
|
|
906
|
+
return `/${pattern.replaceAll(/(?<!\\)\//gu, "\\/")}/${UNICODE_ESCAPE_PATTERN.test(pattern) ? "u" : ""}`;
|
|
907
|
+
}
|
|
908
|
+
//#endregion
|
|
909
|
+
//#region src/helper/type.ts
|
|
910
|
+
/** Whether a node is a 64-bit integer, whose number is a bigint. */
|
|
911
|
+
function isInt64(schema) {
|
|
912
|
+
return schema.format === "int64" || schema.format === "uint64";
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* The TypeScript type of a schema, as the declaration that accompanies a recursive
|
|
916
|
+
* schema (`type _Category = ...`) spells it. A `$ref` names a sibling declaration
|
|
917
|
+
* (`_Name`), the root refers to itself through `inferRoot`, and anything the type cannot
|
|
918
|
+
* say is `unknown`.
|
|
919
|
+
*/
|
|
920
|
+
function typeDeclaration(schema, flavour, rootName = DEFAULT_ROOT_NAME) {
|
|
921
|
+
if (schema === void 0) return "";
|
|
922
|
+
const type = (s) => typeDeclaration(s, flavour, rootName);
|
|
923
|
+
if (schema.$ref) {
|
|
924
|
+
if (isRootRef(schema.$ref)) return flavour.inferRoot(rootName);
|
|
925
|
+
for (const prefix of DEFINITION_REF_PREFIXES) if (schema.$ref.startsWith(prefix)) return `_${toPascalCase(schema.$ref.slice(prefix.length))}`;
|
|
926
|
+
if (schema.$ref.startsWith("#")) {
|
|
927
|
+
const refName = schema.$ref.slice(1);
|
|
928
|
+
if (refName === "") return flavour.inferRoot(rootName);
|
|
929
|
+
if (!refName.includes("/")) return `_${toPascalCase(refName)}`;
|
|
930
|
+
}
|
|
931
|
+
return "unknown";
|
|
932
|
+
}
|
|
933
|
+
if (schema.oneOf || schema.anyOf) return `(${(schema.oneOf ?? schema.anyOf ?? []).map(type).join(" | ")})`;
|
|
934
|
+
if (schema.allOf) {
|
|
935
|
+
const members = schema.allOf.filter((s) => !isShapelessMember(s)).map(type);
|
|
936
|
+
if (members.length === 0) return "unknown";
|
|
937
|
+
if (members.length === 1) return members[0];
|
|
938
|
+
return `(${members.join(" & ")})`;
|
|
939
|
+
}
|
|
940
|
+
if (schema.not) return "unknown";
|
|
941
|
+
const literal = (value) => typeof value === "number" && isInt64(schema) ? `${value}n` : jsLiteral(value);
|
|
942
|
+
if (schema.const !== void 0) return literal(schema.const);
|
|
943
|
+
if (schema.enum) {
|
|
944
|
+
if (schema.enum.length === 1) return literal(schema.enum[0]);
|
|
945
|
+
return `(${schema.enum.map(literal).join(" | ")})`;
|
|
946
|
+
}
|
|
947
|
+
const readonly = flavour.readonly ? "readonly " : "";
|
|
948
|
+
const object = () => {
|
|
949
|
+
if (!schema.properties) {
|
|
950
|
+
if (schema.additionalProperties) {
|
|
951
|
+
if (typeof schema.additionalProperties === "boolean") return schema.additionalProperties ? "{ [key: string]: unknown }" : "{ [key: string]: never }";
|
|
952
|
+
return `{ [key: string]: ${type(schema.additionalProperties)} }`;
|
|
953
|
+
}
|
|
954
|
+
return "{ [key: string]: unknown }";
|
|
955
|
+
}
|
|
956
|
+
const required = new Set(schema.required);
|
|
957
|
+
return `{${Object.entries(schema.properties).map(([key, propSchema]) => {
|
|
958
|
+
const safeKey = makeSafeKey(key);
|
|
959
|
+
const marker = required.has(key) ? "" : "?";
|
|
960
|
+
return `${readonly}${safeKey}${marker}: ${type(propSchema)}`;
|
|
961
|
+
}).join("; ")}}`;
|
|
962
|
+
};
|
|
963
|
+
if (schema.properties) return object();
|
|
964
|
+
const t = normalizeTypes(schema.type);
|
|
965
|
+
const integerType = isInt64(schema) || schema.format === "bigint" ? "bigint" : "number";
|
|
966
|
+
const primitives = [
|
|
967
|
+
t.includes("string") ? "string" : void 0,
|
|
968
|
+
t.includes("number") ? "number" : t.includes("integer") ? integerType : void 0,
|
|
969
|
+
t.includes("boolean") ? "boolean" : void 0
|
|
970
|
+
].filter((p) => p !== void 0);
|
|
971
|
+
if (primitives.length > 1 && !t.includes("array") && !t.includes("object")) return `(${primitives.join(" | ")})`;
|
|
972
|
+
if (primitives.length > 0) return primitives[0];
|
|
973
|
+
if (t.includes("array")) {
|
|
974
|
+
const items = itemsSchemaOf(schema.items);
|
|
975
|
+
return items ? `${readonly}${type(items)}[]` : `${readonly}unknown[]`;
|
|
976
|
+
}
|
|
977
|
+
if (t.includes("object")) return object();
|
|
978
|
+
if (t.includes("date")) return "Date";
|
|
979
|
+
if (t.length === 1 && t[0] === "null") return "null";
|
|
980
|
+
return "unknown";
|
|
981
|
+
}
|
|
982
|
+
//#endregion
|
|
983
|
+
//#region src/helper/typebox-wrap.ts
|
|
984
|
+
/**
|
|
985
|
+
* Wraps a TypeBox schema string with `Type.Union([..., Type.Null()])` (when nullable),
|
|
986
|
+
* `Type.Readonly()` (on `x-readonly`) and, outermost, `Type.Optional()` when a `default`
|
|
987
|
+
* is present: the modifier has to sit on the property schema itself for `Type.Object` to
|
|
988
|
+
* read the key as optional, so it goes outside the union.
|
|
989
|
+
*
|
|
990
|
+
* Metadata (`description`, `examples`, `deprecated`, `externalDocs`,
|
|
991
|
+
* `readOnly`, `writeOnly`) is NOT handled here. Each TypeBox factory call
|
|
992
|
+
* (`Type.String`, `Type.Object`, `Type.Array`, etc.) embeds metadata directly
|
|
993
|
+
* into its own options argument via {@link typeboxMetaOpts} at construction
|
|
994
|
+
* time, because TypeBox stores metadata on the schema object during
|
|
995
|
+
* construction and exposes no post-construction `.meta()` method.
|
|
996
|
+
*/
|
|
997
|
+
function typeboxWrap(typeboxStr, schema) {
|
|
998
|
+
const withNullable = isNullable(schema) ? `Type.Union([${typeboxStr},Type.Null()])` : typeboxStr;
|
|
999
|
+
const withReadonly = schema["x-readonly"] === true ? `Type.Readonly(${withNullable})` : withNullable;
|
|
1000
|
+
return hasKeptDefault(schema) ? `Type.Optional(${withReadonly})` : withReadonly;
|
|
1001
|
+
}
|
|
1002
|
+
//#endregion
|
|
1003
|
+
//#region src/helper/valibot-wrap.ts
|
|
1004
|
+
/** A default as the Valibot literal of the schema's input: a bigint for a 64-bit integer. */
|
|
1005
|
+
function defaultLiteral(schema, value, stringWire) {
|
|
1006
|
+
if (stringWire) return jsLiteral(wireDefaultValue(value));
|
|
1007
|
+
if (typeof value === "number") {
|
|
1008
|
+
if (schema.format === "int64" || schema.format === "uint64") return `${value}n`;
|
|
1009
|
+
if (schema.format === "bigint") return `BigInt(${value})`;
|
|
1010
|
+
}
|
|
1011
|
+
return jsLiteral(value);
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Wraps a Valibot schema string with `v.nullable()`, `v.optional(..., default)`,
|
|
1015
|
+
* metadata actions (`v.description()` / `v.metadata()`) and `v.brand()` based on the
|
|
1016
|
+
* JSON Schema's `default` / `nullable` / `x-brand` and OpenAPI metadata fields. All
|
|
1017
|
+
* actions are consolidated into a single outer `v.pipe(...)`.
|
|
1018
|
+
*
|
|
1019
|
+
* `v.optional(schema, default)` is the outermost of the three so that an object never
|
|
1020
|
+
* has to wrap the property again: the key is optional and its default applies whatever
|
|
1021
|
+
* the schema inside.
|
|
1022
|
+
*
|
|
1023
|
+
* Metadata mapping (Valibot v1 actions):
|
|
1024
|
+
* - `description` → `v.description(text)`
|
|
1025
|
+
* - `examples` (or `[example]`), `deprecated`, `externalDocs`, `readOnly`,
|
|
1026
|
+
* `writeOnly` → `v.metadata({ ... })`
|
|
1027
|
+
*
|
|
1028
|
+
* @see https://valibot.dev/api/metadata/
|
|
1029
|
+
* @see https://valibot.dev/api/description/
|
|
1030
|
+
*/
|
|
1031
|
+
function valibotWrap(valibotStr, schema, options) {
|
|
1032
|
+
const nullText = options?.nullText === true;
|
|
1033
|
+
const withNullable = isNullable(schema) || nullText && !isNullMatchedFirst(schema) ? `v.nullable(${valibotStr})` : valibotStr;
|
|
1034
|
+
const withNullText = nullText ? `v.pipe(v.unknown(),v.transform(${wireNullText("input")}),${withNullable})` : withNullable;
|
|
1035
|
+
const defaultResult = schema.default !== void 0 ? coerceDefault(schema, schema.default) : void 0;
|
|
1036
|
+
const withDefault = defaultResult?.keep ? `v.optional(${withNullText},${defaultLiteral(schema, defaultResult.value, options?.stringWire === true)})` : withNullText;
|
|
1037
|
+
const examples = examplesOf(schema);
|
|
1038
|
+
const actions = [];
|
|
1039
|
+
if (schema.description !== void 0) actions.push(`v.description(${JSON.stringify(schema.description)})`);
|
|
1040
|
+
const metaObj = {};
|
|
1041
|
+
if (examples !== void 0) metaObj.examples = examples;
|
|
1042
|
+
if (schema.deprecated !== void 0) metaObj.deprecated = schema.deprecated;
|
|
1043
|
+
if (schema.externalDocs !== void 0) metaObj.externalDocs = schema.externalDocs;
|
|
1044
|
+
if (schema.readOnly !== void 0) metaObj.readOnly = schema.readOnly;
|
|
1045
|
+
if (schema.writeOnly !== void 0) metaObj.writeOnly = schema.writeOnly;
|
|
1046
|
+
if (Object.keys(metaObj).length > 0) actions.push(`v.metadata(${serializeJSValue(metaObj)})`);
|
|
1047
|
+
if (schema["x-readonly"] === true) actions.push("v.readonly()");
|
|
1048
|
+
const brand = schema["x-brand"];
|
|
1049
|
+
if (typeof brand === "string") actions.push(`v.brand("${brand}")`);
|
|
1050
|
+
const check = readCodeExtension(schema, "x-check", options);
|
|
1051
|
+
if (check) actions.push(check);
|
|
1052
|
+
const transform = readCodeExtension(schema, "x-transform", options);
|
|
1053
|
+
if (transform) actions.push(transform);
|
|
1054
|
+
const pipeExt = readCodeExtension(schema, "x-pipe", options);
|
|
1055
|
+
if (pipeExt) actions.push(pipeExt);
|
|
1056
|
+
const piped = actions.length === 0 ? withDefault : `v.pipe(${withDefault},${actions.join(",")})`;
|
|
1057
|
+
if (schema["x-fallback"] !== void 0) return `v.fallback(${piped},${jsLiteral(schema["x-fallback"])})`;
|
|
1058
|
+
return piped;
|
|
1059
|
+
}
|
|
1060
|
+
//#endregion
|
|
1061
|
+
//#region src/helper/zod-wrap.ts
|
|
1062
|
+
/**
|
|
1063
|
+
* Wraps a Zod schema string with `.default()`, `.nullable()`, `.brand<...>()`
|
|
1064
|
+
* and a single Zod v4 metadata chain (`.meta({ ... })`) based on the JSON
|
|
1065
|
+
* Schema's `default` / `nullable` / `x-brand` and OpenAPI metadata fields.
|
|
1066
|
+
*
|
|
1067
|
+
* When `options.unsafeCodeExtensions` is true, chain-term extensions
|
|
1068
|
+
* (`x-refine` / `x-transform` / `x-pipe`) are appended between brand and
|
|
1069
|
+
* meta, and the outermost extensions (`x-codec` / `x-preprocess`) replace
|
|
1070
|
+
* the final result with their raw expression value.
|
|
1071
|
+
*
|
|
1072
|
+
* @see https://zod.dev/metadata
|
|
1073
|
+
*/
|
|
1074
|
+
function zodWrap(zodStr, schema, options) {
|
|
1075
|
+
const formatLiteral = (value) => {
|
|
1076
|
+
if (typeof value === "boolean") return `${value}`;
|
|
1077
|
+
if (typeof value === "number") {
|
|
1078
|
+
if (schema.format === "int64" || schema.format === "uint64") return `${value}n`;
|
|
1079
|
+
if (schema.format === "bigint") return `BigInt(${value})`;
|
|
1080
|
+
return `${value}`;
|
|
1081
|
+
}
|
|
1082
|
+
if (schema.type === "date" && typeof value === "string") return `new Date(${JSON.stringify(value)})`;
|
|
1083
|
+
return JSON.stringify(value);
|
|
1084
|
+
};
|
|
1085
|
+
const defaultResult = schema.default !== void 0 ? coerceDefault(schema, schema.default) : void 0;
|
|
1086
|
+
const withNullable = isNullable(schema) ? `${zodStr}.nullable()` : zodStr;
|
|
1087
|
+
const withDefault = defaultResult?.keep ? `${withNullable}.default(${formatLiteral(defaultResult.value)})` : withNullable;
|
|
1088
|
+
const withReadonly = schema["x-readonly"] === true ? `${withDefault}.readonly()` : withDefault;
|
|
1089
|
+
const withPrefault = schema["x-prefault"] !== void 0 ? `${withReadonly}.prefault(${formatLiteral(schema["x-prefault"])})` : withReadonly;
|
|
1090
|
+
const withCatch = schema["x-catch"] !== void 0 ? `${withPrefault}.catch(${formatLiteral(schema["x-catch"])})` : withPrefault;
|
|
1091
|
+
const brand = schema["x-brand"];
|
|
1092
|
+
const withBrand = typeof brand === "string" ? `${withCatch}.brand<"${brand}">()` : withCatch;
|
|
1093
|
+
const refine = readCodeExtension(schema, "x-refine", options);
|
|
1094
|
+
const transform = readCodeExtension(schema, "x-transform", options);
|
|
1095
|
+
const pipe = readCodeExtension(schema, "x-pipe", options);
|
|
1096
|
+
const withRefine = refine ? `${withBrand}${refine}` : withBrand;
|
|
1097
|
+
const withTransform = transform ? `${withRefine}${transform}` : withRefine;
|
|
1098
|
+
const withPipe = pipe ? `${withTransform}${pipe}` : withTransform;
|
|
1099
|
+
const examples = examplesOf(schema);
|
|
1100
|
+
const metaObj = {};
|
|
1101
|
+
if (schema.description !== void 0) metaObj.description = schema.description;
|
|
1102
|
+
if (examples !== void 0) metaObj.examples = examples;
|
|
1103
|
+
if (schema.deprecated !== void 0) metaObj.deprecated = schema.deprecated;
|
|
1104
|
+
if (schema.externalDocs !== void 0) metaObj.externalDocs = schema.externalDocs;
|
|
1105
|
+
if (schema.readOnly !== void 0) metaObj.readOnly = schema.readOnly;
|
|
1106
|
+
if (schema.writeOnly !== void 0) metaObj.writeOnly = schema.writeOnly;
|
|
1107
|
+
const withMeta = Object.keys(metaObj).length === 0 ? withPipe : `${withPipe}.meta(${serializeJSValue(metaObj)})`;
|
|
1108
|
+
const codec = readCodeExtension(schema, "x-codec", options);
|
|
1109
|
+
const preprocess = readCodeExtension(schema, "x-preprocess", options);
|
|
1110
|
+
if (codec) return codec;
|
|
1111
|
+
if (preprocess) return preprocess;
|
|
1112
|
+
return withMeta;
|
|
1113
|
+
}
|
|
1114
|
+
//#endregion
|
|
1115
|
+
export { emitOptionsOf as A, arktypePreprocess as B, formatPattern as C, typeboxDefaultOpt as D, jsLiteral as E, schemaNamer as F, findCodeExtensionKeysInSchema as H, cyclicDefinitionNames as I, hasRootSelfReference as L, planDocument as M, renderDefinitions as N, typeboxMetaOpts as O, rootNameOf as P, isOptionalByDefault as R, wireNullText as S, timePattern as T, hasNotKeyword as U, arktypeWrap as V, ownProperties as _, regexLiteral as a, unionPrimitiveTypes as b, parameterReaders as c, effectPreprocess as d, effectWrap as f, isPrimitiveUnion as g, isNullTextRead as h, typeDeclaration as i, missingDefinitionComment as j, typeboxRefOpt as k, withoutParameterSerialization as l, isNullMatchedFirst as m, valibotWrap as n, refTarget as o, impliedWireType as p, typeboxWrap as r, hasParameterSerialization as s, zodWrap as t, notPredicate as u, stringboolPattern as v, regexSource as w, wireArrayOnce as x, stringboolTruthyPattern as y, itemsSchemaOf as z };
|