@kubb/ast 5.0.0-alpha.6 → 5.0.0-alpha.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.
package/src/utils.ts CHANGED
@@ -1,18 +1,60 @@
1
1
  import { camelCase, isValidVarName } from '@internals/utils'
2
2
 
3
+ import { createFunctionParameter, createFunctionParameters, createParameterGroup, createParamsType, createProperty, createSchema } from './factory.ts'
3
4
  import { narrowSchema } from './guards.ts'
4
- import type { ParameterNode, SchemaNode } from './nodes/index.ts'
5
+ import type {
6
+ CodeNode,
7
+ ExportNode,
8
+ FunctionParameterNode,
9
+ FunctionParametersNode,
10
+ ImportNode,
11
+ OperationNode,
12
+ ParameterGroupNode,
13
+ ParameterNode,
14
+ ParamsTypeNode,
15
+ SchemaNode,
16
+ SourceNode,
17
+ } from './nodes/index.ts'
5
18
  import type { SchemaType } from './nodes/schema.ts'
6
19
 
7
- const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'])
20
+ const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)
8
21
 
9
22
  /**
10
- * Returns `true` when a schema node will be represented as a plain string in generated code.
23
+ * Returns a merged schema view for a ref node, combining the resolved `node.schema`
24
+ * (base from the referenced definition) with any usage-site sibling fields set directly
25
+ * on the ref node (description, readOnly, nullable, deprecated, etc.).
26
+ *
27
+ * Usage-site fields take precedence over the resolved schema's own fields when both are defined.
28
+ *
29
+ * For non-ref nodes the node itself is returned unchanged.
30
+ */
31
+ export function syncSchemaRef(node: SchemaNode): SchemaNode {
32
+ const ref = narrowSchema(node, 'ref')
33
+
34
+ if (!ref) return node
35
+ if (!ref.schema) return node
36
+
37
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref
38
+
39
+ // Filter out undefined override values so they don't shadow the resolved schema's fields.
40
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
41
+
42
+ return createSchema({ ...ref.schema, ...definedOverrides })
43
+ }
44
+
45
+ /**
46
+ * Returns `true` when a schema is emitted as a plain `string` type.
11
47
  *
12
48
  * - `string`, `uuid`, `email`, `url`, `datetime` are always plain strings.
13
49
  * - `date` and `time` are plain strings when their `representation` is `'string'` rather than `'date'`.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * isStringType(createSchema({ type: 'uuid' })) // true
54
+ * isStringType(createSchema({ type: 'date', representation: 'date' })) // false
55
+ * ```
14
56
  */
