@kubb/parser-ts 4.1.3 → 5.0.0-alpha.31

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/package.json CHANGED
@@ -1,20 +1,18 @@
1
1
  {
2
2
  "name": "@kubb/parser-ts",
3
- "version": "4.1.3",
4
- "description": "TypeScript parsing and manipulation utilities for Kubb, enabling code generation with proper TypeScript syntax and formatting.",
3
+ "version": "5.0.0-alpha.31",
4
+ "description": "TypeScript and TSX file parser for Kubb, converting generated files to strings using the TypeScript compiler.",
5
5
  "keywords": [
6
6
  "typescript",
7
+ "tsx",
7
8
  "parser",
8
- "ast",
9
- "code-generation",
10
- "syntax",
11
- "formatting",
9
+ "code-generator",
12
10
  "codegen",
13
11
  "kubb"
14
12
  ],
15
13
  "repository": {
16
14
  "type": "git",
17
- "url": "https://github.com/kubb-labs/kubb.git",
15
+ "url": "git+https://github.com/kubb-labs/kubb.git",
18
16
  "directory": "packages/parser-ts"
19
17
  },
20
18
  "license": "MIT",
@@ -26,43 +24,32 @@
26
24
  "import": "./dist/index.js",
27
25
  "require": "./dist/index.cjs"
28
26
  },
29
- "./factory": {
30
- "import": "./dist/factory.js",
31
- "require": "./dist/factory.cjs"
32
- },
33
27
  "./package.json": "./package.json"
34
28
  },
35
- "main": "./dist/index.cjs",
36
- "module": "./dist/index.js",
37
- "types": "./dist/index.d.cts",
38
- "typesVersions": {
39
- "*": {
40
- "factory": [
41
- "./dist/factory.d.ts"
42
- ]
43
- }
44
- },
29
+ "types": "./dist/index.d.ts",
45
30
  "files": [
46
31
  "src",
47
32
  "dist",
48
33
  "!/**/**.test.**",
49
- "!/**/__tests__/**"
34
+ "!/**/__tests__/**",
35
+ "!/**/__snapshots__/**"
50
36
  ],
51
37
  "dependencies": {
52
- "prettier": "^3.6.2",
53
- "remeda": "^2.32.0",
54
- "typescript": "5.9.3"
38
+ "typescript": "^6.0.2",
39
+ "@kubb/core": "5.0.0-alpha.31"
55
40
  },
56
41
  "devDependencies": {
57
- "tsdown": "^0.15.7"
42
+ "@internals/utils": "0.0.0"
58
43
  },
59
44
  "engines": {
60
- "node": ">=20"
45
+ "node": ">=22"
61
46
  },
62
47
  "publishConfig": {
63
48
  "access": "public",
64
49
  "registry": "https://registry.npmjs.org/"
65
50
  },
