@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.
- package/README.md +10 -0
- package/dist/casing-BE2R1RXg.cjs +88 -0
- package/dist/casing-BE2R1RXg.cjs.map +1 -0
- package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
- package/dist/factory-BmcGBdeg.cjs +1251 -0
- package/dist/factory-BmcGBdeg.cjs.map +1 -0
- package/dist/factory-Du7nEP4B.js +282 -0
- package/dist/factory-Du7nEP4B.js.map +1 -0
- package/dist/factory.cjs +25 -28
- package/dist/factory.d.ts +3 -3
- package/dist/factory.js +3 -3
- package/dist/{ast-ClnJg9BN.d.ts → index-BzjwdK2M.d.ts} +74 -372
- package/dist/index.cjs +445 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +94 -59
- package/dist/index.js +7 -113
- package/dist/index.js.map +1 -1
- package/dist/operationParams-BZ07xDm0.d.ts +204 -0
- package/dist/response-DKxTr522.js +683 -0
- package/dist/response-DKxTr522.js.map +1 -0
- package/dist/{types-CB2oY8Dw.d.ts → types-olVl9v5p.d.ts} +222 -227
- package/dist/types.d.ts +4 -3
- package/dist/utils-BCtRXfhI.cjs +275 -0
- package/dist/utils-BCtRXfhI.cjs.map +1 -0
- package/dist/{utils-DN4XLVqz.js → utils-SdZU0F3H.js} +472 -1235
- package/dist/utils-SdZU0F3H.js.map +1 -0
- package/dist/utils.cjs +127 -22
- package/dist/utils.d.ts +112 -80
- package/dist/utils.js +3 -2
- package/package.json +1 -1
- package/src/constants.ts +8 -14
- package/src/dedupe.ts +8 -0
- package/src/factory.ts +1 -2
- package/src/guards.ts +1 -1
- package/src/index.ts +4 -13
- package/src/nodes/code.ts +29 -47
- package/src/nodes/content.ts +2 -2
- package/src/nodes/file.ts +28 -23
- package/src/nodes/function.ts +0 -15
- package/src/nodes/input.ts +6 -6
- package/src/nodes/operation.ts +1 -1
- package/src/nodes/parameter.ts +0 -3
- package/src/nodes/property.ts +0 -3
- package/src/nodes/requestBody.ts +3 -6
- package/src/nodes/schema.ts +3 -2
- package/src/printer.ts +1 -1
- package/src/registry.ts +31 -26
- package/src/signature.ts +3 -3
- package/src/transformers.ts +28 -1
- package/src/types.ts +2 -53
- package/src/utils/codegen.ts +104 -0
- package/src/utils/fileMerge.ts +184 -0
- package/src/utils/index.ts +7 -339
- package/src/utils/operationParams.ts +353 -0
- package/src/utils/refs.ts +112 -0
- package/src/utils/schemaGraph.ts +169 -0
- package/src/utils/strings.ts +139 -0
- package/src/visitor.ts +43 -19
- package/dist/extractStringsFromNodes-Bn9cOos9.d.ts +0 -14
- package/dist/factory-C5gHvtLU.js +0 -138
- package/dist/factory-C5gHvtLU.js.map +0 -1
- package/dist/factory-JN-Ylfl6.cjs +0 -155
- package/dist/factory-JN-Ylfl6.cjs.map +0 -1
- package/dist/utils-C8bWAzhv.cjs +0 -2696
- package/dist/utils-C8bWAzhv.cjs.map +0 -1
- package/dist/utils-DN4XLVqz.js.map +0 -1
- package/src/utils/ast.ts +0 -816
package/src/registry.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { arrowFunctionDef, breakDef, constDef, functionDef, jsxDef, textDef, typ
|
|
|
3
3
|
import { contentDef } from './nodes/content.ts'
|
|
4
4
|
import { exportDef, fileDef, importDef, sourceDef } from './nodes/file.ts'
|
|
5
5
|
import { functionParameterDef, functionParametersDef, indexedAccessTypeDef, objectBindingPatternDef, typeLiteralDef } from './nodes/function.ts'
|
|
6
|
-
import type { Node, NodeKind } from './nodes/index.ts'
|
|
7
6
|
import { inputDef } from './nodes/input.ts'
|
|
8
7
|
import { operationDef } from './nodes/operation.ts'
|
|
9
8
|
import { outputDef } from './nodes/output.ts'
|
|
@@ -13,9 +12,39 @@ import { requestBodyDef } from './nodes/requestBody.ts'
|
|
|
13
12
|
import { responseDef } from './nodes/response.ts'
|
|
14
13
|
import { schemaDef } from './nodes/schema.ts'
|
|
15
14
|
|
|
15
|
+
// Surface every def from one place so the package barrel re-exports them with `export * from './registry.ts'`.
|
|
16
|
+
// Adding a node means adding its `defineNode` to a `nodes/*.ts` file and listing it in `nodeDefs` below, nothing else.
|
|
17
|
+
export {
|
|
18
|
+
arrowFunctionDef,
|
|
19
|
+
breakDef,
|
|
20
|
+
constDef,
|
|
21
|
+
contentDef,
|
|
22
|
+
exportDef,
|
|
23
|
+
fileDef,
|
|
24
|
+
functionDef,
|
|
25
|
+
functionParameterDef,
|
|
26
|
+
functionParametersDef,
|
|
27
|
+
importDef,
|
|
28
|
+
indexedAccessTypeDef,
|
|
29
|
+
inputDef,
|
|
30
|
+
jsxDef,
|
|
31
|
+
objectBindingPatternDef,
|
|
32
|
+
operationDef,
|
|
33
|
+
outputDef,
|
|
34
|
+
parameterDef,
|
|
35
|
+
propertyDef,
|
|
36
|
+
requestBodyDef,
|
|
37
|
+
responseDef,
|
|
38
|
+
schemaDef,
|
|
39
|
+
sourceDef,
|
|
40
|
+
textDef,
|
|
41
|
+
typeDef,
|
|
42
|
+
typeLiteralDef,
|
|
43
|
+
}
|
|
44
|
+
|
|
16
45
|
/**
|
|
17
46
|
* Every node definition. Adding a node means adding its `defineNode` to one
|
|
18
|
-
* `nodes/*.ts` file and listing it here. The visitor tables
|
|
47
|
+
* `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
|
|
19
48
|
*/
|
|
20
49
|
export const nodeDefs = [
|
|
21
50
|
inputDef,
|
|
@@ -44,27 +73,3 @@ export const nodeDefs = [
|
|
|
44
73
|
sourceDef,
|
|
45
74
|
fileDef,
|
|
46
75
|
] satisfies ReadonlyArray<NodeDef>
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
|
|
50
|
-
* Derived from each definition's `children`.
|
|
51
|
-
*/
|
|
52
|
-
export const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => (def.children ? [[def.kind, def.children] as const] : []))) as Partial<
|
|
53
|
-
Record<NodeKind, ReadonlyArray<string>>
|
|
54
|
-
>
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Maps a node kind to the matching visitor callback name. Derived from each
|
|
58
|
-
* definition's `visitorKey`.
|
|
59
|
-
*/
|
|
60
|
-
export const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => (def.visitorKey ? [[def.kind, def.visitorKey] as const] : []))) as Partial<
|
|
61
|
-
Record<NodeKind, NonNullable<NodeDef['visitorKey']>>
|
|
62
|
-
>
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Per-kind builders rerun after children are rebuilt. Derived from each
|
|
66
|
-
* definition's `rebuild` flag.
|
|
67
|
-
*/
|
|
68
|
-
export const nodeRebuilders = Object.fromEntries(
|
|
69
|
-
nodeDefs.flatMap((def) => (def.rebuild ? [[def.kind, def.create as unknown as (node: Node) => Node] as const] : [])),
|
|
70
|
-
) as Partial<Record<NodeKind, (node: Node) => Node>>
|
package/src/signature.ts
CHANGED
|
@@ -170,9 +170,9 @@ function describeShape(node: SchemaNode): string {
|
|
|
170
170
|
}
|
|
171
171
|
|
|
172
172
|
/**
|
|
173
|
-
*
|
|
174
|
-
* hashed during dedupe planning is not walked again when it is rewritten during streaming.
|
|
175
|
-
* is safe because a signature depends only on content, and nodes are immutable once created.
|
|
173
|
+
* Caches the digest per node, keyed by identity. A `WeakMap` so entries die with the node, and so
|
|
174
|
+
* a tree hashed during dedupe planning is not walked again when it is rewritten during streaming.
|
|
175
|
+
* Reuse is safe because a signature depends only on content, and nodes are immutable once created.
|
|
176
176
|
*/
|
|
177
177
|
const signatureCache = new WeakMap<SchemaNode, string>()
|
|
178
178
|
|
package/src/transformers.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { isScalarPrimitive } from './constants.ts'
|
|
|
2
2
|
import { narrowSchema } from './guards.ts'
|
|
3
3
|
import { createProperty } from './nodes/property.ts'
|
|
4
4
|
import { createSchema, type SchemaNode } from './nodes/schema.ts'
|
|
5
|
-
import { enumPropName } from './utils/
|
|
5
|
+
import { enumPropName } from './utils/refs.ts'
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Replaces a discriminator property's schema with a string enum of allowed values.
|
|
@@ -162,3 +162,30 @@ export function setEnumName(propNode: SchemaNode, parentName: string | null | un
|
|
|
162
162
|
|
|
163
163
|
return propNode
|
|
164
164
|
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
|
|
168
|
+
*
|
|
169
|
+
* Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
|
|
170
|
+
* the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```ts
|
|
174
|
+
* // Ref with description override
|
|
175
|
+
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
|
|
176
|
+
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
|
|
177
|
+
* ```
|
|
178
|
+
*/
|
|
179
|
+
export function syncSchemaRef(node: SchemaNode): SchemaNode {
|
|
180
|
+
const ref = narrowSchema(node, 'ref')
|
|
181
|
+
|
|
182
|
+
if (!ref) return node
|
|
183
|
+
if (!ref.schema) return node
|
|
184
|
+
|
|
185
|
+
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref
|
|
186
|
+
|
|
187
|
+
// Filter out undefined override values so they don't shadow the resolved schema's fields.
|
|
188
|
+
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
|
|
189
|
+
|
|
190
|
+
return createSchema({ ...ref.schema, ...definedOverrides })
|
|
191
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -2,59 +2,8 @@ export type { DedupeCanonical, DedupeLookups, DedupePlan } from './dedupe.ts'
|
|
|
2
2
|
export type { SchemaDialect } from './dialect.ts'
|
|
3
3
|
export type { DistributiveOmit } from './node.ts'
|
|
4
4
|
export type { InferSchemaNode, ParserOptions } from './infer.ts'
|
|
5
|
-
export type
|
|
6
|
-
ArraySchemaNode,
|
|
7
|
-
ArrowFunctionNode,
|
|
8
|
-
CodeNode,
|
|
9
|
-
ConstNode,
|
|
10
|
-
DateSchemaNode,
|
|
11
|
-
DatetimeSchemaNode,
|
|
12
|
-
EnumSchemaNode,
|
|
13
|
-
ExportNode,
|
|
14
|
-
FileNode,
|
|
15
|
-
FunctionNode,
|
|
16
|
-
FunctionParamKind,
|
|
17
|
-
FunctionParameterNode,
|
|
18
|
-
FunctionParametersNode,
|
|
19
|
-
FunctionParamNode,
|
|
20
|
-
HttpMethod,
|
|
21
|
-
HttpOperationNode,
|
|
22
|
-
ImportNode,
|
|
23
|
-
IndexedAccessTypeNode,
|
|
24
|
-
InputMeta,
|
|
25
|
-
InputNode,
|
|
26
|
-
IntersectionSchemaNode,
|
|
27
|
-
JSDocNode,
|
|
28
|
-
JsxNode,
|
|
29
|
-
Node,
|
|
30
|
-
NodeKind,
|
|
31
|
-
NumberSchemaNode,
|
|
32
|
-
ObjectBindingPatternNode,
|
|
33
|
-
ObjectSchemaNode,
|
|
34
|
-
OperationNode,
|
|
35
|
-
OutputNode,
|
|
36
|
-
ParameterLocation,
|
|
37
|
-
ParameterNode,
|
|
38
|
-
PrimitiveSchemaType,
|
|
39
|
-
PropertyNode,
|
|
40
|
-
RefSchemaNode,
|
|
41
|
-
ResponseNode,
|
|
42
|
-
ScalarSchemaType,
|
|
43
|
-
SchemaNode,
|
|
44
|
-
SchemaNodeByType,
|
|
45
|
-
SchemaType,
|
|
46
|
-
SourceNode,
|
|
47
|
-
StatusCode,
|
|
48
|
-
StringSchemaNode,
|
|
49
|
-
TextNode,
|
|
50
|
-
TimeSchemaNode,
|
|
51
|
-
TypeExpression,
|
|
52
|
-
TypeLiteralNode,
|
|
53
|
-
TypeNode,
|
|
54
|
-
UnionSchemaNode,
|
|
55
|
-
UrlSchemaNode,
|
|
56
|
-
} from './nodes/index.ts'
|
|
5
|
+
export type * from './nodes/index.ts'
|
|
57
6
|
export type { ParentOf, Visitor, VisitorContext } from './visitor.ts'
|
|
58
7
|
export type { Printer, PrinterFactoryOptions, PrinterPartial } from './printer.ts'
|
|
59
|
-
export type { OperationParamsResolver } from './utils/
|
|
8
|
+
export type { OperationParamsResolver } from './utils/operationParams.ts'
|
|
60
9
|
export type { UserFileNode } from './factory.ts'
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isIdentifier, singleQuote } from '@internals/utils'
|
|
2
|
+
import { INDENT } from '../constants.ts'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
|
|
6
|
+
* comments so callers always get a usable string.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* buildJSDoc(['@type string', '@example hello'])
|
|
11
|
+
* // '/**\n * @type string\n * @example hello\n *\/\n '
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export function buildJSDoc(
|
|
15
|
+
comments: Array<string>,
|
|
16
|
+
options: {
|
|
17
|
+
/**
|
|
18
|
+
* String used to indent each comment line.
|
|
19
|
+
* @default ' * '
|
|
20
|
+
*/
|
|
21
|
+
indent?: string
|
|
22
|
+
/**
|
|
23
|
+
* String appended after the closing tag.
|
|
24
|
+
* @default '\n '
|
|
25
|
+
*/
|
|
26
|
+
suffix?: string
|
|
27
|
+
/**
|
|
28
|
+
* Returned as-is when `comments` is empty.
|
|
29
|
+
* @default ' '
|
|
30
|
+
*/
|
|
31
|
+
fallback?: string
|
|
32
|
+
} = {},
|
|
33
|
+
): string {
|
|
34
|
+
const { indent = ' * ', suffix = '\n ', fallback = ' ' } = options
|
|
35
|
+
|
|
36
|
+
if (comments.length === 0) return fallback
|
|
37
|
+
|
|
38
|
+
return `/**\n${comments.map((c) => `${indent}${c}`).join('\n')}\n */${suffix}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
|
|
43
|
+
*/
|
|
44
|
+
function indentLines(text: string): string {
|
|
45
|
+
if (!text) return ''
|
|
46
|
+
return text
|
|
47
|
+
.split('\n')
|
|
48
|
+
.map((line) => (line.trim() ? `${INDENT}${line}` : ''))
|
|
49
|
+
.join('\n')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
|
|
54
|
+
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* objectKey('name') // 'name'
|
|
59
|
+
* objectKey('x-total') // "'x-total'"
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
export function objectKey(name: string): string {
|
|
63
|
+
return isIdentifier(name) ? name : singleQuote(name)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
68
|
+
* level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
|
|
69
|
+
* so callers never re-parse the generated code. A trailing comma is added per entry to match the
|
|
70
|
+
* formatter's multi-line style.
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
75
|
+
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export function buildObject(entries: Array<string>): string {
|
|
79
|
+
if (entries.length === 0) return '{}'
|
|
80
|
+
const body = entries.map((entry) => `${indentLines(entry)},`).join('\n')
|
|
81
|
+
|
|
82
|
+
return `{\n${body}\n}`
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
87
|
+
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
88
|
+
* one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
|
|
89
|
+
* `z.array([…])`, and similar member lists so objects inside them nest correctly.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```ts
|
|
93
|
+
* buildList(['z.string()', 'z.number()'])
|
|
94
|
+
* // '[z.string(), z.number()]'
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {
|
|
98
|
+
const [open, close] = brackets
|
|
99
|
+
if (items.length === 0) return `${open}${close}`
|
|
100
|
+
if (!items.some((item) => item.includes('\n'))) return `${open}${items.join(', ')}${close}`
|
|
101
|
+
const body = items.map((item) => `${indentLines(item)},`).join('\n')
|
|
102
|
+
|
|
103
|
+
return `${open}\n${body}\n${close}`
|
|
104
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-member merging. `combineImports`, `combineExports`, and `combineSources` deduplicate and sort
|
|
3
|
+
* the import, export, and source entries of one file, and drop imports nothing references. This works
|
|
4
|
+
* on a file's members, not on schema content.
|
|
5
|
+
*
|
|
6
|
+
* For collapsing duplicate schema shapes by structural signature, see `dedupe.ts`.
|
|
7
|
+
*/
|
|
8
|
+
import type { ExportNode, ImportNode, SourceNode } from '../nodes/index.ts'
|
|
9
|
+
import { extractStringsFromNodes } from './extractStringsFromNodes.ts'
|
|
10
|
+
|
|
11
|
+
function sourceKey(source: SourceNode): string {
|
|
12
|
+
const nameKey = source.name ?? extractStringsFromNodes(source.nodes)
|
|
13
|
+
return `${nameKey}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function pathTypeKey(path: string, isTypeOnly: boolean | null | undefined): string {
|
|
17
|
+
return `${path}:${isTypeOnly ?? false}`
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function exportKey(path: string, name: string | null | undefined, isTypeOnly: boolean | null | undefined, asAlias: boolean | null | undefined): string {
|
|
21
|
+
return `${path}:${name ?? ''}:${isTypeOnly ?? false}:${asAlias ?? ''}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function importKey(path: string, name: string | null | undefined, isTypeOnly: boolean | null | undefined): string {
|
|
25
|
+
return `${path}:${name ?? ''}:${isTypeOnly ?? false}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Computes a multi-level sort key for exports and imports:
|
|
30
|
+
* non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
|
|
31
|
+
*/
|
|
32
|
+
function sortKey(node: { name?: string | Array<unknown> | null; isTypeOnly?: boolean | null; path: string }): string {
|
|
33
|
+
const isArray = Array.isArray(node.name) ? '1' : '0'
|
|
34
|
+
const typeOnly = node.isTypeOnly ? '0' : '1'
|
|
35
|
+
const hasName = node.name != null ? '1' : '0'
|
|
36
|
+
const name = Array.isArray(node.name) ? node.name.toSorted().join('\0') : (node.name ?? '')
|
|
37
|
+
return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
|
|
42
|
+
*
|
|
43
|
+
* Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
|
|
44
|
+
*/
|
|
45
|
+
export function combineSources(sources: Array<SourceNode>): Array<SourceNode> {
|
|
46
|
+
const seen = new Map<string, SourceNode>()
|
|
47
|
+
for (const source of sources) {
|
|
48
|
+
const key = sourceKey(source)
|
|
49
|
+
if (!seen.has(key)) seen.set(key, source)
|
|
50
|
+
}
|
|
51
|
+
return [...seen.values()]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Merges `incoming` names into `existing`, preserving order and dropping duplicates.
|
|
56
|
+
*
|
|
57
|
+
* Shared by `combineExports` and `combineImports` for the same-path name-merge case.
|
|
58
|
+
*/
|
|
59
|
+
function mergeNameArrays<TName>(existing: Array<TName>, incoming: Array<TName>): Array<TName> {
|
|
60
|
+
const merged = new Set(existing)
|
|
61
|
+
for (const name of incoming) merged.add(name)
|
|
62
|
+
return [...merged]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Deduplicates and merges `ExportNode` objects by path and type.
|
|
67
|
+
*
|
|
68
|
+
* Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
|
|
69
|
+
* Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
|
|
70
|
+
*/
|
|
71
|
+
export function combineExports(exports: Array<ExportNode>): Array<ExportNode> {
|
|
72
|
+
const result: Array<ExportNode> = []
|
|
73
|
+
// Accumulates array-named exports keyed by `path:isTypeOnly` for name-merging
|
|
74
|
+
const namedByPath = new Map<string, ExportNode>()
|
|
75
|
+
// Deduplicates non-array exports by their exact identity
|
|
76
|
+
const seen = new Set<string>()
|
|
77
|
+
|
|
78
|
+
// Precompute sort keys once, avoids recomputing per comparison.
|
|
79
|
+
const keyed = exports.map((node) => ({ node, key: sortKey(node) }))
|
|
80
|
+
keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
|
|
81
|
+
|
|
82
|
+
for (const { node: curr } of keyed) {
|
|
83
|
+
const { name, path, isTypeOnly, asAlias } = curr
|
|
84
|
+
|
|
85
|
+
if (Array.isArray(name)) {
|
|
86
|
+
if (!name.length) continue
|
|
87
|
+
|
|
88
|
+
const key = pathTypeKey(path, isTypeOnly)
|
|
89
|
+
const existing = namedByPath.get(key)
|
|
90
|
+
|
|
91
|
+
if (existing && Array.isArray(existing.name)) {
|
|
92
|
+
existing.name = mergeNameArrays(existing.name, name)
|
|
93
|
+
} else {
|
|
94
|
+
const newItem: ExportNode = { ...curr, name: [...new Set(name)] }
|
|
95
|
+
result.push(newItem)
|
|
96
|
+
namedByPath.set(key, newItem)
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
const key = exportKey(path, name, isTypeOnly, asAlias)
|
|
100
|
+
if (!seen.has(key)) {
|
|
101
|
+
result.push(curr)
|
|
102
|
+
seen.add(key)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return result
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Deduplicates and merges `ImportNode` objects, filtering out unused imports.
|
|
112
|
+
*
|
|
113
|
+
* Retains imports that are referenced in `source` or re-exported. Imports with the same path and
|
|
114
|
+
* `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
|
|
115
|
+
*/
|
|
116
|
+
export function combineImports(imports: Array<ImportNode>, exports: Array<ExportNode>, source?: string): Array<ImportNode> {
|
|
117
|
+
// Build a lookup of all exported names to retain imports that are re-exported
|
|
118
|
+
const exportedNames = new Set(exports.flatMap((e) => (Array.isArray(e.name) ? e.name : e.name ? [e.name] : [])))
|
|
119
|
+
const isUsed = (importName: string): boolean => !source || source.includes(importName) || exportedNames.has(importName)
|
|
120
|
+
|
|
121
|
+
// Memoize object import names so the same logical (propertyName, name) pair always
|
|
122
|
+
// reuses the same object reference. Set-based deduplication then works correctly.
|
|
123
|
+
const importNameMemo = new Map<string, { propertyName: string; name?: string }>()
|
|
124
|
+
const canonicalizeName = (n: string | { propertyName: string; name?: string }): string | { propertyName: string; name?: string } => {
|
|
125
|
+
if (typeof n === 'string') return n
|
|
126
|
+
const key = `${n.propertyName}:${n.name ?? ''}`
|
|
127
|
+
if (!importNameMemo.has(key)) importNameMemo.set(key, n)
|
|
128
|
+
return importNameMemo.get(key)!
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Paths that keep at least one used named import. A default import from such a path is retained
|
|
132
|
+
// even when its binding can't be found in `source` e.g. a generated `client` default import
|
|
133
|
+
// alongside `import type { Client } from <same path>`, where merged grouped output omits the body.
|
|
134
|
+
const pathsWithUsedNamedImport = new Set<string>()
|
|
135
|
+
for (const node of imports) {
|
|
136
|
+
if (!Array.isArray(node.name)) continue
|
|
137
|
+
if (node.name.some((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.name ?? item.propertyName)))) {
|
|
138
|
+
pathsWithUsedNamedImport.add(node.path)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const result: Array<ImportNode> = []
|
|
143
|
+
// Accumulates array-named imports keyed by `path:isTypeOnly` for name-merging
|
|
144
|
+
const namedByPath = new Map<string, ImportNode>()
|
|
145
|
+
// Deduplicates non-array imports by their exact identity
|
|
146
|
+
const seen = new Set<string>()
|
|
147
|
+
|
|
148
|
+
// Precompute sort keys once, avoids recomputing per comparison.
|
|
149
|
+
const keyed = imports.map((node) => ({ node, key: sortKey(node) }))
|
|
150
|
+
keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
|
|
151
|
+
|
|
152
|
+
for (const { node: curr } of keyed) {
|
|
153
|
+
if (curr.path === curr.root) continue
|
|
154
|
+
|
|
155
|
+
const { path, isTypeOnly } = curr
|
|
156
|
+
let { name } = curr
|
|
157
|
+
|
|
158
|
+
if (Array.isArray(name)) {
|
|
159
|
+
name = [...new Set(name.map(canonicalizeName))].filter((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.name ?? item.propertyName)))
|
|
160
|
+
if (!name.length) continue
|
|
161
|
+
|
|
162
|
+
const key = pathTypeKey(path, isTypeOnly)
|
|
163
|
+
const existing = namedByPath.get(key)
|
|
164
|
+
|
|
165
|
+
if (existing && Array.isArray(existing.name)) {
|
|
166
|
+
existing.name = mergeNameArrays(existing.name, name)
|
|
167
|
+
} else {
|
|
168
|
+
const newItem: ImportNode = { ...curr, name }
|
|
169
|
+
result.push(newItem)
|
|
170
|
+
namedByPath.set(key, newItem)
|
|
171
|
+
}
|
|
172
|
+
} else {
|
|
173
|
+
if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue
|
|
174
|
+
|
|
175
|
+
const key = importKey(path, name, isTypeOnly)
|
|
176
|
+
if (!seen.has(key)) {
|
|
177
|
+
result.push(curr)
|
|
178
|
+
seen.add(key)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return result
|
|
184
|
+
}
|