@kubb/ast 5.0.0-beta.58 → 5.0.0-beta.59

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 (67) hide show
  1. package/README.md +10 -0
  2. package/dist/casing-BE2R1RXg.cjs +88 -0
  3. package/dist/casing-BE2R1RXg.cjs.map +1 -0
  4. package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
  5. package/dist/factory-BmcGBdeg.cjs +1251 -0
  6. package/dist/factory-BmcGBdeg.cjs.map +1 -0
  7. package/dist/factory-Du7nEP4B.js +282 -0
  8. package/dist/factory-Du7nEP4B.js.map +1 -0
  9. package/dist/factory.cjs +25 -28
  10. package/dist/factory.d.ts +3 -3
  11. package/dist/factory.js +3 -3
  12. package/dist/{ast-ClnJg9BN.d.ts → index-BzjwdK2M.d.ts} +74 -372
  13. package/dist/index.cjs +445 -46
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.ts +94 -59
  16. package/dist/index.js +7 -113
  17. package/dist/index.js.map +1 -1
  18. package/dist/operationParams-BZ07xDm0.d.ts +204 -0
  19. package/dist/response-DKxTr522.js +683 -0
  20. package/dist/response-DKxTr522.js.map +1 -0
  21. package/dist/{types-CB2oY8Dw.d.ts → types-olVl9v5p.d.ts} +222 -227
  22. package/dist/types.d.ts +4 -3
  23. package/dist/utils-BCtRXfhI.cjs +275 -0
  24. package/dist/utils-BCtRXfhI.cjs.map +1 -0
  25. package/dist/{utils-DN4XLVqz.js → utils-SdZU0F3H.js} +472 -1235
  26. package/dist/utils-SdZU0F3H.js.map +1 -0
  27. package/dist/utils.cjs +127 -22
  28. package/dist/utils.d.ts +112 -80
  29. package/dist/utils.js +3 -2
  30. package/package.json +1 -1
  31. package/src/constants.ts +8 -14
  32. package/src/dedupe.ts +8 -0
  33. package/src/factory.ts +1 -2
  34. package/src/guards.ts +1 -1
  35. package/src/index.ts +4 -13
  36. package/src/nodes/code.ts +29 -47
  37. package/src/nodes/content.ts +2 -2
  38. package/src/nodes/file.ts +28 -23
  39. package/src/nodes/function.ts +0 -15
  40. package/src/nodes/input.ts +6 -6
  41. package/src/nodes/operation.ts +1 -1
  42. package/src/nodes/parameter.ts +0 -3
  43. package/src/nodes/property.ts +0 -3
  44. package/src/nodes/requestBody.ts +3 -6
  45. package/src/nodes/schema.ts +3 -2
  46. package/src/printer.ts +1 -1
  47. package/src/registry.ts +31 -26
  48. package/src/signature.ts +3 -3
  49. package/src/transformers.ts +28 -1
  50. package/src/types.ts +2 -53
  51. package/src/utils/codegen.ts +104 -0
  52. package/src/utils/fileMerge.ts +184 -0
  53. package/src/utils/index.ts +7 -339
  54. package/src/utils/operationParams.ts +353 -0
  55. package/src/utils/refs.ts +112 -0
  56. package/src/utils/schemaGraph.ts +169 -0
  57. package/src/utils/strings.ts +139 -0
  58. package/src/visitor.ts +43 -19
  59. package/dist/extractStringsFromNodes-Bn9cOos9.d.ts +0 -14
  60. package/dist/factory-C5gHvtLU.js +0 -138
  61. package/dist/factory-C5gHvtLU.js.map +0 -1
  62. package/dist/factory-JN-Ylfl6.cjs +0 -155
  63. package/dist/factory-JN-Ylfl6.cjs.map +0 -1
  64. package/dist/utils-C8bWAzhv.cjs +0 -2696
  65. package/dist/utils-C8bWAzhv.cjs.map +0 -1
  66. package/dist/utils-DN4XLVqz.js.map +0 -1
  67. package/src/utils/ast.ts +0 -816
