@kubb/ast 5.0.0-beta.80 → 5.0.0-beta.82

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.
@@ -1,1203 +0,0 @@
1
- import "./rolldown-runtime-CNktS9qV.js";
2
- import { hash } from "node:crypto";
3
- import path from "node:path";
4
- //#region src/constants.ts
5
- const visitorDepths = {
6
- shallow: "shallow",
7
- deep: "deep"
8
- };
9
- /**
10
- * Schema type discriminators used by all AST schema nodes.
11
- *
12
- * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
13
- */
14
- const schemaTypes = {
15
- /**
16
- * Text value.
17
- */
18
- string: "string",
19
- /**
20
- * Floating-point number (`float`, `double`).
21
- */
22
- number: "number",
23
- /**
24
- * Whole number (`int32`). Use `bigint` for `int64`.
25
- */
26
- integer: "integer",
27
- /**
28
- * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
29
- */
30
- bigint: "bigint",
31
- /**
32
- * Boolean value.
33
- */
34
- boolean: "boolean",
35
- /**
36
- * Explicit null value.
37
- */
38
- null: "null",
39
- /**
40
- * Any value (no type restriction).
41
- */
42
- any: "any",
43
- /**
44
- * Unknown value (must be narrowed before usage).
45
- */
46
- unknown: "unknown",
47
- /**
48
- * No return value (`void`).
49
- */
50
- void: "void",
51
- /**
52
- * Object with named properties.
53
- */
54
- object: "object",
55
- /**
56
- * Sequential list of items.
57
- */
58
- array: "array",
59
- /**
60
- * Fixed-length list with position-specific items.
61
- */
62
- tuple: "tuple",
63
- /**
64
- * "One of" multiple schema members.
65
- */
66
- union: "union",
67
- /**
68
- * "All of" multiple schema members.
69
- */
70
- intersection: "intersection",
71
- /**
72
- * Enum schema.
73
- */
74
- enum: "enum",
75
- /**
76
- * Reference to another schema.
77
- */
78
- ref: "ref",
79
- /**
80
- * Calendar date (for example `2026-03-24`).
81
- */
82
- date: "date",
83
- /**
84
- * Date-time value (for example `2026-03-24T09:00:00Z`).
85
- */
86
- datetime: "datetime",
87
- /**
88
- * Time-only value (for example `09:00:00`).
89
- */
90
- time: "time",
91
- /**
92
- * UUID value.
93
- */
94
- uuid: "uuid",
95
- /**
96
- * Email address value.
97
- */
98
- email: "email",
99
- /**
100
- * URL value.
101
- */
102
- url: "url",
103
- /**
104
- * IPv4 address value.
105
- */
106
- ipv4: "ipv4",
107
- /**
108
- * IPv6 address value.
109
- */
110
- ipv6: "ipv6",
111
- /**
112
- * Binary/blob value.
113
- */
114
- blob: "blob",
115
- /**
116
- * Impossible value (`never`).
117
- */
118
- never: "never"
119
- };
120
- //#endregion
121
- //#region src/guards.ts
122
- /**
123
- * Narrows a `SchemaNode` to the variant that matches `type`.
124
- *
125
- * @example
126
- * ```ts
127
- * const schema = createSchema({ type: 'string' })
128
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
129
- * ```
130
- */
131
- function narrowSchema(node, type) {
132
- return node?.type === type ? node : null;
133
- }
134
- /**
135
- * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
136
- *
137
- * @example
138
- * ```ts
139
- * if (isHttpOperationNode(node)) {
140
- * console.log(node.method, node.path)
141
- * }
142
- * ```
143
- */
144
- function isHttpOperationNode(node) {
145
- return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
146
- }
147
- //#endregion
148
- //#region src/defineNode.ts
149
- /**
150
- * Visitor callback names, one per traversable node kind, in traversal order.
151
- * Kept in sync with the keys of `Visitor` in `visitor.ts`.
152
- */
153
- const visitorKeys = [
154
- "input",
155
- "output",
156
- "operation",
157
- "schema",
158
- "property",
159
- "parameter",
160
- "response"
161
- ];
162
- /**
163
- * Builds a type guard that matches nodes of the given `kind`.
164
- */
165
- function isKind(kind) {
166
- return (node) => node?.kind === kind;
167
- }
168
- /**
169
- * Defines a node once and derives its `create` builder, `is` guard, and traversal
170
- * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
171
- * `kind`, so node construction lives in one place without scattered `as` casts.
172
- *
173
- * @example Simple node
174
- * ```ts
175
- * const importDef = defineNode<ImportNode>({ kind: 'Import' })
176
- * const createImport = importDef.create
177
- * ```
178
- *
179
- * @example Node with a build hook
180
- * ```ts
181
- * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
182
- * kind: 'Property',
183
- * build: (props) => ({ ...props, required: props.required ?? false }),
184
- * children: ['schema'],
185
- * visitorKey: 'property',
186
- * })
187
- * ```
188
- */
189
- function defineNode(config) {
190
- const { kind, defaults, build, children, visitorKey } = config;
191
- function create(input) {
192
- const base = build ? build(input) : input;
193
- const node = {
194
- kind,
195
- ...defaults,
196
- ...base
197
- };
198
- node.kind = kind;
199
- return node;
200
- }
201
- return {
202
- kind,
203
- create,
204
- is: isKind(kind),
205
- children,
206
- visitorKey
207
- };
208
- }
209
- //#endregion
210
- //#region src/nodes/code.ts
211
- /**
212
- * Definition for the {@link ConstNode}.
213
- */
214
- const constDef = defineNode({ kind: "Const" });
215
- /**
216
- * Definition for the {@link TypeNode}.
217
- */
218
- const typeDef = defineNode({ kind: "Type" });
219
- /**
220
- * Definition for the {@link FunctionNode}.
221
- */
222
- const functionDef = defineNode({ kind: "Function" });
223
- /**
224
- * Definition for the {@link ArrowFunctionNode}.
225
- */
226
- const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
227
- /**
228
- * Definition for the {@link TextNode}.
229
- */
230
- const textDef = defineNode({
231
- kind: "Text",
232
- build: (value) => ({ value })
233
- });
234
- /**
235
- * Definition for the {@link BreakNode}.
236
- */
237
- const breakDef = defineNode({
238
- kind: "Break",
239
- build: () => ({})
240
- });
241
- /**
242
- * Definition for the {@link JsxNode}.
243
- */
244
- const jsxDef = defineNode({
245
- kind: "Jsx",
246
- build: (value) => ({ value })
247
- });
248
- /**
249
- * Creates a `ConstNode` representing a TypeScript `const` declaration.
250
- *
251
- * @example Exported constant with type and `as const`
252
- * ```ts
253
- * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
254
- * // export const pets: Pet[] = ... as const
255
- * ```
256
- */
257
- const createConst = constDef.create;
258
- /**
259
- * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
260
- *
261
- * @example
262
- * ```ts
263
- * createType({ name: 'Pet', export: true })
264
- * // export type Pet = ...
265
- * ```
266
- */
267
- const createType = typeDef.create;
268
- /**
269
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
270
- *
271
- * @example
272
- * ```ts
273
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
274
- * // export async function fetchPet(): Promise<Pet> { ... }
275
- * ```
276
- */
277
- const createFunction = functionDef.create;
278
- /**
279
- * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
280
- *
281
- * @example
282
- * ```ts
283
- * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
284
- * // export const double = (n: number) => ...
285
- * ```
286
- */
287
- const createArrowFunction = arrowFunctionDef.create;
288
- /**
289
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
290
- *
291
- * @example
292
- * ```ts
293
- * createText('return fetch(id)')
294
- * // { kind: 'Text', value: 'return fetch(id)' }
295
- * ```
296
- */
297
- const createText = textDef.create;
298
- /**
299
- * Creates a {@link BreakNode} representing a line break in the source output.
300
- *
301
- * @example
302
- * ```ts
303
- * createBreak()
304
- * // { kind: 'Break' }
305
- * ```
306
- */
307
- function createBreak() {
308
- return breakDef.create();
309
- }
310
- /**
311
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
312
- *
313
- * @example
314
- * ```ts
315
- * createJsx('<>\n <a href={href}>Open</a>\n</>')
316
- * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
317
- * ```
318
- */
319
- const createJsx = jsxDef.create;
320
- //#endregion
321
- //#region src/nodes/content.ts
322
- /**
323
- * Definition for the {@link ContentNode}.
324
- */
325
- const contentDef = defineNode({
326
- kind: "Content",
327
- children: ["schema"]
328
- });
329
- /**
330
- * Creates a `ContentNode` for a single request-body or response content type.
331
- */
332
- const createContent = contentDef.create;
333
- //#endregion
334
- //#region ../../internals/utils/src/casing.ts
335
- /**
336
- * Shared implementation for camelCase and PascalCase conversion.
337
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
338
- * and capitalizes each word according to `pascal`.
339
- *
340
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
341
- */
342
- function toCamelOrPascal(text, pascal) {
343
- return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
344
- if (word.length > 1 && word === word.toUpperCase()) return word;
345
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
346
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
347
- }
348
- /**
349
- * Converts `text` to PascalCase.
350
- *
351
- * @example Word boundaries
352
- * `pascalCase('hello-world') // 'HelloWorld'`
353
- *
354
- * @example With a suffix
355
- * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
356
- */
357
- function pascalCase(text, { prefix = "", suffix = "" } = {}) {
358
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
359
- }
360
- //#endregion
361
- //#region ../../internals/utils/src/fs.ts
362
- /**
363
- * Strips the file extension from a path or file name.
364
- * Only removes the last `.ext` segment when the dot is not part of a directory name.
365
- *
366
- * @example
367
- * trimExtName('petStore.ts') // 'petStore'
368
- * trimExtName('/src/models/pet.ts') // '/src/models/pet'
369
- * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
370
- * trimExtName('noExtension') // 'noExtension'
371
- */
372
- function trimExtName(text) {
373
- const dotIndex = text.lastIndexOf(".");
374
- if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
375
- return text;
376
- }
377
- //#endregion
378
- //#region src/utils/extractStringsFromNodes.ts
379
- /**
380
- * Extracts all string content from a `CodeNode` tree recursively.
381
- *
382
- * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
383
- * and nested node content. Used to build the full source string for import filtering.
384
- */
385
- function extractStringsFromNodes(nodes) {
386
- if (!nodes?.length) return "";
387
- const collected = [];
388
- for (const node of nodes) {
389
- if (typeof node === "string") {
390
- if (node) collected.push(node);
391
- continue;
392
- }
393
- if (node.kind === "Text") {
394
- if (node.value) collected.push(node.value);
395
- continue;
396
- }
397
- if (node.kind === "Break") continue;
398
- if (node.kind === "Jsx") {
399
- if (node.value) collected.push(node.value);
400
- continue;
401
- }
402
- const parts = [];
403
- if ("params" in node && node.params) parts.push(node.params);
404
- if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
405
- if ("returnType" in node && node.returnType) parts.push(node.returnType);
406
- if ("type" in node && typeof node.type === "string") parts.push(node.type);
407
- const nested = extractStringsFromNodes(node.nodes);
408
- if (nested) parts.push(nested);
409
- if (parts.length) collected.push(parts.join("\n"));
410
- }
411
- return collected.join("\n");
412
- }
413
- //#endregion
414
- //#region src/utils/fileMerge.ts
415
- function sourceKey(source) {
416
- return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
417
- }
418
- function pathTypeKey(path, isTypeOnly) {
419
- return `${path}:${isTypeOnly ?? false}`;
420
- }
421
- function exportKey(path, name, isTypeOnly, asAlias) {
422
- return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
423
- }
424
- function importKey(path, name, isTypeOnly) {
425
- return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
426
- }
427
- /**
428
- * Computes a multi-level sort key for exports and imports:
429
- * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
430
- */
431
- function sortKey(node) {
432
- const isArray = Array.isArray(node.name) ? "1" : "0";
433
- const typeOnly = node.isTypeOnly ? "0" : "1";
434
- const hasName = node.name != null ? "1" : "0";
435
- const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
436
- return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
437
- }
438
- /**
439
- * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
440
- * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
441
- * the deduplicated array in original order.
442
- */
443
- function combineSources(sources) {
444
- const seen = /* @__PURE__ */ new Map();
445
- for (const source of sources) {
446
- const key = sourceKey(source);
447
- if (!seen.has(key)) seen.set(key, source);
448
- }
449
- return [...seen.values()];
450
- }
451
- /**
452
- * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
453
- *
454
- * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
455
- */
456
- function mergeNameArrays(existing, incoming) {
457
- const merged = new Set(existing);
458
- for (const name of incoming) merged.add(name);
459
- return [...merged];
460
- }
461
- /**
462
- * Deduplicates and merges `ExportNode` objects by path and type.
463
- *
464
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
465
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
466
- */
467
- function combineExports(exports) {
468
- const result = [];
469
- const namedByPath = /* @__PURE__ */ new Map();
470
- const seen = /* @__PURE__ */ new Set();
471
- const keyed = exports.map((node) => ({
472
- node,
473
- key: sortKey(node)
474
- }));
475
- keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
476
- for (const { node: curr } of keyed) {
477
- const { name, path, isTypeOnly, asAlias } = curr;
478
- if (Array.isArray(name)) {
479
- if (!name.length) continue;
480
- const key = pathTypeKey(path, isTypeOnly);
481
- const existing = namedByPath.get(key);
482
- if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
483
- else {
484
- const newItem = {
485
- ...curr,
486
- name: [...new Set(name)]
487
- };
488
- result.push(newItem);
489
- namedByPath.set(key, newItem);
490
- }
491
- } else {
492
- const key = exportKey(path, name, isTypeOnly, asAlias);
493
- if (!seen.has(key)) {
494
- result.push(curr);
495
- seen.add(key);
496
- }
497
- }
498
- }
499
- return result;
500
- }
501
- /**
502
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
503
- *
504
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
505
- * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
506
- */
507
- function combineImports(imports, exports, source) {
508
- const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
509
- const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
510
- const importNameMemo = /* @__PURE__ */ new Map();
511
- const canonicalizeName = (n) => {
512
- if (typeof n === "string") return n;
513
- const key = `${n.propertyName}:${n.name ?? ""}`;
514
- if (!importNameMemo.has(key)) importNameMemo.set(key, n);
515
- return importNameMemo.get(key);
516
- };
517
- const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
518
- for (const node of imports) {
519
- if (!Array.isArray(node.name)) continue;
520
- if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
521
- }
522
- const result = [];
523
- const namedByPath = /* @__PURE__ */ new Map();
524
- const seen = /* @__PURE__ */ new Set();
525
- const keyed = imports.map((node) => ({
526
- node,
527
- key: sortKey(node)
528
- }));
529
- keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
530
- for (const { node: curr } of keyed) {
531
- if (curr.path === curr.root) continue;
532
- const { path, isTypeOnly } = curr;
533
- let { name } = curr;
534
- if (Array.isArray(name)) {
535
- name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
536
- if (!name.length) continue;
537
- const key = pathTypeKey(path, isTypeOnly);
538
- const existing = namedByPath.get(key);
539
- if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
540
- else {
541
- const newItem = {
542
- ...curr,
543
- name
544
- };
545
- result.push(newItem);
546
- namedByPath.set(key, newItem);
547
- }
548
- } else {
549
- if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
550
- const key = importKey(path, name, isTypeOnly);
551
- if (!seen.has(key)) {
552
- result.push(curr);
553
- seen.add(key);
554
- }
555
- }
556
- }
557
- return result;
558
- }
559
- //#endregion
560
- //#region src/nodes/file.ts
561
- /**
562
- * Definition for the {@link ImportNode}.
563
- */
564
- const importDef = defineNode({ kind: "Import" });
565
- /**
566
- * Definition for the {@link ExportNode}.
567
- */
568
- const exportDef = defineNode({ kind: "Export" });
569
- /**
570
- * Definition for the {@link SourceNode}.
571
- */
572
- const sourceDef = defineNode({ kind: "Source" });
573
- /**
574
- * Definition for the {@link FileNode}. The fully resolved builder lives in
575
- * `createFile`, so this definition only supplies the guard.
576
- */
577
- const fileDef = defineNode({ kind: "File" });
578
- /**
579
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
580
- *
581
- * @example Named import
582
- * ```ts
583
- * createImport({ name: ['useState'], path: 'react' })
584
- * // import { useState } from 'react'
585
- * ```
586
- */
587
- const createImport = importDef.create;
588
- /**
589
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
590
- *
591
- * @example Named export
592
- * ```ts
593
- * createExport({ name: ['Pet'], path: './Pet' })
594
- * // export { Pet } from './Pet'
595
- * ```
596
- */
597
- const createExport = exportDef.create;
598
- /**
599
- * Creates a `SourceNode` representing a fragment of source code within a file.
600
- *
601
- * @example
602
- * ```ts
603
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
604
- * ```
605
- */
606
- const createSource = sourceDef.create;
607
- /**
608
- * Creates a fully resolved `FileNode` from a file input descriptor.
609
- *
610
- * Computes:
611
- * - `id` SHA256 hash of the file path
612
- * - `name` `baseName` without extension
613
- * - `extname` extension extracted from `baseName`
614
- *
615
- * Deduplicates:
616
- * - `sources` via `combineSources`
617
- * - `exports` via `combineExports`
618
- * - `imports` via `combineImports` (also filters unused imports)
619
- *
620
- * @throws {Error} when `baseName` has no extension.
621
- *
622
- * @example
623
- * ```ts
624
- * const file = createFile({
625
- * baseName: 'petStore.ts',
626
- * path: 'src/models/petStore.ts',
627
- * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
628
- * imports: [createImport({ name: ['z'], path: 'zod' })],
629
- * exports: [createExport({ name: ['Pet'], path: './petStore' })],
630
- * })
631
- * // file.id = SHA256 hash of 'src/models/petStore.ts'
632
- * // file.name = 'petStore'
633
- * // file.extname = '.ts'
634
- * ```
635
- *
636
- * @example Copy a real file into the output verbatim
637
- * ```ts
638
- * const file = createFile({
639
- * baseName: 'client.ts',
640
- * path: 'src/gen/client.ts',
641
- * copy: '/abs/path/to/templates/client.ts',
642
- * })
643
- * ```
644
- */
645
- function createFile(input) {
646
- const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
647
- if (!extname) throw new Error(`No extname found for ${input.baseName}`);
648
- const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
649
- let resolvedImports = [];
650
- if (input.imports?.length) {
651
- const source = extractStringsFromNodes((input.sources ?? []).flatMap((item) => item.nodes ?? [])) || void 0;
652
- const combinedImports = combineImports(input.imports, resolvedExports, source);
653
- const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
654
- const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
655
- resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
656
- if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
657
- const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
658
- if (!kept.length) return [];
659
- return [kept.length === imp.name.length ? imp : {
660
- ...imp,
661
- name: kept
662
- }];
663
- });
664
- }
665
- const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
666
- return {
667
- kind: "File",
668
- ...input,
669
- id: hash("sha256", input.path, "hex"),
670
- name: trimExtName(input.baseName),
671
- extname,
672
- imports: resolvedImports,
673
- exports: resolvedExports,
674
- sources: resolvedSources,
675
- meta: input.meta ?? {}
676
- };
677
- }
678
- //#endregion
679
- //#region src/nodes/input.ts
680
- /**
681
- * Definition for the {@link InputNode}.
682
- */
683
- const inputDef = defineNode({
684
- kind: "Input",
685
- defaults: {
686
- schemas: [],
687
- operations: [],
688
- meta: {
689
- circularNames: [],
690
- enumNames: []
691
- }
692
- },
693
- children: ["schemas", "operations"],
694
- visitorKey: "input"
695
- });
696
- /**
697
- * Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
698
- * `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
699
- * `schemas`/`operations`. Both variants get the defaulted `meta`.
700
- *
701
- * @example Eager
702
- * ```ts
703
- * const input = createInput()
704
- * // { kind: 'Input', schemas: [], operations: [] }
705
- * ```
706
- *
707
- * @example Streaming
708
- * ```ts
709
- * const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
710
- * ```
711
- */
712
- function createInput(options = {}) {
713
- const { stream, ...overrides } = options;
714
- if (stream) return {
715
- kind: "Input",
716
- meta: {
717
- circularNames: [],
718
- enumNames: []
719
- },
720
- ...overrides
721
- };
722
- return inputDef.create(overrides);
723
- }
724
- //#endregion
725
- //#region src/nodes/requestBody.ts
726
- /**
727
- * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
728
- * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
729
- */
730
- const requestBodyDef = defineNode({
731
- kind: "RequestBody",
732
- children: ["content"]
733
- });
734
- /**
735
- * Creates a `RequestBodyNode`.
736
- */
737
- const createRequestBody = requestBodyDef.create;
738
- //#endregion
739
- //#region src/nodes/operation.ts
740
- /**
741
- * Definition for the {@link OperationNode}. HTTP operations (those carrying both
742
- * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
743
- * normalized into a `RequestBodyNode`.
744
- */
745
- const operationDef = defineNode({
746
- kind: "Operation",
747
- build: (props) => {
748
- const { requestBody, ...rest } = props;
749
- const isHttp = rest.method !== void 0 && rest.path !== void 0;
750
- return {
751
- tags: [],
752
- parameters: [],
753
- responses: [],
754
- ...rest,
755
- ...isHttp ? { protocol: "http" } : {},
756
- requestBody: requestBody ? createRequestBody(requestBody) : void 0
757
- };
758
- },
759
- children: [
760
- "parameters",
761
- "requestBody",
762
- "responses"
763
- ],
764
- visitorKey: "operation"
765
- });
766
- function createOperation(props) {
767
- return operationDef.create(props);
768
- }
769
- //#endregion
770
- //#region src/nodes/output.ts
771
- /**
772
- * Definition for the {@link OutputNode}.
773
- */
774
- const outputDef = defineNode({
775
- kind: "Output",
776
- defaults: { files: [] },
777
- visitorKey: "output"
778
- });
779
- /**
780
- * Creates an `OutputNode` with a stable default for `files`.
781
- *
782
- * @example
783
- * ```ts
784
- * const output = createOutput()
785
- * // { kind: 'Output', files: [] }
786
- * ```
787
- */
788
- function createOutput(overrides = {}) {
789
- return outputDef.create(overrides);
790
- }
791
- //#endregion
792
- //#region src/optionality.ts
793
- /**
794
- * Generic JSON Schema optionality: a non-required field is optional, and a
795
- * non-required nullable field is nullish.
796
- */
797
- function optionality(schema, required) {
798
- const nullable = schema.nullable ?? false;
799
- return {
800
- ...schema,
801
- optional: !required && !nullable ? true : void 0,
802
- nullish: !required && nullable ? true : void 0
803
- };
804
- }
805
- //#endregion
806
- //#region src/nodes/parameter.ts
807
- /**
808
- * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
809
- * `optional`/`nullish` flags are derived from it through {@link optionality}.
810
- */
811
- const parameterDef = defineNode({
812
- kind: "Parameter",
813
- build: (props) => {
814
- const required = props.required ?? false;
815
- return {
816
- ...props,
817
- required,
818
- schema: optionality(props.schema, required)
819
- };
820
- },
821
- children: ["schema"],
822
- visitorKey: "parameter"
823
- });
824
- /**
825
- * Creates a `ParameterNode`.
826
- *
827
- * @example
828
- * ```ts
829
- * const param = createParameter({
830
- * name: 'petId',
831
- * in: 'path',
832
- * required: true,
833
- * schema: createSchema({ type: 'string' }),
834
- * })
835
- * ```
836
- */
837
- const createParameter = parameterDef.create;
838
- //#endregion
839
- //#region src/nodes/property.ts
840
- /**
841
- * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
842
- * `optional`/`nullish` flags are derived from it through {@link optionality}.
843
- */
844
- const propertyDef = defineNode({
845
- kind: "Property",
846
- build: (props) => {
847
- const required = props.required ?? false;
848
- return {
849
- ...props,
850
- required,
851
- schema: optionality(props.schema, required)
852
- };
853
- },
854
- children: ["schema"],
855
- visitorKey: "property"
856
- });
857
- /**
858
- * Creates a `PropertyNode`.
859
- *
860
- * @example
861
- * ```ts
862
- * const property = createProperty({
863
- * name: 'status',
864
- * required: true,
865
- * schema: createSchema({ type: 'string', nullable: true }),
866
- * })
867
- * // required=true, no optional/nullish
868
- * ```
869
- */
870
- const createProperty = propertyDef.create;
871
- //#endregion
872
- //#region src/nodes/response.ts
873
- /**
874
- * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
875
- * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
876
- */
877
- const responseDef = defineNode({
878
- kind: "Response",
879
- build: (props) => {
880
- const { schema, mediaType, keysToOmit, content, ...rest } = props;
881
- const entries = content ?? (schema ? [createContent({
882
- contentType: mediaType ?? "application/json",
883
- schema,
884
- keysToOmit: keysToOmit ?? null
885
- })] : void 0);
886
- return {
887
- ...rest,
888
- content: entries
889
- };
890
- },
891
- children: ["content"],
892
- visitorKey: "response"
893
- });
894
- /**
895
- * Creates a `ResponseNode`.
896
- *
897
- * @example
898
- * ```ts
899
- * const response = createResponse({
900
- * statusCode: '200',
901
- * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
902
- * })
903
- * ```
904
- */
905
- const createResponse = responseDef.create;
906
- //#endregion
907
- //#region src/nodes/schema.ts
908
- /**
909
- * Maps schema `type` to its underlying `primitive`.
910
- * Primitive types map to themselves and special string formats map to `'string'`.
911
- * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
912
- */
913
- const TYPE_TO_PRIMITIVE = {
914
- string: "string",
915
- number: "number",
916
- integer: "integer",
917
- bigint: "bigint",
918
- boolean: "boolean",
919
- null: "null",
920
- any: "any",
921
- unknown: "unknown",
922
- void: "void",
923
- never: "never",
924
- object: "object",
925
- array: "array",
926
- date: "date",
927
- uuid: "string",
928
- email: "string",
929
- url: "string",
930
- datetime: "string",
931
- time: "string"
932
- };
933
- /**
934
- * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
935
- * empty array, and `primitive` is inferred from `type` when not explicitly provided.
936
- */
937
- const schemaDef = defineNode({
938
- kind: "Schema",
939
- build: (props) => {
940
- if (props.type === "object") return {
941
- properties: [],
942
- primitive: "object",
943
- ...props
944
- };
945
- return {
946
- primitive: TYPE_TO_PRIMITIVE[props.type],
947
- ...props
948
- };
949
- },
950
- children: [
951
- "properties",
952
- "items",
953
- "members",
954
- "additionalProperties"
955
- ],
956
- visitorKey: "schema"
957
- });
958
- function createSchema(props) {
959
- return schemaDef.create(props);
960
- }
961
- //#endregion
962
- //#region src/registry.ts
963
- /**
964
- * Every node definition. Adding a node means adding its `defineNode` to one
965
- * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
966
- */
967
- const nodeDefs = [
968
- inputDef,
969
- outputDef,
970
- operationDef,
971
- requestBodyDef,
972
- contentDef,
973
- responseDef,
974
- schemaDef,
975
- propertyDef,
976
- parameterDef,
977
- constDef,
978
- typeDef,
979
- functionDef,
980
- arrowFunctionDef,
981
- textDef,
982
- breakDef,
983
- jsxDef,
984
- importDef,
985
- exportDef,
986
- sourceDef,
987
- fileDef
988
- ];
989
- //#endregion
990
- //#region src/visitor.ts
991
- /**
992
- * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
993
- * Derived from each definition's `children`.
994
- */
995
- const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
996
- /**
997
- * Maps a node kind to the matching visitor callback name. Derived from each
998
- * definition's `visitorKey`.
999
- */
1000
- const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1001
- /**
1002
- * Creates a small async concurrency limiter.
1003
- *
1004
- * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
1005
- *
1006
- * @example
1007
- * ```ts
1008
- * const limit = createLimit(2)
1009
- * for (const task of [taskA, taskB, taskC]) {
1010
- * await limit(() => task())
1011
- * }
1012
- * // only 2 tasks run at the same time
1013
- * ```
1014
- */
1015
- function createLimit(concurrency) {
1016
- let active = 0;
1017
- const queue = [];
1018
- function next() {
1019
- if (active < concurrency && queue.length > 0) {
1020
- active++;
1021
- queue.shift()();
1022
- }
1023
- }
1024
- return function limit(fn) {
1025
- return new Promise((resolve, reject) => {
1026
- queue.push(() => {
1027
- Promise.resolve(fn()).then(resolve, reject).finally(() => {
1028
- active--;
1029
- next();
1030
- });
1031
- });
1032
- next();
1033
- });
1034
- };
1035
- }
1036
- const visitorKeysByKind = VISITOR_KEYS;
1037
- /**
1038
- * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1039
- */
1040
- function isNode(value) {
1041
- return typeof value === "object" && value !== null && typeof value.kind === "string";
1042
- }
1043
- /**
1044
- * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1045
- *
1046
- * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1047
- *
1048
- * @example
1049
- * ```ts
1050
- * const children = getChildren(operationNode, true)
1051
- * // returns parameters, the request body, and responses
1052
- * ```
1053
- */
1054
- function* getChildren(node, recurse) {
1055
- if (node.kind === "Schema" && !recurse) return;
1056
- const keys = visitorKeysByKind[node.kind];
1057
- if (!keys) return;
1058
- const record = node;
1059
- for (const key of keys) {
1060
- const value = record[key];
1061
- if (Array.isArray(value)) {
1062
- for (const item of value) if (isNode(item)) yield item;
1063
- } else if (isNode(value)) yield value;
1064
- }
1065
- }
1066
- /**
1067
- * Runs the visitor callback that matches `node.kind` with the traversal
1068
- * context. The result is a replacement node, a collected value, or `undefined`
1069
- * when no callback is registered for the kind.
1070
- *
1071
- * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
1072
- * in one place. `TResult` is the caller's expected return: the same node type
1073
- * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
1074
- */
1075
- function applyVisitor(node, visitor, parent) {
1076
- const key = VISITOR_KEY_BY_KIND[node.kind];
1077
- if (!key) return void 0;
1078
- const fn = visitor[key];
1079
- return fn?.(node, { parent });
1080
- }
1081
- /**
1082
- * Async depth-first traversal for side effects. Visitor return values are
1083
- * ignored. Use `transform` when you want to rewrite nodes.
1084
- *
1085
- * Sibling nodes at each depth run concurrently up to `options.concurrency`
1086
- * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
1087
- * work. Lower values reduce memory pressure.
1088
- *
1089
- * @example Log every operation
1090
- * ```ts
1091
- * await walk(root, {
1092
- * operation(node) {
1093
- * console.log(node.operationId)
1094
- * },
1095
- * })
1096
- * ```
1097
- *
1098
- * @example Only visit the root node
1099
- * ```ts
1100
- * await walk(root, { depth: 'shallow', input: () => {} })
1101
- * ```
1102
- */
1103
- async function walk(node, options) {
1104
- return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
1105
- }
1106
- async function _walk(node, visitor, recurse, limit, parent) {
1107
- await limit(() => applyVisitor(node, visitor, parent));
1108
- let pending;
1109
- for (const child of getChildren(node, recurse)) (pending ??= []).push(_walk(child, visitor, recurse, limit, node));
1110
- if (pending) await Promise.all(pending);
1111
- }
1112
- function transform(node, options) {
1113
- const { depth, parent, ...visitor } = options;
1114
- return transformNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1115
- }
1116
- /**
1117
- * Visits a single node, then immutably rebuilds its children. Returns the original
1118
- * reference when neither the visitor nor the child rebuild changed anything, so callers
1119
- * can detect "nothing changed" by identity and ancestors avoid reallocating.
1120
- */
1121
- function transformNode(node, visitor, recurse, parent) {
1122
- return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
1123
- }
1124
- /**
1125
- * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1126
- * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1127
- * `Schema` children are skipped in shallow mode.
1128
- */
1129
- function transformChildren(node, visitor, recurse) {
1130
- if (node.kind === "Schema" && !recurse) return node;
1131
- const keys = visitorKeysByKind[node.kind];
1132
- if (!keys) return node;
1133
- const record = node;
1134
- let updates;
1135
- for (const key of keys) {
1136
- if (!(key in record)) continue;
1137
- const value = record[key];
1138
- if (Array.isArray(value)) {
1139
- let mapped;
1140
- for (const [i, item] of value.entries()) {
1141
- const next = isNode(item) ? transformNode(item, visitor, recurse, node) : item;
1142
- if (mapped) {
1143
- mapped.push(next);
1144
- continue;
1145
- }
1146
- if (next !== item) mapped = [...value.slice(0, i), next];
1147
- }
1148
- if (mapped) (updates ??= {})[key] = mapped;
1149
- } else if (isNode(value)) {
1150
- const next = transformNode(value, visitor, recurse, node);
1151
- if (next !== value) (updates ??= {})[key] = next;
1152
- }
1153
- }
1154
- return updates ? {
1155
- ...node,
1156
- ...updates
1157
- } : node;
1158
- }
1159
- /**
1160
- * Lazy depth-first collection pass. Yields every non-null value returned by
1161
- * the visitor callbacks. Use `collect` for the eager array form.
1162
- *
1163
- * @example Collect every operationId
1164
- * ```ts
1165
- * const ids: string[] = []
1166
- * for (const id of collectLazy<string>(root, {
1167
- * operation(node) {
1168
- * return node.operationId
1169
- * },
1170
- * })) {
1171
- * ids.push(id)
1172
- * }
1173
- * ```
1174
- */
1175
- function* collectLazy(node, options) {
1176
- const { depth, parent, ...visitor } = options;
1177
- yield* collectNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1178
- }
1179
- function* collectNode(node, visitor, recurse, parent) {
1180
- const v = applyVisitor(node, visitor, parent);
1181
- if (v != null) yield v;
1182
- for (const child of getChildren(node, recurse)) yield* collectNode(child, visitor, recurse, node);
1183
- }
1184
- /**
1185
- * Eager depth-first collection pass. Gathers every non-null value the visitor
1186
- * callbacks return into an array.
1187
- *
1188
- * @example Collect every operationId
1189
- * ```ts
1190
- * const ids = collect<string>(root, {
1191
- * operation(node) {
1192
- * return node.operationId
1193
- * },
1194
- * })
1195
- * ```
1196
- */
1197
- function collect(node, options) {
1198
- return Array.from(collectLazy(node, options));
1199
- }
1200
- //#endregion
1201
- export { schemaTypes as $, sourceDef as A, createConst as B, createExport as C, exportDef as D, createSource as E, arrowFunctionDef as F, functionDef as G, createJsx as H, breakDef as I, typeDef as J, jsxDef as K, constDef as L, pascalCase as M, contentDef as N, fileDef as O, createContent as P, narrowSchema as Q, createArrowFunction as R, inputDef as S, createImport as T, createText as U, createFunction as V, createType as W, visitorKeys as X, defineNode as Y, isHttpOperationNode as Z, createOperation as _, nodeDefs as a, requestBodyDef as b, createResponse as c, propertyDef as d, createParameter as f, outputDef as g, createOutput as h, walk as i, extractStringsFromNodes as j, importDef as k, responseDef as l, optionality as m, collectLazy as n, createSchema as o, parameterDef as p, textDef as q, transform as r, schemaDef as s, collect as t, createProperty as u, operationDef as v, createFile as w, createInput as x, createRequestBody as y, createBreak as z };
1202
-
1203
- //# sourceMappingURL=visitor-Dk0DNLfC.js.map