15
- export function isPlainStringType(node: SchemaNode): boolean {
57
+ export function isStringType(node: SchemaNode): boolean {
16
58
  if (plainStringTypes.has(node.type)) {
17
59
  return true
18
60
  }
@@ -26,16 +68,23 @@ export function isPlainStringType(node: SchemaNode): boolean {
26
68
  }
27
69
 
28
70
  /**
29
- * Transforms the `name` field of each parameter node according to the given casing strategy.
71
+ * Applies casing rules to parameter names and returns a new parameter array.
30
72
  *
31
- * The original `params` array is never mutated — a new array of cloned nodes is returned.
32
- * When no `casing` is provided the original array is returned as-is.
73
+ * The input array is not mutated.
74
+ * If `casing` is not set, the original array is returned unchanged.
33
75
  *
34
76
  * Use this before passing parameters to schema builders so that property keys
35
- * in the generated output match the desired casing while the original
36
- * `OperationNode.parameters` array remains untouched for other consumers.
77
+ * in generated output match the desired casing while preserving
78
+ * `OperationNode.parameters` for other consumers.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const params = [createParameter({ name: 'pet_id', in: 'query', schema: createSchema({ type: 'string' }) })]
83
+ * const cased = caseParams(params, 'camelcase')
84
+ * // cased[0].name === 'petId'
85
+ * ```
37
86
  */
38
- export function applyParamsCasing(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {
87
+ export function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {
39
88
  if (!casing) {
40
89
  return params
41
90
  }
@@ -46,3 +95,647 @@ export function applyParamsCasing(params: Array<ParameterNode>, casing: 'camelca
46
95
  return { ...param, name: transformed }
47
96
  })
48
97
  }
98
+
99
+ /**
100
+ * Creates a single-property object schema used as a discriminator literal.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * createDiscriminantNode({ propertyName: 'type', value: 'dog' })
105
+ * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
106
+ * ```
107
+ */
108
+ export function createDiscriminantNode({ propertyName, value }: { propertyName: string; value: string }): SchemaNode {
109
+ return createSchema({
110
+ type: 'object',
111
+ primitive: 'object',
112
+ properties: [
113
+ createProperty({
114
+ name: propertyName,
115
+ schema: createSchema({
116
+ type: 'enum',
117
+ primitive: 'string',
118
+ enumValues: [value],
119
+ }),
120
+ required: true,
121
+ }),
122
+ ],
123
+ })
124
+ }
125
+
126
+ /**
127
+ * Named type for a group of parameters (query or header) emitted as a single typed parameter.
128
+ */
129
+ export type ParamGroupType = {
130
+ /**
131
+ * TypeNode for the group type.
132
+ */
133
+ type: ParamsTypeNode
134
+ /**
135
+ * Whether the parameter group is optional.
136
+ */
137
+ optional: boolean
138
+ }
139
+
140
+ /**
141
+ * Resolver interface for {@link createOperationParams}.
142
+ *
143
+ * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.
144
+ */
145
+ export type OperationParamsResolver = {
146
+ /**
147
+ * Resolves the type name for an individual parameter.
148
+ *
149
+ * @example Individual path parameter name
150
+ * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`
151
+ */
152
+ resolveParamName(node: OperationNode, param: ParameterNode): string
153
+ /**
154
+ * Resolves the request body type name.
155
+ *
156
+ * @example Request body type name
157
+ * `resolver.resolveDataName(node) // → 'CreatePetData'`
158
+ */
159
+ resolveDataName(node: OperationNode): string
160
+ /**
161
+ * Resolves the grouped path parameters type name.
162
+ * When the return value equals `resolveParamName`, no indexed access is emitted.
163
+ *
164
+ * @example Grouped path params type name
165
+ * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`
166
+ */
167
+ resolvePathParamsName(node: OperationNode, param: ParameterNode): string
168
+ /**
169
+ * Resolves the grouped query parameters type name.
170
+ * When the return value equals `resolveParamName`, an inline struct type is emitted instead.
171
+ *
172
+ * @example Grouped query params type name
173
+ * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
174
+ */
175
+ resolveQueryParamsName(node: OperationNode, param: ParameterNode): string
176
+ /**
177
+ * Resolves the grouped header parameters type name.
178
+ * When the return value equals `resolveParamName`, an inline struct type is emitted instead.
179
+ *
180
+ * @example Grouped header params type name
181
+ * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
182
+ */
183
+ resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string
184
+ }
185
+
186
+ /**
187
+ * Options for {@link createOperationParams}.
188
+ */
189
+ export type CreateOperationParamsOptions = {
190
+ /**
191
+ * How all operation parameters are grouped in the function signature.
192
+ * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`
193
+ * - `'inline'` emits each param category as a separate top-level parameter
194
+ */
195
+ paramsType: 'object' | 'inline'
196
+ /**
197
+ * How path parameters are emitted when `paramsType` is `'inline'`.
198
+ * - `'object'` groups them as `{ petId, storeId }: PathParams`
199
+ * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`
200
+ * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`
201
+ */
202
+ pathParamsType: 'object' | 'inline' | 'inlineSpread'
203
+ /**
204
+ * Converts parameter names to camelCase before output.
205
+ */
206
+ paramsCasing?: 'camelcase'
207
+ /**
208
+ * Resolver for parameter and request body type names.
209
+ * Pass `ResolverTs` from `@kubb/plugin-ts` directly.
210
+ * When omitted, falls back to the schema primitive or `'unknown'`.
211
+ */
212
+ resolver?: OperationParamsResolver
213
+ /**
214
+ * Default value for the path parameters binding when `pathParamsType` is `'object'`.
215
+ * Falls back to `'{}'` when all path params are optional.
216
+ */
217
+ pathParamsDefault?: string
218
+ /**
219
+ * Extra parameters appended after the standard operation parameters.
220
+ *
221
+ * @example Plugin-specific trailing parameter
222
+ * ```ts
223
+ * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]
224
+ * ```
225
+ */
226
+ extraParams?: Array<FunctionParameterNode | ParameterGroupNode>
227
+ /**
228
+ * Override the default parameter names used for body, query, header, and rest-path groups.
229
+ *
230
+ * Useful when targeting languages or frameworks with different naming conventions.
231
+ *
232
+ * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }
233
+ */
234
+ paramNames?: {
235
+ /**
236
+ * Name for the request body parameter.
237
+ * @default 'data'
238
+ */
239
+ data?: string
240
+ /**
241
+ * Name for the query parameters group parameter.
242
+ * @default 'params'
243
+ */
244
+ params?: string
245
+ /**
246
+ * Name for the header parameters group parameter.
247
+ * @default 'headers'
248
+ */
249
+ headers?: string
250
+ /**
251
+ * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.
252
+ * @default 'pathParams'
253
+ */
254
+ path?: string
255
+ }
256
+ /**
257
+ * Applies a uniform transformation to every resolved type name before it is used
258
+ * in a parameter node. Use this for framework-level type wrappers.
259
+ *
260
+ * @example Vue Query — wrap every parameter type with `MaybeRefOrGetter`
261
+ * `typeWrapper: (t) => \`MaybeRefOrGetter<${t}>\``
262
+ */
263
+ typeWrapper?: (type: string) => string
264
+ }
265
+
266
+ function resolveParamsType({
267
+ node,
268
+ param,
269
+ resolver,
270
+ }: {
271
+ node: OperationNode
272
+ param: ParameterNode
273
+ resolver: OperationParamsResolver | undefined
274
+ }): ParamsTypeNode {
275
+ if (!resolver) {
276
+ return createParamsType({
277
+ variant: 'reference',
278
+ name: param.schema.primitive ?? 'unknown',
279
+ })
280
+ }
281
+
282
+ const individualName = resolver.resolveParamName(node, param)
283
+
284
+ const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined
285
+
286
+ const groupResolvers = {
287
+ path: resolver.resolvePathParamsName,
288
+ query: resolver.resolveQueryParamsName,
289
+ header: resolver.resolveHeaderParamsName,
290
+ } as const
291
+
292
+ const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined
293
+
294
+ if (groupName && groupName !== individualName) {
295
+ return createParamsType({
296
+ variant: 'member',
297
+ base: groupName,
298
+ key: param.name,
299
+ })
300
+ }
301
+
302
+ return createParamsType({ variant: 'reference', name: individualName })
303
+ }
304
+
305
+ /**
306
+ * Converts an {@link OperationNode} into a {@link FunctionParametersNode}.
307
+ *
308
+ * Centralizes the per-plugin `getParams()` pattern. Provide a `resolver` for
309
+ * type resolution and `extraParams` for plugin-specific trailing parameters.
310
+ *
311
+ * @example
312
+ * ```ts
313
+ * const params = createOperationParams(node, {
314
+ * paramsType: 'inline',
315
+ * pathParamsType: 'inline',
316
+ * resolver: tsResolver,
317
+ * extraParams: [createFunctionParameter({ name: 'options', type: createParamsType({ variant: 'reference', name: 'Partial<RequestOptions>' }), default: '{}' })],
318
+ * })
319
+ * ```
320
+ */
321
+ export function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {
322
+ const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options
323
+
324
+ const dataName = paramNames?.data ?? 'data'
325
+ const paramsName = paramNames?.params ?? 'params'
326
+ const headersName = paramNames?.headers ?? 'headers'
327
+ const pathName = paramNames?.path ?? 'pathParams'
328
+
329
+ const wrapType = (type: string): ParamsTypeNode =>
330
+ createParamsType({
331
+ variant: 'reference',
332
+ name: typeWrapper ? typeWrapper(type) : type,
333
+ })
334
+ // Only reference-variant TypeNodes are wrapped — they hold a plain type name string that needs casing applied.
335
+ // Member and struct TypeNodes are pre-resolved structured expressions and are passed through unchanged.
336
+ const wrapTypeNode = (type: ParamsTypeNode): ParamsTypeNode => (type.kind === 'ParamsType' && type.variant === 'reference' ? wrapType(type.name) : type)
337
+
338
+ const casedParams = caseParams(node.parameters, paramsCasing)
339
+ const pathParams = casedParams.filter((p) => p.in === 'path')
340
+ const queryParams = casedParams.filter((p) => p.in === 'query')
341
+ const headerParams = casedParams.filter((p) => p.in === 'header')
342
+
343
+ const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined
344
+ const bodyRequired = node.requestBody?.required ?? false
345
+
346
+ const queryGroupType = resolver
347
+ ? resolveGroupType({
348
+ node,
349
+ params: queryParams,
350
+ groupMethod: resolver.resolveQueryParamsName,
351
+ resolver,
352
+ })
353
+ : undefined
354
+ const headerGroupType = resolver
355
+ ? resolveGroupType({
356
+ node,
357
+ params: headerParams,
358
+ groupMethod: resolver.resolveHeaderParamsName,
359
+ resolver,
360
+ })
361
+ : undefined
362
+
363
+ const params: Array<FunctionParameterNode | ParameterGroupNode> = []
364
+
365
+ if (paramsType === 'object') {
366
+ const children: Array<FunctionParameterNode> = [
367
+ ...pathParams.map((p) => {
368
+ const type = resolveParamsType({ node, param: p, resolver })
369
+ return createFunctionParameter({
370
+ name: p.name,
371
+ type: wrapTypeNode(type),
372
+ optional: !p.required,
373
+ })
374
+ }),
375
+ ...(bodyType
376
+ ? [
377
+ createFunctionParameter({
378
+ name: dataName,
379
+ type: bodyType,
380
+ optional: !bodyRequired,
381
+ }),
382
+ ]
383
+ : []),
384
+ ...buildGroupParam({
385
+ name: paramsName,
386
+ node,
387
+ params: queryParams,
388
+ groupType: queryGroupType,
389
+ resolver,
390
+ wrapType,
391
+ }),
392
+ ...buildGroupParam({
393
+ name: headersName,
394
+ node,
395
+ params: headerParams,
396
+ groupType: headerGroupType,
397
+ resolver,
398
+ wrapType,
399
+ }),
400
+ ]
401
+
402
+ if (children.length) {
403
+ params.push(
404
+ createParameterGroup({
405
+ properties: children,
406
+ default: children.every((c) => c.optional) ? '{}' : undefined,
407
+ }),
408
+ )
409
+ }
410
+ } else {
411
+ if (pathParams.length) {
412
+ if (pathParamsType === 'inlineSpread') {
413
+ const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!) ?? undefined
414
+ params.push(
415
+ createFunctionParameter({
416
+ name: pathName,
417
+ type: spreadType ? wrapType(spreadType) : undefined,
418
+ rest: true,
419
+ }),
420
+ )
421
+ } else {
422
+ const pathChildren = pathParams.map((p) => {
423
+ const type = resolveParamsType({ node, param: p, resolver })
424
+ return createFunctionParameter({
425
+ name: p.name,
426
+ type: wrapTypeNode(type),
427
+ optional: !p.required,
428
+ })
429
+ })
430
+ params.push(
431
+ createParameterGroup({
432
+ properties: pathChildren,
433
+ inline: pathParamsType === 'inline',
434
+ default: pathParamsDefault ?? (pathChildren.every((c) => c.optional) ? '{}' : undefined),
435
+ }),
436
+ )
437
+ }
438
+ }
439
+
440
+ if (bodyType) {
441
+ params.push(
442
+ createFunctionParameter({
443
+ name: dataName,
444
+ type: bodyType,
445
+ optional: !bodyRequired,
446
+ }),
447
+ )
448
+ }
449
+
450
+ params.push(
451
+ ...buildGroupParam({
452
+ name: paramsName,
453
+ node,
454
+ params: queryParams,
455
+ groupType: queryGroupType,
456
+ resolver,
457
+ wrapType,
458
+ }),
459
+ )
460
+ params.push(
461
+ ...buildGroupParam({
462
+ name: headersName,
463
+ node,
464
+ params: headerParams,
465
+ groupType: headerGroupType,
466
+ resolver,
467
+ wrapType,
468
+ }),
469
+ )
470
+ }
471
+
472
+ params.push(...extraParams)
473
+
474
+ return createFunctionParameters({ params })
475
+ }
476
+
477
+ /**
478
+ * Builds a single {@link FunctionParameterNode} for a query or header group.
479
+ * Returns an empty array when there are no params to emit.
480
+ *
481
+ * If a pre-resolved `groupType` is provided it emits `name: GroupType`.
482
+ * Otherwise, it builds an inline struct from the individual params.
483
+ */
484
+ function buildGroupParam({
485
+ name,
486
+ node,
487
+ params,
488
+ groupType,
489
+ resolver,
490
+ wrapType,
491
+ }: {
492
+ name: string
493
+ node: OperationNode
494
+ params: Array<ParameterNode>
495
+ groupType: ParamGroupType | undefined
496
+ resolver: OperationParamsResolver | undefined
497
+ wrapType: (type: string) => ParamsTypeNode
498
+ }): Array<FunctionParameterNode> {
499
+ if (groupType) {
500
+ const type = groupType.type.kind === 'ParamsType' && groupType.type.variant === 'reference' ? wrapType(groupType.type.name) : groupType.type
501
+ return [createFunctionParameter({ name, type, optional: groupType.optional })]
502
+ }
503
+ if (params.length) {
504
+ return [
505
+ createFunctionParameter({
506
+ name,
507
+ type: toStructType({ node, params, resolver }),
508
+ optional: params.every((p) => !p.required),
509
+ }),
510
+ ]
511
+ }
512
+ return []
513
+ }
514
+
515
+ /**
516
+ * Derives a {@link ParamGroupType} from the resolver's group method.
517
+ * Returns `undefined` when the group name equals the individual param name (no real group).
518
+ */
519
+ function resolveGroupType({
520
+ node,
521
+ params,
522
+ groupMethod,
523
+ resolver,
524
+ }: {
525
+ node: OperationNode
526
+ params: Array<ParameterNode>
527
+ groupMethod: (_node: OperationNode, _param: ParameterNode) => string
528
+ resolver: OperationParamsResolver
529
+ }): ParamGroupType | undefined {
530
+ if (!params.length) {
531
+ return undefined
532
+ }
533
+ const firstParam = params[0]!
534
+ const groupName = groupMethod.call(resolver, node, firstParam)
535
+ if (groupName === resolver.resolveParamName(node, firstParam)) {
536
+ return undefined
537
+ }
538
+ const allOptional = params.every((p) => !p.required)
539
+ return {
540
+ type: createParamsType({ variant: 'reference', name: groupName }),
541
+ optional: allOptional,
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Builds a {@link TypeNode} with `variant: 'struct'` for an inline anonymous type grouping named fields.
547
+ *
548
+ * Used when query or header parameters have no dedicated group type name.
549
+ * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
550
+ */
551
+ function toStructType({
552
+ node,
553
+ params,
554
+ resolver,
555
+ }: {
556
+ node: OperationNode
557
+ params: Array<ParameterNode>
558
+ resolver: OperationParamsResolver | undefined
559
+ }): ParamsTypeNode {
560
+ return createParamsType({
561
+ variant: 'struct',
562
+ properties: params.map((p) => ({
563
+ name: p.name,
564
+ optional: !p.required,
565
+ type: resolveParamsType({ node, param: p, resolver }),
566
+ })),
567
+ })
568
+ }
569
+
570
+ function sourceKey(source: SourceNode): string {
571
+ const nameKey = source.name ?? extractStringsFromNodes(source.nodes)
572
+ return `${nameKey}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`
573
+ }
574
+
575
+ function pathTypeKey(path: string, isTypeOnly: boolean | undefined): string {
576
+ return `${path}:${isTypeOnly ?? false}`
577
+ }
578
+
579
+ function exportKey(path: string, name: string | undefined, isTypeOnly: boolean | undefined, asAlias: boolean | undefined): string {
580
+ return `${path}:${name ?? ''}:${isTypeOnly ?? false}:${asAlias ?? ''}`
581
+ }
582
+
583
+ function importKey(path: string, name: string | undefined, isTypeOnly: boolean | undefined): string {
584
+ return `${path}:${name ?? ''}:${isTypeOnly ?? false}`
585
+ }
586
+
587
+ /**
588
+ * Computes a multi-level sort key for exports and imports:
589
+ * non-array names first (wildcards/namespace aliases); type-only before value; alphabetical path; unnamed before named.
590
+ */
591
+ function sortKey(node: { name?: string | Array<unknown>; isTypeOnly?: boolean; path: string }): string {
592
+ const isArray = Array.isArray(node.name) ? '1' : '0'
593
+ const typeOnly = node.isTypeOnly ? '0' : '1'
594
+ const hasName = node.name != null ? '1' : '0'
595
+ const name = Array.isArray(node.name) ? [...node.name].sort().join('\0') : (node.name ?? '')
596
+ return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`
597
+ }
598
+
599
+ /**
600
+ * Deduplicates an array of `SourceNode` objects.
601
+ * Named sources are deduplicated by `name + isExportable + isTypeOnly`.
602
+ * Unnamed sources are deduplicated by object reference.
603
+ */
604
+ export function combineSources(sources: Array<SourceNode>): Array<SourceNode> {
605
+ const seen = new Map<string, SourceNode>()
606
+ for (const source of sources) {
607
+ const key = sourceKey(source)
608
+ if (!seen.has(key)) seen.set(key, source)
609
+ }
610
+ return [...seen.values()]
611
+ }
612
+
613
+ /**
614
+ * Deduplicates and merges an array of `ExportNode` objects.
615
+ * Exports with the same path and `isTypeOnly` flag have their names merged.
616
+ */
617
+ export function combineExports(exports: Array<ExportNode>): Array<ExportNode> {
618
+ const result: Array<ExportNode> = []
619
+ // Accumulates array-named exports keyed by `path:isTypeOnly` for name-merging
620
+ const namedByPath = new Map<string, ExportNode>()
621
+ // Deduplicates non-array exports by their exact identity
622
+ const seen = new Set<string>()
623
+
624
+ // Precompute sort keys once — avoids recomputing per comparison.
625
+ const keyed = exports.map((node) => ({ node, key: sortKey(node) }))
626
+ keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
627
+
628
+ for (const { node: curr } of keyed) {
629
+ const { name, path, isTypeOnly, asAlias } = curr
630
+
631
+ if (Array.isArray(name)) {
632
+ if (!name.length) continue
633
+
634
+ const key = pathTypeKey(path, isTypeOnly)
635
+ const existing = namedByPath.get(key)
636
+
637
+ if (existing && Array.isArray(existing.name)) {
638
+ const merged = new Set(existing.name)
639
+ for (const n of name) merged.add(n)
640
+ existing.name = [...merged]
641
+ } else {
642
+ const newItem: ExportNode = { ...curr, name: [...new Set(name)] }
643
+ result.push(newItem)
644
+ namedByPath.set(key, newItem)
645
+ }
646
+ } else {
647
+ const key = exportKey(path, name, isTypeOnly, asAlias)
648
+ if (!seen.has(key)) {
649
+ result.push(curr)
650
+ seen.add(key)
651
+ }
652
+ }
653
+ }
654
+
655
+ return result
656
+ }
657
+
658
+ /**
659
+ * Deduplicates and merges an array of `ImportNode` objects.
660
+ * Filters out unused imports (names not referenced in `source` or re-exported).
661
+ * Imports with the same path and `isTypeOnly` flag have their names merged.
662
+ */
663
+ export function combineImports(imports: Array<ImportNode>, exports: Array<ExportNode>, source?: string): Array<ImportNode> {
664
+ // Build a lookup of all exported names to retain imports that are re-exported
665
+ const exportedNames = new Set(exports.flatMap((e) => (Array.isArray(e.name) ? e.name : e.name ? [e.name] : [])))
666
+ const isUsed = (importName: string): boolean => !source || source.includes(importName) || exportedNames.has(importName)
667
+
668
+ const result: Array<ImportNode> = []
669
+ // Accumulates array-named imports keyed by `path:isTypeOnly` for name-merging
670
+ const namedByPath = new Map<string, ImportNode>()
671
+ // Deduplicates non-array imports by their exact identity
672
+ const seen = new Set<string>()
673
+
674
+ // Precompute sort keys once — avoids recomputing per comparison.
675
+ const keyed = imports.map((node) => ({ node, key: sortKey(node) }))
676
+ keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
677
+
678
+ for (const { node: curr } of keyed) {
679
+ if (curr.path === curr.root) continue
680
+
681
+ const { path, isTypeOnly } = curr
682
+ let { name } = curr
683
+
684
+ if (Array.isArray(name)) {
685
+ name = [...new Set(name)].filter((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.propertyName)))
686
+ if (!name.length) continue
687
+
688
+ const key = pathTypeKey(path, isTypeOnly)
689
+ const existing = namedByPath.get(key)
690
+
691
+ if (existing && Array.isArray(existing.name)) {
692
+ const merged = new Set(existing.name)
693
+ for (const n of name) merged.add(n)
694
+ existing.name = [...merged]
695
+ } else {
696
+ const newItem: ImportNode = { ...curr, name }
697
+ result.push(newItem)
698
+ namedByPath.set(key, newItem)
699
+ }
700
+ } else {
701
+ if (name && !isUsed(name)) continue
702
+
703
+ const key = importKey(path, name, isTypeOnly)
704
+ if (!seen.has(key)) {
705
+ result.push(curr)
706
+ seen.add(key)
707
+ }
708
+ }
709
+ }
710
+
711
+ return result
712
+ }
713
+
714
+ /**
715
+ * Recursively extracts all string content embedded in a {@link CodeNode} tree.
716
+ *
717
+ * Includes text node values, and string attribute fields (`params`, `generics`,
718
+ * `returnType`, `type`) that may reference identifiers needing imports.
719
+ * Used by `createFile` to build the full source string for import filtering.
720
+ */
721
+ export function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): string {
722
+ if (!nodes?.length) return ''
723
+ return nodes
724
+ .map((node) => {
725
+ // Backward-compat: compiled plugins may still pass bare strings at runtime
726
+ if (typeof node === 'string') return node as string
727
+ if (node.kind === 'Text') return node.value
728
+ if (node.kind === 'Break') return ''
729
+ if (node.kind === 'Jsx') return node.value
730
+ const parts: string[] = []
731
+ if ('params' in node && node.params) parts.push(node.params)
732
+ if ('generics' in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(', ') : node.generics)
733
+ if ('returnType' in node && node.returnType) parts.push(node.returnType)
734
+ if ('type' in node && typeof node.type === 'string') parts.push(node.type)
735
+ const nested = extractStringsFromNodes(node.nodes)
736
+ if (nested) parts.push(nested)
737
+ return parts.join('\n')
738
+ })
739
+ .filter(Boolean)
740
+ .join('\n')
741
+ }