@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
@@ -1,157 +1,6 @@
1
1
  import "./chunk-CNktS9qV.js";
2
- import { A as contentDef, D as fileDef, E as exportDef, G as typeDef, H as functionDef, K as createProperty, M as arrowFunctionDef, N as breakDef, O as importDef, P as constDef, Q as schemaDef, S as typeLiteralDef, U as jsxDef, W as textDef, X as pascalCase, Y as camelCase, Z as createSchema, _ as createTypeLiteral, b as indexedAccessTypeDef, c as operationDef, f as inputDef, h as createIndexedAccessType, i as parameterDef, k as sourceDef, m as createFunctionParameters, n as responseDef, o as outputDef, p as createFunctionParameter, q as propertyDef, u as requestBodyDef, v as functionParameterDef, x as objectBindingPatternDef, y as functionParametersDef } from "./response-DKxTr522.js";
3
- //#region src/constants.ts
4
- const visitorDepths = {
5
- shallow: "shallow",
6
- deep: "deep"
7
- };
8
- /**
9
- * Schema type discriminators used by all AST schema nodes.
10
- *
11
- * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
12
- * Call `isScalarPrimitive()` to check for the scalar types.
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
- /**
121
- * Scalar primitive schema types used for union simplification and type narrowing.
122
- */
123
- const SCALAR_PRIMITIVE_TYPES = new Set([
124
- "string",
125
- "number",
126
- "integer",
127
- "bigint",
128
- "boolean"
129
- ]);
130
- /**
131
- * Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
132
- * (for example `string | number | boolean`).
133
- */
134
- function isScalarPrimitive(type) {
135
- return SCALAR_PRIMITIVE_TYPES.has(type);
136
- }
137
- /**
138
- * HTTP method identifiers used by operation nodes.
139
- */
140
- const httpMethods = {
141
- get: "GET",
142
- post: "POST",
143
- put: "PUT",
144
- patch: "PATCH",
145
- delete: "DELETE",
146
- head: "HEAD",
147
- options: "OPTIONS",
148
- trace: "TRACE"
149
- };
150
- /**
151
- * One indentation level, derived from {@link INDENT_SIZE}.
152
- */
153
- const INDENT = Array.from({ length: 2 }, () => " ").join("");
154
- //#endregion
2
+ import { d as resolveRefName, h as INDENT, m as narrowSchema, n as collectLazy, t as collect, u as resolveGroupType } from "./visitor-DJ6ZEJvq.js";
3
+ import { J as camelCase, X as createSchema, _ as createIndexedAccessType, g as createFunctionParameters, h as createFunctionParameter, y as createTypeLiteral } from "./response-KUdWiDWw.js";
155
4
  //#region ../../internals/utils/src/promise.ts
