@kubb/parser-ts 5.0.0-beta.2 → 5.0.0-beta.21

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 ADDED
@@ -0,0 +1,482 @@
1
+ import { normalize, relative } from 'node:path'
2
+ import type { ArrowFunctionNode, CodeNode, ConstNode, FunctionNode, JSDocNode, JsxNode, SourceNode, TextNode, TypeNode } from '@kubb/ast'
3
+ import ts from 'typescript'
4
+ import {
5
+ CARRIAGE_RETURN_PATTERN,
6
+ CRLF_PATTERN,
7
+ CURRENT_DIRECTORY_PREFIX,
8
+ FILE_EXTENSION_PATTERN,
9
+ INDENT_SIZE,
10
+ JSDOC_TERMINATOR_PATTERN,
11
+ LEADING_DIGIT_PATTERN,
12
+ PARENT_DIRECTORY_PREFIX,
13
+ WINDOWS_PATH_SEPARATOR,
14
+ } from './constants.ts'
15
+
16
+ const { factory } = ts
17
+
18
+ /**
19
+ * Normalizes a file-system path to POSIX separators and strips any leading `../` segment.
20
+ */
21
+ export function slash(path: string): string {
22
+ return normalize(path).replaceAll(WINDOWS_PATH_SEPARATOR, '/').replace(PARENT_DIRECTORY_PREFIX, '')
23
+ }
24
+
25
+ /**
26
+ * Resolves `filePath` relative to `rootDir` and returns a POSIX-style path
27
+ * prefixed with `./` when the target sits inside the root, or `../` when it escapes it.
28
+ */
29
+ export function getRelativePath(rootDir: string, filePath: string): string {
30
+ const rel = relative(rootDir, filePath)
31
+ const slashed = slash(rel)
32
+ return slashed.startsWith(PARENT_DIRECTORY_PREFIX) ? slashed : `${CURRENT_DIRECTORY_PREFIX}${slashed}`
33
+ }
34
+
35
+ /**
36
+ * Strips the trailing file extension (for example `.ts`) from a path.
37
+ * Preserves intermediate dots like `foo.bar.ts` → `foo.bar`.
38
+ */
39
+ export function trimExtName(text: string): string {
40
+ return text.replace(FILE_EXTENSION_PATTERN, '')
41
+ }
42
+
43
+ /**
44
+ * Rewrites an import/export path so its extension matches the caller-supplied
45
+ * `options.extname`. When the source path has no extension the original is kept,
46
+ * so virtual/module-only paths flow through unchanged.
47
+ */
48
+ export function resolveOutputPath(path: string, options: { extname?: string } | undefined, rootAware: boolean): string {
49
+ const hasExtname = FILE_EXTENSION_PATTERN.test(path)
50
+ if (options?.extname && hasExtname) {
51
+ return `${trimExtName(path)}${options.extname}`
52
+ }
53
+ return rootAware ? trimExtName(path) : path
54
+ }
55
+
56
+ /**
57
+ * Serializes the body / value content from a `nodes` array.
58
+ *
59
+ * Each element is either a raw string or a structured {@link CodeNode}
60
+ * (recursively converted via {@link printCodeNode}).
61
+ * Elements are joined with `\n`.
62
+ */
63
+ export function printNodes(nodes: Array<CodeNode> | undefined): string {
64
+ if (!nodes || nodes.length === 0) return ''
65
+
66
+ const parts: string[] = []
67
+
68
+ for (const node of nodes) {
69
+ parts.push(printCodeNode(node))
70
+ }
71
+
72
+ return parts.join('\n')
73
+ }
74
+
75
+ /**
76
+ * Indents every non-empty line of `text` by `spaces` spaces.
77
+ */
78
+ export function indentLines(text: string, spaces: number = INDENT_SIZE): string {
79
+ if (!text) return ''
80
+ const pad = ' '.repeat(spaces)
81
+ return text
82
+ .split('\n')
83
+ .map((line) => (line.trim() ? `${pad}${line}` : ''))
84
+ .join('\n')
85
+ }
86
+
87
+ /**
88
+ * Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.
89
+ * Accepts either a raw string (rendered verbatim) or an array of type-parameter names.
90
+ */
91
+ export function formatGenerics(generics: FunctionNode['generics'] | ArrowFunctionNode['generics']): string {
92
+ if (!generics) return ''
93
+ return `<${Array.isArray(generics) ? generics.join(', ') : generics}>`
94
+ }
95
+
96
+ /**
97
+ * Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).
98
+ * Returns an empty string when no return type is provided.
99
+ */
100
+ export function formatReturnType(returnType: string | undefined, isAsync: boolean | undefined): string {
101
+ if (!returnType) return ''
102
+ return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`
103
+ }
104
+
105
+ /**
106
+ * Validates TypeScript AST nodes before printing.
107
+ * Throws an error if any node has SyntaxKind.Unknown which would cause the
108
+ * TypeScript printer to crash.
109
+ */
110
+ export function validateNodes(...nodes: ts.Node[]): void {
111
+ for (const node of nodes) {
112
+ if (!node) {
113
+ throw new Error('Attempted to print undefined or null TypeScript node')
114
+ }
115
+ if (node.kind === ts.SyntaxKind.Unknown) {
116
+ throw new Error(
117
+ 'Invalid TypeScript AST node detected with SyntaxKind.Unknown. ' +
118
+ 'This typically indicates a schema pattern that could not be properly converted to TypeScript. ' +
119
+ `Node: ${JSON.stringify(node, null, 2)}`,
120
+ )
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Module-scoped TypeScript printer instance. `ts.createPrinter()` is stateless across calls
127
+ * (it does not mutate the source file) so a single instance can be safely reused for every
128
+ * `print()` call. Hoisting it out of `print()` avoids re-running the printer initialization
129
+ * for each file's import/export section.
130
+ */
131
+ const TS_PRINTER = ts.createPrinter({
132
+ omitTrailingSemicolon: true,
133
+ newLine: ts.NewLineKind.LineFeed,
134
+ removeComments: false,
135
+ noEmitHelpers: true,
136
+ })
137
+
138
+ /**
139
+ * Module-scoped source file used as the print target. `printList` only reads the source
140
+ * file's compiler options / language version; it never mutates it.
141
+ */
142
+ const PRINT_SOURCE_FILE = ts.createSourceFile('print.tsx', '', ts.ScriptTarget.ES2022, true, ts.ScriptKind.TSX)
143
+
144
+ // Pre-warm the printer at module load. The first `printList` call lazily initializes
145
+ // the printer's internal string-builder and identifier tables; doing it once at import
146
+ // time keeps that cost off the critical path for short-lived CLI builds.
147
+ TS_PRINTER.printList(ts.ListFormat.MultiLine, factory.createNodeArray([]), PRINT_SOURCE_FILE)
148
+
149
+ /**
150
+ * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.
151
+ */
152
+ export function print(...elements: Array<ts.Node>): string {
153
+ const filtered = elements.filter(Boolean)
154
+ if (filtered.length === 0) return ''
155
+
156
+ const output = TS_PRINTER.printList(ts.ListFormat.MultiLine, factory.createNodeArray(filtered), PRINT_SOURCE_FILE)
157
+
158
+ return output.replace(CRLF_PATTERN, '\n')
159
+ }
160
+
161
+ /**
162
+ * Like `print` but validates nodes first to surface issues early.
163
+ */
164
+ export function safePrint(...elements: Array<ts.Node>): string {
165
+ validateNodes(...elements)
166
+ return print(...elements)
167
+ }
168
+
169
+ /**
170
+ * Converts a {@link JSDocNode} to a JSDoc comment block string.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * printJSDoc({ comments: ['@description A pet', '@deprecated'] })
175
+ * // /**
176
+ * // * @description A pet
177
+ * // * @deprecated
178
+ * // *\/
179
+ * ```
180
+ */
181
+ export function printJSDoc(jsDoc: JSDocNode): string {
182
+ const comments = (jsDoc.comments ?? []).filter((c) => c != null)
183
+ if (comments.length === 0) return ''
184
+
185
+ const lines = comments
186
+ .flatMap((c) => c.split(/\r?\n/))
187
+ .map((l) => l.replace(JSDOC_TERMINATOR_PATTERN, '* /').replace(CARRIAGE_RETURN_PATTERN, ''))
188
+ .filter((l) => l.trim().length > 0)
189
+
190
+ if (lines.length === 0) return ''
191
+
192
+ return ['/**', ...lines.map((l) => ` * ${l}`), ' */'].join('\n')
193
+ }
194
+
195
+ /**
196
+ * Converts a {@link ConstNode} to a TypeScript `const` declaration string.
197
+ *
198
+ * Mirrors the `Const` component from `@kubb/renderer-jsx`.
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * printConst(createConst({ name: 'pet', export: true, nodes: ['{}'] }))
203
+ * // 'export const pet = {}'
204
+ * ```
205
+ *
206
+ * @example With type and `as const`
207
+ * ```ts
208
+ * printConst(createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true, nodes: ['[]'] }))
209
+ * // 'export const pets: Pet[] = [] as const'
210
+ * ```
211
+ */
212
+ export function printConst(node: ConstNode): string {
213
+ const { name, export: canExport, type, JSDoc, asConst, nodes } = node
214
+
215
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''
216
+ const body = printNodes(nodes)
217
+
218
+ const parts: string[] = []
219
+ if (canExport) parts.push('export ')
220
+ parts.push('const ')
221
+ parts.push(name)
222
+ if (type) {
223
+ parts.push(`: ${type}`)
224
+ }
225
+ parts.push(' = ')
226
+ parts.push(body)
227
+ if (asConst) parts.push(' as const')
228
+
229
+ const declaration = parts.join('')
230
+ return [jsDocStr, declaration].filter(Boolean).join('\n')
231
+ }
232
+
233
+ /**
234
+ * Converts a {@link TypeNode} to a TypeScript `type` alias declaration string.
235
+ *
236
+ * Mirrors the `Type` component from `@kubb/renderer-jsx`.
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * printType(createType({ name: 'Pet', export: true, nodes: ['{ id: number }'] }))
241
+ * // 'export type Pet = { id: number }'
242
+ * ```
243
+ */
244
+ export function printType(node: TypeNode): string {
245
+ const { name, export: canExport, JSDoc, nodes } = node
246
+
247
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''
248
+ const body = printNodes(nodes)
249
+
250
+ const parts: string[] = []
251
+ if (canExport) parts.push('export ')
252
+ parts.push('type ')
253
+ parts.push(name)
254
+ parts.push(' = ')
255
+ parts.push(body)
256
+
257
+ const declaration = parts.join('')
258
+ return [jsDocStr, declaration].filter(Boolean).join('\n')
259
+ }
260
+
261
+ /**
262
+ * Converts a {@link FunctionNode} to a TypeScript `function` declaration string.
263
+ *
264
+ * Mirrors the `Function` component from `@kubb/renderer-jsx`.
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * printFunction(createFunction({ name: 'getPet', export: true, params: 'id: string', returnType: 'Pet', nodes: ['return fetch(id)'] }))
269
+ * // 'export function getPet(id: string): Pet {\n return fetch(id)\n}'
270
+ * ```
271
+ *
272
+ * @example Async with generics
273
+ * ```ts
274
+ * printFunction(createFunction({ name: 'fetchPet', export: true, async: true, generics: ['T'], params: 'id: string', returnType: 'T' }))
275
+ * // 'export async function fetchPet<T>(id: string): Promise<T> {\n}'
276
+ * ```
277
+ */
278
+ export function printFunction(node: FunctionNode): string {
279
+ const { name, default: isDefault, export: canExport, async: isAsync, generics, params, returnType, JSDoc, nodes } = node
280
+
281
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''
282
+ const body = printNodes(nodes)
283
+ const indented = body ? indentLines(body) : ''
284
+
285
+ const parts: string[] = []
286
+ if (canExport) parts.push('export ')
287
+ if (isDefault) parts.push('default ')
288
+ if (isAsync) parts.push('async ')
289
+ parts.push('function ')
290
+ parts.push(name)
291
+ parts.push(formatGenerics(generics))
292
+ parts.push(`(${params ?? ''})`)
293
+ parts.push(formatReturnType(returnType, isAsync))
294
+ parts.push(' {')
295
+ if (indented) {
296
+ parts.push(`\n${indented}\n`)
297
+ }
298
+ parts.push('}')
299
+
300
+ const declaration = parts.join('')
301
+ return [jsDocStr, declaration].filter(Boolean).join('\n')
302
+ }
303
+
304
+ /**
305
+ * Converts an {@link ArrowFunctionNode} to a TypeScript arrow function declaration string.
306
+ *
307
+ * Mirrors the `Function.Arrow` component from `@kubb/renderer-jsx`.
308
+ *
309
+ * @example Multi-line arrow function
310
+ * ```ts
311
+ * printArrowFunction(createArrowFunction({ name: 'getPet', export: true, params: 'id: string', nodes: ['return fetch(id)'] }))
312
+ * // 'export const getPet = (id: string) => {\n return fetch(id)\n}'
313
+ * ```
314
+ *
315
+ * @example Single-line arrow function
316
+ * ```ts
317
+ * printArrowFunction(createArrowFunction({ name: 'double', params: 'n: number', singleLine: true, nodes: ['n * 2'] }))
318
+ * // 'const double = (n: number) => n * 2'
319
+ * ```
320
+ */
321
+ export function printArrowFunction(node: ArrowFunctionNode): string {
322
+ const { name, default: isDefault, export: canExport, async: isAsync, generics, params, returnType, JSDoc, nodes, singleLine } = node
323
+
324
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''
325
+ const body = printNodes(nodes)
326
+ const arrowBody = singleLine ? ` => ${body}` : body ? ` => {\n${indentLines(body)}\n}` : ' => {}'
327
+
328
+ const parts: string[] = []
329
+ if (canExport) parts.push('export ')
330
+ if (isDefault) parts.push('default ')
331
+ parts.push('const ')
332
+ parts.push(name)
333
+ parts.push(' = ')
334
+ if (isAsync) parts.push('async ')
335
+ parts.push(formatGenerics(generics))
336
+ parts.push(`(${params ?? ''})`)
337
+ parts.push(formatReturnType(returnType, isAsync))
338
+ parts.push(arrowBody)
339
+
340
+ const declaration = parts.join('')
341
+ return [jsDocStr, declaration].filter(Boolean).join('\n')
342
+ }
343
+
344
+ /**
345
+ * Converts a {@link CodeNode} to its TypeScript string representation.
346
+ *
347
+ * Dispatches to the appropriate printer based on the node's `kind`.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * printCodeNode(createConst({ name: 'x', nodes: ['1'] }))
352
+ * // 'const x = 1'
353
+ * ```
354
+ */
355
+ export function printCodeNode(node: CodeNode): string {
356
+ if (node.kind === 'Break') return ''
357
+ if (node.kind === 'Text') return (node as TextNode).value
358
+ if (node.kind === 'Jsx') return (node as JsxNode).value
359
+ if (node.kind === 'Const') return printConst(node)
360
+ if (node.kind === 'Type') return printType(node)
361
+ if (node.kind === 'Function') return printFunction(node)
362
+ if (node.kind === 'ArrowFunction') return printArrowFunction(node)
363
+ return ''
364
+ }
365
+
366
+ /**
367
+ * Converts a {@link SourceNode} to its TypeScript string representation.
368
+ *
369
+ * Iterates `nodes` in DOM order, rendering each {@link CodeNode} via
370
+ * {@link printCodeNode}.
371
+ *
372
+ * @example From nodes
373
+ * ```ts
374
+ * printSource({ kind: 'Source', nodes: [createConst({ name: 'x', nodes: [createText('1')] }), createText('x.toString()')] })
375
+ * // 'const x = 1\nx.toString()'
376
+ * ```
377
+ */
378
+ export function printSource(node: SourceNode): string {
379
+ const nodes = node.nodes
380
+
381
+ if (!nodes || nodes.length === 0) return ''
382
+ const parts: string[] = []
383
+
384
+ for (const child of nodes) {
385
+ parts.push(printCodeNode(child as CodeNode))
386
+ }
387
+
388
+ return parts.join('\n')
389
+ }
390
+
391
+ export function createImport({
392
+ name,
393
+ path,
394
+ root,
395
+ isTypeOnly = false,
396
+ isNameSpace = false,
397
+ }: {
398
+ name: string | Array<string | { propertyName: string; name?: string }>
399
+ path: string
400
+ root?: string
401
+ /** @default false */
402
+ isTypeOnly?: boolean
403
+ /** @default false */
404
+ isNameSpace?: boolean
405
+ }): ts.ImportDeclaration {
406
+ const resolvePath = root ? getRelativePath(root, path) : path
407
+
408
+ if (!Array.isArray(name)) {
409
+ if (isNameSpace) {
410
+ return factory.createImportDeclaration(
411
+ undefined,
412
+ factory.createImportClause(isTypeOnly, undefined, factory.createNamespaceImport(factory.createIdentifier(name))),
413
+ factory.createStringLiteral(resolvePath),
414
+ undefined,
415
+ )
416
+ }
417
+
418
+ return factory.createImportDeclaration(
419
+ undefined,
420
+ factory.createImportClause(isTypeOnly, factory.createIdentifier(name), undefined),
421
+ factory.createStringLiteral(resolvePath),
422
+ undefined,
423
+ )
424
+ }
425
+
426
+ const specifiers = name.map((item) => {
427
+ if (typeof item === 'object') {
428
+ const { propertyName, name: alias } = item
429
+ return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : undefined, factory.createIdentifier(alias ?? propertyName))
430
+ }
431
+ return factory.createImportSpecifier(false, undefined, factory.createIdentifier(item))
432
+ })
433
+
434
+ return factory.createImportDeclaration(
435
+ undefined,
436
+ factory.createImportClause(isTypeOnly, undefined, factory.createNamedImports(specifiers)),
437
+ factory.createStringLiteral(resolvePath),
438
+ undefined,
439
+ )
440
+ }
441
+
442
+ export function createExport({
443
+ path,
444
+ asAlias,
445
+ isTypeOnly = false,
446
+ name,
447
+ }: {
448
+ path: string
449
+ /** @default false */
450
+ asAlias?: boolean
451
+ /** @default false */
452
+ isTypeOnly?: boolean
453
+ name?: string | Array<ts.Identifier | string>
454
+ }): ts.ExportDeclaration {
455
+ if (name && !Array.isArray(name) && !asAlias) {
456
+ console.warn(`When using name as string, asAlias should be true: ${name}`)
457
+ }
458
+
459
+ if (!Array.isArray(name)) {
460
+ const parsedName = name && LEADING_DIGIT_PATTERN.test(name) ? `_${name.slice(1)}` : name
461
+
462
+ return factory.createExportDeclaration(
463
+ undefined,
464
+ isTypeOnly,
465
+ asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : undefined,
466
+ factory.createStringLiteral(path),
467
+ undefined,
468
+ )
469
+ }
470
+
471
+ return factory.createExportDeclaration(
472
+ undefined,
473
+ isTypeOnly,
474
+ factory.createNamedExports(
475
+ name.map((propertyName) =>
476
+ factory.createExportSpecifier(false, undefined, typeof propertyName === 'string' ? factory.createIdentifier(propertyName) : propertyName),
477
+ ),
478
+ ),
479
+ factory.createStringLiteral(path),
480
+ undefined,
481
+ )
482
+ }