@kubb/ast 5.22.0 → 5.23.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 (155) hide show
  1. package/dist/base-IpYuh3ZP.d.cts +173 -0
  2. package/dist/base-IpYuh3ZP.d.ts +173 -0
  3. package/dist/constants-Ckeonm-D.js +141 -0
  4. package/dist/constants-Ckeonm-D.js.map +1 -0
  5. package/dist/constants-CquR083U.cjs +152 -0
  6. package/dist/constants-CquR083U.cjs.map +1 -0
  7. package/dist/factory.cjs +23 -0
  8. package/dist/factory.d.cts +4 -0
  9. package/dist/factory.d.ts +4 -0
  10. package/dist/factory.js +4 -0
  11. package/dist/file-BVqSiSvV.d.cts +624 -0
  12. package/dist/file-Cg0T6cgz.cjs +319 -0
  13. package/dist/file-Cg0T6cgz.cjs.map +1 -0
  14. package/dist/file-CnuL8oUj.js +283 -0
  15. package/dist/file-CnuL8oUj.js.map +1 -0
  16. package/dist/file-CvlMAp_d.js +131 -0
  17. package/dist/file-CvlMAp_d.js.map +1 -0
  18. package/dist/file-Dd50jPkH.cjs +142 -0
  19. package/dist/file-Dd50jPkH.cjs.map +1 -0
  20. package/dist/file-xJnBQPGq.d.ts +624 -0
  21. package/dist/file.cjs +3 -0
  22. package/dist/file.d.cts +2 -0
  23. package/dist/file.d.ts +2 -0
  24. package/dist/file.js +1 -0
  25. package/dist/graph-BcwFCvei.js +144 -0
  26. package/dist/graph-BcwFCvei.js.map +1 -0
  27. package/dist/graph-DcIY6tQb.cjs +173 -0
  28. package/dist/graph-DcIY6tQb.cjs.map +1 -0
  29. package/dist/graph.cjs +6 -0
  30. package/dist/graph.d.cts +2 -0
  31. package/dist/graph.d.ts +2 -0
  32. package/dist/graph.js +1 -0
  33. package/dist/guards-B8qDgSaT.d.cts +23 -0
  34. package/dist/guards-COVJE6TU.cjs +41 -0
  35. package/dist/guards-COVJE6TU.cjs.map +1 -0
  36. package/dist/guards-D-h9R_sV.d.ts +23 -0
  37. package/dist/guards-DlJkKsT1.js +30 -0
  38. package/dist/guards-DlJkKsT1.js.map +1 -0
  39. package/dist/http-Bm5lhVK4.cjs +12 -0
  40. package/dist/http-Bm5lhVK4.cjs.map +1 -0
  41. package/dist/http-DwboM6pK.js +7 -0
  42. package/dist/http-DwboM6pK.js.map +1 -0
  43. package/dist/http.cjs +4 -0
  44. package/dist/http.d.cts +3 -0
  45. package/dist/http.d.ts +3 -0
  46. package/dist/http.js +2 -0
  47. package/dist/index-BWd95onW.d.cts +5 -0
  48. package/dist/index-Bb1kqq8H.d.cts +20 -0
  49. package/dist/index-BngGJux5.d.cts +12 -0
  50. package/dist/index-BwnMIoLl.d.ts +24 -0
  51. package/dist/index-C-vhkzwR.d.cts +79 -0
  52. package/dist/index-CAGuKv6t.d.ts +74 -0
  53. package/dist/index-CFH4ZC7q.d.ts +44 -0
  54. package/dist/index-CIqwy4EE.d.cts +74 -0
  55. package/dist/index-Cc2K3OzU.d.cts +11 -0
  56. package/dist/index-Cc2K3OzU.d.ts +11 -0
  57. package/dist/index-Csf8xsCc.d.cts +46 -0
  58. package/dist/index-D3M2spDR.d.ts +12 -0
  59. package/dist/index-DNiIem0x.d.ts +79 -0
  60. package/dist/index-DSVef1pp.d.cts +24 -0
  61. package/dist/index-DU_jYpBt.d.cts +44 -0
  62. package/dist/index-DYDha-3I.d.cts +67 -0
  63. package/dist/index-DaHsMJ_S.d.ts +5 -0
  64. package/dist/index-Dp50LM3a.d.ts +67 -0
  65. package/dist/index-cpjUxIik.d.ts +46 -0
  66. package/dist/index-eGkM4FE9.d.ts +20 -0
  67. package/dist/index.cjs +87 -2131
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.cts +25 -2745
  70. package/dist/index.d.ts +25 -2745
  71. package/dist/index.js +40 -2052
  72. package/dist/index.js.map +1 -1
  73. package/dist/json-DH7_lcWm.js +74 -0
  74. package/dist/json-DH7_lcWm.js.map +1 -0
  75. package/dist/json-DURdtz9A.cjs +91 -0
  76. package/dist/json-DURdtz9A.cjs.map +1 -0
  77. package/dist/json.cjs +4 -0
  78. package/dist/json.d.cts +2 -0
  79. package/dist/json.d.ts +2 -0
  80. package/dist/json.js +1 -0
  81. package/dist/macro-D0KfNtff.js +104 -0
  82. package/dist/macro-D0KfNtff.js.map +1 -0
  83. package/dist/macro-DrTBT7fh.cjs +127 -0
  84. package/dist/macro-DrTBT7fh.cjs.map +1 -0
  85. package/dist/macro.cjs +4 -0
  86. package/dist/macro.d.cts +2 -0
  87. package/dist/macro.d.ts +2 -0
  88. package/dist/macro.js +1 -0
  89. package/dist/mediaType-CRjggmoG.js +19 -0
  90. package/dist/mediaType-CRjggmoG.js.map +1 -0
  91. package/dist/mediaType-D8uIO8sG.cjs +35 -0
  92. package/dist/mediaType-D8uIO8sG.cjs.map +1 -0
  93. package/dist/mediaType.cjs +4 -0
  94. package/dist/mediaType.d.cts +2 -0
  95. package/dist/mediaType.d.ts +2 -0
  96. package/dist/mediaType.js +1 -0
  97. package/dist/node-DjcETnc8.cjs +19 -0
  98. package/dist/node-DjcETnc8.cjs.map +1 -0
  99. package/dist/node-Djh-mZB2.js +14 -0
  100. package/dist/node-Djh-mZB2.js.map +1 -0
  101. package/dist/node.cjs +9 -0
  102. package/dist/node.d.cts +4 -0
  103. package/dist/node.d.ts +4 -0
  104. package/dist/node.js +5 -0
  105. package/dist/nodeText-DRb_rVd1.cjs +58 -0
  106. package/dist/nodeText-DRb_rVd1.cjs.map +1 -0
  107. package/dist/nodeText-DVVDZQjF.js +47 -0
  108. package/dist/nodeText-DVVDZQjF.js.map +1 -0
  109. package/dist/nodes-BB60Bq2H.cjs +320 -0
  110. package/dist/nodes-BB60Bq2H.cjs.map +1 -0
  111. package/dist/nodes-CWMa9xhW.js +231 -0
  112. package/dist/nodes-CWMa9xhW.js.map +1 -0
  113. package/dist/operation-BgRyVS7z.d.ts +1272 -0
  114. package/dist/operation-X7chCdL2.d.cts +1272 -0
  115. package/dist/optionality-D-zqzVMH.cjs +22 -0
  116. package/dist/optionality-D-zqzVMH.cjs.map +1 -0
  117. package/dist/optionality-DISn8ytP.js +17 -0
  118. package/dist/optionality-DISn8ytP.js.map +1 -0
  119. package/dist/promise-BOdlgT0N.cjs +50 -0
  120. package/dist/promise-BOdlgT0N.cjs.map +1 -0
  121. package/dist/promise-RpnEev9D.js +45 -0
  122. package/dist/promise-RpnEev9D.js.map +1 -0
  123. package/dist/ref-Bu7PoHar.js +22 -0
  124. package/dist/ref-Bu7PoHar.js.map +1 -0
  125. package/dist/ref-P0ZLT1Bg.cjs +39 -0
  126. package/dist/ref-P0ZLT1Bg.cjs.map +1 -0
  127. package/dist/ref.cjs +7 -0
  128. package/dist/ref.d.cts +2 -0
  129. package/dist/ref.d.ts +2 -0
  130. package/dist/ref.js +3 -0
  131. package/dist/refs-CYHpRlQo.cjs +131 -0
  132. package/dist/refs-CYHpRlQo.cjs.map +1 -0
  133. package/dist/refs-YCV3CznS.js +102 -0
  134. package/dist/refs-YCV3CznS.js.map +1 -0
  135. package/dist/rolldown-runtime-BV8xUvPy.cjs +52 -0
  136. package/dist/rolldown-runtime-BYyVTPww.js +16 -0
  137. package/dist/schema-2ZAQk7qE.js +44 -0
  138. package/dist/schema-2ZAQk7qE.js.map +1 -0
  139. package/dist/schema-BIErWqgc.cjs +214 -0
  140. package/dist/schema-BIErWqgc.cjs.map +1 -0
  141. package/dist/schema-DloctnMm.js +179 -0
  142. package/dist/schema-DloctnMm.js.map +1 -0
  143. package/dist/schema-hxMlgCrV.cjs +49 -0
  144. package/dist/schema-hxMlgCrV.cjs.map +1 -0
  145. package/dist/schema.cjs +16 -0
  146. package/dist/schema.d.cts +5 -0
  147. package/dist/schema.d.ts +5 -0
  148. package/dist/schema.js +6 -0
  149. package/dist/visitor-BZozlXBF.d.ts +179 -0
  150. package/dist/visitor-Bw_opzjF.d.cts +179 -0
  151. package/dist/visitor-DTrzvA3R.cjs +382 -0
  152. package/dist/visitor-DTrzvA3R.cjs.map +1 -0
  153. package/dist/visitor-NoQSUQTu.js +347 -0
  154. package/dist/visitor-NoQSUQTu.js.map +1 -0
  155. package/package.json +101 -1