156
5
  /**
157
6
  * Wraps `factory` with a keyed cache backed by the provided store.
@@ -398,173 +247,15 @@ function buildList(items, brackets = ["[", "]"]) {
398
247
  return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
399
248
  }
400
249
  //#endregion
401
- //#region src/guards.ts
402
- /**
403
- * Narrows a `SchemaNode` to the variant that matches `type`.
404
- *
405
- * @example
406
- * ```ts
407
- * const schema = createSchema({ type: 'string' })
408
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
409
- * ```
410
- */
411
- function narrowSchema(node, type) {
412
- return node?.type === type ? node : null;
413
- }
414
- /**
415
- * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
416
- *
417
- * @example
418
- * ```ts
419
- * if (isHttpOperationNode(node)) {
420
- * console.log(node.method, node.path)
421
- * }
422
- * ```
423
- */
424
- function isHttpOperationNode(node) {
425
- return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
426
- }
427
- //#endregion
428
- //#region src/utils/refs.ts
429
- const plainStringTypes = new Set([
430
- "string",
431
- "uuid",
432
- "email",
433
- "url",
434
- "datetime"
435
- ]);
436
- /**
437
- * Returns the last path segment of a reference string.
438
- *
439
- * @example
440
- * ```ts
441
- * extractRefName('#/components/schemas/Pet') // 'Pet'
442
- * ```
443
- */
444
- function extractRefName(ref) {
445
- return ref.split("/").at(-1) ?? ref;
446
- }
250
+ //#region src/utils/schemaMerge.ts
447
251
  /**
448
- * Resolves the schema name of a ref node, falling back through `ref` `name` nested `schema.name`.
449
- *
450
- * Returns `null` for non-ref nodes or when no name resolves.
252
+ * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
253
+ * run and pass through. Stays a construction-time helper, not a macro, so callers keep control of the
254
+ * member boundaries (such as keeping synthetic discriminant objects out of a run).
451
255
  *
452
256
  * @example
453
257
  * ```ts
454
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
455
- * // => 'Pet'
456
- * ```
457
- */
458
- function resolveRefName(node) {
459
- if (!node || node.type !== "ref") return null;
460
- if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
461
- return node.name ?? node.schema?.name ?? null;
462
- }
463
- /**
464
- * Builds a PascalCase child schema name by joining a parent name and property name.
465
- * Returns `null` when there is no parent to nest under.
466
- *
467
- * @example
468
- * ```ts
469
- * childName('Order', 'shipping_address') // 'OrderShippingAddress'
470
- * childName(undefined, 'params') // null
471
- * ```
472
- */
473
- function childName(parentName, propName) {
474
- return parentName ? pascalCase([parentName, propName].join(" ")) : null;
475
- }
476
- /**
477
- * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
478
- * empty parts.
479
- *
480
- * @example
481
- * ```ts
482
- * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
483
- * ```
484
- */
485
- function enumPropName(parentName, propName, enumSuffix) {
486
- return pascalCase([
487
- parentName,
488
- propName,
489
- enumSuffix
490
- ].filter(Boolean).join(" "));
491
- }
492
- /**
493
- * Type guard that returns `true` when a schema emits as a plain `string` type.
494
- *
495
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
496
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
497
- */
498
- function isStringType(node) {
499
- if (plainStringTypes.has(node.type)) return true;
500
- const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
501
- if (temporal) return temporal.representation !== "date";
502
- return false;
503
- }
504
- /**
505
- * Derives a {@link ParamGroupType} for a query or header group from the resolver.
506
- *
507
- * Returns `null` when there is no resolver, no params, or the group name equals the
508
- * individual param name (so there is no real group to emit).
509
- */
510
- function resolveGroupType({ node, params, group, resolver }) {
511
- if (!resolver || !params.length) return null;
512
- const firstParam = params[0];
513
- const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
514
- if (groupName === resolver.resolveParamName(node, firstParam)) return null;
515
- return {
516
- type: groupName,
517
- optional: params.every((p) => !p.required)
518
- };
519
- }
520
- //#endregion
521
- //#region src/transformers.ts
522
- /**
523
- * Replaces a discriminator property's schema with a string enum of allowed values.
524
- *
525
- * If `node` is not an object schema, or if the property does not exist, the input
526
- * node is returned as-is.
527
- *
528
- * @example
529
- * ```ts
530
- * const schema = createSchema({
531
- * type: 'object',
532
- * properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
533
- * })
534
- * const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
535
- * ```
536
- */
537
- function setDiscriminatorEnum({ node, propertyName, values, enumName }) {
538
- const objectNode = narrowSchema(node, "object");
539
- if (!objectNode?.properties?.length) return node;
540
- if (!objectNode.properties.some((prop) => prop.name === propertyName)) return node;
541
- return createSchema({
542
- ...objectNode,
543
- properties: objectNode.properties.map((prop) => {
544
- if (prop.name !== propertyName) return prop;
545
- return createProperty({
546
- ...prop,
547
- schema: createSchema({
548
- type: "enum",
549
- primitive: "string",
550
- enumValues: values,
551
- name: enumName,
552
- readOnly: prop.schema.readOnly,
553
- writeOnly: prop.schema.writeOnly
554
- })
555
- });
556
- })
557
- });
558
- }
559
- /**
560
- * Merges adjacent anonymous object members into a single anonymous object member.
561
- *
562
- * @example
563
- * ```ts
564
- * const merged = mergeAdjacentObjects([
565
- * createSchema({ type: 'object', properties: [createProperty({ name: 'a', schema: createSchema({ type: 'string' }) })] }),
566
- * createSchema({ type: 'object', properties: [createProperty({ name: 'b', schema: createSchema({ type: 'number' }) })] }),
567
- * ])
258
+ * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
568
259
  * ```
569
260
  */
