@kubb/fabric-core 0.0.1 → 0.1.1
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/dist/{types-lS0JaZqX.d.cts → KubbFile-BrN7Wwp6.d.cts} +3 -3
- package/dist/{types-BY5X8xoR.d.ts → KubbFile-BzVkcu9M.d.ts} +3 -3
- package/dist/createFileParser-BD8yn0LT.cjs +14 -0
- package/dist/createFileParser-BD8yn0LT.cjs.map +1 -0
- package/dist/createFileParser-Cix3AMLd.js +8 -0
- package/dist/createFileParser-Cix3AMLd.js.map +1 -0
- package/dist/default-DCpuPmrL.js +10 -0
- package/dist/default-DCpuPmrL.js.map +1 -0
- package/dist/default-DNBu_jsL.cjs +15 -0
- package/dist/default-DNBu_jsL.cjs.map +1 -0
- package/dist/defineApp-CZYKsxTp.d.ts +95 -0
- package/dist/defineApp-c9lWJ96_.d.cts +95 -0
- package/dist/index.cjs +146 -87
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -60
- package/dist/index.d.ts +13 -60
- package/dist/index.js +136 -76
- package/dist/index.js.map +1 -1
- package/dist/parsers/default.cjs +4 -0
- package/dist/parsers/default.d.cts +8 -0
- package/dist/parsers/default.d.ts +8 -0
- package/dist/parsers/default.js +4 -0
- package/dist/parsers/tsx.cjs +4 -2
- package/dist/parsers/tsx.d.cts +3 -3
- package/dist/parsers/tsx.d.ts +3 -3
- package/dist/parsers/tsx.js +3 -1
- package/dist/parsers/typescript.cjs +6 -5
- package/dist/parsers/typescript.d.cts +3 -3
- package/dist/parsers/typescript.d.ts +3 -3
- package/dist/parsers/typescript.js +2 -1
- package/dist/tsx-BSUaIML3.cjs +16 -0
- package/dist/tsx-BSUaIML3.cjs.map +1 -0
- package/dist/tsx-DBAk9dqS.js +11 -0
- package/dist/tsx-DBAk9dqS.js.map +1 -0
- package/dist/types-CkbelZaS.d.ts +15 -0
- package/dist/types-GueHciQ3.d.cts +15 -0
- package/dist/types.cjs +12 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +3 -0
- package/dist/types.d.ts +3 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/{parser-CWB_OBtr.js → typescript-C60gWBu8.js} +4 -34
- package/dist/typescript-C60gWBu8.js.map +1 -0
- package/dist/{parser-QF8j8-pj.cjs → typescript-Z90jN87k.cjs} +5 -47
- package/dist/typescript-Z90jN87k.cjs.map +1 -0
- package/package.json +15 -1
- package/src/FileManager.ts +21 -200
- package/src/FileProcessor.ts +86 -0
- package/src/KubbFile.ts +132 -0
- package/src/createFile.ts +167 -0
- package/src/defineApp.ts +6 -6
- package/src/index.ts +4 -2
- package/src/parsers/createFileParser.ts +5 -0
- package/src/parsers/default.ts +7 -0
- package/src/parsers/tsx.ts +1 -1
- package/src/parsers/types.ts +12 -0
- package/src/parsers/typescript.ts +1 -1
- package/src/types.ts +2 -132
- package/src/utils/EventEmitter.ts +23 -0
- package/dist/parser-Bck6QDwN.d.cts +0 -15
- package/dist/parser-CRl-iUw1.d.ts +0 -15
- package/dist/parser-CWB_OBtr.js.map +0 -1
- package/dist/parser-QF8j8-pj.cjs.map +0 -1
- package/src/parsers/parser.ts +0 -56
package/src/defineApp.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type * as KubbFile from './
|
|
1
|
+
import type * as KubbFile from './KubbFile.ts'
|
|
2
2
|
import { FileManager } from './FileManager.ts'
|
|
3
3
|
import { isPromise } from 'remeda'
|
|
4
4
|
|
|
@@ -40,7 +40,7 @@ export interface App {
|
|
|
40
40
|
_component: Component
|
|
41
41
|
render(): Promise<void>
|
|
42
42
|
renderToString(): Promise<string>
|
|
43
|
-
|
|
43
|
+
files: Array<KubbFile.ResolvedFile>
|
|
44
44
|
use<Options>(plugin: Plugin<Options>, options: NoInfer<Options>): this
|
|
45
45
|
write(options?: WriteOptions): Promise<void>
|
|
46
46
|
addFile(...files: Array<KubbFile.File>): Promise<void>
|
|
@@ -63,7 +63,7 @@ export function defineApp<THostElement, TContext extends AppContext>(instance: R
|
|
|
63
63
|
context.fileManager.clear()
|
|
64
64
|
},
|
|
65
65
|
get files() {
|
|
66
|
-
return fileManager.
|
|
66
|
+
return fileManager.files
|
|
67
67
|
},
|
|
68
68
|
} as TContext
|
|
69
69
|
|
|
@@ -81,8 +81,8 @@ export function defineApp<THostElement, TContext extends AppContext>(instance: R
|
|
|
81
81
|
async renderToString() {
|
|
82
82
|
return renderToString()
|
|
83
83
|
},
|
|
84
|
-
|
|
85
|
-
return fileManager.
|
|
84
|
+
get files() {
|
|
85
|
+
return fileManager.files
|
|
86
86
|
},
|
|
87
87
|
waitUntilExit,
|
|
88
88
|
addFile: context.addFile,
|
|
@@ -92,7 +92,7 @@ export function defineApp<THostElement, TContext extends AppContext>(instance: R
|
|
|
92
92
|
dryRun: false,
|
|
93
93
|
},
|
|
94
94
|
) {
|
|
95
|
-
await fileManager.
|
|
95
|
+
await fileManager.processor.run({
|
|
96
96
|
extension: options.extension,
|
|
97
97
|
dryRun: options.dryRun,
|
|
98
98
|
})
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { createApp } from './createApp.ts'
|
|
2
|
-
export type { DefineApp, AppContext } from './defineApp.ts'
|
|
3
2
|
export { defineApp } from './defineApp.ts'
|
|
4
|
-
export
|
|
3
|
+
export { FileManager } from './FileManager.ts'
|
|
4
|
+
export { createFile } from './createFile.ts'
|
|
5
|
+
export { FileProcessor } from './FileProcessor.ts'
|
|
6
|
+
export { createFileParser } from './parsers/createFileParser.ts'
|
package/src/parsers/tsx.ts
CHANGED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type * as KubbFile from '../KubbFile.ts'
|
|
2
|
+
|
|
3
|
+
type PrintOptions = {
|
|
4
|
+
extname?: KubbFile.Extname
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export type Parser<TMeta extends object = object> = {
|
|
8
|
+
/**
|
|
9
|
+
* Convert a file to string
|
|
10
|
+
*/
|
|
11
|
+
print: (file: KubbFile.ResolvedFile<TMeta>, options: PrintOptions) => Promise<string>
|
|
12
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,132 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export type Import = {
|
|
4
|
-
/**
|
|
5
|
-
* Import name to be used
|
|
6
|
-
* @example ["useState"]
|
|
7
|
-
* @example "React"
|
|
8
|
-
*/
|
|
9
|
-
name:
|
|
10
|
-
| string
|
|
11
|
-
| Array<
|
|
12
|
-
| string
|
|
13
|
-
| {
|
|
14
|
-
propertyName: string
|
|
15
|
-
name?: string
|
|
16
|
-
}
|
|
17
|
-
>
|
|
18
|
-
/**
|
|
19
|
-
* Path for the import
|
|
20
|
-
* @example '@kubb/core'
|
|
21
|
-
*/
|
|
22
|
-
path: string
|
|
23
|
-
/**
|
|
24
|
-
* Add `type` prefix to the import, this will result in: `import type { Type } from './path'`.
|
|
25
|
-
*/
|
|
26
|
-
isTypeOnly?: boolean
|
|
27
|
-
|
|
28
|
-
isNameSpace?: boolean
|
|
29
|
-
/**
|
|
30
|
-
* When root is set it will get the path with relative getRelativePath(root, path).
|
|
31
|
-
*/
|
|
32
|
-
root?: string
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export type Source = {
|
|
36
|
-
name?: string
|
|
37
|
-
value?: string
|
|
38
|
-
isTypeOnly?: boolean
|
|
39
|
-
/**
|
|
40
|
-
* Has const or type 'export'
|
|
41
|
-
* @default false
|
|
42
|
-
*/
|
|
43
|
-
isExportable?: boolean
|
|
44
|
-
/**
|
|
45
|
-
* When set, barrel generation will add this
|
|
46
|
-
* @default false
|
|
47
|
-
*/
|
|
48
|
-
isIndexable?: boolean
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export type Export = {
|
|
52
|
-
/**
|
|
53
|
-
* Export name to be used.
|
|
54
|
-
* @example ["useState"]
|
|
55
|
-
* @example "React"
|
|
56
|
-
*/
|
|
57
|
-
name?: string | Array<string>
|
|
58
|
-
/**
|
|
59
|
-
* Path for the import.
|
|
60
|
-
* @example '@kubb/core'
|
|
61
|
-
*/
|
|
62
|
-
path: string
|
|
63
|
-
/**
|
|
64
|
-
* Add `type` prefix to the export, this will result in: `export type { Type } from './path'`.
|
|
65
|
-
*/
|
|
66
|
-
isTypeOnly?: boolean
|
|
67
|
-
/**
|
|
68
|
-
* Make it possible to override the name, this will result in: `export * as aliasName from './path'`.
|
|
69
|
-
*/
|
|
70
|
-
asAlias?: boolean
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export type Extname = '.ts' | '.js' | '.tsx' | '.json' | `.${string}`
|
|
74
|
-
|
|
75
|
-
export type Mode = 'single' | 'split'
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Name to be used to dynamicly create the baseName(based on input.path)
|
|
79
|
-
* Based on UNIX basename
|
|
80
|
-
* @link https://nodejs.org/api/path.html#pathbasenamepath-suffix
|
|
81
|
-
*/
|
|
82
|
-
export type BaseName = `${string}.${string}`
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Path will be full qualified path to a specified file
|
|
86
|
-
*/
|
|
87
|
-
export type Path = string
|
|
88
|
-
|
|
89
|
-
export type AdvancedPath<T extends BaseName = BaseName> = `${BasePath}${T}`
|
|
90
|
-
|
|
91
|
-
export type OptionalPath = Path | undefined | null
|
|
92
|
-
|
|
93
|
-
export type File<TMeta extends object = object> = {
|
|
94
|
-
/**
|
|
95
|
-
* Name to be used to create the path
|
|
96
|
-
* Based on UNIX basename, `${name}.extname`
|
|
97
|
-
* @link https://nodejs.org/api/path.html#pathbasenamepath-suffix
|
|
98
|
-
*/
|
|
99
|
-
baseName: BaseName
|
|
100
|
-
/**
|
|
101
|
-
* Path will be full qualified path to a specified file
|
|
102
|
-
*/
|
|
103
|
-
path: AdvancedPath<BaseName> | Path
|
|
104
|
-
sources: Array<Source>
|
|
105
|
-
imports?: Array<Import>
|
|
106
|
-
exports?: Array<Export>
|
|
107
|
-
/**
|
|
108
|
-
* Use extra meta, this is getting used to generate the barrel/index files.
|
|
109
|
-
*/
|
|
110
|
-
meta?: TMeta
|
|
111
|
-
banner?: string
|
|
112
|
-
footer?: string
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export type ResolvedImport = Import
|
|
116
|
-
|
|
117
|
-
export type ResolvedExport = Export
|
|
118
|
-
|
|
119
|
-
export type ResolvedFile<TMeta extends object = object> = File<TMeta> & {
|
|
120
|
-
/**
|
|
121
|
-
* @default hash
|
|
122
|
-
*/
|
|
123
|
-
id: string
|
|
124
|
-
/**
|
|
125
|
-
* Contains the first part of the baseName, generated based on baseName
|
|
126
|
-
* @link https://nodejs.org/api/path.html#pathformatpathobject
|
|
127
|
-
*/
|
|
128
|
-
name: string
|
|
129
|
-
extname: Extname
|
|
130
|
-
imports: Array<ResolvedImport>
|
|
131
|
-
exports: Array<ResolvedExport>
|
|
132
|
-
}
|
|
1
|
+
export * as KubbFile from './KubbFile.ts'
|
|
2
|
+
export type { DefineApp, AppContext, App } from './defineApp.ts'
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { EventEmitter as NodeEventEmitter } from 'node:events'
|
|
2
|
+
|
|
3
|
+
export class EventEmitter<TEvents extends Record<string, any>> {
|
|
4
|
+
constructor(maxListener = 100) {
|
|
5
|
+
this.#emitter.setMaxListeners(maxListener)
|
|
6
|
+
}
|
|
7
|
+
#emitter = new NodeEventEmitter()
|
|
8
|
+
|
|
9
|
+
emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArg: TEvents[TEventName]): void {
|
|
10
|
+
this.#emitter.emit(eventName, ...(eventArg as any))
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void {
|
|
14
|
+
this.#emitter.on(eventName, handler as any)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void {
|
|
18
|
+
this.#emitter.off(eventName, handler as any)
|
|
19
|
+
}
|
|
20
|
+
removeAll(): void {
|
|
21
|
+
this.#emitter.removeAllListeners()
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { i as ResolvedFile, t as Extname } from "./types-lS0JaZqX.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/parsers/parser.d.ts
|
|
4
|
-
type ParserModule<TMeta extends object = object> = {
|
|
5
|
-
/**
|
|
6
|
-
* Convert a file to string
|
|
7
|
-
*/
|
|
8
|
-
print: (file: ResolvedFile<TMeta>, options: PrintOptions) => Promise<string>;
|
|
9
|
-
};
|
|
10
|
-
type PrintOptions = {
|
|
11
|
-
extname?: Extname;
|
|
12
|
-
};
|
|
13
|
-
//#endregion
|
|
14
|
-
export { ParserModule as t };
|
|
15
|
-
//# sourceMappingURL=parser-Bck6QDwN.d.cts.map
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { i as ResolvedFile, t as Extname } from "./types-BY5X8xoR.js";
|
|
2
|
-
|
|
3
|
-
//#region src/parsers/parser.d.ts
|
|
4
|
-
type ParserModule<TMeta extends object = object> = {
|
|
5
|
-
/**
|
|
6
|
-
* Convert a file to string
|
|
7
|
-
*/
|
|
8
|
-
print: (file: ResolvedFile<TMeta>, options: PrintOptions) => Promise<string>;
|
|
9
|
-
};
|
|
10
|
-
type PrintOptions = {
|
|
11
|
-
extname?: Extname;
|
|
12
|
-
};
|
|
13
|
-
//#endregion
|
|
14
|
-
export { ParserModule as t };
|
|
15
|
-
//# sourceMappingURL=parser-CRl-iUw1.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parser-CWB_OBtr.js","names":["path","data","output: string","path","importPropertyName: ts.Identifier | undefined","importName: ts.NamedImportBindings | undefined","parsers: Record<KubbFile.Extname, ParserModule<any>>","extname"],"sources":["../src/fs.ts","../src/parsers/typescript.ts","../src/parsers/tsx.ts","../src/parsers/parser.ts"],"sourcesContent":["import { normalize, relative, resolve } from 'node:path'\nimport fs from 'fs-extra'\nimport { switcher } from 'js-runtime'\n\ntype Options = { sanity?: boolean }\n\nexport async function write(path: string, data: string, options: Options = {}): Promise<string | undefined> {\n if (data.trim() === '') {\n return undefined\n }\n return switcher(\n {\n node: async (path: string, data: string, { sanity }: Options) => {\n try {\n const oldContent = await fs.readFile(resolve(path), {\n encoding: 'utf-8',\n })\n if (oldContent?.toString() === data?.toString()) {\n return\n }\n } catch (_err) {\n /* empty */\n }\n\n await fs.outputFile(resolve(path), data, { encoding: 'utf-8' })\n\n if (sanity) {\n const savedData = await fs.readFile(resolve(path), {\n encoding: 'utf-8',\n })\n\n if (savedData?.toString() !== data?.toString()) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n\n return savedData\n }\n\n return data\n },\n bun: async (path: string, data: string, { sanity }: Options) => {\n try {\n await Bun.write(resolve(path), data)\n\n if (sanity) {\n const file = Bun.file(resolve(path))\n const savedData = await file.text()\n\n if (savedData?.toString() !== data?.toString()) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${path.length}]:\\n${path}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n\n return savedData\n }\n\n return data\n } catch (e) {\n console.error(e)\n }\n },\n },\n 'node',\n )(path, data.trim(), options)\n}\n\nexport async function read(path: string): Promise<string> {\n return switcher(\n {\n node: async (path: string) => {\n return fs.readFile(path, { encoding: 'utf8' })\n },\n bun: async (path: string) => {\n const file = Bun.file(path)\n\n return file.text()\n },\n },\n 'node',\n )(path)\n}\n\nexport function readSync(path: string): string {\n return switcher(\n {\n node: (path: string) => {\n return fs.readFileSync(path, { encoding: 'utf8' })\n },\n bun: () => {\n throw new Error('Bun cannot read sync')\n },\n },\n 'node',\n )(path)\n}\n\nexport async function exists(path: string): Promise<boolean> {\n return switcher(\n {\n node: async (path: string) => {\n return fs.pathExists(path)\n },\n bun: async (path: string) => {\n const file = Bun.file(path)\n\n return file.exists()\n },\n },\n 'node',\n )(path)\n}\n\nexport function existsSync(path: string): boolean {\n return switcher(\n {\n node: (path: string) => {\n return fs.pathExistsSync(path)\n },\n bun: () => {\n throw new Error('Bun cannot read sync')\n },\n },\n 'node',\n )(path)\n}\n\nexport async function clean(path: string): Promise<void> {\n return fs.remove(path)\n}\n\nexport async function unlink(path: string): Promise<void> {\n return fs.unlink(path)\n}\n\nfunction slash(path: string, platform: 'windows' | 'mac' | 'linux' = 'linux') {\n const isWindowsPath = /^\\\\\\\\\\?\\\\/.test(path)\n const normalizedPath = normalize(path)\n\n if (['linux', 'mac'].includes(platform) && !isWindowsPath) {\n // linux and mac\n return normalizedPath.replaceAll(/\\\\/g, '/').replace('../', '')\n }\n\n // windows\n return normalizedPath.replaceAll(/\\\\/g, '/').replace('../', '')\n}\n\nexport function trimExtName(text: string): string {\n return text.replace(/\\.[^/.]+$/, '')\n}\n\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null, platform: 'windows' | 'mac' | 'linux' = 'linux'): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = relative(rootDir, filePath)\n\n // On Windows, paths are separated with a \"\\\"\n // However, web browsers use \"/\" no matter the platform\n const slashedPath = slash(relativePath, platform)\n\n if (slashedPath.startsWith('../')) {\n return slashedPath\n }\n\n return `./${slashedPath}`\n}\n","import ts from 'typescript'\nimport { getRelativePath, trimExtName } from '../fs.ts'\nimport path from 'node:path'\nimport { createFileParser } from './parser.ts'\n\nconst { factory } = ts\n\ntype PrintOptions = {\n source?: string\n baseName?: string\n scriptKind?: ts.ScriptKind\n}\n\n/**\n * Escaped new lines in code with block comments so they can be restored by {@link restoreNewLines}\n */\nconst escapeNewLines = (code: string) => code.replace(/\\n\\n/g, '\\n/* :newline: */')\n\n/**\n * Reverses {@link escapeNewLines} and restores new lines\n */\nconst restoreNewLines = (code: string) => code.replace(/\\/\\* :newline: \\*\\//g, '\\n')\n\n/**\n * Convert AST TypeScript/TSX nodes to a string based on the TypeScript printer.\n * Ensures consistent output across environments.\n * Also works as a formatter when `source` is provided without `elements`.\n */\nexport function print(elements: Array<ts.Node> = [], { source = '', baseName = 'print.tsx', scriptKind = ts.ScriptKind.TSX }: PrintOptions = {}): string {\n const sourceFile = ts.createSourceFile(baseName, escapeNewLines(source), ts.ScriptTarget.ES2022, true, scriptKind)\n\n const printer = ts.createPrinter({\n omitTrailingSemicolon: true,\n newLine: ts.NewLineKind.LineFeed,\n removeComments: false,\n noEmitHelpers: true,\n })\n\n let output: string\n\n if (elements.length > 0) {\n // Print only provided nodes\n const nodes = elements.filter(Boolean).sort((a, b) => (a.pos ?? 0) - (b.pos ?? 0))\n output = printer.printList(ts.ListFormat.MultiLine, factory.createNodeArray(nodes), sourceFile)\n } else {\n // Format the whole file\n output = printer.printFile(sourceFile)\n }\n\n return restoreNewLines(output).replace(/\\r\\n/g, '\\n')\n}\n\nexport function createImport({\n name,\n path,\n root,\n isTypeOnly = false,\n isNameSpace = false,\n}: {\n name: string | Array<string | { propertyName: string; name?: string }>\n path: string\n root?: string\n isTypeOnly?: boolean\n isNameSpace?: boolean\n}) {\n const resolvePath = root ? getRelativePath(root, path) : path\n\n if (!Array.isArray(name)) {\n let importPropertyName: ts.Identifier | undefined = factory.createIdentifier(name)\n let importName: ts.NamedImportBindings | undefined\n\n if (isNameSpace) {\n importPropertyName = undefined\n importName = factory.createNamespaceImport(factory.createIdentifier(name))\n }\n\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(isTypeOnly, importPropertyName, importName),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n }\n\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(\n isTypeOnly,\n undefined,\n factory.createNamedImports(\n name.map((item) => {\n if (typeof item === 'object') {\n const obj = item as { propertyName: string; name?: string }\n if (obj.name) {\n return factory.createImportSpecifier(false, factory.createIdentifier(obj.propertyName), factory.createIdentifier(obj.name))\n }\n\n return factory.createImportSpecifier(false, undefined, factory.createIdentifier(obj.propertyName))\n }\n\n return factory.createImportSpecifier(false, undefined, factory.createIdentifier(item))\n }),\n ),\n ),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n}\n\nexport function createExport({\n path,\n asAlias,\n isTypeOnly = false,\n name,\n}: {\n path: string\n asAlias?: boolean\n isTypeOnly?: boolean\n name?: string | Array<ts.Identifier | string>\n}) {\n if (name && !Array.isArray(name) && !asAlias) {\n console.warn(`When using name as string, asAlias should be true ${name}`)\n }\n\n if (!Array.isArray(name)) {\n const parsedName = name?.match(/^\\d/) ? `_${name?.slice(1)}` : name\n\n return factory.createExportDeclaration(\n undefined,\n isTypeOnly,\n asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : undefined,\n factory.createStringLiteral(path),\n undefined,\n )\n }\n\n return factory.createExportDeclaration(\n undefined,\n isTypeOnly,\n factory.createNamedExports(\n name.map((propertyName) => {\n return factory.createExportSpecifier(false, undefined, typeof propertyName === 'string' ? factory.createIdentifier(propertyName) : propertyName)\n }),\n ),\n factory.createStringLiteral(path),\n undefined,\n )\n}\n\nexport const typeScriptParser = createFileParser({\n async print(file, options = { extname: '.ts' }) {\n const source = file.sources.map((item) => item.value).join('\\n\\n')\n\n const importNodes = file.imports\n .map((item) => {\n const importPath = item.root ? getRelativePath(item.root, item.path) : item.path\n const hasExtname = !!path.extname(importPath)\n\n return createImport({\n name: item.name,\n path: options.extname && hasExtname ? `${trimExtName(importPath)}${options.extname}` : item.root ? trimExtName(importPath) : importPath,\n isTypeOnly: item.isTypeOnly,\n })\n })\n .filter(Boolean)\n\n const exportNodes = file.exports\n .map((item) => {\n const exportPath = item.path\n\n const hasExtname = !!path.extname(exportPath)\n\n return createExport({\n name: item.name,\n path: options.extname && hasExtname ? `${trimExtName(item.path)}${options.extname}` : trimExtName(item.path),\n isTypeOnly: item.isTypeOnly,\n asAlias: item.asAlias,\n })\n })\n .filter(Boolean)\n\n return [file.banner, print([...importNodes, ...exportNodes]), source, file.footer].join('\\n')\n },\n})\n","import { typeScriptParser } from './typescript.ts'\nimport { createFileParser } from './parser.ts'\n\nexport const tsxParser = createFileParser({\n async print(file, options = { extname: '.tsx' }) {\n return typeScriptParser.print(file, options)\n },\n})\n","import type * as KubbFile from '../types.ts'\nimport { typeScriptParser } from './typescript.ts'\nimport { tsxParser } from './tsx.ts'\n\nexport type ParserModule<TMeta extends object = object> = {\n /**\n * Convert a file to string\n */\n print: (file: KubbFile.ResolvedFile<TMeta>, options: PrintOptions) => Promise<string>\n}\n\nexport function createFileParser<TMeta extends object = object>(parser: ParserModule<TMeta>): ParserModule<TMeta> {\n return parser\n}\n\ntype PrintOptions = {\n extname?: KubbFile.Extname\n}\n\nconst defaultParser = createFileParser({\n async print(file) {\n return file.sources.map((item) => item.value).join('\\n\\n')\n },\n})\n\nconst parsers: Record<KubbFile.Extname, ParserModule<any>> = {\n '.ts': typeScriptParser,\n '.js': typeScriptParser,\n '.jsx': tsxParser,\n '.tsx': tsxParser,\n '.json': defaultParser,\n}\n\ntype GetSourceOptions = {\n extname?: KubbFile.Extname\n}\n\nexport async function parseFile(file: KubbFile.ResolvedFile, { extname }: GetSourceOptions = {}): Promise<string> {\n async function getFileParser<TMeta extends object = object>(extname: KubbFile.Extname | undefined): Promise<ParserModule<TMeta>> {\n if (!extname) {\n return defaultParser\n }\n\n const parser = parsers[extname]\n\n if (!parser) {\n console.warn(`[parser] No parser found for ${extname}, default parser will be used`)\n }\n\n return parser || defaultParser\n }\n\n const parser = await getFileParser(file.extname)\n\n return parser.print(file, { extname })\n}\n"],"mappings":";;;;;;AAMA,eAAsB,MAAM,QAAc,MAAc,UAAmB,EAAE,EAA+B;AAC1G,KAAI,KAAK,MAAM,KAAK,GAClB;AAEF,QAAO,SACL;EACE,MAAM,OAAO,QAAc,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AE;AAC/C,QAAO,iBAAiB,MAAM,MAAM,QAAQ;GAE/C,CAAC;;;;ACIF,SAAgB,iBAAgD,QAAkD;AAChH,QAAO;;AAOT,MAAM,gBAAgB,iBAAiB,EACrC,MAAM,MAAM,MAAM;AAChB,QAAO,KAAK,QAAQ,KAAK,SAAS,KAAK,MAAM,CAAC,KAAK,OAAO;GAE7D,CAAC;AAEF,MAAMG,UAAuD;CAC3D,OAAO;CACP,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACV;AAMD,eAAsB,UAAU,MAA6B,EAAE,YAA8B,EAAE,EAAmB;CAChH,eAAe,cAA6C,WAAqE;AAC/H,MAAI,CAACC,UACH,QAAO;EAGT,MAAM,SAAS,QAAQA;AAEvB,MAAI,CAAC,OACH,SAAQ,KAAK,gCAAgCA,UAAQ,+BAA+B;AAGtF,SAAO,UAAU;;AAKnB,SAFe,MAAM,cAAc,KAAK,QAAQ,EAElC,MAAM,MAAM,EAAE,SAAS,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parser-QF8j8-pj.cjs","names":["fs","path","data","ts","output: string","path","importPropertyName: ts.Identifier | undefined","importName: ts.NamedImportBindings | undefined","parsers: Record<KubbFile.Extname, ParserModule<any>>","extname"],"sources":["../src/fs.ts","../src/parsers/typescript.ts","../src/parsers/tsx.ts","../src/parsers/parser.ts"],"sourcesContent":["import { normalize, relative, resolve } from 'node:path'\nimport fs from 'fs-extra'\nimport { switcher } from 'js-runtime'\n\ntype Options = { sanity?: boolean }\n\nexport async function write(path: string, data: string, options: Options = {}): Promise<string | undefined> {\n if (data.trim() === '') {\n return undefined\n }\n return switcher(\n {\n node: async (path: string, data: string, { sanity }: Options) => {\n try {\n const oldContent = await fs.readFile(resolve(path), {\n encoding: 'utf-8',\n })\n if (oldContent?.toString() === data?.toString()) {\n return\n }\n } catch (_err) {\n /* empty */\n }\n\n await fs.outputFile(resolve(path), data, { encoding: 'utf-8' })\n\n if (sanity) {\n const savedData = await fs.readFile(resolve(path), {\n encoding: 'utf-8',\n })\n\n if (savedData?.toString() !== data?.toString()) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n\n return savedData\n }\n\n return data\n },\n bun: async (path: string, data: string, { sanity }: Options) => {\n try {\n await Bun.write(resolve(path), data)\n\n if (sanity) {\n const file = Bun.file(resolve(path))\n const savedData = await file.text()\n\n if (savedData?.toString() !== data?.toString()) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${path.length}]:\\n${path}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n\n return savedData\n }\n\n return data\n } catch (e) {\n console.error(e)\n }\n },\n },\n 'node',\n )(path, data.trim(), options)\n}\n\nexport async function read(path: string): Promise<string> {\n return switcher(\n {\n node: async (path: string) => {\n return fs.readFile(path, { encoding: 'utf8' })\n },\n bun: async (path: string) => {\n const file = Bun.file(path)\n\n return file.text()\n },\n },\n 'node',\n )(path)\n}\n\nexport function readSync(path: string): string {\n return switcher(\n {\n node: (path: string) => {\n return fs.readFileSync(path, { encoding: 'utf8' })\n },\n bun: () => {\n throw new Error('Bun cannot read sync')\n },\n },\n 'node',\n )(path)\n}\n\nexport async function exists(path: string): Promise<boolean> {\n return switcher(\n {\n node: async (path: string) => {\n return fs.pathExists(path)\n },\n bun: async (path: string) => {\n const file = Bun.file(path)\n\n return file.exists()\n },\n },\n 'node',\n )(path)\n}\n\nexport function existsSync(path: string): boolean {\n return switcher(\n {\n node: (path: string) => {\n return fs.pathExistsSync(path)\n },\n bun: () => {\n throw new Error('Bun cannot read sync')\n },\n },\n 'node',\n )(path)\n}\n\nexport async function clean(path: string): Promise<void> {\n return fs.remove(path)\n}\n\nexport async function unlink(path: string): Promise<void> {\n return fs.unlink(path)\n}\n\nfunction slash(path: string, platform: 'windows' | 'mac' | 'linux' = 'linux') {\n const isWindowsPath = /^\\\\\\\\\\?\\\\/.test(path)\n const normalizedPath = normalize(path)\n\n if (['linux', 'mac'].includes(platform) && !isWindowsPath) {\n // linux and mac\n return normalizedPath.replaceAll(/\\\\/g, '/').replace('../', '')\n }\n\n // windows\n return normalizedPath.replaceAll(/\\\\/g, '/').replace('../', '')\n}\n\nexport function trimExtName(text: string): string {\n return text.replace(/\\.[^/.]+$/, '')\n}\n\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null, platform: 'windows' | 'mac' | 'linux' = 'linux'): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = relative(rootDir, filePath)\n\n // On Windows, paths are separated with a \"\\\"\n // However, web browsers use \"/\" no matter the platform\n const slashedPath = slash(relativePath, platform)\n\n if (slashedPath.startsWith('../')) {\n return slashedPath\n }\n\n return `./${slashedPath}`\n}\n","import ts from 'typescript'\nimport { getRelativePath, trimExtName } from '../fs.ts'\nimport path from 'node:path'\nimport { createFileParser } from './parser.ts'\n\nconst { factory } = ts\n\ntype PrintOptions = {\n source?: string\n baseName?: string\n scriptKind?: ts.ScriptKind\n}\n\n/**\n * Escaped new lines in code with block comments so they can be restored by {@link restoreNewLines}\n */\nconst escapeNewLines = (code: string) => code.replace(/\\n\\n/g, '\\n/* :newline: */')\n\n/**\n * Reverses {@link escapeNewLines} and restores new lines\n */\nconst restoreNewLines = (code: string) => code.replace(/\\/\\* :newline: \\*\\//g, '\\n')\n\n/**\n * Convert AST TypeScript/TSX nodes to a string based on the TypeScript printer.\n * Ensures consistent output across environments.\n * Also works as a formatter when `source` is provided without `elements`.\n */\nexport function print(elements: Array<ts.Node> = [], { source = '', baseName = 'print.tsx', scriptKind = ts.ScriptKind.TSX }: PrintOptions = {}): string {\n const sourceFile = ts.createSourceFile(baseName, escapeNewLines(source), ts.ScriptTarget.ES2022, true, scriptKind)\n\n const printer = ts.createPrinter({\n omitTrailingSemicolon: true,\n newLine: ts.NewLineKind.LineFeed,\n removeComments: false,\n noEmitHelpers: true,\n })\n\n let output: string\n\n if (elements.length > 0) {\n // Print only provided nodes\n const nodes = elements.filter(Boolean).sort((a, b) => (a.pos ?? 0) - (b.pos ?? 0))\n output = printer.printList(ts.ListFormat.MultiLine, factory.createNodeArray(nodes), sourceFile)\n } else {\n // Format the whole file\n output = printer.printFile(sourceFile)\n }\n\n return restoreNewLines(output).replace(/\\r\\n/g, '\\n')\n}\n\nexport function createImport({\n name,\n path,\n root,\n isTypeOnly = false,\n isNameSpace = false,\n}: {\n name: string | Array<string | { propertyName: string; name?: string }>\n path: string\n root?: string\n isTypeOnly?: boolean\n isNameSpace?: boolean\n}) {\n const resolvePath = root ? getRelativePath(root, path) : path\n\n if (!Array.isArray(name)) {\n let importPropertyName: ts.Identifier | undefined = factory.createIdentifier(name)\n let importName: ts.NamedImportBindings | undefined\n\n if (isNameSpace) {\n importPropertyName = undefined\n importName = factory.createNamespaceImport(factory.createIdentifier(name))\n }\n\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(isTypeOnly, importPropertyName, importName),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n }\n\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(\n isTypeOnly,\n undefined,\n factory.createNamedImports(\n name.map((item) => {\n if (typeof item === 'object') {\n const obj = item as { propertyName: string; name?: string }\n if (obj.name) {\n return factory.createImportSpecifier(false, factory.createIdentifier(obj.propertyName), factory.createIdentifier(obj.name))\n }\n\n return factory.createImportSpecifier(false, undefined, factory.createIdentifier(obj.propertyName))\n }\n\n return factory.createImportSpecifier(false, undefined, factory.createIdentifier(item))\n }),\n ),\n ),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n}\n\nexport function createExport({\n path,\n asAlias,\n isTypeOnly = false,\n name,\n}: {\n path: string\n asAlias?: boolean\n isTypeOnly?: boolean\n name?: string | Array<ts.Identifier | string>\n}) {\n if (name && !Array.isArray(name) && !asAlias) {\n console.warn(`When using name as string, asAlias should be true ${name}`)\n }\n\n if (!Array.isArray(name)) {\n const parsedName = name?.match(/^\\d/) ? `_${name?.slice(1)}` : name\n\n return factory.createExportDeclaration(\n undefined,\n isTypeOnly,\n asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : undefined,\n factory.createStringLiteral(path),\n undefined,\n )\n }\n\n return factory.createExportDeclaration(\n undefined,\n isTypeOnly,\n factory.createNamedExports(\n name.map((propertyName) => {\n return factory.createExportSpecifier(false, undefined, typeof propertyName === 'string' ? factory.createIdentifier(propertyName) : propertyName)\n }),\n ),\n factory.createStringLiteral(path),\n undefined,\n )\n}\n\nexport const typeScriptParser = createFileParser({\n async print(file, options = { extname: '.ts' }) {\n const source = file.sources.map((item) => item.value).join('\\n\\n')\n\n const importNodes = file.imports\n .map((item) => {\n const importPath = item.root ? getRelativePath(item.root, item.path) : item.path\n const hasExtname = !!path.extname(importPath)\n\n return createImport({\n name: item.name,\n path: options.extname && hasExtname ? `${trimExtName(importPath)}${options.extname}` : item.root ? trimExtName(importPath) : importPath,\n isTypeOnly: item.isTypeOnly,\n })\n })\n .filter(Boolean)\n\n const exportNodes = file.exports\n .map((item) => {\n const exportPath = item.path\n\n const hasExtname = !!path.extname(exportPath)\n\n return createExport({\n name: item.name,\n path: options.extname && hasExtname ? `${trimExtName(item.path)}${options.extname}` : trimExtName(item.path),\n isTypeOnly: item.isTypeOnly,\n asAlias: item.asAlias,\n })\n })\n .filter(Boolean)\n\n return [file.banner, print([...importNodes, ...exportNodes]), source, file.footer].join('\\n')\n },\n})\n","import { typeScriptParser } from './typescript.ts'\nimport { createFileParser } from './parser.ts'\n\nexport const tsxParser = createFileParser({\n async print(file, options = { extname: '.tsx' }) {\n return typeScriptParser.print(file, options)\n },\n})\n","import type * as KubbFile from '../types.ts'\nimport { typeScriptParser } from './typescript.ts'\nimport { tsxParser } from './tsx.ts'\n\nexport type ParserModule<TMeta extends object = object> = {\n /**\n * Convert a file to string\n */\n print: (file: KubbFile.ResolvedFile<TMeta>, options: PrintOptions) => Promise<string>\n}\n\nexport function createFileParser<TMeta extends object = object>(parser: ParserModule<TMeta>): ParserModule<TMeta> {\n return parser\n}\n\ntype PrintOptions = {\n extname?: KubbFile.Extname\n}\n\nconst defaultParser = createFileParser({\n async print(file) {\n return file.sources.map((item) => item.value).join('\\n\\n')\n },\n})\n\nconst parsers: Record<KubbFile.Extname, ParserModule<any>> = {\n '.ts': typeScriptParser,\n '.js': typeScriptParser,\n '.jsx': tsxParser,\n '.tsx': tsxParser,\n '.json': defaultParser,\n}\n\ntype GetSourceOptions = {\n extname?: KubbFile.Extname\n}\n\nexport async function parseFile(file: KubbFile.ResolvedFile, { extname }: GetSourceOptions = {}): Promise<string> {\n async function getFileParser<TMeta extends object = object>(extname: KubbFile.Extname | undefined): Promise<ParserModule<TMeta>> {\n if (!extname) {\n return defaultParser\n }\n\n const parser = parsers[extname]\n\n if (!parser) {\n console.warn(`[parser] No parser found for ${extname}, default parser will be used`)\n }\n\n return parser || defaultParser\n }\n\n const parser = await getFileParser(file.extname)\n\n return parser.print(file, { extname })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,eAAsB,MAAM,QAAc,MAAc,UAAmB,EAAE,EAA+B;AAC1G,KAAI,KAAK,MAAM,KAAK,GAClB;AAEF,iCACE;EACE,MAAM,OAAO,QAAc,QAAc,EAAE,aAAsB;AAC/D,OAAI;IACF,MAAM,aAAa,MAAMA,iBAAG,gCAAiBC,OAAK,EAAE,EAClD,UAAU,SACX,CAAC;AACF,iEAAI,WAAY,UAAU,uDAAKC,OAAM,UAAU,EAC7C;YAEK,MAAM;AAIf,SAAMF,iBAAG,kCAAmBC,OAAK,EAAEC,QAAM,EAAE,UAAU,SAAS,CAAC;AAE/D,OAAI,QAAQ;IACV,MAAM,YAAY,MAAMF,iBAAG,gCAAiBC,OAAK,EAAE,EACjD,UAAU,SACX,CAAC;AAEF,+DAAI,UAAW,UAAU,uDAAKC,OAAM,UAAU,EAC5C,OAAM,I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AI,CAACC,UACH,QAAO;EAGT,MAAM,SAAS,QAAQA;AAEvB,MAAI,CAAC,OACH,SAAQ,KAAK,gCAAgCA,UAAQ,+BAA+B;AAGtF,SAAO,UAAU;;AAKnB,SAFe,MAAM,cAAc,KAAK,QAAQ,EAElC,MAAM,MAAM,EAAE,SAAS,CAAC"}
|
package/src/parsers/parser.ts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import type * as KubbFile from '../types.ts'
|
|
2
|
-
import { typeScriptParser } from './typescript.ts'
|
|
3
|
-
import { tsxParser } from './tsx.ts'
|
|
4
|
-
|
|
5
|
-
export type ParserModule<TMeta extends object = object> = {
|
|
6
|
-
/**
|
|
7
|
-
* Convert a file to string
|
|
8
|
-
*/
|
|
9
|
-
print: (file: KubbFile.ResolvedFile<TMeta>, options: PrintOptions) => Promise<string>
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function createFileParser<TMeta extends object = object>(parser: ParserModule<TMeta>): ParserModule<TMeta> {
|
|
13
|
-
return parser
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
type PrintOptions = {
|
|
17
|
-
extname?: KubbFile.Extname
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const defaultParser = createFileParser({
|
|
21
|
-
async print(file) {
|
|
22
|
-
return file.sources.map((item) => item.value).join('\n\n')
|
|
23
|
-
},
|
|
24
|
-
})
|
|
25
|
-
|
|
26
|
-
const parsers: Record<KubbFile.Extname, ParserModule<any>> = {
|
|
27
|
-
'.ts': typeScriptParser,
|
|
28
|
-
'.js': typeScriptParser,
|
|
29
|
-
'.jsx': tsxParser,
|
|
30
|
-
'.tsx': tsxParser,
|
|
31
|
-
'.json': defaultParser,
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
type GetSourceOptions = {
|
|
35
|
-
extname?: KubbFile.Extname
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export async function parseFile(file: KubbFile.ResolvedFile, { extname }: GetSourceOptions = {}): Promise<string> {
|
|
39
|
-
async function getFileParser<TMeta extends object = object>(extname: KubbFile.Extname | undefined): Promise<ParserModule<TMeta>> {
|
|
40
|
-
if (!extname) {
|
|
41
|
-
return defaultParser
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const parser = parsers[extname]
|
|
45
|
-
|
|
46
|
-
if (!parser) {
|
|
47
|
-
console.warn(`[parser] No parser found for ${extname}, default parser will be used`)
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
return parser || defaultParser
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const parser = await getFileParser(file.extname)
|
|
54
|
-
|
|
55
|
-
return parser.print(file, { extname })
|
|
56
|
-
}
|