package/dist/index.js CHANGED
@@ -1,1165 +1,20 @@
1
- import path from "node:path";
2
- import { hash } from "node:crypto";
3
- // \0rolldown/runtime.js
4
- var __defProp = Object.defineProperty;
5
- var __name = (target, value) => __defProp(target, "name", {
6
- value,
7
- configurable: true
8
- });
9
- var __exportAll = (all, flags) => {
10
- let target = Object.setPrototypeOf({}, null);
11
- for (var name in all) __defProp(target, name, {
12
- get: all[name],
13
- enumerable: true
14
- });
15
- if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
- return flags & 2 ? target : Object.preventExtensions(target);
17
- };
18
- // ../../internals/utils/src/promise.ts
19
- /**
20
- * Returns the value cached under `key` in `store`, computing and storing it on the first call.
21
- * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
22
- * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
23
- *
24
- * @example
25
- * `const refs = memo(refCache, node, () => collectRefs(node))`
26
- */
27
- function memo(store, key, compute) {
28
- const cached = store.get(key);
29
- if (cached !== void 0 || store.has(key)) return cached;
30
- const value = compute();
31
- store.set(key, value);
32
- return value;
33
- }
34
- function createStore({ weak, max } = {}) {
35
- if (weak) return /* @__PURE__ */ new WeakMap();
36
- const entry = /* @__PURE__ */ new Map();
37
- if (max === void 0) return entry;
38
- const set = (key, value) => {
39
- if (entry.size >= max) entry.clear();
40
- entry.set(key, value);
41
- };
42
- if (max !== 1) return {
43
- has: (key) => entry.has(key),
44
- get: (key) => entry.get(key),
45
- set
46
- };
47
- const touch = (key) => {
48
- if (!entry.has(key)) return false;
49
- set(key, entry.get(key));
50
- return true;
51
- };
52
- return {
53
- has: touch,
54
- get: (key) => touch(key) ? entry.get(key) : void 0,
55
- set
56
- };
57
- }
58
- memo.create = createStore;
59
- // src/constants.ts
60
- /**
61
- * Node kind discriminators used by every AST node (for example `node.kind === nodeKinds.text`).
62
- */
63
- const nodeKinds$1 = {
64
- input: "Input",
65
- operation: "Operation",
66
- schema: "Schema",
67
- property: "Property",
68
- parameter: "Parameter",
69
- response: "Response",
70
- requestBody: "RequestBody",
71
- content: "Content",
72
- type: "Type",
73
- file: "File",
74
- import: "Import",
75
- export: "Export",
76
- source: "Source",
77
- const: "Const",
78
- function: "Function",
79
- arrowFunction: "ArrowFunction",
80
- text: "Text",
81
- break: "Break",
82
- jsx: "Jsx"
83
- };
84
- /**
85
- * Schema type discriminators used by all AST schema nodes.
86
- *
87
- * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
88
- */
89
- const schemaTypes$1 = {
90
- /**
91
- * Text value.
92
- */
93
- string: "string",
94
- /**
95
- * Floating-point number (`float`, `double`).
96
- */
97
- number: "number",
98
- /**
99
- * Whole number (`int32`). Use `bigint` for `int64`.
100
- */
101
- integer: "integer",
102
- /**
103
- * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
104
- */
105
- bigint: "bigint",
106
- /**
107
- * Boolean value.
108
- */
109
- boolean: "boolean",
110
- /**
111
- * Explicit null value.
112
- */
113
- null: "null",
114
- /**
115
- * Any value (no type restriction).
116
- */
117
- any: "any",
118
- /**
119
- * Unknown value (must be narrowed before usage).
120
- */
121
- unknown: "unknown",
122
- /**
123
- * No return value (`void`).
124
- */
125
- void: "void",
126
- /**
127
- * Object with named properties.
128
- */
129
- object: "object",
130
- /**
131
- * Sequential list of items.
132
- */
133
- array: "array",
134
- /**
135
- * Fixed-length list with position-specific items.
136
- */
137
- tuple: "tuple",
138
- /**
139
- * "One of" multiple schema members.
140
- */
141
- union: "union",
142
- /**
143
- * "All of" multiple schema members.
144
- */
145
- intersection: "intersection",
146
- /** "Not" a single schema member. */
147
- not: "not",
148
- /**
149
- * Enum schema.
150
- */
151
- enum: "enum",
152
- /**
153
- * Reference to another schema.
154
- */
155
- ref: "ref",
156
- /**
157
- * Calendar date (for example `2026-03-24`).
158
- */
159
- date: "date",
160
- /**
161
- * Date-time value (for example `2026-03-24T09:00:00Z`).
162
- */
163
- datetime: "datetime",
164
- /**
165
- * Time-only value (for example `09:00:00`).
166
- */
167
- time: "time",
168
- /**
169
- * UUID value.
170
- */
171
- uuid: "uuid",
172
- /**
173
- * Email address value.
174
- */
175
- email: "email",
176
- /**
177
- * URL value.
178
- */
179
- url: "url",
180
- /**
181
- * IPv4 address value.
182
- */
183
- ipv4: "ipv4",
184
- /**
185
- * IPv6 address value.
186
- */
187
- ipv6: "ipv6",
188
- /**
189
- * Binary/blob value.
190
- */
191
- blob: "blob",
192
- /**
193
- * Impossible value (`never`).
194
- */
195
- never: "never"
196
- };
197
- // src/mediaType/index.ts
198
- var mediaType_exports = /* @__PURE__ */ __exportAll({
199
- getBase: () => getBase,
200
- isJson: () => isJson,
201
- isStream: () => isStream
202
- });
203
- const jsonMediaTypes = /* @__PURE__ */ new Set(["application/json", "text/json"]);
204
- const streamMediaTypes = /* @__PURE__ */ new Set([
205
- "application/jsonl",
206
- "application/x-ndjson",
207
- "application/json-seq",
208
- "text/event-stream"
209
- ]);
210
- /** The media type without its parameters, in lower case: `Text/Plain; charset=utf-8` gives `text/plain`. */
211
- function getBase(mediaType) {
212
- return (typeof mediaType === "string" ? mediaType : mediaType.contentType).split(";")[0].trim().toLowerCase();
213
- }
214
- /** Whether the media type is `application/json`, `text/json`, or has a `+json` suffix. */
215
- function isJson(mediaType) {
216
- const baseType = getBase(mediaType);
217
- return jsonMediaTypes.has(baseType) || baseType.endsWith("+json");
218
- }
219
- /** Whether the media type is a stream of items: SSE, JSON Lines, or a `+json-seq` sequence. */
220
- function isStream(mediaType) {
221
- const baseType = getBase(mediaType);
222
- return streamMediaTypes.has(baseType) || baseType.startsWith("application/") && baseType.endsWith("+json-seq");
223
- }
224
- // src/schema/embeddedJson.ts
225
- /** The schema of the JSON document a string holds (`contentMediaType` with `contentSchema`), else `undefined`. */
226
- function getEmbeddedJson({ content }) {
227
- if (!content?.schema || content.encoding || !content.mediaType) return void 0;
228
- return isJson(content.mediaType) ? content.schema : void 0;
229
- }
230
- // src/visitor.ts
231
- /**
232
- * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
233
- */
234
- const VISITOR_KEYS = {
235
- Input: ["schemas", "operations"],
236
- Operation: [
237
- "parameters",
238
- "requestBody",
239
- "responses"
240
- ],
241
- RequestBody: ["content"],
242
- Content: ["schema", "stream"],
243
- Response: ["content", "headers"],
244
- Schema: [
245
- "properties",
246
- "items",
247
- "members",
248
- "additionalProperties",
249
- "patternProperties",
250
- "propertyNames",
251
- "rest"
252
- ],
253
- Property: ["schema"],
254
- Parameter: ["schema"]
255
- };
256
- /**
257
- * Schema fields that hold checks rather than shape: the `conditionals` entries, `contains` and a string's `content`.
258
- * `transform` and `collect` skip them, and `visitChildNodes` walks them with `checks: true`.
259
- */
260
- const schemaCheckKeys = [
261
- "conditionals",
262
- "contains",
263
- "content"
264
- ];
265
- /** Visitor callback names in traversal order, the keys of {@link Visitor}. */
266
- const visitorKeys = [
267
- "input",
268
- "operation",
269
- "schema",
270
- "property",
271
- "parameter",
272
- "response"
273
- ];
274
- /**
275
- * Maps a node kind to the matching visitor callback name.
276
- */
277
- const VISITOR_KEY_BY_KIND = {
278
- Input: "input",
279
- Operation: "operation",
280
- Schema: "schema",
281
- Property: "property",
282
- Parameter: "parameter",
283
- Response: "response"
284
- };
285
- /**
286
- * Returns `true` when `value` is an AST node (an object carrying a `kind`).
287
- */
288
- function isNode(value) {
289
- return typeof value === "object" && value !== null && typeof value.kind === "string";
290
- }
291
- /**
292
- * Returns `true` for a plain object that maps names to nodes, such as `patternProperties`.
293
- */
294
- function isNodeRecord(value) {
295
- return typeof value === "object" && value !== null && !Array.isArray(value);
296
- }
297
- function isNeverPrinted({ node, key }) {
298
- if (node.kind !== nodeKinds$1.schema) return false;
299
- if (key === "contains" && (node.type === "array" || node.type === "tuple")) return node.contains?.min === 0 && node.contains.max === void 0;
300
- if (key === "content" && node.type === "string") return !getEmbeddedJson(node);
301
- return false;
302
- }
303
- /**
304
- * Child keys of a schema walked with `checks: true`: the shape keys, then {@link schemaCheckKeys}.
305
- */
306
- const SCHEMA_CHECK_VISITOR_KEYS = [...VISITOR_KEYS.Schema, ...schemaCheckKeys];
307
- function visitOnce(child, seen, visit) {
308
- if (seen.first === void 0) {
309
- seen.first = child;
310
- return visit(child);
311
- }
312
- if (seen.first === child || seen.rest?.has(child)) return false;
313
- (seen.rest ??= /* @__PURE__ */ new Set()).add(child);
314
- return visit(child);
315
- }
316
- function visitRecord(value, seen, visit) {
317
- for (const name in value) {
318
- if (!Object.hasOwn(value, name)) continue;
319
- const item = value[name];
320
- if (isNode(item) && visitOnce(item, seen, visit)) return true;
321
- }
322
- return false;
323
- }
324
- /**
325
- * Calls `visit` for each direct child node and stops at the first call that returns `true`.
326
- * With `checks: true`, a schema's {@link schemaCheckKeys} fields are walked too, except checks that cannot fail.
327
- */
328
- function visitChildNodes(node, visit, { checks = false } = {}) {
329
- const withChecks = checks && node.kind === nodeKinds$1.schema;
330
- const keys = withChecks ? SCHEMA_CHECK_VISITOR_KEYS : VISITOR_KEYS[node.kind];
331
- if (!keys) return false;
332
- const record = node;
333
- let seen;
334
- for (const key of keys) {
335
- const value = record[key];
336
- if (value === void 0 || value === null) continue;
337
- if (withChecks && isNeverPrinted({
338
- node,
339
- key
340
- })) continue;
341
- seen ??= {
342
- first: void 0,
343
- rest: void 0
344
- };
345
- if (Array.isArray(value)) {
346
- for (const item of value) if (isNode(item) ? visitOnce(item, seen, visit) : isNodeRecord(item) && visitRecord(item, seen, visit)) return true;
347
- continue;
348
- }
349
- if (isNode(value)) {
350
- if (visitOnce(value, seen, visit)) return true;
351
- continue;
352
- }
353
- if (isNodeRecord(value) && visitRecord(value, seen, visit)) return true;
354
- }
355
- return false;
356
- }
357
- const notFound = {
358
- found: void 0,
359
- low: Number.POSITIVE_INFINITY
360
- };
361
- /**
362
- * Finds the first schema that matches `predicate` in depth-first order. Set `followRefs` to include resolved ref targets.
363
- *
364
- * @example
365
- * ```ts
366
- * const firstString = findSchema(operationNode, {
367
- * predicate: (schema) => schema.type === 'string',
368
- * })
369
- * ```
370
- */
371
- function findSchema$1(node, { predicate, followRefs = false, cache }) {
372
- const state = followRefs ? /* @__PURE__ */ new Map() : void 0;
373
- const pending = [];
374
- let order = 0;
375
- const walkChildren = (current, initial) => {
376
- let result = initial;
377
- visitChildNodes(current, (child) => {
378
- const next = walk(child);
379
- result = next.found || next.low < result.low ? next : result;
380
- return next.found !== void 0;
381
- });
382
- return result;
383
- };
384
- const walkSchema = (current) => {
385
- const target = state && current.type === "ref" && current.schema ? walk(current.schema) : notFound;
386
- if (target.found) return target;
387
- return walkChildren(current, target);
388
- };
389
- const walk = (current) => {
390
- if (current.kind !== nodeKinds$1.schema) return walkChildren(current, notFound);
391
- const cached = cache?.get(current);
392
- if (cached === null) return notFound;
393
- if (cached) return {
394
- found: cached,
395
- low: Number.POSITIVE_INFINITY
396
- };
397
- if (predicate(current)) {
398
- cache?.set(current, current);
399
- return {
400
- found: current,
401
- low: Number.POSITIVE_INFINITY
402
- };
403
- }
404
- const known = state?.get(current);
405
- if (known !== void 0) return {
406
- found: void 0,
407
- low: known
408
- };
409
- const index = order++;
410
- const start = pending.length;
411
- state?.set(current, index);
412
- const result = walkSchema(current);
413
- if (result.found) {
414
- cache?.set(current, result.found);
415
- return result;
416
- }
417
- if (!state) {
418
- cache?.set(current, null);
419
- return notFound;
420
- }
421
- if (result.low < index) {
422
- state.set(current, result.low);
423
- pending.push(current);
424
- return result;
425
- }
426
- for (const done of [...pending.splice(start), current]) {
427
- state.set(done, Number.POSITIVE_INFINITY);
428
- cache?.set(done, null);
429
- }
430
- return notFound;
431
- };
432
- return walk(node).found;
433
- }
434
- __name(findSchema$1, "findSchema");
435
- /**
436
- * Runs the visitor callback that matches `node.kind` with the traversal
437
- * context. The result is a replacement node, a collected value, or `undefined`
438
- * when no callback is registered for the kind.
439
- *
440
- * Shared by `transform` and `collect` so node-kind dispatch lives in one place.
441
- * `TResult` is the caller's expected return: the same node type for `transform`,
442
- * the collected value type for `collect`.
443
- */
444
- function applyVisitor(node, visitor, parent) {
445
- const key = VISITOR_KEY_BY_KIND[node.kind];
446
- if (!key) return void 0;
447
- const fn = visitor[key];
448
- return fn?.(node, { parent });
449
- }
450
- /**
451
- * Synchronous depth-first transform. Each visitor callback can return a
452
- * replacement node. Returning `undefined` keeps the original.
453
- *
454
- * The original tree is never mutated, a new tree is returned. Pass
455
- * `depth: 'shallow'` to skip recursion into children.
456
- *
457
- * @example Prefix every operationId
458
- * ```ts
459
- * const next = transform(root, {
460
- * operation(node) {
461
- * return { ...node, operationId: `prefixed_${node.operationId}` }
462
- * },
463
- * })
464
- * ```
465
- *
466
- * @example Replace only the root node
467
- * ```ts
468
- * const next = transform(root, {
469
- * depth: 'shallow',
470
- * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),
471
- * })
472
- * ```
473
- */
474
- function transform$1(node, options) {
475
- const { depth, parent, ...visitor } = options;
476
- return transformNode(node, visitor, (depth ?? "deep") === "deep", parent);
477
- }
478
- __name(transform$1, "transform");
479
- /**
480
- * Visits a single node, then immutably rebuilds its children. Returns the original
481
- * reference when neither the visitor nor the child rebuild changed anything, so callers
482
- * can detect "nothing changed" by identity and ancestors avoid reallocating.
483
- */
484
- function transformNode(node, visitor, recurse, parent) {
485
- return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
486
- }
487
- /**
488
- * Immutably rebuilds a node's children, transforming each child node and leaving non-node values
489
- * (e.g. `additionalProperties: true`) intact.
490
- */
491
- function transformChildren(node, visitor, recurse) {
492
- const keys = node.kind === nodeKinds$1.schema && !recurse ? void 0 : VISITOR_KEYS[node.kind];
493
- if (!keys) return node;
494
- const record = node;
495
- let updates;
496
- let done;
497
- const transformOnce = (child) => {
498
- done ??= /* @__PURE__ */ new Map();
499
- const next = done.get(child) ?? transformNode(child, visitor, recurse, node);
500
- done.set(child, next);
501
- return next;
502
- };
503
- for (const key of keys) {
504
- const value = record[key];
505
- if (value === void 0 || value === null) continue;
506
- if (Array.isArray(value)) {
507
- let mapped;
508
- for (const [i, item] of value.entries()) {
509
- const next = isNode(item) ? transformOnce(item) : item;
510
- if (mapped) {
511
- mapped.push(next);
512
- continue;
513
- }
514
- if (next !== item) mapped = [...value.slice(0, i), next];
515
- }
516
- if (mapped) (updates ??= {})[key] = mapped;
517
- continue;
518
- }
519
- if (isNode(value)) {
520
- const next = transformOnce(value);
521
- if (next !== value) (updates ??= {})[key] = next;
522
- continue;
523
- }
524
- if (isNodeRecord(value)) {
525
- let mapped;
526
- for (const [name, item] of Object.entries(value)) {
527
- const next = isNode(item) ? transformOnce(item) : item;
528
- if (next !== item) (mapped ??= { ...value })[name] = next;
529
- }
530
- if (mapped) (updates ??= {})[key] = mapped;
531
- }
532
- }
533
- if (!updates) return node;
534
- return {
535
- ...node,
536
- ...updates
537
- };
538
- }
539
- /**
540
- * Depth-first collection pass. Gathers every non-null value the visitor
541
- * callbacks return into an array.
542
- *
543
- * @example Collect every operationId
544
- * ```ts
545
- * const ids = collect<string>(root, {
546
- * operation(node) {
547
- * return node.operationId
548
- * },
549
- * })
550
- * ```
551
- */
552
- function collect$1(node, options) {
553
- const { depth, parent, ...visitor } = options;
554
- const result = [];
555
- collectInto(node, visitor, (depth ?? "deep") === "deep", parent, result);
556
- return result;
557
- }
558
- __name(collect$1, "collect");
559
- function collectInto(node, visitor, recurse, parent, result) {
560
- const v = applyVisitor(node, visitor, parent);
561
- if (v != null) result.push(v);
562
- if (node.kind === nodeKinds$1.schema && !recurse) return;
563
- visitChildNodes(node, (child) => {
564
- collectInto(child, visitor, recurse, node, result);
565
- return false;
566
- });
567
- }
568
- // src/utils/refs.ts
569
- /**
570
- * Returns the last segment of a `$ref` pointer, for example `'Pet'` for `#/components/schemas/Pet`.
571
- * The segment is decoded like the pointer resolver does: percent-escapes first, then `~1` and `~0`
572
- * (RFC 6901), so `a~1b~0c` names the component `a/b~c`.
573
- */
574
- function refName$1(ref) {
575
- return memo(refNames, ref, () => {
576
- const segment = ref.split("/").at(-1) ?? ref;
577
- let decoded = segment;
578
- try {
579
- decoded = decodeURIComponent(segment);
580
- } catch {}
581
- return decoded.replaceAll("~1", "/").replaceAll("~0", "~");
582
- });
583
- }
584
- __name(refName$1, "refName");
585
- const refNames = memo.create({ max: 1e5 });
586
- /**
587
- * Resolves the emitted name of the schema a ref node points at. Prefers `targetName` (set when
588
- * the referenced schema was renamed, e.g. to break a collision), then the last segment of `ref`,
589
- * then `name`, then the nested `schema.name`.
590
- *
591
- * Returns `null` for non-ref nodes or when no name resolves.
592
- *
593
- * @example
594
- * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
595
- *
596
- * @example Collision-renamed target
597
- * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Order', targetName: 'OrderSchema' }) // 'OrderSchema'`
598
- */
599
- function resolveRefName$1(node) {
600
- if (!node || node.type !== "ref") return null;
601
- if (node.targetName) return node.targetName;
602
- if (node.ref) return refName$1(node.ref);
603
- return node.name ?? node.schema?.name ?? null;
604
- }
605
- __name(resolveRefName$1, "resolveRefName");
606
- /**
607
- * Follows a resolved ref chain to its target schema. Returns an unresolved or cyclic ref as is.
608
- *
609
- * @example
610
- * ```ts
611
- * const target = resolveRef(refSchema)
612
- * ```
613
- */
614
- function resolveRef$1(node) {
615
- if (node.type !== "ref" || !node.schema) return node;
616
- const seen = /* @__PURE__ */ new WeakSet();
617
- let current = node;
618
- while (current.type === "ref" && current.schema) {
619
- if (seen.has(current)) return current;
620
- seen.add(current);
621
- current = current.schema;
622
- }
623
- return current;
624
- }
625
- __name(resolveRef$1, "resolveRef");
626
- /** Fields of a ref node that describe the ref itself, so they never override the resolved schema. */
627
- const REF_OWN_KEYS = /* @__PURE__ */ new Set([
628
- "kind",
629
- "type",
630
- "name",
631
- "ref",
632
- "schema"
633
- ]);
634
- /**
635
- * Merges a ref node with its resolved schema, giving the fields set at the usage site precedence.
636
- *
637
- * Every field on the ref except `kind`, `type`, `name`, `ref`, and `schema` overrides the same field
638
- * of the resolved `schema` (for example `description`, `nullable`, `readOnly`, `deprecated`). Fields
639
- * left `undefined` on the ref do not shadow the resolved schema. A ref without a resolved `schema`
640
- * is returned as is.
641
- *
642
- * @example
643
- * ```ts
644
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A pet', schema: petSchema })
645
- * mergeRefWithSchema(ref) // petSchema's fields with description 'A pet'
646
- * ```
647
- */
648
- function mergeRefWithSchema$1(node) {
649
- if (!node.schema) return node;
650
- const merged = { ...node.schema };
651
- for (const key of Object.keys(node)) {
652
- const value = node[key];
653
- if (value !== void 0 && !REF_OWN_KEYS.has(key)) merged[key] = value;
654
- }
655
- return merged;
656
- }
657
- __name(mergeRefWithSchema$1, "mergeRefWithSchema");
658
- /**
659
- * Returns `true` when a schema is a bare ref without modifiers, metadata, or omit keys.
660
- *
661
- * Modifiers inherited from the resolved schema are included in the check because a ref emits the
662
- * referenced schema variable with those modifiers already applied.
663
- */
664
- function isBareRef$1(node, keysToOmit) {
665
- if (!node || node.type !== "ref") return false;
666
- const meta = mergeRefWithSchema$1(node);
667
- return !meta.nullable && !meta.optional && !meta.nullish && meta.default === void 0 && !meta.description && !meta.examples?.length && !keysToOmit?.length;
668
- }
669
- __name(isBareRef$1, "isBareRef");
670
- // src/utils/schemaGraph.ts
671
- const refEntries = memo.create({ weak: true });
672
- const checkRefEntries = memo.create({ weak: true });
673
- const schemaRefs = memo.create({ weak: true });
674
- const importedRefNames = memo.create({ weak: true });
675
- const importedCheckRefNames = memo.create({ weak: true });
676
- /**
677
- * Walks a node's subtree once and lists every ref it holds, in traversal order, as the resolved
678
- * name plus whether the ref carries a `$ref` pointer. Memoized per node and per `checks` mode, so
679
- * each helper below scans a schema once.
680
- */
681
- function collectRefEntries(node, { checks }) {
682
- return memo(checks ? checkRefEntries : refEntries, node, () => {
683
- const entries = [];
684
- const walk = (current) => {
685
- if (current.kind === nodeKinds$1.schema && current.type === "ref") {
686
- const name = resolveRefName$1(current);
687
- if (name) entries.push({
688
- name,
689
- hasPointer: Boolean(current.ref)
690
- });
691
- }
692
- visitChildNodes(current, walk, { checks });
693
- return false;
694
- };
695
- walk(node);
696
- return entries;
697
- });
698
- }
699
- /**
700
- * Collects the names of every schema a node's subtree references, resolved with `ast.ref.getName`.
701
- * Each ref contributes its name only, so the schema it points to is never traversed. Memoized by
702
- * node identity, which lets `findCircularSchemas` and `ast.graph.containsCircular` share one scan per schema.
703
- *
704
- * @example
705
- * ```ts
706
- * collectSchemaRefs(petSchema)
707
- * // Set { 'Category', 'Tag' }
708
- * ```
709
- */
710
- function collectSchemaRefs$1(node) {
711
- return memo(schemaRefs, node, () => new Set(collectRefEntries(node, { checks: true }).map((entry) => entry.name)));
712
- }
713
- __name(collectSchemaRefs$1, "collectSchemaRefs");
714
- /**
715
- * Collects the de-duplicated target names of every pointer-carrying ref in a node's subtree, in
716
- * first-occurrence order. Memoized by node identity, so `resolver.imports` reads the same result
717
- * across the ts, zod, and faker plugins instead of re-scanning the same schema per plugin.
718
- *
719
- * Only refs that carry a `$ref` pointer count, so a synthesized ref pointing at a sibling in the
720
- * same file (a union member created by name) is left out. That leaves exactly the set
721
- * `resolver.imports` emits. Refs inside `conditionals`, `contains` and `content` count only with
722
- * `checks: true`, for a plugin that prints those checks.
723
- *
724
- * @example
725
- * ```ts
726
- * collectImportedRefNames(petSchema)
727
- * // ['Category', 'Tag']
728
- * ```
729
- */
730
- function collectImportedRefNames$1(node, { checks = false } = {}) {
731
- return memo(checks ? importedCheckRefNames : importedRefNames, node, () => [...new Set(collectRefEntries(node, { checks }).flatMap((entry) => entry.hasPointer ? [entry.name] : []))]);
732
- }
733
- __name(collectImportedRefNames$1, "collectImportedRefNames");
734
- /**
735
- * Collects the names of all top-level schemas transitively used by a set of operations.
736
- *
737
- * An operation uses a schema when its parameters, request body, or responses reference it, directly
738
- * or through other named schemas. Once a name is added to the result it is not revisited, so
739
- * reference cycles terminate.
740
- *
741
- * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
742
- *
743
- * @example Only generate schemas referenced by included operations
744
- * ```ts
745
- * const includedOps = operations.filter((op) => resolver.default.options(op, { options, include }) !== null)
746
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
747
- *
748
- * for (const schema of schemas) {
749
- * if (schema.name && !allowed.has(schema.name)) continue
750
- * // generate schema
751
- * }
752
- * ```
753
- */
754
- function collectUsedSchemaNames$1(operations, schemas) {
755
- const schemaMap = /* @__PURE__ */ new Map();
756
- for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
757
- const result = /* @__PURE__ */ new Set();
758
- function visitSchema(schema) {
759
- for (const name of collectSchemaRefs$1(schema)) if (!result.has(name)) {
760
- result.add(name);
761
- const namedSchema = schemaMap.get(name);
762
- if (namedSchema) visitSchema(namedSchema);
763
- }
764
- }
765
- for (const op of operations) for (const schema of collect$1(op, {
766
- depth: "shallow",
767
- schema: (node) => node
768
- })) visitSchema(schema);
769
- return result;
770
- }
771
- __name(collectUsedSchemaNames$1, "collectUsedSchemaNames");
772
- /**
773
- * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
774
- *
775
- * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
776
- * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
777
- * linear in the size of the schema graph.
778
- *
779
- * @note Call this once on the full graph, then check individual schemas with `ast.graph.containsCircular()`.
780
- */
781
- function findCircularSchemas$1(schemas) {
782
- const graph = /* @__PURE__ */ new Map();
783
- for (const schema of schemas) if (schema.name) graph.set(schema.name, collectSchemaRefs$1(schema));
784
- const circular = /* @__PURE__ */ new Set();
785
- for (const start of graph.keys()) {
786
- const visited = /* @__PURE__ */ new Set();
787
- const stack = [...graph.get(start) ?? []];
788
- while (stack.length > 0) {
789
- const node = stack.pop();
790
- if (node === start) {
791
- circular.add(start);
792
- break;
793
- }
794
- if (visited.has(node)) continue;
795
- visited.add(node);
796
- const next = graph.get(node);
797
- if (next) for (const r of next) stack.push(r);
798
- }
799
- }
800
- return circular;
801
- }
802
- __name(findCircularSchemas$1, "findCircularSchemas");
803
- // src/graph/index.ts
804
- var graph_exports = /* @__PURE__ */ __exportAll({
805
- containsCircular: () => containsCircular,
806
- getCircularNames: () => findCircularSchemas$1,
807
- getImportedNames: () => collectImportedRefNames$1,
808
- getRefNames: () => collectSchemaRefs$1,
809
- getUsedNames: () => collectUsedSchemaNames$1
810
- });
811
- /** Whether a schema, or anything inside it, refers to one of `circularSchemas`, other than `excludeName`. */
812
- function containsCircular(node, { circularSchemas, excludeName }) {
813
- if (!node || circularSchemas.size === 0) return false;
814
- for (const name of collectSchemaRefs$1(node)) if (name !== excludeName && circularSchemas.has(name)) return true;
815
- return false;
816
- }
817
- // src/guards.ts
818
- /**
819
- * Narrows a `SchemaNode` to the variant that matches `type`.
820
- *
821
- * @example
822
- * ```ts
823
- * const schema = createSchema({ type: 'string' })
824
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
825
- * ```
826
- */
827
- function narrowSchema$1(node, type) {
828
- return node?.type === type ? node : null;
829
- }
830
- __name(narrowSchema$1, "narrowSchema");
831
- /**
832
- * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
833
- *
834
- * @example
835
- * ```ts
836
- * if (ast.http.isOperation(node)) {
837
- * console.log(node.method, node.path)
838
- * }
839
- * ```
840
- */
841
- function isHttpOperationNode$1(node) {
842
- return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
843
- }
844
- __name(isHttpOperationNode$1, "isHttpOperationNode");
845
- // src/http/requestBody.ts
846
- var requestBody_exports = /* @__PURE__ */ __exportAll({ getSchema: () => getSchema });
847
- /** The schema of the first request body entry, else `undefined` when the operation takes no body. */
848
- function getSchema(node) {
849
- return node.requestBody?.content?.[0]?.schema;
850
- }
851
- // src/http/status.ts
852
- var status_exports = /* @__PURE__ */ __exportAll({
853
- getClass: () => statusClass,
854
- isError: () => isError,
855
- isSuccess: () => isSuccess,
856
- toCode: () => toCode
857
- });
858
- const classByRange = /* @__PURE__ */ new Map([
859
- ["1xx", 1],
860
- ["2xx", 2],
861
- ["3xx", 3],
862
- ["4xx", 4],
863
- ["5xx", 5]
864
- ]);
865
- /** The class digit of a status code or range: `2` for `201` and `2xx`, `null` for `default`. */
866
- function statusClass(input) {
867
- const statusCode = typeof input === "object" ? input.statusCode : input;
868
- const rangeClass = classByRange.get(String(statusCode));
869
- if (rangeClass) return rangeClass;
870
- const code = Number(statusCode);
871
- return Number.isNaN(code) ? null : Math.floor(code / 100);
872
- }
873
- function isSuccess(statusCode) {
874
- return statusClass(statusCode) === 2;
875
- }
876
- function isError(statusCode) {
877
- const code = statusClass(statusCode);
878
- return code !== null && code >= 4;
879
- }
880
- /** One concrete code for a status or range: `200` for `2xx` and `default`, the code itself otherwise. */
881
- function toCode(input) {
882
- const statusCode = typeof input === "object" ? input.statusCode : input;
883
- const code = Number(statusCode);
884
- return Number.isNaN(code) ? (statusClass(statusCode) ?? 2) * 100 : code;
885
- }
886
- // src/http/responses.ts
887
- var responses_exports = /* @__PURE__ */ __exportAll({
888
- filterError: () => filterError,
889
- filterSuccess: () => filterSuccess,
890
- findPrimary: () => findPrimary,
891
- getImportedNames: () => getImportedNames
892
- });
893
- /** The `4xx` and `5xx` responses, ranges included. */
894
- function filterError(node) {
895
- return node.responses.filter((response) => isError(response.statusCode));
896
- }
897
- /** The ref names the response bodies import, in order, with repeats. */
898
- function getImportedNames(responses) {
899
- return responses.flatMap((response) => (response.content ?? []).flatMap((entry) => entry.schema ? collectImportedRefNames$1(entry.schema) : []));
900
- }
901
- function filterSuccess(node) {
902
- return node.responses.filter((response) => isSuccess(response.statusCode));
903
- }
904
- /** The success response a client returns: one with a body first, then an exact code over a `2xx` range. */
905
- function findPrimary(node) {
906
- const responses = filterSuccess(node);
907
- const withBody = responses.filter((response) => response.content?.some((entry) => entry.contentType));
908
- const candidates = withBody.length ? withBody : responses;
909
- return candidates.find((response) => !Number.isNaN(Number(response.statusCode))) ?? candidates[0] ?? null;
910
- }
911
- // src/http/index.ts
912
- var http_exports = /* @__PURE__ */ __exportAll({
913
- getBaseURL: () => getBaseURL,
914
- groupParameters: () => groupParameters,
915
- isOperation: () => isHttpOperationNode$1,
916
- requestBody: () => requestBody_exports,
917
- responses: () => responses_exports,
918
- status: () => status_exports
919
- });
920
- /** The server's URL when it is absolute and has no template variables, else `undefined`. */
921
- function getBaseURL(server) {
922
- if (!server || server.variables || server.url.includes("{") || !server.url.includes("://")) return void 0;
923
- return URL.canParse(server.url) ? server.url : void 0;
924
- }
925
- const parametersByNode = memo.create({ weak: true });
926
- /** The operation's parameters by location, with a `querystring` parameter in `query`. A repeated name keeps its first parameter. */
927
- function groupParameters(node) {
928
- return memo(parametersByNode, node, () => {
929
- const group = (...locations) => {
930
- const seen = /* @__PURE__ */ new Set();
931
- return locations.flatMap((location) => node.parameters.filter((param) => {
932
- if (param.in !== location || seen.has(param.name)) return false;
933
- seen.add(param.name);
934
- return true;
935
- }));
936
- };
937
- return {
938
- path: group("path"),
939
- query: group("query", "querystring"),
940
- header: group("header"),
941
- cookie: group("cookie")
942
- };
943
- });
944
- }
945
- // src/nodes/schema.ts
946
- /**
947
- * Maps schema `type` to its underlying `primitive`.
948
- * Primitive types map to themselves and special string formats map to `'string'`.
949
- * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `not`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
950
- */
951
- const TYPE_TO_PRIMITIVE = {
952
- string: "string",
953
- number: "number",
954
- integer: "integer",
955
- bigint: "bigint",
956
- boolean: "boolean",
957
- null: "null",
958
- any: "any",
959
- unknown: "unknown",
960
- void: "void",
961
- never: "never",
962
- object: "object",
963
- array: "array",
964
- date: "date",
965
- uuid: "string",
966
- email: "string",
967
- url: "string",
968
- datetime: "string",
969
- time: "string"
970
- };
971
- function createSchema(props) {
972
- if (props.type === "object") return {
973
- properties: [],
974
- primitive: "object",
975
- ...props,
976
- kind: nodeKinds$1.schema
977
- };
978
- return {
979
- primitive: TYPE_TO_PRIMITIVE[props.type],
980
- ...props,
981
- kind: nodeKinds$1.schema
982
- };
983
- }
984
- // src/ref/index.ts
985
- var ref_exports = /* @__PURE__ */ __exportAll({
986
- getName: () => getName,
987
- getSchema: () => resolveRef$1,
988
- isAlias: () => isBareRef$1,
989
- mergeSchema: () => mergeSchema
990
- });
991
- /** A resolved ref merged with its target schema, so usage-site fields such as `description` win. Other nodes come back unchanged. */
992
- function mergeSchema(node) {
993
- const ref = narrowSchema$1(node, "ref");
994
- return ref?.schema ? createSchema(mergeRefWithSchema$1(ref)) : node;
995
- }
996
- function getName(input) {
997
- return typeof input === "string" ? refName$1(input) : resolveRefName$1(input);
998
- }
999
- // src/optionality.ts
1000
- /**
1001
- * Generic JSON Schema optionality: a non-required field is optional, and a
1002
- * non-required nullable field is nullish.
1003
- */
1004
- function applyOptionality(schema, required) {
1005
- const nullable = schema.nullable ?? false;
1006
- return {
1007
- ...schema,
1008
- optional: !required && !nullable ? true : void 0,
1009
- nullish: !required && nullable ? true : void 0
1010
- };
1011
- }
1012
- // src/utils/schemaProperties.ts
1013
- /**
1014
- * Finds every matching property exposed by an object, resolved reference, or intersection.
1015
- *
1016
- * References are followed through their parsed `schema`. Circular references terminate without
1017
- * revisiting a node. Unions are not traversed because a property on one branch does not describe
1018
- * every branch.
1019
- *
1020
- * @example Faker discriminator narrowing
1021
- * ```ts
1022
- * const values = resolveSchemaProperties({ node: member, propertyName: union.discriminatorPropertyName }).flatMap(({ schema }) =>
1023
- * getSchemaLiteralValues(schema),
1024
- * )
1025
- * const typeName = `Extract<Pet, { type: ${values.map(JSON.stringify).join(' | ')} }>`
1026
- * ```
1027
- *
1028
- * @example Zod discriminated unions
1029
- * ```ts
1030
- * const canDiscriminate = union.members?.every(
1031
- * (member) => resolveSchemaProperties({ node: member, propertyName: 'type' }).length > 0,
1032
- * )
1033
- * const expression = canDiscriminate ? `z.discriminatedUnion('type', members)` : `z.union(members)`
1034
- * ```
1035
- *
1036
- * @example TypeScript property lookup
1037
- * ```ts
1038
- * const properties = resolveSchemaProperties({ node: schema, propertyName: 'status' })
1039
- * const statusSchemas = properties.map((property) => print(property.schema))
1040
- * ```
1041
- */
1042
- function resolveSchemaProperties$1({ node, propertyName }) {
1043
- const properties = [];
1044
- walkSchema(node, "intersection", (current) => {
1045
- if (current.type !== "object") return;
1046
- const property = current.properties.find((candidate) => candidate.name === propertyName);
1047
- if (property) properties.push(property);
1048
- });
1049
- return properties;
1050
- }
1051
- __name(resolveSchemaProperties$1, "resolveSchemaProperties");
1052
- function walkSchema(node, through, visit) {
1053
- const visited = /* @__PURE__ */ new WeakSet();
1054
- function walk(current) {
1055
- if (!current || visited.has(current)) return;
1056
- visited.add(current);
1057
- visit(current);
1058
- if (current.type === "ref") return walk(current.schema);
1059
- if (current.type === through) for (const member of current.members ?? []) walk(member);
1060
- }
1061
- walk(node);
1062
- }
1063
- /**
1064
- * Reads the unique literal values represented by an enum, resolved reference, or union.
1065
- *
1066
- * Named enum values take precedence over simple enum values, matching how renderers consume
1067
- * `EnumSchemaNode`.
1068
- *
1069
- * @example
1070
- * ```ts
1071
- * const values = getSchemaLiteralValues(enumNode)
1072
- * // ['cat', 'dog']
1073
- * ```
1074
- */
1075
- function getSchemaLiteralValues$1(node) {
1076
- return memo(literalValues, node, () => {
1077
- const values = /* @__PURE__ */ new Set();
1078
- walkSchema(node, "union", (current) => {
1079
- if (current.type !== "enum") return;
1080
- for (const { value } of current.namedEnumValues ?? current.enumValues?.map((value) => ({ value })) ?? []) values.add(value);
1081
- });
1082
- return Object.freeze([...values]);
1083
- });
1084
- }
1085
- __name(getSchemaLiteralValues$1, "getSchemaLiteralValues");
1086
- const literalValues = memo.create({ weak: true });
1087
- function collectPropertyNames(node) {
1088
- const names = /* @__PURE__ */ new Set();
1089
- walkSchema(node, "intersection", (current) => {
1090
- if (current.type === "object") for (const property of current.properties) names.add(property.name);
1091
- });
1092
- return names;
1093
- }
1094
- /**
1095
- * Infers an implicit discriminator: a property every member exposes with a distinct single
1096
- * literal value, the same shape a declared OpenAPI `discriminator` already narrows on.
1097
- */
1098
- function inferDiscriminatorPropertyName$1(members) {
1099
- if (members.length < 2) return void 0;
1100
- let candidates;
1101
- for (const member of members) {
1102
- const names = collectPropertyNames(member);
1103
- candidates = candidates ? new Set([...candidates].filter((name) => names.has(name))) : names;
1104
- }
1105
- for (const name of candidates ?? []) {
1106
- const values = members.map((member) => {
1107
- const literals = new Set(resolveSchemaProperties$1({
1108
- node: member,
1109
- propertyName: name
1110
- }).flatMap((property) => getSchemaLiteralValues$1(property.schema)));
1111
- return literals.size === 1 ? [...literals][0] : void 0;
1112
- });
1113
- if (values.every((value) => value !== void 0) && new Set(values).size === members.length) return name;
1114
- }
1115
- }
1116
- __name(inferDiscriminatorPropertyName$1, "inferDiscriminatorPropertyName");
1117
- // src/schema/index.ts
1118
- var schema_exports = /* @__PURE__ */ __exportAll({
1119
- applyOptionality: () => applyOptionality,
1120
- find: () => findSchema$1,
1121
- findProperties: () => resolveSchemaProperties$1,
1122
- getEmbeddedJson: () => getEmbeddedJson,
1123
- getLiterals: () => getSchemaLiteralValues$1,
1124
- getNumberBounds: () => getNumberBounds,
1125
- inferDiscriminator: () => inferDiscriminatorPropertyName$1,
1126
- isString: () => isString,
1127
- narrow: () => narrowSchema$1,
1128
- types: () => schemaTypes$1
1129
- });
1130
- const plainStringTypes = /* @__PURE__ */ new Set([
1131
- "string",
1132
- "uuid",
1133
- "email",
1134
- "url",
1135
- "datetime"
1136
- ]);
1137
- /** Whether a schema prints as a plain `string`: string-like types, and `date` or `time` with a `'string'` representation. */
1138
- function isString(node) {
1139
- if (plainStringTypes.has(node.type)) return true;
1140
- const temporal = narrowSchema$1(node, "date") ?? narrowSchema$1(node, "time");
1141
- return temporal ? temporal.representation !== "date" : false;
1142
- }
1143
- /**
1144
- * The tightest inclusive bounds of a number schema. An exclusive bound moves to the next point of `step` (`1` for an
1145
- * integer), an integer bound rounds inward, and an integer bound past `Number.MAX_SAFE_INTEGER` is left out, since it
1146
- * prints as a rounded or invalid literal.
1147
- */
1148
- function getNumberBounds({ min, max, exclusive, integer = false, step }) {
1149
- const grid = step ?? (integer ? 1 : void 0);
1150
- const above = (bound) => grid ? (Math.floor(bound / grid) + 1) * grid : bound;
1151
- const below = (bound) => grid ? (Math.ceil(bound / grid) - 1) * grid : bound;
1152
- const tightest = (pick, bounds) => {
1153
- const usable = bounds.filter((bound) => bound !== void 0 && (!integer || Number.isSafeInteger(bound)));
1154
- return usable.length ? pick(...usable) : void 0;
1155
- };
1156
- const lower = tightest(Math.max, [min !== void 0 && integer ? Math.ceil(min) : min, exclusive?.min === void 0 ? void 0 : above(exclusive.min)]);
1157
- const upper = tightest(Math.min, [max !== void 0 && integer ? Math.floor(max) : max, exclusive?.max === void 0 ? void 0 : below(exclusive.max)]);
1158
- return {
1159
- ...lower !== void 0 ? { min: lower } : {},
1160
- ...upper !== void 0 ? { max: upper } : {}
1161
- };
1162
- }
1
+ import { n as __name, t as __exportAll } from "./rolldown-runtime-BYyVTPww.js";
2
+ import { n as schemaTypes$1, t as nodeKinds$1 } from "./constants-Ckeonm-D.js";
3
+ import { a as findCircularSchemas$1, i as collectUsedSchemaNames$1, n as collectImportedRefNames$1, r as collectSchemaRefs$1, t as graph_exports } from "./graph-BcwFCvei.js";
4
+ import { n as findSchema$1, r as transform$1, t as collect$1 } from "./visitor-NoQSUQTu.js";
5
+ import { r as ref_exports, t as getName } from "./ref-Bu7PoHar.js";
6
+ import { a as resolveSchemaProperties$1, i as inferDiscriminatorPropertyName$1, n as schema_exports, r as getSchemaLiteralValues$1 } from "./schema-DloctnMm.js";
7
+ import { n as narrowSchema$1, t as isHttpOperationNode$1 } from "./guards-DlJkKsT1.js";
8
+ import { i as resolveRef$1, n as mergeRefWithSchema$1, t as isBareRef$1 } from "./refs-YCV3CznS.js";
9
+ import { i as defineMacro$1, n as applyMacros$1, r as compareMacroOrder, t as macro_exports } from "./macro-D0KfNtff.js";
10
+ import { t as applyOptionality } from "./optionality-DISn8ytP.js";
11
+ import { t as node_exports } from "./node-Djh-mZB2.js";
12
+ import { n as inlineFiles$1, t as file_exports } from "./file-CvlMAp_d.js";
13
+ import { n as getNodeText } from "./nodeText-DVVDZQjF.js";
14
+ import { t as nodes_exports } from "./nodes-CWMa9xhW.js";
15
+ import { t as http_exports } from "./http-DwboM6pK.js";
16
+ import { t as json_exports } from "./json-DH7_lcWm.js";
17
+ import { r as mediaType_exports } from "./mediaType-CRjggmoG.js";
1163
18
  // src/createPrinter.ts
