@kubb/ast 5.0.0-beta.60 → 5.0.0-beta.61

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 (61) hide show
  1. package/README.md +2 -1
  2. package/dist/defineMacro-BLIR6k-j.d.ts +475 -0
  3. package/dist/defineMacro-BTXvS8nI.js +106 -0
  4. package/dist/defineMacro-BTXvS8nI.js.map +1 -0
  5. package/dist/defineMacro-Bv9R_9a2.cjs +123 -0
  6. package/dist/defineMacro-Bv9R_9a2.cjs.map +1 -0
  7. package/dist/extractStringsFromNodes-Cja-xxx5.js +29 -0
  8. package/dist/extractStringsFromNodes-Cja-xxx5.js.map +1 -0
  9. package/dist/extractStringsFromNodes-DKgDjFO0.cjs +34 -0
  10. package/dist/extractStringsFromNodes-DKgDjFO0.cjs.map +1 -0
  11. package/dist/extractStringsFromNodes-p4mX1TQD.d.ts +14 -0
  12. package/dist/{factory-Du7nEP4B.js → factory-CZNOGI-N.js} +3 -2
  13. package/dist/{factory-Du7nEP4B.js.map → factory-CZNOGI-N.js.map} +1 -1
  14. package/dist/{factory-Cl8Z7mcc.cjs → factory-DG1CVkEb.cjs} +5 -4
  15. package/dist/{factory-Cl8Z7mcc.cjs.map → factory-DG1CVkEb.cjs.map} +1 -1
  16. package/dist/factory.cjs +2 -2
  17. package/dist/factory.js +2 -2
  18. package/dist/index.cjs +22 -20
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +18 -17
  21. package/dist/index.js +7 -4
  22. package/dist/index.js.map +1 -1
  23. package/dist/macros.cjs +117 -0
  24. package/dist/macros.cjs.map +1 -0
  25. package/dist/macros.d.ts +59 -0
  26. package/dist/macros.js +115 -0
  27. package/dist/macros.js.map +1 -0
  28. package/dist/{response-DKxTr522.js → response-KUdWiDWw.js} +36 -61
  29. package/dist/response-KUdWiDWw.js.map +1 -0
  30. package/dist/{response-DS5S3IG4.cjs → response-hnSw2NKE.cjs} +35 -66
  31. package/dist/response-hnSw2NKE.cjs.map +1 -0
  32. package/dist/{types-olVl9v5p.d.ts → types-DyDzizSf.d.ts} +3 -403
  33. package/dist/types.d.ts +4 -3
  34. package/dist/{utils-D83JA6Xx.cjs → utils-BLJwyza-.cjs} +18 -751
  35. package/dist/utils-BLJwyza-.cjs.map +1 -0
  36. package/dist/{utils-Dj_KoXMv.js → utils-CF_-Pn_c.js} +9 -628
  37. package/dist/utils-CF_-Pn_c.js.map +1 -0
  38. package/dist/utils.cjs +12 -10
  39. package/dist/utils.d.ts +28 -2
  40. package/dist/utils.js +4 -3
  41. package/dist/visitor-DJ6ZEJvq.js +548 -0
  42. package/dist/visitor-DJ6ZEJvq.js.map +1 -0
  43. package/dist/visitor-DpKZ9Tk0.cjs +654 -0
  44. package/dist/visitor-DpKZ9Tk0.cjs.map +1 -0
  45. package/package.json +5 -1
  46. package/src/defineMacro.ts +132 -0
  47. package/src/index.ts +3 -7
  48. package/src/macros/index.ts +3 -0
  49. package/src/macros/macroDiscriminatorEnum.ts +44 -0
  50. package/src/macros/macroEnumName.ts +25 -0
  51. package/src/macros/macroSimplifyUnion.ts +50 -0
  52. package/src/types.ts +2 -1
  53. package/src/utils/index.ts +2 -2
  54. package/src/utils/refs.ts +27 -1
  55. package/src/utils/schemaMerge.ts +34 -0
  56. package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +0 -82
  57. package/dist/response-DKxTr522.js.map +0 -1
  58. package/dist/response-DS5S3IG4.cjs.map +0 -1
  59. package/dist/utils-D83JA6Xx.cjs.map +0 -1
  60. package/dist/utils-Dj_KoXMv.js.map +0 -1
  61. package/src/transformers.ts +0 -191