570
261
  function* mergeAdjacentObjectsLazy(members) {
@@ -586,68 +277,6 @@ function* mergeAdjacentObjectsLazy(members) {
586
277
  }
587
278
  if (acc !== void 0) yield acc;
588
279
  }
589
- /**
590
- * Removes enum members that are covered by broader scalar primitives in the same union.
591
- *
592
- * @example
593
- * ```ts
594
- * const simplified = simplifyUnion([
595
- * createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
596
- * createSchema({ type: 'string' }),
597
- * ])
598
- * // keeps only string member
599
- * ```
600
- */
601
- function simplifyUnion(members) {
602
- const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
603
- if (!scalarPrimitives.size) return members;
604
- return members.filter((member) => {
605
- const enumNode = narrowSchema(member, "enum");
606
- if (!enumNode) return true;
607
- const primitive = enumNode.primitive;
608
- if (!primitive) return true;
609
- if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
610
- if (scalarPrimitives.has(primitive)) return false;
611
- if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
612
- return true;
613
- });
614
- }
615
- function setEnumName(propNode, parentName, propName, enumSuffix) {
616
- const enumNode = narrowSchema(propNode, "enum");
617
- if (enumNode?.primitive === "boolean") return {
618
- ...propNode,
619
- name: null
620
- };
621
- if (enumNode) return {
622
- ...propNode,
623
- name: enumPropName(parentName, propName, enumSuffix)
624
- };
625
- return propNode;
626
- }
627
- /**
628
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
629
- *
630
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
631
- * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
632
- *
633
- * @example
634
- * ```ts
635
- * // Ref with description override
636
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
637
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
638
- * ```
639
- */
640
- function syncSchemaRef(node) {
641
- const ref = narrowSchema(node, "ref");
642
- if (!ref) return node;
643
- if (!ref.schema) return node;
644
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
645
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
646
- return createSchema({
647
- ...ref.schema,
648
- ...definedOverrides
649
- });
650
- }
651
280
  //#endregion
652
281
  //#region src/utils/strings.ts