1164
19
  /**
1165
20
  * Creates a schema printer: a function that takes a `SchemaNode` and emits
@@ -1210,578 +65,39 @@ function createPrinter$1(build) {
1210
65
  ...overrides
1211
66
  } : nodes;
1212
67
  const collectedImports = [];
1213
- const dispatch = (table) => (node) => {
68
+ const importNode = (node) => {
69
+ collectedImports.push(node);
70
+ };
71
+ const withOptions = (current, extra) => extra ? {
72
+ ...current,
73
+ ...extra
74
+ } : current;
75
+ const dispatch = (table, node, options, parent) => {
1214
76
  const handler = table[node.type];
1215
77
  if (!handler) return null;
1216
- return handler.call(context, node);
1217
- };
1218
- const context = {
1219
- options: resolvedOptions,
1220
- import: (node) => {
1221
- collectedImports.push(node);
1222
- },
1223
- transform: dispatch(merged),
1224
- base: dispatch(nodes)
78
+ return handler.call(createContext(options, node, parent), node);
1225
79
  };
80
+ function createContext(options, current, parent) {
81
+ const context = {
82
+ options,
83
+ parent,
84
+ import: importNode,
85
+ transform: (node, extra) => dispatch(merged, node, withOptions(context.options, extra), current),
86
+ base: (node, extra) => dispatch(nodes, node, withOptions(context.options, extra), parent)
87
+ };
88
+ return context;
89
+ }
90
+ const root = createContext(resolvedOptions);
1226
91
  return {
1227
92
  name,
1228
93
  options: resolvedOptions,
1229
- transform: context.transform,
1230
- print: printOverride ? printOverride.bind(context) : context.transform,
94
+ transform: root.transform,
95
+ print: printOverride ? (node, extra) => printOverride.call(extra ? createContext(withOptions(resolvedOptions, extra)) : root, node) : root.transform,
1231
96
  drainImports: () => collectedImports.splice(0)
1232
97
  };
1233
98
  };
1234
99
  }
1235
100
  __name(createPrinter$1, "createPrinter");
1236
- // src/defineMacro.ts
1237
- /**
1238
- * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
1239
- * list keeps its authored order.
1240
- */
1241
- function enforceWeight(enforce) {
1242
- if (enforce === "pre") return 0;
1243
- if (enforce === "post") return 2;
1244
- return 1;
1245
- }
1246
- /**
1247
- * Compares two `enforce` hints for `Array.prototype.sort`: `pre` first, unmarked next, `post`
1248
- * last. Equal hints compare as `0`, so a stable sort keeps authored order within a bucket.
1249
- *
1250
- * @example
1251
- * `plugins.sort((a, b) => compareMacroOrder(a.enforce, b.enforce))`
1252
- */
1253
- function compareMacroOrder(a, b) {
1254
- return enforceWeight(a) - enforceWeight(b);
1255
- }
1256
- /**
1257
- * Types a macro for inference and a single construction site, mirroring `defineExtension`.
1258
- * Adds no runtime behavior.
1259
- *
1260
- * @example
1261
- * ```ts
1262
- * const macroUntagged = defineMacro({
1263
- * name: 'untagged',
1264
- * operation(node) {
1265
- * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
1266
- * },
1267
- * })
1268
- * ```
1269
- */
1270
- function defineMacro$1(macro) {
1271
- return macro;
1272
- }
1273
- __name(defineMacro$1, "defineMacro");
1274
- /**
1275
- * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
1276
- * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
1277
- * original reference (structural sharing).
1278
- */
1279
- function chain({ macros, key, node, context }) {
1280
- let current = node;
1281
- for (const macro of macros) {
1282
- const callback = macro[key];
1283
- if (!callback) continue;
1284
- if (macro.match && !macro.match(current)) continue;
1285
- const next = callback(current, context);
1286
- if (next != null) current = next;
1287
- }
1288
- return current === node ? void 0 : current;
1289
- }
1290
- /**
1291
- * Folds an ordered list of macros into a single {@link Visitor} for `transform`. Macros are
1292
- * stable-sorted by `enforce`, then applied sequentially per node so later macros see earlier output.
1293
- */
1294
- function composeMacros(macros) {
1295
- const ordered = [...macros].sort((a, b) => compareMacroOrder(a.enforce, b.enforce));
1296
- const visitor = {};
1297
- for (const key of visitorKeys) {
1298
- if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
1299
- const callback = (node, context) => chain({
1300
- macros: ordered,
1301
- key,
1302
- node,
1303
- context
1304
- });
1305
- visitor[key] = callback;
1306
- }
1307
- return visitor;
1308
- }
1309
- /**
1310
- * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
1311
- * structural sharing, so an empty or no-op macro list returns the same reference. Pass
1312
- * `depth: 'shallow'` to rewrite the root node only.
1313
- *
1314
- * @example
1315
- * ```ts
1316
- * const next = applyMacros(root, [macroIntegerToString])
1317
- * ```
1318
- *
1319
- * @example Apply to the root node only
1320
- * ```ts
1321
- * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
1322
- * ```
1323
- */
1324
- function applyMacros$1(root, macros, options) {
1325
- if (macros.length === 0) return root;
1326
- return transform$1(root, {
1327
- ...composeMacros(macros),
1328
- ...options
1329
- });
1330
- }
1331
- __name(applyMacros$1, "applyMacros");
1332
- // src/macro/index.ts
1333
- var macro_exports = /* @__PURE__ */ __exportAll({
1334
- apply: () => applyMacros$1,
1335
- compareOrder: () => compareMacroOrder
1336
- });
1337
- // src/utils/nodeText.ts
1338
- const CODE_NODE_TEXT_FIELDS = {
1339
- Text: ["value"],
1340
- Jsx: ["value"],
1341
- Function: [
1342
- "params",
1343
- "generics",
1344
- "returnType"
1345
- ],
1346
- ArrowFunction: [
1347
- "params",
1348
- "generics",
1349
- "returnType"
1350
- ],
1351
- Const: ["type"]
1352
- };
1353
- /**
1354
- * Extracts all string content from a `CodeNode` tree recursively.
1355
- * Collects the text fields and nested node content, to build the source string for import filtering.
1356
- */
1357
- function getNodeText(nodes) {
1358
- if (!nodes?.length) return "";
1359
- const collected = [];
1360
- for (const node of nodes) {
1361
- if (typeof node === "string") {
1362
- if (node) collected.push(node);
1363
- continue;
1364
- }
1365
- if (node.kind === nodeKinds$1.break) continue;
1366
- const parts = [];
1367
- const record = node;
1368
- for (const field of CODE_NODE_TEXT_FIELDS[node.kind] ?? []) {
1369
- const value = record[field];
1370
- if (Array.isArray(value)) parts.push(value.join(", "));
1371
- if (typeof value === "string" && value) parts.push(value);
1372
- }
1373
- const nested = "nodes" in node ? getNodeText(node.nodes) : "";
1374
- if (nested) parts.push(nested);
1375
- if (parts.length) collected.push(parts.join("\n"));
1376
- }
1377
- return collected.join("\n");
1378
- }
1379
- // src/node/index.ts
1380
- var node_exports = /* @__PURE__ */ __exportAll({
1381
- collect: () => collect$1,
1382
- getText: () => getNodeText,
1383
- kinds: () => nodeKinds$1,
1384
- transform: () => transform$1
1385
- });
1386
- // src/utils/combineFileMembers.ts
1387
- /**
1388
- * File-member merging. `combineImports` and `combineExports` deduplicate and sort the import and
1389
- * export entries of one file, while `combineSources` deduplicates source entries in original order.
1390
- * `combineImports` also drops imports nothing references. This works on a file's members, not on
1391
- * schema content.
1392
- */
1393
- const IDENTIFIER_RUN = /[\w$]+/g;
1394
- /**
1395
- * How many imports a file needs before indexing the source beats scanning it once per name.
1396
- */
1397
- const INDEX_ABOVE_IMPORTS = 128;
1398
- /**
1399
- * Returns the local binding an import name item introduces: the alias when there is one, else the
1400
- * imported name.
1401
- */
1402
- function importLocalName(item) {
1403
- return typeof item === "string" ? item : item.name ?? item.propertyName;
1404
- }
1405
- /**
1406
- * Returns the specifier a member is written with: POSIX and relative to the importing file when it
1407
- * has a `root`, like `getRelativePath` in parser-ts. Sorting on it keeps the order the same on every OS.
1408
- */
1409
- function specifier(node) {
1410
- if (!node.root) return node.path;
1411
- const relative = path.relative(path.dirname(node.root), node.path).replaceAll("\\", "/");
1412
- return relative.startsWith("../") ? relative : `./${relative}`;
1413
- }
1414
- /**
1415
- * Computes a multi-level sort key for exports and imports:
1416
- * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical specifier. Unnamed before named.
1417
- */
1418
- function sortKey(node) {
1419
- const isArray = Array.isArray(node.name) ? "1" : "0";
1420
- const typeOnly = node.isTypeOnly ? "0" : "1";
1421
- const hasName = node.name != null ? "1" : "0";
1422
- const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
1423
- return `${isArray}:${typeOnly}:${specifier(node)}:${hasName}:${name}`;
1424
- }
1425
- /**
1426
- * Sorts members by {@link sortKey}. Keys are computed once per node, not per comparison.
1427
- */
1428
- function sortMembers(nodes) {
1429
- return nodes.map((node) => ({
1430
- node,
1431
- key: sortKey(node)
1432
- })).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0).map(({ node }) => node);
1433
- }
1434
- /**
1435
- * Returns a collector for array-named members. A member whose path and `isTypeOnly` were already
1436
- * seen folds its names into that entry, otherwise it joins `result` as a new entry.
1437
- */
1438
- function mergeByPath(result) {
1439
- const byPath = /* @__PURE__ */ new Map();
1440
- return ({ node, names }) => {
1441
- const key = `${node.path}:${node.isTypeOnly ?? false}`;
1442
- const existing = byPath.get(key);
1443
- if (existing) {
1444
- for (const name of names) {
1445
- if (existing.seen.has(name)) continue;
1446
- existing.seen.add(name);
1447
- existing.names.push(name);
1448
- }
1449
- return;
1450
- }
1451
- const item = {
1452
- ...node,
1453
- name: [...names]
1454
- };
1455
- result.push(item);
1456
- byPath.set(key, {
1457
- names: item.name,
1458
- seen: new Set(names)
1459
- });
1460
- };
1461
- }
1462
- /**
1463
- * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
1464
- * key. An unnamed source only drops when the same node appears twice, so markdown can repeat a
1465
- * paragraph or a table. Returns the deduplicated array in original order.
1466
- */
1467
- function combineSources(sources) {
1468
- const seen = /* @__PURE__ */ new Set();
1469
- return sources.filter((source) => {
1470
- const key = source.name != null ? `${source.name}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}` : source;
1471
- if (seen.has(key)) return false;
1472
- seen.add(key);
1473
- return true;
1474
- });
1475
- }
1476
- /**
1477
- * Deduplicates and merges `ExportNode` objects by path and type.
1478
- *
1479
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
1480
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
1481
- */
1482
- function combineExports(exports) {
1483
- const result = [];
1484
- const merge = mergeByPath(result);
1485
- const seen = /* @__PURE__ */ new Set();
1486
- for (const curr of sortMembers(exports)) {
1487
- const { name, path, isTypeOnly, asAlias } = curr;
1488
- if (Array.isArray(name)) {
1489
- if (name.length) merge({
1490
- node: curr,
1491
- names: [...new Set(name)]
1492
- });
1493
- continue;
1494
- }
1495
- const key = `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
1496
- if (!seen.has(key)) {
1497
- result.push(curr);
1498
- seen.add(key);
1499
- }
1500
- }
1501
- return result;
1502
- }
1503
- /**
1504
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
1505
- *
1506
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
1507
- * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
1508
- */
1509
- function combineImports(imports, exports, source) {
1510
- const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
1511
- const identifiers = source && imports.length > INDEX_ABOVE_IMPORTS ? new Set(source.match(IDENTIFIER_RUN)) : null;
1512
- const isUsed = (importName) => !source || identifiers?.has(importName) || source.includes(importName) || exportedNames.has(importName);
1513
- const importNameMemo = memo.create();
1514
- const canonicalizeName = (n) => {
1515
- if (typeof n === "string") return n;
1516
- const key = `${n.propertyName}:${n.name ?? ""}`;
1517
- return memo(importNameMemo, key, () => n);
1518
- };
1519
- const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
1520
- for (const node of imports) if (Array.isArray(node.name) && node.name.some((item) => isUsed(importLocalName(item)))) pathsWithUsedNamedImport.add(node.path);
1521
- const result = [];
1522
- const merge = mergeByPath(result);
1523
- const seen = /* @__PURE__ */ new Set();
1524
- for (const curr of sortMembers(imports)) {
1525
- if (curr.path === curr.root) continue;
1526
- const { name, path, isTypeOnly } = curr;
1527
- if (Array.isArray(name)) {
1528
- const names = [...new Set(name.map(canonicalizeName))].filter((item) => isUsed(importLocalName(item)));
1529
- if (names.length) merge({
1530
- node: curr,
1531
- names
1532
- });
1533
- continue;
1534
- }
1535
- if (!isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
1536
- const key = `${path}:${name}:${isTypeOnly ?? false}`;
1537
- if (!seen.has(key)) {
1538
- result.push(curr);
1539
- seen.add(key);
1540
- }
1541
- }
1542
- return result;
1543
- }
1544
- // src/nodes/base.ts
1545
- /** Builds a `createX` factory for a node whose only computed field is `kind`. */
1546
- function nodeFactory(kind) {
1547
- return (input) => {
1548
- return {
1549
- ...input,
1550
- kind
1551
- };
1552
- };
1553
- }
1554
- // src/nodes/file.ts
1555
- /**
1556
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1557
- *
1558
- * @example Named import
1559
- * ```ts
1560
- * createImport({ name: ['useState'], path: 'react' })
1561
- * // import { useState } from 'react'
1562
- * ```
1563
- */
1564
- const createImport = nodeFactory(nodeKinds$1.import);
1565
- /**
1566
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1567
- *
1568
- * @example Named export
1569
- * ```ts
1570
- * createExport({ name: ['Pet'], path: './Pet' })
1571
- * // export { Pet } from './Pet'
1572
- * ```
1573
- */
1574
- const createExport = nodeFactory(nodeKinds$1.export);
1575
- /**
1576
- * Creates a `SourceNode` representing a fragment of source code within a file.
1577
- *
1578
- * @example
1579
- * ```ts
1580
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1581
- * ```
1582
- */
1583
- const createSource = nodeFactory(nodeKinds$1.source);
1584
- /**
1585
- * Creates a fully resolved `FileNode` from a file input descriptor.
1586
- *
1587
- * Computes:
1588
- * - `id` SHA256 hash of the file path
1589
- * - `name` `baseName` without extension
1590
- * - `extname` extension extracted from `baseName`
1591
- *
1592
- * Deduplicates:
1593
- * - `sources` via `combineSources`
1594
- * - `exports` via `combineExports`
1595
- * - `imports` via `combineImports` (also filters unused imports)
1596
- *
1597
- * @throws {Error} when `baseName` has no extension.
1598
- *
1599
- * @example
1600
- * ```ts
1601
- * const file = createFile({
1602
- * baseName: 'petStore.ts',
1603
- * path: 'src/models/petStore.ts',
1604
- * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
1605
- * imports: [createImport({ name: ['z'], path: 'zod' })],
1606
- * exports: [createExport({ name: ['Pet'], path: './petStore' })],
1607
- * })
1608
- * // file.id = SHA256 hash of 'src/models/petStore.ts'
1609
- * // file.name = 'petStore'
1610
- * // file.extname = '.ts'
1611
- * ```
1612
- *
1613
- * @example Copy a real file into the output
1614
- * ```ts
1615
- * const file = createFile({
1616
- * baseName: 'client.ts',
1617
- * path: 'src/gen/client.ts',
1618
- * copy: '/abs/path/to/templates/client.ts',
1619
- * })
1620
- * ```
1621
- */
1622
- function createFile(input) {
1623
- const extname = path.extname(input.baseName);
1624
- if (!extname) throw new Error(`No extname found for ${input.baseName}`);
1625
- const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
1626
- const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
1627
- const resolvedImports = (() => {
1628
- if (!input.imports?.length) return [];
1629
- const sourceParts = [];
1630
- const localNames = /* @__PURE__ */ new Set();
1631
- for (const item of resolvedSources) {
1632
- const extracted = item.nodes && getNodeText(item.nodes);
1633
- if (extracted) sourceParts.push(extracted);
1634
- if (item.name) localNames.add(item.name);
1635
- }
1636
- const source = sourceParts.join("\n") || void 0;
1637
- return combineImports(input.imports, resolvedExports, source).flatMap((imp) => {
1638
- if (imp.path === input.path) return [];
1639
- if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
1640
- const kept = imp.name.filter((item) => !localNames.has(importLocalName(item)));
1641
- if (!kept.length) return [];
1642
- return [kept.length === imp.name.length ? imp : {
1643
- ...imp,
1644
- name: kept
1645
- }];
1646
- });
1647
- })();
1648
- return {
1649
- ...input,
1650
- kind: nodeKinds$1.file,
1651
- id: hash("sha256", input.path, "hex"),
1652
- name: path.basename(input.baseName, extname),
1653
- extname,
1654
- imports: resolvedImports,
1655
- exports: resolvedExports,
1656
- sources: resolvedSources,
1657
- meta: input.meta ?? {}
1658
- };
1659
- }
1660
- // src/utils/inline.ts
1661
- /**
1662
- * Replaces every name a file imports from a virtual file (one whose sources are all inline, so it is never written) with that name's
1663
- * `inline.expression`, until no inline names are left. The definitions' own imports move to the importing file.
1664
- */
1665
- function inlineFiles$1(files, { language }) {
1666
- const virtualFiles = new Map(files.filter((file) => file.sources.length > 0 && file.sources.every((source) => source.inline)).map((file) => [file.path, file]));
1667
- const result = {
1668
- files: [],
1669
- virtualPaths: [...virtualFiles.keys()],
1670
- problems: []
1671
- };
1672
- if (virtualFiles.size === 0) return result;
1673
- const definitions = /* @__PURE__ */ new Map();
1674
- function define(path, name, from, lang) {
1675
- const key = `${path}\0${name}`;
1676
- if (definitions.has(key)) {
1677
- const definition = definitions.get(key);
1678
- if (definition === null) result.problems.push({
1679
- path: from,
1680
- message: `"${name}" from "${path}" is defined in terms of itself.`
1681
- });
1682
- return definition ?? void 0;
1683
- }
1684
- const file = virtualFiles.get(path);
1685
- const inline = file.sources.find((source) => source.name === name)?.inline;
1686
- if (!inline) {
1687
- result.problems.push({
1688
- path: from,
1689
- message: `"${name}" is imported from "${path}", which never writes it and has no inline definition for it.`
1690
- });
1691
- return;
1692
- }
1693
- definitions.set(key, null);
1694
- const imports = [];
1695
- const { text, used } = replaceNames(inline.expression, file, lang, imports);
1696
- imports.push(...file.imports.flatMap((imp) => virtualFiles.has(imp.path) ? [] : pickNames(imp, used)));
1697
- const definition = {
1698
- expression: text,
1699
- imports
1700
- };
1701
- definitions.set(key, definition);
1702
- return definition;
1703
- }
1704
- function replaceNames(input, file, lang, imports) {
1705
- const used = /* @__PURE__ */ new Set();
1706
- return {
1707
- text: lang.replaceIdentifiers(input, (local) => {
1708
- const target = findTarget(file, local);
1709
- const definition = target && define(target.path, target.name, file.path, lang);
1710
- if (!definition) {
1711
- used.add(local);
1712
- return;
1713
- }
1714
- imports.push(...definition.imports);
1715
- return lang.wrap(definition.expression);
1716
- }),
1717
- used
1718
- };
1719
- }
1720
- function findTarget(file, local) {
1721
- if (virtualFiles.has(file.path) && file.sources.some((source) => source.name === local)) return {
1722
- path: file.path,
1723
- name: local
1724
- };
1725
- for (const imp of file.imports) {
1726
- const item = virtualFiles.has(imp.path) && [imp.name].flat().find((item) => importLocalName(item) === local);
1727
- if (item) return {
1728
- path: imp.path,
1729
- name: typeof item === "string" ? item : item.propertyName
1730
- };
1731
- }
1732
- }
1733
- for (const file of files) {
1734
- if (virtualFiles.has(file.path) || !file.imports.some((imp) => virtualFiles.has(imp.path))) continue;
1735
- const lang = language(file);
1736
- if (!lang) {
1737
- result.problems.push({
1738
- path: file.path,
1739
- message: `No parser for "${file.extname}" files supports inline sources.`
1740
- });
1741
- continue;
1742
- }
1743
- const carried = [];
1744
- const sources = file.sources.map((source) => ({
1745
- ...source,
1746
- nodes: rewriteNodes(source.nodes, (text) => replaceNames(text, file, lang, carried).text)
1747
- }));
1748
- const imports = [...file.imports.filter((imp) => !virtualFiles.has(imp.path)), ...carried.map((imp) => imp.root ? {
1749
- ...imp,
1750
- root: file.path
1751
- } : imp)];
1752
- result.files.push(createFile({
1753
- ...file,
1754
- sources,
1755
- imports
1756
- }));
1757
- }
1758
- return result;
1759
- }
1760
- __name(inlineFiles$1, "inlineFiles");
1761
- function pickNames(imp, used) {
1762
- if (!Array.isArray(imp.name)) return used.has(imp.name) ? [imp] : [];
1763
- const name = imp.name.filter((item) => used.has(importLocalName(item)));
1764
- return name.length > 0 ? [{
1765
- ...imp,
1766
- name
1767
- }] : [];
1768
- }
1769
- function rewriteNodes(nodes, rewrite) {
1770
- return nodes?.map((node) => {
1771
- if (typeof node === "string") return rewrite(node);
1772
- if (node.kind === nodeKinds$1.break) return node;
1773
- const next = { ...node };
1774
- for (const field of CODE_NODE_TEXT_FIELDS[node.kind] ?? []) {
1775
- const value = next[field];
1776
- if (Array.isArray(value)) next[field] = value.map(rewrite);
1777
- if (typeof value === "string" && value) next[field] = rewrite(value);
1778
- }
1779
- if ("nodes" in node && node.nodes) next.nodes = rewriteNodes(node.nodes, rewrite);
1780
- return next;
1781
- });
1782
- }
1783
- // src/file/index.ts
1784
- var file_exports = /* @__PURE__ */ __exportAll({ inline: () => inlineFiles$1 });
1785
101
  // src/deprecated.ts
1786
102
  /** @deprecated Use `ast.ref.isAlias`. Removed in Kubb v6. */
1787
103
  const isBareRef = isBareRef$1;
@@ -1837,337 +153,10 @@ const transform = transform$1;
1837
153
  const collect = collect$1;
1838
154
  /** @deprecated Use `ast.file.inline`. Removed in Kubb v6. */
1839
155
  const inlineFiles = inlineFiles$1;
1840
- // src/auth/index.ts
1841
- var auth_exports = /* @__PURE__ */ __exportAll({ getRequirements: () => getRequirements });
1842
- /** Joins each requirement with its schemes. Drops undeclared and repeated requirements, and keeps an empty one (no auth needed). */
1843
- function getRequirements({ auth, schemes }) {
1844
- const credentials = new Map(schemes?.map((scheme) => [scheme.name, scheme.credential]));
1845
- const seen = /* @__PURE__ */ new Set();
1846
- const resolved = [];
1847
- for (const requirement of auth ?? []) {
1848
- const key = requirement.map(({ scheme, scopes }) => [scheme, ...scopes ?? []].join(" ")).join("\0");
1849
- if (seen.has(key) || !requirement.every(({ scheme }) => credentials.has(scheme))) continue;
1850
- seen.add(key);
1851
- resolved.push(requirement.map(({ scheme, scopes }) => ({
1852
- name: scheme,
1853
- credential: credentials.get(scheme),
1854
- scopes: scopes ?? []
1855
- })));
1856
- }
1857
- return resolved;
1858
- }
1859
- // src/nodes/code.ts
1860
- /**
1861
- * Creates a `ConstNode` representing a TypeScript `const` declaration.
1862
- *
1863
- * @example Exported constant with type and `as const`
1864
- * ```ts
1865
- * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
1866
- * // export const pets: Pet[] = ... as const
1867
- * ```
1868
- */
1869
- const createConst = nodeFactory(nodeKinds$1.const);
1870
- /**
1871
- * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
1872
- *
1873
- * @example
1874
- * ```ts
1875
- * createType({ name: 'Pet', export: true })
1876
- * // export type Pet = ...
1877
- * ```
1878
- */
1879
- const createType = nodeFactory(nodeKinds$1.type);
1880
- /**
1881
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
1882
- *
1883
- * @example
1884
- * ```ts
1885
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
1886
- * // export async function fetchPet(): Promise<Pet> { ... }
1887
- * ```
1888
- */
1889
- const createFunction = nodeFactory(nodeKinds$1.function);
1890
- /**
1891
- * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
1892
- *
1893
- * @example
1894
- * ```ts
1895
- * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
1896
- * // export const double = (n: number) => ...
1897
- * ```
1898
- */
1899
- const createArrowFunction = nodeFactory(nodeKinds$1.arrowFunction);
1900
- /**
1901
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
1902
- *
1903
- * @example
1904
- * ```ts
1905
- * createText('return fetch(id)')
1906
- * // { kind: 'Text', value: 'return fetch(id)' }
1907
- * ```
1908
- */
1909
- function createText(value) {
1910
- return {
1911
- kind: nodeKinds$1.text,
1912
- value
1913
- };
1914
- }
1915
- /**
1916
- * Creates a {@link BreakNode} representing a line break in the source output.
1917
- *
1918
- * @example
1919
- * ```ts
1920
- * createBreak()
1921
- * // { kind: 'Break' }
1922
- * ```
1923
- */
1924
- function createBreak() {
1925
- return { kind: nodeKinds$1.break };
1926
- }
1927
- /**
1928
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
1929
- *
1930
- * @example
1931
- * ```ts
1932
- * createJsx('<>\n <a href={href}>Open</a>\n</>')
1933
- * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
1934
- * ```
1935
- */
1936
- function createJsx(value) {
1937
- return {
1938
- kind: nodeKinds$1.jsx,
1939
- value
1940
- };
1941
- }
1942
- // src/nodes/content.ts
1943
- /**
1944
- * Creates a `ContentNode` for a single request-body or response content type.
1945
- */
1946
- const createContent = nodeFactory(nodeKinds$1.content);
1947
- // src/nodes/input.ts
1948
- /**
1949
- * Creates an `InputNode`, defaulting `schemas`/`operations` to empty arrays and `meta` to an empty
1950
- * object. Every call allocates fresh defaults so no two inputs share them.
1951
- *
1952
- * @example
1953
- * ```ts
1954
- * const input = createInput()
1955
- * // { kind: 'Input', schemas: [], operations: [] }
1956
- * ```
1957
- */
1958
- function createInput(overrides = {}) {
1959
- return {
1960
- schemas: [],
1961
- operations: [],
1962
- meta: {},
1963
- ...overrides,
1964
- kind: nodeKinds$1.input
1965
- };
1966
- }
1967
- // src/nodes/requestBody.ts
1968
- /**
1969
- * Creates a `RequestBodyNode`.
1970
- */
1971
- const createRequestBody = nodeFactory(nodeKinds$1.requestBody);
1972
- // src/nodes/operation.ts
1973
- function createOperation(props) {
1974
- const { requestBody, ...rest } = props;
1975
- const isHttp = rest.method !== void 0 && rest.path !== void 0;
1976
- return {
1977
- tags: [],
1978
- parameters: [],
1979
- responses: [],
1980
- ...rest,
1981
- kind: nodeKinds$1.operation,
1982
- ...isHttp ? { protocol: "http" } : {},
1983
- requestBody: requestBody ? createRequestBody(requestBody) : void 0
1984
- };
1985
- }
1986
- // src/nodes/parameter.ts
1987
- /**
1988
- * Creates a `ParameterNode`. `required` defaults to `false`, and the schema's
1989
- * `optional`/`nullish` flags are derived from it.
1990
- *
1991
- * @example
1992
- * ```ts
1993
- * const param = createParameter({
1994
- * name: 'petId',
1995
- * in: 'path',
1996
- * required: true,
1997
- * schema: createSchema({ type: 'string' }),
1998
- * })
1999
- * ```
2000
- */
2001
- function createParameter(input) {
2002
- const required = input.required ?? false;
2003
- return {
2004
- ...input,
2005
- required,
2006
- schema: applyOptionality(input.schema, required),
2007
- kind: nodeKinds$1.parameter
2008
- };
2009
- }
2010
- // src/nodes/property.ts
2011
- /**
2012
- * Creates a `PropertyNode`. `required` defaults to `false`, and the schema's
2013
- * `optional`/`nullish` flags are derived from it.
2014
- *
2015
- * @example
2016
- * ```ts
2017
- * const property = createProperty({
2018
- * name: 'status',
2019
- * required: true,
2020
- * schema: createSchema({ type: 'string', nullable: true }),
2021
- * })
2022
- * // required=true, no optional/nullish
2023
- * ```
2024
- */
2025
- function createProperty(input) {
2026
- const required = input.required ?? false;
2027
- return {
2028
- ...input,
2029
- required,
2030
- schema: applyOptionality(input.schema, required),
2031
- kind: nodeKinds$1.property
2032
- };
2033
- }
2034
- // src/nodes/response.ts
2035
- /**
2036
- * Creates a `ResponseNode`. A single legacy `schema` (with optional `mediaType`/`keysToOmit`)
2037
- * is normalized into one `content` entry.
2038
- *
2039
- * @example
2040
- * ```ts
2041
- * const response = createResponse({
2042
- * statusCode: '200',
2043
- * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
2044
- * })
2045
- * ```
2046
- */
2047
- function createResponse(props) {
2048
- const { schema, mediaType, keysToOmit, content, ...rest } = props;
2049
- const entries = content ?? (schema ? [createContent({
2050
- contentType: mediaType ?? "application/json",
2051
- schema,
2052
- keysToOmit: keysToOmit ?? null
2053
- })] : void 0);
2054
- return {
2055
- ...rest,
2056
- content: entries,
2057
- kind: nodeKinds$1.response
2058
- };
2059
- }
2060
- // src/nodes/index.ts
2061
- var nodes_exports = /* @__PURE__ */ __exportAll({
2062
- createArrowFunction: () => createArrowFunction,
2063
- createBreak: () => createBreak,
2064
- createConst: () => createConst,
2065
- createContent: () => createContent,
2066
- createExport: () => createExport,
2067
- createFile: () => createFile,
2068
- createFunction: () => createFunction,
2069
- createImport: () => createImport,
2070
- createInput: () => createInput,
2071
- createJsx: () => createJsx,
2072
- createOperation: () => createOperation,
2073
- createParameter: () => createParameter,
2074
- createProperty: () => createProperty,
2075
- createRequestBody: () => createRequestBody,
2076
- createResponse: () => createResponse,
2077
- createSchema: () => createSchema,
2078
- createSource: () => createSource,
2079
- createText: () => createText,
2080
- createType: () => createType
2081
- });
2082
- // src/json/index.ts
2083
- var json_exports = /* @__PURE__ */ __exportAll({
2084
- parse: () => parse,
2085
- stringify: () => stringify
2086
- });
2087
- const version = 1;
2088
- function isRef(value) {
2089
- const node = value;
2090
- return node?.kind === nodeKinds$1.schema && node.type === schemaTypes$1.ref;
2091
- }
2092
- /**
2093
- * Turns an `InputNode` into JSON text that `parse` reads back. Every schema a ref points at is written once,
2094
- * where a plain `JSON.stringify(input)` writes it again at every ref.
2095
- *
2096
- * @example
2097
- * ```ts
2098
- * await writeFile('input.json', ast.json.stringify(input))
2099
- * ```
2100
- */
2101
- function stringify(input) {
2102
- const ids = /* @__PURE__ */ new Map();
2103
- const targets = [];
2104
- function replacer(key, value) {
2105
- if (key !== "schema" || !isRef(this)) return value;
2106
- if (typeof value === "number") return [value];
2107
- if (typeof value !== "object" || value === null) return value;
2108
- if (!ids.has(value)) {
2109
- ids.set(value, targets.length);
2110
- targets.push(value);
2111
- }
2112
- return ids.get(value);
2113
- }
2114
- const root = JSON.stringify(input, replacer);
2115
- const encoded = [];
2116
- for (const target of targets) encoded.push(JSON.stringify(target, replacer));
2117
- return `{"version":${version},"input":${root},"targets":[${encoded.join(",")}]}`;
2118
- }
2119
- /**
2120
- * Reads the text `stringify` wrote back into an `InputNode`. Refs to one schema share one object again.
2121
- * Throws on another format version, or on a ref whose target is missing.
2122
- */
2123
- function parse(text) {
2124
- const document = JSON.parse(text);
2125
- if (document?.version !== version) throw new Error(`Cannot read this AST JSON: expected format version ${version}, got ${JSON.stringify(document?.version)}.`);
2126
- if (!document.input || !Array.isArray(document.targets)) throw new Error("Cannot read this AST JSON: `input` or `targets` is missing.");
2127
- const targets = document.targets;
2128
- const stack = [document.input, ...targets];
2129
- while (stack.length) {
2130
- const value = stack.pop();
2131
- const ref = isRef(value);
2132
- for (const key in value) {
2133
- const child = value[key];
2134
- if (ref && key === "schema") {
2135
- if (Array.isArray(child)) {
2136
- value.schema = child[0];
2137
- continue;
2138
- }
2139
- if (typeof child === "number") {
2140
- const target = targets[child];
2141
- if (!target) throw new Error(`Cannot read this AST JSON: a ref points at target ${child}, which is missing.`);
2142
- value.schema = target;
2143
- continue;
2144
- }
2145
- }
2146
- if (typeof child === "object" && child !== null) stack.push(child);
2147
- }
2148
- }
2149
- return document.input;
2150
- }
2151
- // src/server/index.ts
2152
- var server_exports = /* @__PURE__ */ __exportAll({
2153
- get: () => get,
2154
- groupByName: () => groupByName
2155
- });
2156
- /** The server at `index`, else the first one. */
2157
- function get({ servers, index = 0 }) {
2158
- return servers?.[index] ?? servers?.[0];
2159
- }
2160
- /** Named servers by name. The first server with a name wins. */
2161
- function groupByName(servers) {
2162
- const named = /* @__PURE__ */ new Map();
2163
- for (const server of servers ?? []) if (server.name && !named.has(server.name)) named.set(server.name, server);
2164
- return named;
2165
- }
2166
156
  // src/index.ts
2167
157
  var src_exports = /* @__PURE__ */ __exportAll({
2168
158
  applyMacros: () => applyMacros,
2169
159
  ast: () => src_exports,
2170
- auth: () => auth_exports,
2171
160
  collect: () => collect,
2172
161
  collectImportedRefNames: () => collectImportedRefNames,
2173
162
  collectSchemaRefs: () => collectSchemaRefs,
@@ -2203,9 +192,8 @@ var src_exports = /* @__PURE__ */ __exportAll({
2203
192
  resolveSchemaProperties: () => resolveSchemaProperties,
2204
193
  schema: () => schema_exports,
2205
194
  schemaTypes: () => schemaTypes,
2206
- server: () => server_exports,
2207
195
  transform: () => transform
2208
196
  });
2209
- export { applyMacros, src_exports as ast, auth_exports as auth, collect, collectImportedRefNames, collectSchemaRefs, collectSync, collectUsedSchemaNames, compareEnforce, createPrinter, defineMacro, extractStringsFromNodes, nodes_exports as factory, file_exports as file, findCircularSchemas, findSchema, getSchemaLiteralValues, graph_exports as graph, http_exports as http, inferDiscriminatorPropertyName, inlineFiles, isBareRef, isHttpOperationNode, json_exports as json, macro_exports as macro, mediaType_exports as mediaType, mergeRefWithSchema, narrowSchema, node_exports as node, nodeKinds, optionality, ref_exports as ref, refName, resolveRef, resolveRefName, resolveSchemaProperties, schema_exports as schema, schemaTypes, server_exports as server, transform };
197
+ export { applyMacros, src_exports as ast, collect, collectImportedRefNames, collectSchemaRefs, collectSync, collectUsedSchemaNames, compareEnforce, createPrinter, defineMacro, extractStringsFromNodes, nodes_exports as factory, file_exports as file, findCircularSchemas, findSchema, getSchemaLiteralValues, graph_exports as graph, http_exports as http, inferDiscriminatorPropertyName, inlineFiles, isBareRef, isHttpOperationNode, json_exports as json, macro_exports as macro, mediaType_exports as mediaType, mergeRefWithSchema, narrowSchema, node_exports as node, nodeKinds, optionality, ref_exports as ref, refName, resolveRef, resolveRefName, resolveSchemaProperties, schema_exports as schema, schemaTypes, transform };
2210
198
 
2211
199
  //# sourceMappingURL=index.js.map