51
+ "main": "./dist/index.cjs",
52
+ "module": "./dist/index.js",
66
53
  "scripts": {
67
54
  "build": "tsdown",
68
55
  "clean": "npx rimraf ./dist",
package/src/index.ts CHANGED
@@ -1,3 +1,2 @@
1
- export * as factory from './factory.ts'
2
- export { format } from './format.ts'
3
- export { print } from './print.ts'
1
+ export { createExport, createImport, parserTs, print, safePrint, validateNodes } from './parserTs.ts'
2
+ export { parserTsx } from './parserTsx.ts'
@@ -0,0 +1,212 @@
1
+ import { normalize, relative } from 'node:path'
2
+ import type { KubbFile, Parser } from '@kubb/core'
3
+ import { defineParser } from '@kubb/core'
4
+ import ts from 'typescript'
5
+
6
+ const { factory } = ts
7
+
8
+ function slash(path: string): string {
9
+ return normalize(path).replaceAll(/\\/g, '/').replace('../', '')
10
+ }
11
+
12
+ function getRelativePath(rootDir: string, filePath: string): string {
13
+ const rel = relative(rootDir, filePath)
14
+ const slashed = slash(rel)
15
+ return slashed.startsWith('../') ? slashed : `./${slashed}`
16
+ }
17
+
18
+ function trimExtName(text: string): string {
19
+ return text.replace(/\.[^/.]+$/, '')
20
+ }
21
+
22
+ /**
23
+ * Validates TypeScript AST nodes before printing.
24
+ * Throws an error if any node has SyntaxKind.Unknown which would cause the
25
+ * TypeScript printer to crash.
26
+ */
27
+ export function validateNodes(...nodes: ts.Node[]): void {
28
+ for (const node of nodes) {
29
+ if (!node) {
30
+ throw new Error('Attempted to print undefined or null TypeScript node')
31
+ }
32
+ if (node.kind === ts.SyntaxKind.Unknown) {
33
+ throw new Error(
34
+ 'Invalid TypeScript AST node detected with SyntaxKind.Unknown. ' +
35
+ 'This typically indicates a schema pattern that could not be properly converted to TypeScript. ' +
36
+ `Node: ${JSON.stringify(node, null, 2)}`,
37
+ )
38
+ }
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.
44
+ */
45
+ export function print(...elements: Array<ts.Node>): string {
46
+ const sourceFile = ts.createSourceFile('print.tsx', '', ts.ScriptTarget.ES2022, true, ts.ScriptKind.TSX)
47
+
48
+ const printer = ts.createPrinter({
49
+ omitTrailingSemicolon: true,
50
+ newLine: ts.NewLineKind.LineFeed,
51
+ removeComments: false,
52
+ noEmitHelpers: true,
53
+ })
54
+
55
+ const output = printer.printList(ts.ListFormat.MultiLine, factory.createNodeArray(elements.filter(Boolean)), sourceFile)
56
+
57
+ return output.replace(/\r\n/g, '\n')
58
+ }
59
+
60
+ /**
61
+ * Like `print` but validates nodes first to surface issues early.
62
+ */
63
+ export function safePrint(...elements: Array<ts.Node>): string {
64
+ validateNodes(...elements)
65
+ return print(...elements)
66
+ }
67
+
68
+ export function createImport({
69
+ name,
70
+ path,
71
+ root,
72
+ isTypeOnly = false,
73
+ isNameSpace = false,
74
+ }: {
75
+ name: string | Array<string | { propertyName: string; name?: string }>
76
+ path: string
77
+ root?: string
78
+ /** @default false */
79
+ isTypeOnly?: boolean
80
+ /** @default false */
81
+ isNameSpace?: boolean
82
+ }): ts.ImportDeclaration {
83
+ const resolvePath = root ? getRelativePath(root, path) : path
84
+
85
+ if (!Array.isArray(name)) {
86
+ if (isNameSpace) {
87
+ return factory.createImportDeclaration(
88
+ undefined,
89
+ factory.createImportClause(isTypeOnly, undefined, factory.createNamespaceImport(factory.createIdentifier(name))),
90
+ factory.createStringLiteral(resolvePath),
91
+ undefined,
92
+ )
93
+ }
94
+
95
+ return factory.createImportDeclaration(
96
+ undefined,
97
+ factory.createImportClause(isTypeOnly, factory.createIdentifier(name), undefined),
98
+ factory.createStringLiteral(resolvePath),
99
+ undefined,
100
+ )
101
+ }
102
+
103
+ const specifiers = name.map((item) => {
104
+ if (typeof item === 'object') {
105
+ const { propertyName, name: alias } = item
106
+ return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : undefined, factory.createIdentifier(alias ?? propertyName))
107
+ }
108
+ return factory.createImportSpecifier(false, undefined, factory.createIdentifier(item))
109
+ })
110
+
111
+ return factory.createImportDeclaration(
112
+ undefined,
113
+ factory.createImportClause(isTypeOnly, undefined, factory.createNamedImports(specifiers)),
114
+ factory.createStringLiteral(resolvePath),
115
+ undefined,
116
+ )
117
+ }
118
+
119
+ export function createExport({
120
+ path,
121
+ asAlias,
122
+ isTypeOnly = false,
123
+ name,
124
+ }: {
125
+ path: string
126
+ /** @default false */
127
+ asAlias?: boolean
128
+ /** @default false */
129
+ isTypeOnly?: boolean
130
+ name?: string | Array<ts.Identifier | string>
131
+ }): ts.ExportDeclaration {
132
+ if (name && !Array.isArray(name) && !asAlias) {
133
+ console.warn(`When using name as string, asAlias should be true: ${name}`)
134
+ }
135
+
136
+ if (!Array.isArray(name)) {
137
+ const parsedName = name?.match(/^\d/) ? `_${name?.slice(1)}` : name
138
+
139
+ return factory.createExportDeclaration(
140
+ undefined,
141
+ isTypeOnly,
142
+ asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : undefined,
143
+ factory.createStringLiteral(path),
144
+ undefined,
145
+ )
146
+ }
147
+
148
+ return factory.createExportDeclaration(
149
+ undefined,
150
+ isTypeOnly,
151
+ factory.createNamedExports(
152
+ name.map((propertyName) =>
153
+ factory.createExportSpecifier(false, undefined, typeof propertyName === 'string' ? factory.createIdentifier(propertyName) : propertyName),
154
+ ),
155
+ ),
156
+ factory.createStringLiteral(path),
157
+ undefined,
158
+ )
159
+ }
160
+
161
+ /**
162
+ * Parser that converts `.ts` and `.js` files to strings using the TypeScript
163
+ * compiler. Handles import/export statement generation from file metadata.
164
+ *
165
+ * @default Used automatically when no `parsers` option is set in `defineConfig`.
166
+ */
167
+ export const parserTs: Parser = defineParser({
168
+ name: 'typescript',
169
+ extNames: ['.ts', '.js'],
170
+ async parse(file, options = { extname: '.ts' }) {
171
+ const sourceParts: Array<string> = []
172
+ for (const item of file.sources) {
173
+ if (item.value) {
174
+ sourceParts.push(item.value)
175
+ }
176
+ }
177
+ const source = sourceParts.join('\n\n')
178
+
179
+ const importNodes: Array<ts.ImportDeclaration> = []
180
+ for (const item of (file as KubbFile.ResolvedFile).imports) {
181
+ const importPath = item.root ? getRelativePath(item.root, item.path) : item.path
182
+ const hasExtname = !!/\.[^/.]+$/.exec(importPath)
183
+
184
+ importNodes.push(
185
+ createImport({
186
+ name: item.name as string | Array<string | { propertyName: string; name?: string }>,
187
+ path: options?.extname && hasExtname ? `${trimExtName(importPath)}${options.extname}` : item.root ? trimExtName(importPath) : importPath,
188
+ isTypeOnly: item.isTypeOnly,
189
+ isNameSpace: item.isNameSpace,
190
+ }),
191
+ )
192
+ }
193
+
194
+ const exportNodes: Array<ts.ExportDeclaration> = []
195
+ for (const item of (file as KubbFile.ResolvedFile).exports) {
196
+ const exportPath = item.path
197
+ const hasExtname = !!/\.[^/.]+$/.exec(exportPath)
198
+
199
+ exportNodes.push(
200
+ createExport({
201
+ name: item.name as string | Array<ts.Identifier | string> | undefined,
202
+ path: options?.extname && hasExtname ? `${trimExtName(item.path)}${options.extname}` : trimExtName(item.path),
203
+ isTypeOnly: item.isTypeOnly,
204
+ asAlias: item.asAlias,
205
+ }),
206
+ )
207
+ }
208
+
209
+ const parts = [file.banner, print(...importNodes, ...exportNodes), source, file.footer].filter((segment): segment is string => segment != null)
210
+ return parts.join('\n')
211
+ },
212
+ })
@@ -0,0 +1,20 @@
1
+ import type { Parser } from '@kubb/core'
2
+ import { defineParser } from '@kubb/core'
3
+ import { parserTs } from './parserTs.ts'
4
+
5
+ /**
6
+ * Parser that converts `.tsx` and `.jsx` files to strings.
7
+ * Delegates to `typescriptParser` since the TypeScript compiler natively
8
+ * supports JSX/TSX syntax via `ScriptKind.TSX`.
9
+ *
10
+ * Add this parser to the `parsers` option in `defineConfig` when generating `.tsx`/`.jsx` files.
11
+ *
12
+ * @default extname '.tsx'
13
+ */
14
+ export const parserTsx: Parser = defineParser({
15
+ name: 'tsx',
16
+ extNames: ['.tsx', '.jsx'],
17
+ async parse(file, options = { extname: '.tsx' }) {
18
+ return parserTs.parse(file, options)
19
+ },
20
+ })
package/README.md DELETED
@@ -1,52 +0,0 @@
1
- <div align="center">
2
-
3
- <!-- <img src="assets/logo.png" alt="logo" width="200" height="auto" /> -->
4
- <h1>@kubb/parser-ts</h1>
5
-
6
- <p>
7
- TypeScript parser
8
- </p>
9
- <img src="https://raw.githubusercontent.com/kubb-labs/kubb/main/assets/banner.png" alt="logo" height="auto" />
10
-
11
- [![npm version][npm-version-src]][npm-version-href]
12
- [![npm downloads][npm-downloads-src]][npm-downloads-href]
13
- [![Coverage][coverage-src]][coverage-href]
14
- [![License][license-src]][license-href]
15
-
16
- <h4>
17
- <a href="https://codesandbox.io/s/github/kubb-labs/kubb/tree/main//examples/typescript" target="_blank">View Demo</a>
18
- <span> · </span>
19
- <a href="https://kubb.dev/" target="_blank">Documentation</a>
20
- <span> · </span>
21
- <a href="https://github.com/kubb-labs/kubb/issues/" target="_blank">Report Bug</a>
22
- <span> · </span>
23
- <a href="https://github.com/kubb-labs/kubb/issues/" target="_blank">Request Feature</a>
24
- </h4>
25
- </div>
26
- ## Supporting Kubb
27
-
28
- Kubb uses an MIT-licensed open source project with its ongoing development made possible entirely by the support of Sponsors. If you would like to become a sponsor, please consider:
29
-
30
- - [Become a Sponsor on GitHub](https://github.com/sponsors/stijnvanhulle)
31
-
32
- <p align="center">
33
- <a href="https://github.com/sponsors/stijnvanhulle">
34
- <img src="https://raw.githubusercontent.com/stijnvanhulle/sponsors/main/sponsors.svg" alt="My sponsors" />
35
- </a>
36
- </p>
37
-
38
-
39
- <!-- Badges -->
40
-
41
- [npm-version-src]: https://img.shields.io/npm/v/@kubb/parser-ts?flat&colorA=18181B&colorB=f58517
42
- [npm-version-href]: https://npmjs.com/package/@kubb/parser-ts
43
- [npm-downloads-src]: https://img.shields.io/npm/dm/@kubb/parser-ts?flat&colorA=18181B&colorB=f58517
44
- [npm-downloads-href]: https://npmjs.com/package/@kubb/parser-ts
45
- [license-src]: https://img.shields.io/github/license/kubb-labs/kubb.svg?flat&colorA=18181B&colorB=f58517
46
- [license-href]: https://github.com/kubb-labs/kubb/blob/main/LICENSE
47
- [build-src]: https://img.shields.io/github/actions/workflow/status/kubb-labs/kubb/ci.yaml?style=flat&colorA=18181B&colorB=f58517
48
- [build-href]: https://www.npmjs.com/package/@kubb/parser-ts
49
- [minified-src]: https://img.shields.io/bundlephobia/min/@kubb/parser-ts?style=flat&colorA=18181B&colorB=f58517
50
- [minified-href]: https://www.npmjs.com/package/@kubb/parser-ts
51
- [coverage-src]: https://img.shields.io/codecov/c/github/kubb-labs/kubb?style=flat&colorA=18181B&colorB=f58517
52
- [coverage-href]: https://www.npmjs.com/package/@kubb/parser-ts
@@ -1,13 +0,0 @@
1
- //#region rolldown:runtime
2
- var __defProp = Object.defineProperty;
3
- var __export = (all) => {
4
- let target = {};
5
- for (var name in all) __defProp(target, name, {
6
- get: all[name],
7
- enumerable: true
8
- });
9
- return target;
10
- };
11
-
12
- //#endregion
13
- export { __export };
@@ -1,245 +0,0 @@
1
- import { __export } from "./chunk-CTAAG5j7.js";
2
- import { isNumber } from "remeda";
3
- import ts from "typescript";
4
-
5
- //#region src/factory.ts
6
- var factory_exports = /* @__PURE__ */ __export({
7
- appendJSDocToNode: () => appendJSDocToNode,
8
- createArrayDeclaration: () => createArrayDeclaration,
9
- createArrayTypeNode: () => createArrayTypeNode,
10
- createEnumDeclaration: () => createEnumDeclaration,
11
- createExportDeclaration: () => createExportDeclaration,
12
- createFalse: () => createFalse,
13
- createIdentifier: () => createIdentifier,
14
- createImportDeclaration: () => createImportDeclaration,
15
- createIndexSignature: () => createIndexSignature,
16
- createInterfaceDeclaration: () => createInterfaceDeclaration,
17
- createIntersectionDeclaration: () => createIntersectionDeclaration,
18
- createJSDoc: () => createJSDoc,
19
- createLiteralTypeNode: () => createLiteralTypeNode,
20
- createNamespaceDeclaration: () => createNamespaceDeclaration,
21
- createNull: () => createNull,
22
- createNumericLiteral: () => createNumericLiteral,
23
- createOmitDeclaration: () => createOmitDeclaration,
24
- createOptionalTypeNode: () => createOptionalTypeNode,
25
- createParameterSignature: () => createParameterSignature,
26
- createPropertySignature: () => createPropertySignature,
27
- createQuestionToken: () => createQuestionToken,
28
- createRestTypeNode: () => createRestTypeNode,
29
- createStringLiteral: () => createStringLiteral,
30
- createTrue: () => createTrue,
31
- createTupleDeclaration: () => createTupleDeclaration,
32
- createTupleTypeNode: () => createTupleTypeNode,
33
- createTypeAliasDeclaration: () => createTypeAliasDeclaration,
34
- createTypeDeclaration: () => createTypeDeclaration,
35
- createTypeLiteralNode: () => createTypeLiteralNode,
36
- createTypeReferenceNode: () => createTypeReferenceNode,
37
- createUnionDeclaration: () => createUnionDeclaration,
38
- keywordTypeNodes: () => keywordTypeNodes,
39
- modifiers: () => modifiers,
40
- syntaxKind: () => syntaxKind
41
- });
42
- const { SyntaxKind, factory } = ts;
43
- const modifiers = {
44
- async: factory.createModifier(ts.SyntaxKind.AsyncKeyword),
45
- export: factory.createModifier(ts.SyntaxKind.ExportKeyword),
46
- const: factory.createModifier(ts.SyntaxKind.ConstKeyword),
47
- static: factory.createModifier(ts.SyntaxKind.StaticKeyword)
48
- };
49
- const syntaxKind = { union: SyntaxKind.UnionType };
50
- function isValidIdentifier(str) {
51
- if (!str.length || str.trim() !== str) return false;
52
- const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
53
- return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
54
- }
55
- function propertyName(name) {
56
- if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
57
- return name;
58
- }
59
- const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
60
- function createQuestionToken(token) {
61
- if (!token) return;
62
- if (token === true) return questionToken;
63
- return token;
64
- }
65
- function createIntersectionDeclaration({ nodes, withParentheses }) {
66
- if (!nodes.length) return null;
67
- if (nodes.length === 1) return nodes[0] || null;
68
- const node = factory.createIntersectionTypeNode(nodes);
69
- if (withParentheses) return factory.createParenthesizedType(node);
70
- return node;
71
- }
72
- /**
73
- * Minimum nodes length of 2
74
- * @example `string & number`
75
- */
76
- function createTupleDeclaration({ nodes, withParentheses }) {
77
- if (!nodes.length) return null;
78
- if (nodes.length === 1) return nodes[0] || null;
79
- const node = factory.createTupleTypeNode(nodes);
80
- if (withParentheses) return factory.createParenthesizedType(node);
81
- return node;
82
- }
83
- function createArrayDeclaration({ nodes }) {
84
- if (!nodes.length) return factory.createTupleTypeNode([]);
85
- if (nodes.length === 1) return factory.createArrayTypeNode(nodes.at(0));
86
- return factory.createExpressionWithTypeArguments(factory.createIdentifier("Array"), [factory.createUnionTypeNode(nodes)]);
87
- }
88
- /**
89
- * Minimum nodes length of 2
90
- * @example `string | number`
91
- */
92
- function createUnionDeclaration({ nodes, withParentheses }) {
93
- if (!nodes.length) return keywordTypeNodes.any;
94
- if (nodes.length === 1) return nodes[0];
95
- const node = factory.createUnionTypeNode(nodes);
96
- if (withParentheses) return factory.createParenthesizedType(node);
97
- return node;
98
- }
99
- function createPropertySignature({ readOnly, modifiers: modifiers$1 = [], name, questionToken: questionToken$1, type }) {
100
- return factory.createPropertySignature([...modifiers$1, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken$1), type);
101
- }
102
- function createParameterSignature(name, { modifiers: modifiers$1, dotDotDotToken, questionToken: questionToken$1, type, initializer }) {
103
- return factory.createParameterDeclaration(modifiers$1, dotDotDotToken, name, createQuestionToken(questionToken$1), type, initializer);
104
- }
105
- function createJSDoc({ comments }) {
106
- if (!comments.length) return null;
107
- return factory.createJSDocComment(factory.createNodeArray(comments.map((comment, i) => {
108
- if (i === comments.length - 1) return factory.createJSDocText(comment);
109
- return factory.createJSDocText(`${comment}\n`);
110
- })));
111
- }
112
- /**
113
- * @link https://github.com/microsoft/TypeScript/issues/44151
114
- */
115
- function appendJSDocToNode({ node, comments }) {
116
- const filteredComments = comments.filter(Boolean);
117
- if (!filteredComments.length) return node;
118
- const text = filteredComments.reduce((acc = "", comment = "") => {
119
- return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
120
- }, "*");
121
- return ts.addSyntheticLeadingComment({ ...node }, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
122
- }
123
- function createIndexSignature(type, { modifiers: modifiers$1, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
124
- return factory.createIndexSignature(modifiers$1, [createParameterSignature(indexName, { type: indexType })], type);
125
- }
126
- function createTypeAliasDeclaration({ modifiers: modifiers$1, name, typeParameters, type }) {
127
- return factory.createTypeAliasDeclaration(modifiers$1, name, typeParameters, type);
128
- }
129
- function createInterfaceDeclaration({ modifiers: modifiers$1, name, typeParameters, members }) {
130
- return factory.createInterfaceDeclaration(modifiers$1, name, typeParameters, void 0, members);
131
- }
132
- function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
133
- if (syntax === "interface" && "members" in type) return appendJSDocToNode({
134
- node: createInterfaceDeclaration({
135
- members: type.members,
136
- modifiers: isExportable ? [modifiers.export] : [],
137
- name,
138
- typeParameters: void 0
139
- }),
140
- comments
141
- });
142
- return appendJSDocToNode({
143
- node: createTypeAliasDeclaration({
144
- type,
145
- modifiers: isExportable ? [modifiers.export] : [],
146
- name,
147
- typeParameters: void 0
148
- }),
149
- comments
150
- });
151
- }
152
- function createNamespaceDeclaration({ statements, name }) {
153
- return factory.createModuleDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(name), factory.createModuleBlock(statements), ts.NodeFlags.Namespace);
154
- }
155
- /**
156
- * In { propertyName: string; name?: string } is `name` being used to make the type more unique when multiple same names are used.
157
- * @example `import { Pet as Cat } from './Pet'`
158
- */
159
- function createImportDeclaration({ name, path, isTypeOnly = false, isNameSpace = false }) {
160
- if (!Array.isArray(name)) {
161
- let importPropertyName = factory.createIdentifier(name);
162
- let importName;
163
- if (isNameSpace) {
164
- importPropertyName = void 0;
165
- importName = factory.createNamespaceImport(factory.createIdentifier(name));
166
- }
167
- return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, importPropertyName, importName), factory.createStringLiteral(path), void 0);
168
- }
169
- return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(name.map((item) => {
170
- if (typeof item === "object") {
171
- const obj = item;
172
- if (obj.name) return factory.createImportSpecifier(false, factory.createIdentifier(obj.propertyName), factory.createIdentifier(obj.name));
173
- return factory.createImportSpecifier(false, void 0, factory.createIdentifier(obj.propertyName));
174
- }
175
- return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
176
- }))), factory.createStringLiteral(path), void 0);
177
- }
178
- function createExportDeclaration({ path, asAlias, isTypeOnly = false, name }) {
179
- if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true ${name}`);
180
- if (!Array.isArray(name)) {
181
- const parsedName = name?.match(/^\d/) ? `_${name?.slice(1)}` : name;
182
- return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path), void 0);
183
- }
184
- return factory.createExportDeclaration(void 0, isTypeOnly, factory.createNamedExports(name.map((propertyName$1) => {
185
- return factory.createExportSpecifier(false, void 0, typeof propertyName$1 === "string" ? factory.createIdentifier(propertyName$1) : propertyName$1);
186
- })), factory.createStringLiteral(path), void 0);
187
- }
188
- function createEnumDeclaration({ type = "enum", name, typeName, enums }) {
189
- if (type === "literal") return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createUnionTypeNode(enums.map(([_key, value]) => {
190
- if (isNumber(value)) return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
191
- if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
192
- if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
193
- }).filter(Boolean)))];
194
- if (type === "enum" || type === "constEnum") return [void 0, factory.createEnumDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword), type === "constEnum" ? factory.createToken(ts.SyntaxKind.ConstKeyword) : void 0].filter(Boolean), factory.createIdentifier(typeName), enums.map(([key, value]) => {
195
- let initializer = factory.createStringLiteral(value?.toString());
196
- if (Number.parseInt(value.toString(), 10) === value && isNumber(Number.parseInt(value.toString(), 10))) initializer = factory.createNumericLiteral(value);
197
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
198
- if (isNumber(Number.parseInt(key.toString(), 10))) return factory.createEnumMember(factory.createStringLiteral(`${typeName}_${key}`), initializer);
199
- if (key) return factory.createEnumMember(factory.createStringLiteral(`${key}`), initializer);
200
- }).filter(Boolean))];
201
- const identifierName = type === "asPascalConst" ? typeName : name;
202
- return [factory.createVariableStatement([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(identifierName), void 0, void 0, factory.createAsExpression(factory.createObjectLiteralExpression(enums.map(([key, value]) => {
203
- let initializer = factory.createStringLiteral(value?.toString());
204
- if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
205
- else initializer = factory.createNumericLiteral(value);
206
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
207
- if (key) return factory.createPropertyAssignment(factory.createStringLiteral(`${key}`), initializer);
208
- }).filter(Boolean), true), factory.createTypeReferenceNode(factory.createIdentifier("const"), void 0)))], ts.NodeFlags.Const)), factory.createTypeAliasDeclaration(type === "asPascalConst" ? [] : [factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0)), factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0))))];
209
- }
210
- function createOmitDeclaration({ keys, type, nonNullable }) {
211
- const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
212
- if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
213
- return factory.createLiteralTypeNode(factory.createStringLiteral(key));
214
- }))]);
215
- return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
216
- }
217
- const keywordTypeNodes = {
218
- any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
219
- unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
220
- void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
221
- number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
222
- integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
223
- object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
224
- string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
225
- boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
226
- undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
227
- null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword))
228
- };
229
- const createTypeLiteralNode = factory.createTypeLiteralNode;
230
- const createTypeReferenceNode = factory.createTypeReferenceNode;
231
- const createNumericLiteral = factory.createNumericLiteral;
232
- const createStringLiteral = factory.createStringLiteral;
233
- const createArrayTypeNode = factory.createArrayTypeNode;
234
- const createLiteralTypeNode = factory.createLiteralTypeNode;
235
- const createNull = factory.createNull;
236
- const createIdentifier = factory.createIdentifier;
237
- const createOptionalTypeNode = factory.createOptionalTypeNode;
238
- const createTupleTypeNode = factory.createTupleTypeNode;
239
- const createRestTypeNode = factory.createRestTypeNode;
240
- const createTrue = factory.createTrue;
241
- const createFalse = factory.createFalse;
242
-
243
- //#endregion
244
- export { appendJSDocToNode, createArrayDeclaration, createArrayTypeNode, createEnumDeclaration, createExportDeclaration, createFalse, createIdentifier, createImportDeclaration, createIndexSignature, createInterfaceDeclaration, createIntersectionDeclaration, createJSDoc, createLiteralTypeNode, createNamespaceDeclaration, createNull, createNumericLiteral, createOmitDeclaration, createOptionalTypeNode, createParameterSignature, createPropertySignature, createQuestionToken, createRestTypeNode, createStringLiteral, createTrue, createTupleDeclaration, createTupleTypeNode, createTypeAliasDeclaration, createTypeDeclaration, createTypeLiteralNode, createTypeReferenceNode, createUnionDeclaration, factory_exports, keywordTypeNodes, modifiers, syntaxKind };
245
- //# sourceMappingURL=factory-BB7TA5iA.js.map