653
282
  /**
@@ -763,254 +392,6 @@ function getNestedAccessor(param, accessor) {
763
392
  return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
764
393
  }
765
394
  //#endregion
766
- //#region src/registry.ts
767
- /**
768
- * Every node definition. Adding a node means adding its `defineNode` to one
769
- * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
770
- */
771
- const nodeDefs = [
772
- inputDef,
773
- outputDef,
774
- operationDef,
775
- requestBodyDef,
776
- contentDef,
777
- responseDef,
778
- schemaDef,
779
- propertyDef,
780
- parameterDef,
781
- functionParameterDef,
782
- functionParametersDef,
783
- typeLiteralDef,
784
- indexedAccessTypeDef,
785
- objectBindingPatternDef,
786
- constDef,
787
- typeDef,
788
- functionDef,
789
- arrowFunctionDef,
790
- textDef,
791
- breakDef,
792
- jsxDef,
793
- importDef,
794
- exportDef,
795
- sourceDef,
796
- fileDef
797
- ];
798
- //#endregion
799
- //#region src/visitor.ts
800
- /**
801
- * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
802
- * Derived from each definition's `children`.
803
- */
804
- const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
805
- /**
806
- * Maps a node kind to the matching visitor callback name. Derived from each
807
- * definition's `visitorKey`.
808
- */
809
- const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
810
- /**
811
- * Per-kind builders rerun after children are rebuilt. Derived from each
812
- * definition's `rebuild` flag.
813
- */
814
- const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
815
- /**
816
- * Creates a small async concurrency limiter.
817
- *
818
- * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
819
- *
820
- * @example
821
- * ```ts
822
- * const limit = createLimit(2)
823
- * for (const task of [taskA, taskB, taskC]) {
824
- * await limit(() => task())
825
- * }
826
- * // only 2 tasks run at the same time
827
- * ```
828
- */
829
- function createLimit(concurrency) {
830
- let active = 0;
831
- const queue = [];
832
- function next() {
833
- if (active < concurrency && queue.length > 0) {
834
- active++;
835
- queue.shift()();
836
- }
837
- }
838
- return function limit(fn) {
839
- return new Promise((resolve, reject) => {
840
- queue.push(() => {
841
- Promise.resolve(fn()).then(resolve, reject).finally(() => {
842
- active--;
843
- next();
844
- });
845
- });
846
- next();
847
- });
848
- };
849
- }
850
- const visitorKeysByKind = VISITOR_KEYS;
851
- /**
852
- * Returns `true` when `value` is an AST node (an object carrying a `kind`).
853
- */
854
- function isNode(value) {
855
- return typeof value === "object" && value !== null && "kind" in value;
856
- }
857
- /**
858
- * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
859
- *
860
- * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
861
- *
862
- * @example
863
- * ```ts
864
- * const children = getChildren(operationNode, true)
865
- * // returns parameters, the request body, and responses
866
- * ```
867
- */
868
- function* getChildren(node, recurse) {
869
- if (node.kind === "Schema" && !recurse) return;
870
- const keys = visitorKeysByKind[node.kind];
871
- if (!keys) return;
872
- const record = node;
873
- for (const key of keys) {
874
- const value = record[key];
875
- if (Array.isArray(value)) {
876
- for (const item of value) if (isNode(item)) yield item;
877
- } else if (isNode(value)) yield value;
878
- }
879
- }
880
- /**
881
- * Runs the visitor callback that matches `node.kind` with the traversal
882
- * context. The result is a replacement node, a collected value, or `undefined`
883
- * when no callback is registered for the kind.
884
- *
885
- * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
886
- * in one place. `TResult` is the caller's expected return: the same node type
887
- * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
888
- */
889
- function applyVisitor(node, visitor, parent) {
890
- const key = VISITOR_KEY_BY_KIND[node.kind];
891
- if (!key) return void 0;
892
- const fn = visitor[key];
893
- return fn?.(node, { parent });
894
- }
895
- /**
896
- * Async depth-first traversal for side effects. Visitor return values are
897
- * ignored. Use `transform` when you want to rewrite nodes.
898
- *
899
- * Sibling nodes at each depth run concurrently up to `options.concurrency`
900
- * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
901
- * work. Lower values reduce memory pressure.
902
- *
903
- * @example Log every operation
904
- * ```ts
905
- * await walk(root, {
906
- * operation(node) {
907
- * console.log(node.operationId)
908
- * },
909
- * })
910
- * ```
911
- *
912
- * @example Only visit the root node
913
- * ```ts
914
- * await walk(root, { depth: 'shallow', input: () => {} })
915
- * ```
916
- */
917
- async function walk(node, options) {
918
- return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
919
- }
920
- async function _walk(node, visitor, recurse, limit, parent) {
921
- await limit(() => applyVisitor(node, visitor, parent));
922
- const children = Array.from(getChildren(node, recurse));
923
- if (children.length === 0) return;
924
- await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
925
- }
926
- function transform(node, options) {
927
- const { depth, parent, ...visitor } = options;
928
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
929
- const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
930
- if (rebuilt === node) return node;
931
- const rebuild = nodeRebuilders[rebuilt.kind];
932
- return rebuild ? rebuild(rebuilt) : rebuilt;
933
- }
934
- /**
935
- * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
936
- * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
937
- * `Schema` children are skipped in shallow mode.
938
- */
939
- function transformChildren(node, options, recurse) {
940
- if (node.kind === "Schema" && !recurse) return node;
941
- const keys = visitorKeysByKind[node.kind];
942
- if (!keys) return node;
943
- const record = node;
944
- const childOptions = {
945
- ...options,
946
- parent: node
947
- };
948
- let updates;
949
- for (const key of keys) {
950
- if (!(key in record)) continue;
951
- const value = record[key];
952
- if (Array.isArray(value)) {
953
- let changed = false;
954
- const mapped = value.map((item) => {
955
- if (!isNode(item)) return item;
956
- const next = transform(item, childOptions);
957
- if (next !== item) changed = true;
958
- return next;
959
- });
960
- if (changed) (updates ??= {})[key] = mapped;
961
- } else if (isNode(value)) {
962
- const next = transform(value, childOptions);
963
- if (next !== value) (updates ??= {})[key] = next;
964
- }
965
- }
966
- return updates ? {
967
- ...node,
968
- ...updates
969
- } : node;
970
- }
971
- /**
972
- * Lazy depth-first collection pass. Yields every non-null value returned by
973
- * the visitor callbacks. Use `collect` for the eager array form.
974
- *
975
- * @example Collect every operationId
976
- * ```ts
977
- * const ids: string[] = []
978
- * for (const id of collectLazy<string>(root, {
979
- * operation(node) {
980
- * return node.operationId
981
- * },
982
- * })) {
983
- * ids.push(id)
984
- * }
985
- * ```
986
- */
987
- function* collectLazy(node, options) {
988
- const { depth, parent, ...visitor } = options;
989
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
990
- const v = applyVisitor(node, visitor, parent);
991
- if (v != null) yield v;
992
- for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
993
- ...options,
994
- parent: node
995
- });
996
- }
997
- /**
998
- * Eager depth-first collection pass. Gathers every non-null value the visitor
999
- * callbacks return into an array.
1000
- *
1001
- * @example Collect every operationId
1002
- * ```ts
1003
- * const ids = collect<string>(root, {
1004
- * operation(node) {
1005
- * return node.operationId
1006
- * },
1007
- * })
1008
- * ```
1009
- */
1010
- function collect(node, options) {
1011
- return Array.from(collectLazy(node, options));
1012
- }
1013
- //#endregion
1014
395
  //#region src/utils/schemaGraph.ts