package/src/utils/ast.ts DELETED
@@ -1,816 +0,0 @@
1
- import { camelCase, isValidVarName, memoize } from '@internals/utils'
2
-
3
- import { narrowSchema } from '../guards.ts'
4
- import { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'
5
- import { createProperty } from '../nodes/property.ts'
6
- import { createSchema } from '../nodes/schema.ts'
7
- import type {
8
- ExportNode,
9
- FunctionParameterNode,
10
- FunctionParametersNode,
11
- ImportNode,
12
- OperationNode,
13
- ParameterNode,
14
- SchemaNode,
15
- SourceNode,
16
- TypeExpression,
17
- TypeLiteralNode,
18
- } from '../nodes/index.ts'
19
- import type { SchemaType } from '../nodes/schema.ts'
20
- import { extractRefName, extractStringsFromNodes, resolveGroupType } from './index.ts'
21
- import { collect, collectLazy } from '../visitor.ts'
22
-
23
- const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)
24
-
25
- /**
26
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
27
- *
28
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
29
- * override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
30
- *
31
- * @example
32
- * ```ts
33
- * // Ref with description override
34
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
35
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
36
- * ```
37
- */
38
- export function syncSchemaRef(node: SchemaNode): SchemaNode {
39
- const ref = narrowSchema(node, 'ref')
40
-
41
- if (!ref) return node
42
- if (!ref.schema) return node
43
-
44
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref
45
-
46
- // Filter out undefined override values so they don't shadow the resolved schema's fields.
47
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
48
-
49
- return createSchema({ ...ref.schema, ...definedOverrides })
50
- }
51
-
52
- /**
53
- * Type guard that returns `true` when a schema emits as a plain `string` type.
54
- *
55
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
56
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
57
- */
58
- export function isStringType(node: SchemaNode): boolean {
59
- if (plainStringTypes.has(node.type)) {
60
- return true
61
- }
62
-
63
- const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')
64
- if (temporal) {
65
- return temporal.representation !== 'date'
66
- }
67
-
68
- return false
69
- }
70
-
71
- /**
72
- * Applies casing rules to parameter names and returns a new parameter array.
73
- *
74
- * Use this before passing parameters to schema builders so output property keys match
75
- * the desired casing while preserving `OperationNode.parameters` for other consumers.
76
- * The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
77
- */
78
- const caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>
79
- memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>
80
- params.map((param) => {
81
- const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name
82
- return { ...param, name: transformed }
83
- }),
84
- ),
85
- )
86
-
87
- export function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {
88
- if (!casing) return params
89
- return caseParamsMemo(params)(casing)
90
- }
91
-
92
- /**
93
- * Creates a single-property object schema used as a discriminator literal.
94
- *
95
- * @example
96
- * ```ts
97
- * createDiscriminantNode({ propertyName: 'type', value: 'dog' })
98
- * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
99
- * ```
100
- */
101
- export function createDiscriminantNode({ propertyName, value }: { propertyName: string; value: string }): SchemaNode {
102
- return createSchema({
103
- type: 'object',
104
- primitive: 'object',
105
- properties: [
106
- createProperty({
107
- name: propertyName,
108
- schema: createSchema({
109
- type: 'enum',
110
- primitive: 'string',
111
- enumValues: [value],
112
- }),
113
- required: true,
114
- }),
115
- ],
116
- })
117
- }
118
-
119
- /**
120
- * Named type for a group of parameters (query or header) emitted as a single typed parameter.
121
- */
122
- export type ParamGroupType = {
123
- /**
124
- * Type expression for the group, a plain group-name reference.
125
- */
126
- type: TypeExpression
127
- /**
128
- * Whether the parameter group is optional.
129
- */
130
- optional: boolean
131
- }
132
-
133
- /**
134
- * A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.
135
- */
136
- type GroupProperty = {
137
- name: string
138
- type: TypeExpression
139
- optional?: boolean
140
- }
141
-
142
- /**
143
- * Resolver interface for {@link createOperationParams}.
144
- *
145
- * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.
146
- */
147
- export type OperationParamsResolver = {
148
- /**
149
- * Resolves the type name for an individual parameter.
150
- *
151
- * @example Individual path parameter name
152
- * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`
153
- */
154
- resolveParamName(node: OperationNode, param: ParameterNode): string
155
- /**
156
- * Resolves the request body type name.
157
- *
158
- * @example Request body type name
159
- * `resolver.resolveDataName(node) // → 'CreatePetData'`
160
- */
161
- resolveDataName(node: OperationNode): string
162
- /**
163
- * Resolves the grouped path parameters type name.
164
- * When the return value equals `resolveParamName`, no indexed access is emitted.
165
- *
166
- * @example Grouped path params type name
167
- * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`
168
- */
169
- resolvePathParamsName(node: OperationNode, param: ParameterNode): string
170
- /**
171
- * Resolves the grouped query parameters type name.
172
- * When the return value equals `resolveParamName`, an inline struct type is emitted instead.
173
- *
174
- * @example Grouped query params type name
175
- * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
176
- */
177
- resolveQueryParamsName(node: OperationNode, param: ParameterNode): string
178
- /**
179
- * Resolves the grouped header parameters type name.
180
- * When the return value equals `resolveParamName`, an inline struct type is emitted instead.
181
- *
182
- * @example Grouped header params type name
183
- * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
184
- */
185
- resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string
186
- }
187
-
188
- /**
189
- * Options for {@link createOperationParams}.
190
- */
191
- export type CreateOperationParamsOptions = {
192
- /**
193
- * How all operation parameters are grouped in the function signature.
194
- * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`
195
- * - `'inline'` emits each param category as a separate top-level parameter
196
- */
197
- paramsType: 'object' | 'inline'
198
- /**
199
- * How path parameters are emitted when `paramsType` is `'inline'`.
200
- * - `'object'` groups them as `{ petId, storeId }: PathParams`
201
- * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`
202
- * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`
203
- */
204
- pathParamsType: 'object' | 'inline' | 'inlineSpread'
205
- /**
206
- * Converts parameter names to camelCase before output.
207
- */
208
- paramsCasing?: 'camelcase'
209
- /**
210
- * Resolver for parameter and request body type names.
211
- * Pass `ResolverTs` from `@kubb/plugin-ts` directly.
212
- * When omitted, falls back to the schema primitive or `'unknown'`.
213
- */
214
- resolver?: OperationParamsResolver
215
- /**
216
- * Default value for the path parameters binding when `pathParamsType` is `'object'`.
217
- * Falls back to `'{}'` when all path params are optional.
218
- */
219
- pathParamsDefault?: string
220
- /**
221
- * Extra parameters appended after the standard operation parameters.
222
- *
223
- * @example Plugin-specific trailing parameter
224
- * ```ts
225
- * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]
226
- * ```
227
- */
228
- extraParams?: Array<FunctionParameterNode>
229
- /**
230
- * Override the default parameter names used for body, query, header, and rest-path groups.
231
- *
232
- * Useful when targeting languages or frameworks with different naming conventions.
233
- *
234
- * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }
235
- */
236
- paramNames?: {
237
- /**
238
- * Name for the request body parameter.
239
- * @default 'data'
240
- */
241
- data?: string
242
- /**
243
- * Name for the query parameters group parameter.
244
- * @default 'params'
245
- */
246
- params?: string
247
- /**
248
- * Name for the header parameters group parameter.
249
- * @default 'headers'
250
- */
251
- headers?: string
252
- /**
253
- * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.
254
- * @default 'pathParams'
255
- */
256
- path?: string
257
- }
258
- /**
259
- * Applies a uniform transformation to every resolved type name before it is used
260
- * in a parameter node. Use this for framework-level type wrappers.
261
- *
262
- * @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`
263
- * `typeWrapper: (t) => \`MaybeRefOrGetter<${t}>\``
264
- */
265
- typeWrapper?: (type: string) => string
266
- }
267
-
268
- /**
269
- * Resolves the {@link TypeExpression} for an individual parameter.
270
- *
271
- * Without a resolver, falls back to the schema primitive (a plain type-name string).
272
- * When the parameter belongs to a named group, emits an {@link IndexedAccessTypeNode}
273
- * (`GroupParams['petId']`); otherwise the resolved individual name as a plain string.
274
- */
275
- export function resolveParamType({
276
- node,
277
- param,
278
- resolver,
279
- }: {
280
- node: OperationNode
281
- param: ParameterNode
282
- resolver: OperationParamsResolver | undefined
283
- }): TypeExpression {
284
- if (!resolver) {
285
- return param.schema.primitive ?? 'unknown'
286
- }
287
-
288
- const individualName = resolver.resolveParamName(node, param)
289
-
290
- const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined
291
-
292
- const groupResolvers = {
293
- path: resolver.resolvePathParamsName,
294
- query: resolver.resolveQueryParamsName,
295
- header: resolver.resolveHeaderParamsName,
296
- } as const
297
-
298
- const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined
299
-
300
- if (groupName && groupName !== individualName) {
301
- return createIndexedAccessType({ objectType: groupName, indexType: param.name })
302
- }
303
-
304
- return individualName
305
- }
306
-
307
- /**
308
- * Converts an `OperationNode` into function parameters for code generation.
309
- *
310
- * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
311
- * destructured object parameter (`object`) and separate top-level parameters (`inline`), while
312
- * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
313
- * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
314
- */
315
- export function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {
316
- const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options
317
-
318
- const dataName = paramNames?.data ?? 'data'
319
- const paramsName = paramNames?.params ?? 'params'
320
- const headersName = paramNames?.headers ?? 'headers'
321
- const pathName = paramNames?.path ?? 'pathParams'
322
-
323
- const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)
324
- // Only plain type-name references are wrapped, they need casing applied.
325
- // TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.
326
- const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)
327
-
328
- const casedParams = caseParams(node.parameters, paramsCasing)
329
- const pathParams = casedParams.filter((p) => p.in === 'path')
330
- const queryParams = casedParams.filter((p) => p.in === 'query')
331
- const headerParams = casedParams.filter((p) => p.in === 'header')
332
-
333
- const toProperty = (param: ParameterNode): GroupProperty => ({
334
- name: param.name,
335
- type: wrapTypeExpression(resolveParamType({ node, param, resolver })),
336
- optional: !param.required,
337
- })
338
- const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)
339
-
340
- const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined
341
- const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []
342
-
343
- const trailingGroups: Array<BuildGroupArgs> = [
344
- { name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },
345
- {
346
- name: headersName,
347
- node,
348
- params: headerParams,
349
- groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),
350
- resolver,
351
- wrapType,
352
- },
353
- ]
354
-
355
- const params: Array<FunctionParameterNode> = []
356
-
357
- if (paramsType === 'object') {
358
- const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]
359
- if (children.length) {
360
- params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))
361
- }
362
- } else {
363
- if (pathParamsType === 'inlineSpread' && pathParams.length) {
364
- const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)
365
- params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))
366
- } else if (pathParamsType === 'inline') {
367
- params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))
368
- } else if (pathParams.length) {
369
- const pathChildren = pathParams.map(toProperty)
370
- params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))
371
- }
372
-
373
- params.push(...bodyProperty.map((p) => createFunctionParameter(p)))
374
- params.push(...trailingGroups.flatMap(buildGroupParam))
375
- }
376
-
377
- params.push(...extraParams)
378
-
379
- return createFunctionParameters({ params })
380
- }
381
-
382
- /**
383
- * Shared arguments for building a query or header parameter group.
384
- */
385
- export type BuildGroupArgs = {
386
- name: string
387
- node: OperationNode
388
- params: Array<ParameterNode>
389
- groupType: ParamGroupType | null
390
- resolver: OperationParamsResolver | undefined
391
- wrapType: (type: string) => string
392
- }
393
-
394
- /**
395
- * Builds the property descriptor for a query or header group.
396
- * Returns an empty array when there are no params to emit.
397
- *
398
- * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
399
- * {@link TypeLiteralNode} from the individual params.
400
- */
401
- function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {
402
- if (groupType) {
403
- const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type
404
- return [{ name, type, optional: groupType.optional }]
405
- }
406
- if (params.length) {
407
- return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]
408
- }
409
- return []
410
- }
411
-
412
- /**
413
- * Builds a single {@link FunctionParameterNode} for a query or header group.
414
- * Returns an empty array when there are no params to emit.
415
- *
416
- * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
417
- * {@link TypeLiteralNode} from the individual params.
418
- */
419
- export function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {
420
- return buildGroupProperty(args).map((p) => createFunctionParameter(p))
421
- }
422
-
423
- /**
424
- * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
425
- *
426
- * Used when query or header parameters have no dedicated group type name.
427
- * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
428
- */
429
- export function buildTypeLiteral({
430
- node,
431
- params,
432
- resolver,
433
- }: {
434
- node: OperationNode
435
- params: Array<ParameterNode>
436
- resolver: OperationParamsResolver | undefined
437
- }): TypeLiteralNode {
438
- return createTypeLiteral({
439
- members: params.map((p) => ({
440
- name: p.name,
441
- type: resolveParamType({ node, param: p, resolver }),
442
- optional: !p.required,
443
- })),
444
- })
445
- }
446
-
447
- function sourceKey(source: SourceNode): string {
448
- const nameKey = source.name ?? extractStringsFromNodes(source.nodes)
449
- return `${nameKey}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`
450
- }
451
-
452
- function pathTypeKey(path: string, isTypeOnly: boolean | null | undefined): string {
453
- return `${path}:${isTypeOnly ?? false}`
454
- }
455
-
456
- function exportKey(path: string, name: string | null | undefined, isTypeOnly: boolean | null | undefined, asAlias: boolean | null | undefined): string {
457
- return `${path}:${name ?? ''}:${isTypeOnly ?? false}:${asAlias ?? ''}`
458
- }
459
-
460
- function importKey(path: string, name: string | null | undefined, isTypeOnly: boolean | null | undefined): string {
461
- return `${path}:${name ?? ''}:${isTypeOnly ?? false}`
462
- }
463
-
464
- /**
465
- * Computes a multi-level sort key for exports and imports:
466
- * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
467
- */
468
- function sortKey(node: { name?: string | Array<unknown> | null; isTypeOnly?: boolean | null; path: string }): string {
469
- const isArray = Array.isArray(node.name) ? '1' : '0'
470
- const typeOnly = node.isTypeOnly ? '0' : '1'
471
- const hasName = node.name != null ? '1' : '0'
472
- const name = Array.isArray(node.name) ? node.name.toSorted().join('\0') : (node.name ?? '')
473
- return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`
474
- }
475
-
476
- /**
477
- * Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
478
- *
479
- * Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
480
- */
481
- export function combineSources(sources: Array<SourceNode>): Array<SourceNode> {
482
- const seen = new Map<string, SourceNode>()
483
- for (const source of sources) {
484
- const key = sourceKey(source)
485
- if (!seen.has(key)) seen.set(key, source)
486
- }
487
- return [...seen.values()]
488
- }
489
-
490
- /**
491
- * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
492
- *
493
- * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
494
- */
495
- function mergeNameArrays<TName>(existing: Array<TName>, incoming: Array<TName>): Array<TName> {
496
- const merged = new Set(existing)
497
- for (const name of incoming) merged.add(name)
498
- return [...merged]
499
- }
500
-
501
- /**
502
- * Deduplicates and merges `ExportNode` objects by path and type.
503
- *
504
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
505
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
506
- */
507
- export function combineExports(exports: Array<ExportNode>): Array<ExportNode> {
508
- const result: Array<ExportNode> = []
509
- // Accumulates array-named exports keyed by `path:isTypeOnly` for name-merging
510
- const namedByPath = new Map<string, ExportNode>()
511
- // Deduplicates non-array exports by their exact identity
512
- const seen = new Set<string>()
513
-
514
- // Precompute sort keys once, avoids recomputing per comparison.
515
- const keyed = exports.map((node) => ({ node, key: sortKey(node) }))
516
- keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
517
-
518
- for (const { node: curr } of keyed) {
519
- const { name, path, isTypeOnly, asAlias } = curr
520
-
521
- if (Array.isArray(name)) {
522
- if (!name.length) continue
523
-
524
- const key = pathTypeKey(path, isTypeOnly)
525
- const existing = namedByPath.get(key)
526
-
527
- if (existing && Array.isArray(existing.name)) {
528
- existing.name = mergeNameArrays(existing.name, name)
529
- } else {
530
- const newItem: ExportNode = { ...curr, name: [...new Set(name)] }
531
- result.push(newItem)
532
- namedByPath.set(key, newItem)
533
- }
534
- } else {
535
- const key = exportKey(path, name, isTypeOnly, asAlias)
536
- if (!seen.has(key)) {
537
- result.push(curr)
538
- seen.add(key)
539
- }
540
- }
541
- }
542
-
543
- return result
544
- }
545
-
546
- /**
547
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
548
- *
549
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
550
- * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
551
- *
552
- * @note Use this when combining imports from multiple files to avoid duplicate declarations.
553
- */
554
- export function combineImports(imports: Array<ImportNode>, exports: Array<ExportNode>, source?: string): Array<ImportNode> {
555
- // Build a lookup of all exported names to retain imports that are re-exported
556
- const exportedNames = new Set(exports.flatMap((e) => (Array.isArray(e.name) ? e.name : e.name ? [e.name] : [])))
557
- const isUsed = (importName: string): boolean => !source || source.includes(importName) || exportedNames.has(importName)
558
-
559
- // Memoize object import names so the same logical (propertyName, name) pair always
560
- // reuses the same object reference. Set-based deduplication then works correctly.
561
- const importNameMemo = new Map<string, { propertyName: string; name?: string }>()
562
- const canonicalizeName = (n: string | { propertyName: string; name?: string }): string | { propertyName: string; name?: string } => {
563
- if (typeof n === 'string') return n
564
- const key = `${n.propertyName}:${n.name ?? ''}`
565
- if (!importNameMemo.has(key)) importNameMemo.set(key, n)
566
- return importNameMemo.get(key)!
567
- }
568
-
569
- // Paths that keep at least one used named import. A default import from such a path is retained
570
- // even when its binding can't be found in `source` e.g. a generated `client` default import
571
- // alongside `import type { Client } from <same path>`, where merged grouped output omits the body.
572
- const pathsWithUsedNamedImport = new Set<string>()
573
- for (const node of imports) {
574
- if (!Array.isArray(node.name)) continue
575
- if (node.name.some((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.name ?? item.propertyName)))) {
576
- pathsWithUsedNamedImport.add(node.path)
577
- }
578
- }
579
-
580
- const result: Array<ImportNode> = []
581
- // Accumulates array-named imports keyed by `path:isTypeOnly` for name-merging
582
- const namedByPath = new Map<string, ImportNode>()
583
- // Deduplicates non-array imports by their exact identity
584
- const seen = new Set<string>()
585
-
586
- // Precompute sort keys once, avoids recomputing per comparison.
587
- const keyed = imports.map((node) => ({ node, key: sortKey(node) }))
588
- keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
589
-
590
- for (const { node: curr } of keyed) {
591
- if (curr.path === curr.root) continue
592
-
593
- const { path, isTypeOnly } = curr
594
- let { name } = curr
595
-
596
- if (Array.isArray(name)) {
597
- name = [...new Set(name.map(canonicalizeName))].filter((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.name ?? item.propertyName)))
598
- if (!name.length) continue
599
-
600
- const key = pathTypeKey(path, isTypeOnly)
601
- const existing = namedByPath.get(key)
602
-
603
- if (existing && Array.isArray(existing.name)) {
604
- existing.name = mergeNameArrays(existing.name, name)
605
- } else {
606
- const newItem: ImportNode = { ...curr, name }
607
- result.push(newItem)
608
- namedByPath.set(key, newItem)
609
- }
610
- } else {
611
- if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue
612
-
613
- const key = importKey(path, name, isTypeOnly)
614
- if (!seen.has(key)) {
615
- result.push(curr)
616
- seen.add(key)
617
- }
618
- }
619
- }
620
-
621
- return result
622
- }
623
-
624
- /**
625
- * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
626
- *
627
- * Returns `null` for non-ref nodes or when no name can be resolved. Use this to get a schema's
628
- * identifier for type definitions or error messages.
629
- *
630
- * @example
631
- * ```ts
632
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
633
- * // => 'Pet'
634
- * ```
635
- */
636
- export function resolveRefName(node: SchemaNode | undefined): string | null {
637
- if (!node || node.type !== 'ref') return null
638
- if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null
639
-
640
- return node.name ?? node.schema?.name ?? null
641
- }
642
-
643
- /**
644
- * Collects every named schema referenced (transitively) from a node via ref edges.
645
- *
646
- * Refs are followed by name only, the resolved `node.schema` is not traversed inline.
647
- * Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
648
- *
649
- * @example Collect refs from a single schema
650
- * ```ts
651
- * const names = collectReferencedSchemaNames(petSchema)
652
- * // → Set { 'Category', 'Tag' }
653
- * ```
654
- *
655
- * @example Accumulate refs from multiple schemas into one set
656
- * ```ts
657
- * const out = new Set<string>()
658
- * for (const schema of schemas) {
659
- * collectReferencedSchemaNames(schema, out)
660
- * }
661
- * ```
662
- */
663
- const collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {
664
- const refs = new Set<string>()
665
- collect<void>(node, {
666
- schema(child) {
667
- if (child.type === 'ref') {
668
- const name = resolveRefName(child)
669
- if (name) refs.add(name)
670
- }
671
- },
672
- })
673
- return refs
674
- })
675
-
676
- export function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {
677
- if (!node) return out
678
- for (const name of collectSchemaRefs(node)) out.add(name)
679
- return out
680
- }
681
-
682
- /**
683
- * Collects the names of all top-level schemas transitively used by a set of operations.
684
- *
685
- * An operation uses a schema when any of its parameters, request body content, or responses
686
- * reference it, directly or indirectly through other named schemas.
687
- * The walk is iterative and safe against reference cycles.
688
- *
689
- * Use this together with `include` filters to determine which schemas from `components/schemas`
690
- * are reachable from the allowed operations, so that schemas used only by excluded operations
691
- * are not generated.
692
- *
693
- * @example Only generate schemas referenced by included operations
694
- * ```ts
695
- * const includedOps = operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
696
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
697
- *
698
- * for (const schema of schemas) {
699
- * if (schema.name && !allowed.has(schema.name)) continue
700
- * // … generate schema
701
- * }
702
- * ```
703
- *
704
- * @example Check whether a specific schema is needed
705
- * ```ts
706
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
707
- * allowed.has('OrderStatus') // false when no included operation references OrderStatus
708
- * ```
709
- */
710
- const collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>
711
- memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),
712
- )
713
-
714
- function computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
715
- const schemaMap = new Map<string, SchemaNode>()
716
- for (const schema of schemas) {
717
- if (schema.name) schemaMap.set(schema.name, schema)
718
- }
719
-
720
- const result = new Set<string>()
721
-
722
- function visitSchema(schema: SchemaNode): void {
723
- const directRefs = collectReferencedSchemaNames(schema)
724
- for (const name of directRefs) {
725
- if (!result.has(name)) {
726
- result.add(name)
727
- const namedSchema = schemaMap.get(name)
728
- if (namedSchema) visitSchema(namedSchema)
729
- }
730
- }
731
- }
732
-
733
- for (const op of operations) {
734
- for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {
735
- visitSchema(schema)
736
- }
737
- }
738
-
739
- return result
740
- }
741
-
742
- export function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
743
- return collectUsedSchemaNamesMemo(operations)(schemas)
744
- }
745
-
746
- const EMPTY_CIRCULAR_SET = new Set<string>()
747
-
748
- const findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {
749
- const graph = new Map<string, Set<string>>()
750
-
751
- for (const schema of schemas) {
752
- if (!schema.name) continue
753
- graph.set(schema.name, collectReferencedSchemaNames(schema))
754
- }
755
-
756
- const circular = new Set<string>()
757
- for (const start of graph.keys()) {
758
- const visited = new Set<string>()
759
- const stack: Array<string> = [...(graph.get(start) ?? [])]
760
- while (stack.length > 0) {
761
- const node = stack.pop()!
762
- if (node === start) {
763
- circular.add(start)
764
- break
765
- }
766
- if (visited.has(node)) continue
767
- visited.add(node)
768
-
769
- const next = graph.get(node)
770
- if (next) for (const r of next) stack.push(r)
771
- }
772
- }
773
-
774
- return circular
775
- })
776
-
777
- /**
778
- * Identifies all schemas that participate in circular dependency chains, including direct self-loops.
779
- *
780
- * Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
781
- * in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
782
- * Refs are followed by name only, keeping the algorithm linear in the schema graph size.
783
- *
784
- * @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
785
- */
786
- export function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {
787
- if (schemas.length === 0) return EMPTY_CIRCULAR_SET
788
- return findCircularSchemasMemo(schemas)
789
- }
790
-
791
- /**
792
- * Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
793
- *
794
- * Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
795
- * Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
796
- *
797
- * @note Returns `true` for the first matching circular ref found. Use for fast dependency checks.
798
- */
799
- export function containsCircularRef(
800
- node: SchemaNode | undefined,
801
- { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },
802
- ): boolean {
803
- if (!node || circularSchemas.size === 0) return false
804
-
805
- for (const _ of collectLazy<true>(node, {
806
- schema(child) {
807
- if (child.type !== 'ref') return null
808
- const name = resolveRefName(child)
809
- return name && name !== excludeName && circularSchemas.has(name) ? true : null
810
- },
811
- })) {
812
- return true
813
- }
814
-
815
- return false
816
- }