package/README.md CHANGED
@@ -30,8 +30,9 @@ Defines the node tree, visitor pattern, factory functions, and type guards used
30
30
 
31
31
  | Path | Contents |
32
32
  | ------------------- | ---------------------------------------------------------------------------------------- |
33
- | `@kubb/ast` | Runtime: node definitions, guards, visitor, transformers, constants |
33
+ | `@kubb/ast` | Runtime: node definitions, guards, visitor, macro engine, constants |
34
34
  | `@kubb/ast/factory` | Node constructors (`createSchema`, `createFile`, and friends), the `ts.factory` analogue |
35
+ | `@kubb/ast/macros` | Built-in macro presets: `macroDiscriminatorEnum`, `macroSimplifyUnion`, `macroEnumName` |
35
36
  | `@kubb/ast/types` | Types only: all node interfaces, type aliases, visitor types |
36
37
  | `@kubb/ast/utils` | Spec-agnostic string and identifier helpers, ref helpers |
37
38
 
@@ -0,0 +1,475 @@
1
+ import { n as __name } from "./chunk-CNktS9qV.js";
2
+ import { Et as PropertyNode, _t as SchemaNode, f as OperationNode, h as ResponseNode, n as OutputNode, nt as ContentNode, o as InputNode, t as Node, w as ParameterNode, y as RequestBodyNode } from "./index-BzjwdK2M.js";
3
+
4
+ //#region src/constants.d.ts
5
+ /**
6
+ * Traversal depth for AST visitor utilities.
7
+ *
8
+ * - `'shallow'` visits only the immediate node, skipping children.
9
+ * - `'deep'` recursively visits all descendant nodes.
10
+ */
11
+ type VisitorDepth = 'shallow' | 'deep';
12
+ /**
13
+ * Schema type discriminators used by all AST schema nodes.
14
+ *
15
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
16
+ * Call `isScalarPrimitive()` to check for the scalar types.
17
+ */
18
+ declare const schemaTypes: {
19
+ /**
20
+ * Text value.
21
+ */
22
+ readonly string: "string";
23
+ /**
24
+ * Floating-point number (`float`, `double`).
25
+ */
26
+ readonly number: "number";
27
+ /**
28
+ * Whole number (`int32`). Use `bigint` for `int64`.
29
+ */
30
+ readonly integer: "integer";
31
+ /**
32
+ * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
33
+ */
34
+ readonly bigint: "bigint";
35
+ /**
36
+ * Boolean value.
37
+ */
38
+ readonly boolean: "boolean";
39
+ /**
40
+ * Explicit null value.
41
+ */
42
+ readonly null: "null";
43
+ /**
44
+ * Any value (no type restriction).
45
+ */
46
+ readonly any: "any";
47
+ /**
48
+ * Unknown value (must be narrowed before usage).
49
+ */
50
+ readonly unknown: "unknown";
51
+ /**
52
+ * No return value (`void`).
53
+ */
54
+ readonly void: "void";
55
+ /**
56
+ * Object with named properties.
57
+ */
58
+ readonly object: "object";
59
+ /**
60
+ * Sequential list of items.
61
+ */
62
+ readonly array: "array";
63
+ /**
64
+ * Fixed-length list with position-specific items.
65
+ */
66
+ readonly tuple: "tuple";
67
+ /**
68
+ * "One of" multiple schema members.
69
+ */
70
+ readonly union: "union";
71
+ /**
72
+ * "All of" multiple schema members.
73
+ */
74
+ readonly intersection: "intersection";
75
+ /**
76
+ * Enum schema.
77
+ */
78
+ readonly enum: "enum";
79
+ /**
80
+ * Reference to another schema.
81
+ */
82
+ readonly ref: "ref";
83
+ /**
84
+ * Calendar date (for example `2026-03-24`).
85
+ */
86
+ readonly date: "date";
87
+ /**
88
+ * Date-time value (for example `2026-03-24T09:00:00Z`).
89
+ */
90
+ readonly datetime: "datetime";
91
+ /**
92
+ * Time-only value (for example `09:00:00`).
93
+ */
94
+ readonly time: "time";
95
+ /**
96
+ * UUID value.
97
+ */
98
+ readonly uuid: "uuid";
99
+ /**
100
+ * Email address value.
101
+ */
102
+ readonly email: "email";
103
+ /**
104
+ * URL value.
105
+ */
106
+ readonly url: "url";
107
+ /**
108
+ * IPv4 address value.
109
+ */
110
+ readonly ipv4: "ipv4";
111
+ /**
112
+ * IPv6 address value.
113
+ */
114
+ readonly ipv6: "ipv6";
115
+ /**
116
+ * Binary/blob value.
117
+ */
118
+ readonly blob: "blob";
119
+ /**
120
+ * Impossible value (`never`).
121
+ */
122
+ readonly never: "never";
123
+ };
124
+ /**
125
+ * HTTP method identifiers used by operation nodes.
126
+ */
127
+ declare const httpMethods: {
128
+ readonly get: "GET";
129
+ readonly post: "POST";
130
+ readonly put: "PUT";
131
+ readonly patch: "PATCH";
132
+ readonly delete: "DELETE";
133
+ readonly head: "HEAD";
134
+ readonly options: "OPTIONS";
135
+ readonly trace: "TRACE";
136
+ };
137
+ //#endregion
138
+ //#region src/visitor.d.ts
139
+ /**
140
+ * Ordered mapping of `[NodeType, ParentType]` pairs.
141
+ *
142
+ * `ParentOf` uses this map to find parent types.
143
+ */
144
+ type ParentNodeMap = [[InputNode, undefined], [OutputNode, undefined], [OperationNode, InputNode], [RequestBodyNode, OperationNode], [ContentNode, RequestBodyNode | ResponseNode], [SchemaNode, InputNode | ContentNode | SchemaNode | PropertyNode | ParameterNode], [PropertyNode, SchemaNode], [ParameterNode, OperationNode], [ResponseNode, OperationNode]];
145
+ /**
146
+ * Resolves the parent node type for a given AST node type.
147
+ *
148
+ * Visitor context relies on this so `ctx.parent` is typed for each callback.
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * type InputParent = ParentOf<InputNode>
153
+ * // undefined
154
+ * ```
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * type PropertyParent = ParentOf<PropertyNode>
159
+ * // SchemaNode
160
+ * ```
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * type SchemaParent = ParentOf<SchemaNode>
165
+ * // InputNode | OperationNode | SchemaNode | PropertyNode | ParameterNode | ResponseNode
166
+ * ```
167
+ */
168
+ type ParentOf<T extends Node, TEntries extends ReadonlyArray<[Node, unknown]> = ParentNodeMap> = TEntries extends [infer TEntry extends [Node, unknown], ...infer TRest extends ReadonlyArray<[Node, unknown]>] ? T extends TEntry[0] ? TEntry[1] : ParentOf<T, TRest> : Node;
169
+ /**
170
+ * Traversal context passed as the second argument to every visitor callback.
171
+ * `parent` is typed from the current node type.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * const visitor: Visitor = {
176
+ * schema(node, { parent }) {
177
+ * // parent type is narrowed by node kind
178
+ * },
179
+ * }
180
+ * ```
181
+ */
182
+ type VisitorContext<T extends Node = Node> = {
183
+ /**
184
+ * Parent node of the currently visited node.
185
+ * For `InputNode`, this is `undefined`.
186
+ */
187
+ parent?: ParentOf<T>;
188
+ };
189
+ /**
190
+ * Synchronous visitor consumed by `transform`. Each optional callback runs
191
+ * for the matching node type. Return a new node to replace it, or `undefined`
192
+ * to leave it untouched.
193
+ *
194
+ * Plugins typically expose `transformer` so users can supply a `Visitor` that
195
+ * rewrites the AST before printing.
196
+ *
197
+ * @example Prefix every operationId
198
+ * ```ts
199
+ * const visitor: Visitor = {
200
+ * operation(node) {
201
+ * return { ...node, operationId: `api_${node.operationId}` }
202
+ * },
203
+ * }
204
+ * ```
205
+ *
206
+ * @example Strip schema descriptions
207
+ * ```ts
208
+ * const visitor: Visitor = {
209
+ * schema(node) {
210
+ * return { ...node, description: undefined }
211
+ * },
212
+ * }
213
+ * ```
214
+ */
215
+ type Visitor = {
216
+ input?(node: InputNode, context: VisitorContext<InputNode>): undefined | null | InputNode;
217
+ output?(node: OutputNode, context: VisitorContext<OutputNode>): undefined | null | OutputNode;
218
+ operation?(node: OperationNode, context: VisitorContext<OperationNode>): undefined | null | OperationNode;
219
+ schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): undefined | null | SchemaNode;
220
+ property?(node: PropertyNode, context: VisitorContext<PropertyNode>): undefined | null | PropertyNode;
221
+ parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): undefined | null | ParameterNode;
222
+ response?(node: ResponseNode, context: VisitorContext<ResponseNode>): undefined | null | ResponseNode;
223
+ };
224
+ /**
225
+ * A visitor callback result that may be sync or async.
226
+ */
227
+ type MaybePromise<T> = T | Promise<T>;
228
+ /**
229
+ * Async visitor for `walk`. Synchronous `Visitor` objects are compatible.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * const visitor: AsyncVisitor = {
234
+ * async operation(node) {
235
+ * await Promise.resolve(node.operationId)
236
+ * },
237
+ * }
238
+ * ```
239
+ */
240
+ type AsyncVisitor = {
241
+ input?(node: InputNode, context: VisitorContext<InputNode>): MaybePromise<undefined | null | InputNode>;
242
+ output?(node: OutputNode, context: VisitorContext<OutputNode>): MaybePromise<undefined | null | OutputNode>;
243
+ operation?(node: OperationNode, context: VisitorContext<OperationNode>): MaybePromise<undefined | null | OperationNode>;
244
+ schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): MaybePromise<undefined | null | SchemaNode>;
245
+ property?(node: PropertyNode, context: VisitorContext<PropertyNode>): MaybePromise<undefined | null | PropertyNode>;
246
+ parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): MaybePromise<undefined | null | ParameterNode>;
247
+ response?(node: ResponseNode, context: VisitorContext<ResponseNode>): MaybePromise<undefined | null | ResponseNode>;
248
+ };
249
+ /**
250
+ * Visitor used by `collect`.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * const visitor: CollectVisitor<string> = {
255
+ * operation(node) {
256
+ * return node.operationId
257
+ * },
258
+ * }
259
+ * ```
260
+ */
261
+ type CollectVisitor<T> = {
262
+ input?(node: InputNode, context: VisitorContext<InputNode>): T | null | undefined;
263
+ output?(node: OutputNode, context: VisitorContext<OutputNode>): T | null | undefined;
264
+ operation?(node: OperationNode, context: VisitorContext<OperationNode>): T | null | undefined;
265
+ schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): T | null | undefined;
266
+ property?(node: PropertyNode, context: VisitorContext<PropertyNode>): T | null | undefined;
267
+ parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): T | null | undefined;
268
+ response?(node: ResponseNode, context: VisitorContext<ResponseNode>): T | null | undefined;
269
+ };
270
+ /**
271
+ * Options for `transform`.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const options: TransformOptions = { depth: 'deep', schema: (node) => node }
276
+ * ```
277
+ *
278
+ * @example
279
+ * ```ts
280
+ * // Only transform the current node, not nested children
281
+ * const options: TransformOptions = { depth: 'shallow', schema: (node) => node }
282
+ * ```
283
+ */
284
+ type TransformOptions = Visitor & {
285
+ /**
286
+ * Traversal depth.
287
+ * @default 'deep'
288
+ */
289
+ depth?: VisitorDepth;
290
+ /**
291
+ * Internal parent override used during recursion.
292
+ */
293
+ parent?: Node;
294
+ };
295
+ /**
296
+ * Options for `walk`.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * const options: WalkOptions = { depth: 'deep', concurrency: 10, root: () => {} }
301
+ * ```
302
+ */
303
+ type WalkOptions = AsyncVisitor & {
304
+ /**
305
+ * Traversal depth.
306
+ * @default 'deep'
307
+ */
308
+ depth?: VisitorDepth;
309
+ /**
310
+ * Maximum number of sibling nodes visited concurrently.
311
+ * @default 30
312
+ */
313
+ concurrency?: number;
314
+ };
315
+ /**
316
+ * Options for `collect`.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }
321
+ * ```
322
+ */
323
+ type CollectOptions<T> = CollectVisitor<T> & {
324
+ /**
325
+ * Traversal depth.
326
+ * @default 'deep'
327
+ */
328
+ depth?: VisitorDepth;
329
+ /**
330
+ * Internal parent override used during recursion.
331
+ */
332
+ parent?: Node;
333
+ };
334
+ /**
335
+ * Async depth-first traversal for side effects. Visitor return values are
336
+ * ignored. Use `transform` when you want to rewrite nodes.
337
+ *
338
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
339
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
340
+ * work. Lower values reduce memory pressure.
341
+ *
342
+ * @example Log every operation
343
+ * ```ts
344
+ * await walk(root, {
345
+ * operation(node) {
346
+ * console.log(node.operationId)
347
+ * },
348
+ * })
349
+ * ```
350
+ *
351
+ * @example Only visit the root node
352
+ * ```ts
353
+ * await walk(root, { depth: 'shallow', input: () => {} })
354
+ * ```
355
+ */
356
+ declare function walk(node: Node, options: WalkOptions): Promise<void>;
357
+ /**
358
+ * Synchronous depth-first transform. Each visitor callback can return a
359
+ * replacement node. Returning `undefined` keeps the original.
360
+ *
361
+ * The original tree is never mutated, a new tree is returned. Pass
362
+ * `depth: 'shallow'` to skip recursion into children.
363
+ *
364
+ * @example Prefix every operationId
365
+ * ```ts
366
+ * const next = transform(root, {
367
+ * operation(node) {
368
+ * return { ...node, operationId: `prefixed_${node.operationId}` }
369
+ * },
370
+ * })
371
+ * ```
372
+ *
373
+ * @example Replace only the root node
374
+ * ```ts
375
+ * const next = transform(root, {
376
+ * depth: 'shallow',
377
+ * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),
378
+ * })
379
+ * ```
380
+ */
381
+ declare function transform(node: InputNode, options: TransformOptions): InputNode;
382
+ declare function transform(node: OutputNode, options: TransformOptions): OutputNode;
383
+ declare function transform(node: OperationNode, options: TransformOptions): OperationNode;
384
+ declare function transform(node: SchemaNode, options: TransformOptions): SchemaNode;
385
+ declare function transform(node: PropertyNode, options: TransformOptions): PropertyNode;
386
+ declare function transform(node: ParameterNode, options: TransformOptions): ParameterNode;
387
+ declare function transform(node: ResponseNode, options: TransformOptions): ResponseNode;
388
+ declare function transform(node: Node, options: TransformOptions): Node;
389
+ /**
390
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
391
+ * callbacks return into an array.
392
+ *
393
+ * @example Collect every operationId
394
+ * ```ts
395
+ * const ids = collect<string>(root, {
396
+ * operation(node) {
397
+ * return node.operationId
398
+ * },
399
+ * })
400
+ * ```
401
+ */
402
+ declare function collect<T>(node: Node, options: CollectOptions<T>): Array<T>;
403
+ //#endregion
404
+ //#region src/defineMacro.d.ts
405
+ /**
406
+ * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a
407
+ * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an
408
+ * optional `when` gate. Macros run on the shared AST, so the same macro works across every adapter
409
+ * and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).
410
+ */
411
+ type Macro = Visitor & {
412
+ /**
413
+ * Macro identifier, surfaced in diagnostics. Follows the `macro<Name>` convention.
414
+ */
415
+ name: string;
416
+ /**
417
+ * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.
418
+ * Ordering within a bucket follows list order.
419
+ */
420
+ enforce?: 'pre' | 'post';
421
+ /**
422
+ * Gate checked against the current node before any callback runs. When it returns `false`
423
+ * the macro is skipped for that node.
424
+ */
425
+ when?: (node: Node) => boolean;
426
+ };
427
+ /**
428
+ * Types a macro for inference and a single construction site, mirroring `definePlugin`.
429
+ * Adds no runtime behavior.
430
+ *
431
+ * @example
432
+ * ```ts
433
+ * const macroUntagged = defineMacro({
434
+ * name: 'untagged',
435
+ * operation(node) {
436
+ * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
437
+ * },
438
+ * })
439
+ * ```
440
+ */
441
+ declare function defineMacro(macro: Macro): Macro;
442
+ /**
443
+ * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
444
+ * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
445
+ * sequentially per node so later macros see earlier output. This differs from a plain visitor, which
446
+ * has no names, ordering, or composition.
447
+ *
448
+ * @example
449
+ * ```ts
450
+ * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
451
+ * const next = transform(root, visitor)
452
+ * ```
453
+ */
454
+ declare function composeMacros(macros: ReadonlyArray<Macro>): Visitor;
455
+ /**
456
+ * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
457
+ * structural sharing, so an empty or no-op macro list returns the same reference. Pass
458
+ * `depth: 'shallow'` to rewrite the root node only.
459
+ *
460
+ * @example
461
+ * ```ts
462
+ * const next = applyMacros(root, [macroIntegerToString])
463
+ * ```
464
+ *
465
+ * @example Apply to the root node only
466
+ * ```ts
467
+ * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
468
+ * ```
469
+ */
470
+ declare function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: {
471
+ depth?: VisitorDepth;
472
+ }): TNode;
473
+ //#endregion
474
+ export { ParentOf as a, collect as c, httpMethods as d, schemaTypes as f, defineMacro as i, transform as l, applyMacros as n, Visitor as o, composeMacros as r, VisitorContext as s, Macro as t, walk as u };
475
+ //# sourceMappingURL=defineMacro-BLIR6k-j.d.ts.map
@@ -0,0 +1,106 @@
1
+ import "./chunk-CNktS9qV.js";
2
+ import { r as transform } from "./visitor-DJ6ZEJvq.js";
3
+ //#region src/defineMacro.ts
4
+ /**
5
+ * Visitor callback names a macro can implement, one per traversable node kind.
6
+ * Mirrors the keys of {@link Visitor}.
7
+ */
8
+ const macroKeys = [
9
+ "input",
10
+ "output",
11
+ "operation",
12
+ "schema",
13
+ "property",
14
+ "parameter",
15
+ "response"
16
+ ];
17
+ /**
18
+ * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
19
+ * list keeps its authored order.
20
+ */
21
+ function enforceWeight(enforce) {
22
+ if (enforce === "pre") return 0;
23
+ if (enforce === "post") return 2;
24
+ return 1;
25
+ }
26
+ /**
27
+ * Types a macro for inference and a single construction site, mirroring `definePlugin`.
28
+ * Adds no runtime behavior.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * const macroUntagged = defineMacro({
33
+ * name: 'untagged',
34
+ * operation(node) {
35
+ * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
36
+ * },
37
+ * })
38
+ * ```
39
+ */
40
+ function defineMacro(macro) {
41
+ return macro;
42
+ }
43
+ /**
44
+ * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
45
+ * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
46
+ * original reference (structural sharing).
47
+ */
48
+ function chain(macros, key, node, context) {
49
+ let current = node;
50
+ for (const macro of macros) {
51
+ const callback = macro[key];
52
+ if (!callback) continue;
53
+ if (macro.when && !macro.when(current)) continue;
54
+ const next = callback(current, context);
55
+ if (next != null) current = next;
56
+ }
57
+ return current === node ? void 0 : current;
58
+ }
59
+ /**
60
+ * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
61
+ * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
62
+ * sequentially per node so later macros see earlier output. This differs from a plain visitor, which
63
+ * has no names, ordering, or composition.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
68
+ * const next = transform(root, visitor)
69
+ * ```
70
+ */
71
+ function composeMacros(macros) {
72
+ const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce));
73
+ const visitor = {};
74
+ for (const key of macroKeys) {
75
+ if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
76
+ const callback = (node, context) => chain(ordered, key, node, context);
77
+ visitor[key] = callback;
78
+ }
79
+ return visitor;
80
+ }
81
+ /**
82
+ * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
83
+ * structural sharing, so an empty or no-op macro list returns the same reference. Pass
84
+ * `depth: 'shallow'` to rewrite the root node only.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const next = applyMacros(root, [macroIntegerToString])
89
+ * ```
90
+ *
91
+ * @example Apply to the root node only
92
+ * ```ts
93
+ * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
94
+ * ```
95
+ */
96
+ function applyMacros(root, macros, options) {
97
+ if (macros.length === 0) return root;
98
+ return transform(root, {
99
+ ...composeMacros(macros),
100
+ depth: options?.depth
101
+ });
102
+ }
103
+ //#endregion
104
+ export { composeMacros as n, defineMacro as r, applyMacros as t };
105
+
106
+ //# sourceMappingURL=defineMacro-BTXvS8nI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defineMacro-BTXvS8nI.js","names":[],"sources":["../src/defineMacro.ts"],"sourcesContent":["import type { VisitorDepth } from './constants.ts'\nimport type { Node } from './nodes/index.ts'\nimport type { Visitor, VisitorContext } from './visitor.ts'\nimport { transform } from './visitor.ts'\n\n/**\n * Visitor callback names a macro can implement, one per traversable node kind.\n * Mirrors the keys of {@link Visitor}.\n */\nconst macroKeys = ['input', 'output', 'operation', 'schema', 'property', 'parameter', 'response'] as const\n\ntype MacroKey = (typeof macroKeys)[number]\n\n/**\n * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain\n * list keeps its authored order.\n */\nfunction enforceWeight(enforce?: 'pre' | 'post'): number {\n if (enforce === 'pre') return 0\n if (enforce === 'post') return 2\n return 1\n}\n\n/**\n * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a\n * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an\n * optional `when` gate. Macros run on the shared AST, so the same macro works across every adapter\n * and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).\n */\nexport type Macro = Visitor & {\n /**\n * Macro identifier, surfaced in diagnostics. Follows the `macro<Name>` convention.\n */\n name: string\n /**\n * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.\n * Ordering within a bucket follows list order.\n */\n enforce?: 'pre' | 'post'\n /**\n * Gate checked against the current node before any callback runs. When it returns `false`\n * the macro is skipped for that node.\n */\n when?: (node: Node) => boolean\n}\n\n/**\n * Types a macro for inference and a single construction site, mirroring `definePlugin`.\n * Adds no runtime behavior.\n *\n * @example\n * ```ts\n * const macroUntagged = defineMacro({\n * name: 'untagged',\n * operation(node) {\n * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }\n * },\n * })\n * ```\n */\nexport function defineMacro(macro: Macro): Macro {\n return macro\n}\n\ntype MacroCallback = (node: Node, context: VisitorContext) => Node | null | undefined\n\n/**\n * Runs every macro's callback for one node kind in order, chaining the result so each macro sees\n * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the\n * original reference (structural sharing).\n */\nfunction chain(macros: ReadonlyArray<Macro>, key: MacroKey, node: Node, context: VisitorContext): Node | undefined {\n let current = node\n\n for (const macro of macros) {\n const callback = macro[key] as MacroCallback | undefined\n if (!callback) continue\n if (macro.when && !macro.when(current)) continue\n\n const next = callback(current, context)\n if (next != null) current = next\n }\n\n return current === node ? undefined : current\n}\n\n/**\n * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin\n * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied\n * sequentially per node so later macros see earlier output. This differs from a plain visitor, which\n * has no names, ordering, or composition.\n *\n * @example\n * ```ts\n * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])\n * const next = transform(root, visitor)\n * ```\n */\nexport function composeMacros(macros: ReadonlyArray<Macro>): Visitor {\n const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce))\n\n const visitor: Visitor = {}\n for (const key of macroKeys) {\n if (!ordered.some((macro) => typeof macro[key] === 'function')) continue\n\n const callback = (node: Node, context: VisitorContext) => chain(ordered, key, node, context)\n ;(visitor as Record<MacroKey, MacroCallback>)[key] = callback\n }\n\n return visitor\n}\n\n/**\n * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s\n * structural sharing, so an empty or no-op macro list returns the same reference. Pass\n * `depth: 'shallow'` to rewrite the root node only.\n *\n * @example\n * ```ts\n * const next = applyMacros(root, [macroIntegerToString])\n * ```\n *\n * @example Apply to the root node only\n * ```ts\n * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })\n * ```\n */\nexport function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {\n if (macros.length === 0) return root\n\n return transform(root, { ...composeMacros(macros), depth: options?.depth }) as TNode\n}\n"],"mappings":";;;;;;;AASA,MAAM,YAAY;CAAC;CAAS;CAAU;CAAa;CAAU;CAAY;CAAa;AAAU;;;;;AAQhG,SAAS,cAAc,SAAkC;CACvD,IAAI,YAAY,OAAO,OAAO;CAC9B,IAAI,YAAY,QAAQ,OAAO;CAC/B,OAAO;AACT;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAqB;CAC/C,OAAO;AACT;;;;;;AASA,SAAS,MAAM,QAA8B,KAAe,MAAY,SAA2C;CACjH,IAAI,UAAU;CAEd,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,MAAM;EACvB,IAAI,CAAC,UAAU;EACf,IAAI,MAAM,QAAQ,CAAC,MAAM,KAAK,OAAO,GAAG;EAExC,MAAM,OAAO,SAAS,SAAS,OAAO;EACtC,IAAI,QAAQ,MAAM,UAAU;CAC9B;CAEA,OAAO,YAAY,OAAO,KAAA,IAAY;AACxC;;;;;;;;;;;;;AAcA,SAAgB,cAAc,QAAuC;CACnE,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,cAAc,EAAE,OAAO,IAAI,cAAc,EAAE,OAAO,CAAC;CAE9F,MAAM,UAAmB,CAAC;CAC1B,KAAK,MAAM,OAAO,WAAW;EAC3B,IAAI,CAAC,QAAQ,MAAM,UAAU,OAAO,MAAM,SAAS,UAAU,GAAG;EAEhE,MAAM,YAAY,MAAY,YAA4B,MAAM,SAAS,KAAK,MAAM,OAAO;EAC1F,QAA6C,OAAO;CACvD;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAgC,MAAa,QAA8B,SAA2C;CACpI,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAO,UAAU,MAAM;EAAE,GAAG,cAAc,MAAM;EAAG,OAAO,SAAS;CAAM,CAAC;AAC5E"}