1015
396
  /**
1016
397
  * Collects every named schema referenced transitively from a node through its ref edges.
@@ -1384,6 +765,6 @@ function buildTypeLiteral({ node, params, resolver }) {
1384
765
  })) });
1385
766
  }
1386
767
  //#endregion
1387
- export { enumPropName as A, objectKey as B, trimQuotes as C, simplifyUnion as D, setEnumName as E, isHttpOperationNode as F, httpMethods as H, narrowSchema as I, buildJSDoc as L, isStringType as M, resolveGroupType as N, syncSchemaRef as O, resolveRefName as P, buildList as R, toRegExpString as S, setDiscriminatorEnum as T, schemaTypes as U, isValidVarName as V, nodeDefs as _, resolveParamType as a, stringify as b, mapSchemaMembers as c, containsCircularRef as d, findCircularSchemas as f, walk as g, transform as h, createOperationParams as i, extractRefName as j, childName as k, mapSchemaProperties as l, collectLazy as m, buildTypeLiteral as n, lazyGetter as o, collect as p, caseParams as r, mapSchemaItems as s, buildGroupParam as t, collectUsedSchemaNames as u, getNestedAccessor as v, mergeAdjacentObjectsLazy as w, stringifyObject as x, jsStringEscape as y, buildObject as z };
768
+ export { objectKey as C, buildObject as S, toRegExpString as _, resolveParamType as a, buildJSDoc as b, mapSchemaMembers as c, containsCircularRef as d, findCircularSchemas as f, stringifyObject as g, stringify as h, createOperationParams as i, mapSchemaProperties as l, jsStringEscape as m, buildTypeLiteral as n, lazyGetter as o, getNestedAccessor as p, caseParams as r, mapSchemaItems as s, buildGroupParam as t, collectUsedSchemaNames as u, trimQuotes as v, isValidVarName as w, buildList as x, mergeAdjacentObjectsLazy as y };
1388
769
 
1389
- //# sourceMappingURL=utils-Dj_KoXMv.js.map
770
+ //# sourceMappingURL=utils-CF_-Pn_c.js.map