@kubb/fabric-core 0.1.0 → 0.1.2
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/App-DZuROf6f.d.ts +292 -0
- package/dist/App-zyf9KG3p.d.cts +292 -0
- package/dist/chunk-CUT6urMc.cjs +30 -0
- package/dist/defineApp-D3B0bU-z.d.cts +14 -0
- package/dist/defineApp-DJVMk9lc.d.ts +14 -0
- package/dist/index.cjs +217 -73
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -5
- package/dist/index.d.ts +10 -5
- package/dist/index.js +204 -63
- package/dist/index.js.map +1 -1
- package/dist/parsers/typescript.cjs +5 -5
- package/dist/parsers/typescript.d.cts +3 -51
- package/dist/parsers/typescript.d.ts +3 -51
- package/dist/parsers/typescript.js +2 -2
- package/dist/parsers.cjs +7 -0
- package/dist/parsers.d.cts +14 -0
- package/dist/parsers.d.ts +14 -0
- package/dist/parsers.js +4 -0
- package/dist/plugins.cjs +76 -0
- package/dist/plugins.cjs.map +1 -0
- package/dist/plugins.d.cts +28 -0
- package/dist/plugins.d.ts +28 -0
- package/dist/plugins.js +71 -0
- package/dist/plugins.js.map +1 -0
- package/dist/tsxParser-C741ZKCN.js +26 -0
- package/dist/tsxParser-C741ZKCN.js.map +1 -0
- package/dist/tsxParser-HDf_3TMc.cjs +37 -0
- package/dist/tsxParser-HDf_3TMc.cjs.map +1 -0
- package/dist/types.d.cts +2 -2
- package/dist/types.d.ts +2 -2
- package/dist/{parser-CWB_OBtr.js → typescriptParser-BBGeFKlP.js} +51 -98
- package/dist/typescriptParser-BBGeFKlP.js.map +1 -0
- package/dist/typescriptParser-BBbbmG5W.cjs +171 -0
- package/dist/typescriptParser-BBbbmG5W.cjs.map +1 -0
- package/dist/typescriptParser-C-sBy1iR.d.cts +50 -0
- package/dist/typescriptParser-CtMmz0UV.d.ts +50 -0
- package/package.json +13 -6
- package/src/App.ts +91 -0
- package/src/FileManager.ts +14 -193
- package/src/FileProcessor.ts +89 -0
- package/src/createFile.ts +167 -0
- package/src/defineApp.ts +49 -74
- package/src/index.ts +3 -1
- package/src/parsers/createParser.ts +8 -0
- package/src/parsers/defaultParser.ts +10 -0
- package/src/parsers/index.ts +5 -0
- package/src/parsers/tsxParser.ts +11 -0
- package/src/parsers/types.ts +22 -0
- package/src/parsers/{typescript.ts → typescriptParser.ts} +8 -4
- package/src/plugins/createPlugin.ts +10 -0
- package/src/plugins/fsPlugin.ts +112 -0
- package/src/plugins/index.ts +3 -0
- package/src/plugins/types.ts +15 -0
- package/src/types.ts +4 -1
- package/src/utils/AsyncEventEmitter.ts +37 -0
- package/src/utils/EventEmitter.ts +23 -0
- package/src/utils/getRelativePath.ts +32 -0
- package/src/utils/trimExtName.ts +3 -0
- package/dist/KubbFile-BrN7Wwp6.d.cts +0 -119
- package/dist/KubbFile-BzVkcu9M.d.ts +0 -119
- package/dist/defineApp-Bg7JewJQ.d.ts +0 -62
- package/dist/defineApp-DKW3IRO8.d.cts +0 -62
- package/dist/parser-CWB_OBtr.js.map +0 -1
- package/dist/parser-D64DdV1v.d.cts +0 -21
- package/dist/parser-QF8j8-pj.cjs +0 -260
- package/dist/parser-QF8j8-pj.cjs.map +0 -1
- package/dist/parser-yYqnryUV.d.ts +0 -21
- package/dist/parsers/tsx.cjs +0 -3
- package/dist/parsers/tsx.d.cts +0 -8
- package/dist/parsers/tsx.d.ts +0 -8
- package/dist/parsers/tsx.js +0 -3
- package/src/fs.ts +0 -167
- package/src/parsers/parser.ts +0 -56
- package/src/parsers/tsx.ts +0 -8
package/dist/parser-QF8j8-pj.cjs
DELETED
|
@@ -1,260 +0,0 @@
|
|
|
1
|
-
//#region rolldown:runtime
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
-
key = keys[i];
|
|
11
|
-
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
-
get: ((k) => from[k]).bind(null, key),
|
|
13
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
-
value: mod,
|
|
20
|
-
enumerable: true
|
|
21
|
-
}) : target, mod));
|
|
22
|
-
|
|
23
|
-
//#endregion
|
|
24
|
-
let typescript = require("typescript");
|
|
25
|
-
typescript = __toESM(typescript);
|
|
26
|
-
let node_path = require("node:path");
|
|
27
|
-
node_path = __toESM(node_path);
|
|
28
|
-
let fs_extra = require("fs-extra");
|
|
29
|
-
fs_extra = __toESM(fs_extra);
|
|
30
|
-
let js_runtime = require("js-runtime");
|
|
31
|
-
js_runtime = __toESM(js_runtime);
|
|
32
|
-
|
|
33
|
-
//#region src/fs.ts
|
|
34
|
-
async function write(path$1, data, options = {}) {
|
|
35
|
-
if (data.trim() === "") return;
|
|
36
|
-
return (0, js_runtime.switcher)({
|
|
37
|
-
node: async (path$2, data$1, { sanity }) => {
|
|
38
|
-
try {
|
|
39
|
-
const oldContent = await fs_extra.default.readFile((0, node_path.resolve)(path$2), { encoding: "utf-8" });
|
|
40
|
-
if ((oldContent === null || oldContent === void 0 ? void 0 : oldContent.toString()) === (data$1 === null || data$1 === void 0 ? void 0 : data$1.toString())) return;
|
|
41
|
-
} catch (_err) {}
|
|
42
|
-
await fs_extra.default.outputFile((0, node_path.resolve)(path$2), data$1, { encoding: "utf-8" });
|
|
43
|
-
if (sanity) {
|
|
44
|
-
const savedData = await fs_extra.default.readFile((0, node_path.resolve)(path$2), { encoding: "utf-8" });
|
|
45
|
-
if ((savedData === null || savedData === void 0 ? void 0 : savedData.toString()) !== (data$1 === null || data$1 === void 0 ? void 0 : data$1.toString())) throw new Error(`Sanity check failed for ${path$2}\n\nData[${data$1.length}]:\n${data$1}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
|
|
46
|
-
return savedData;
|
|
47
|
-
}
|
|
48
|
-
return data$1;
|
|
49
|
-
},
|
|
50
|
-
bun: async (path$2, data$1, { sanity }) => {
|
|
51
|
-
try {
|
|
52
|
-
await Bun.write((0, node_path.resolve)(path$2), data$1);
|
|
53
|
-
if (sanity) {
|
|
54
|
-
const savedData = await Bun.file((0, node_path.resolve)(path$2)).text();
|
|
55
|
-
if ((savedData === null || savedData === void 0 ? void 0 : savedData.toString()) !== (data$1 === null || data$1 === void 0 ? void 0 : data$1.toString())) throw new Error(`Sanity check failed for ${path$2}\n\nData[${path$2.length}]:\n${path$2}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
|
|
56
|
-
return savedData;
|
|
57
|
-
}
|
|
58
|
-
return data$1;
|
|
59
|
-
} catch (e) {
|
|
60
|
-
console.error(e);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
}, "node")(path$1, data.trim(), options);
|
|
64
|
-
}
|
|
65
|
-
function slash(path$1, platform = "linux") {
|
|
66
|
-
const isWindowsPath = /^\\\\\?\\/.test(path$1);
|
|
67
|
-
const normalizedPath = (0, node_path.normalize)(path$1);
|
|
68
|
-
if (["linux", "mac"].includes(platform) && !isWindowsPath) return normalizedPath.replaceAll(/\\/g, "/").replace("../", "");
|
|
69
|
-
return normalizedPath.replaceAll(/\\/g, "/").replace("../", "");
|
|
70
|
-
}
|
|
71
|
-
function trimExtName(text) {
|
|
72
|
-
return text.replace(/\.[^/.]+$/, "");
|
|
73
|
-
}
|
|
74
|
-
function getRelativePath(rootDir, filePath, platform = "linux") {
|
|
75
|
-
if (!rootDir || !filePath) throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
|
|
76
|
-
const slashedPath = slash((0, node_path.relative)(rootDir, filePath), platform);
|
|
77
|
-
if (slashedPath.startsWith("../")) return slashedPath;
|
|
78
|
-
return `./${slashedPath}`;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
//#endregion
|
|
82
|
-
//#region src/parsers/typescript.ts
|
|
83
|
-
const { factory } = typescript.default;
|
|
84
|
-
/**
|
|
85
|
-
* Escaped new lines in code with block comments so they can be restored by {@link restoreNewLines}
|
|
86
|
-
*/
|
|
87
|
-
const escapeNewLines = (code) => code.replace(/\n\n/g, "\n/* :newline: */");
|
|
88
|
-
/**
|
|
89
|
-
* Reverses {@link escapeNewLines} and restores new lines
|
|
90
|
-
*/
|
|
91
|
-
const restoreNewLines = (code) => code.replace(/\/\* :newline: \*\//g, "\n");
|
|
92
|
-
/**
|
|
93
|
-
* Convert AST TypeScript/TSX nodes to a string based on the TypeScript printer.
|
|
94
|
-
* Ensures consistent output across environments.
|
|
95
|
-
* Also works as a formatter when `source` is provided without `elements`.
|
|
96
|
-
*/
|
|
97
|
-
function print(elements = [], { source = "", baseName = "print.tsx", scriptKind = typescript.default.ScriptKind.TSX } = {}) {
|
|
98
|
-
const sourceFile = typescript.default.createSourceFile(baseName, escapeNewLines(source), typescript.default.ScriptTarget.ES2022, true, scriptKind);
|
|
99
|
-
const printer = typescript.default.createPrinter({
|
|
100
|
-
omitTrailingSemicolon: true,
|
|
101
|
-
newLine: typescript.default.NewLineKind.LineFeed,
|
|
102
|
-
removeComments: false,
|
|
103
|
-
noEmitHelpers: true
|
|
104
|
-
});
|
|
105
|
-
let output;
|
|
106
|
-
if (elements.length > 0) {
|
|
107
|
-
const nodes = elements.filter(Boolean).sort((a, b) => {
|
|
108
|
-
var _a$pos, _b$pos;
|
|
109
|
-
return ((_a$pos = a.pos) !== null && _a$pos !== void 0 ? _a$pos : 0) - ((_b$pos = b.pos) !== null && _b$pos !== void 0 ? _b$pos : 0);
|
|
110
|
-
});
|
|
111
|
-
output = printer.printList(typescript.default.ListFormat.MultiLine, factory.createNodeArray(nodes), sourceFile);
|
|
112
|
-
} else output = printer.printFile(sourceFile);
|
|
113
|
-
return restoreNewLines(output).replace(/\r\n/g, "\n");
|
|
114
|
-
}
|
|
115
|
-
function createImport({ name, path: path$1, root, isTypeOnly = false, isNameSpace = false }) {
|
|
116
|
-
const resolvePath = root ? getRelativePath(root, path$1) : path$1;
|
|
117
|
-
if (!Array.isArray(name)) {
|
|
118
|
-
let importPropertyName = factory.createIdentifier(name);
|
|
119
|
-
let importName;
|
|
120
|
-
if (isNameSpace) {
|
|
121
|
-
importPropertyName = void 0;
|
|
122
|
-
importName = factory.createNamespaceImport(factory.createIdentifier(name));
|
|
123
|
-
}
|
|
124
|
-
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, importPropertyName, importName), factory.createStringLiteral(resolvePath), void 0);
|
|
125
|
-
}
|
|
126
|
-
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(name.map((item) => {
|
|
127
|
-
if (typeof item === "object") {
|
|
128
|
-
const obj = item;
|
|
129
|
-
if (obj.name) return factory.createImportSpecifier(false, factory.createIdentifier(obj.propertyName), factory.createIdentifier(obj.name));
|
|
130
|
-
return factory.createImportSpecifier(false, void 0, factory.createIdentifier(obj.propertyName));
|
|
131
|
-
}
|
|
132
|
-
return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
|
|
133
|
-
}))), factory.createStringLiteral(resolvePath), void 0);
|
|
134
|
-
}
|
|
135
|
-
function createExport({ path: path$1, asAlias, isTypeOnly = false, name }) {
|
|
136
|
-
if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true ${name}`);
|
|
137
|
-
if (!Array.isArray(name)) {
|
|
138
|
-
const parsedName = (name === null || name === void 0 ? void 0 : name.match(/^\d/)) ? `_${name === null || name === void 0 ? void 0 : name.slice(1)}` : name;
|
|
139
|
-
return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path$1), void 0);
|
|
140
|
-
}
|
|
141
|
-
return factory.createExportDeclaration(void 0, isTypeOnly, factory.createNamedExports(name.map((propertyName) => {
|
|
142
|
-
return factory.createExportSpecifier(false, void 0, typeof propertyName === "string" ? factory.createIdentifier(propertyName) : propertyName);
|
|
143
|
-
})), factory.createStringLiteral(path$1), void 0);
|
|
144
|
-
}
|
|
145
|
-
const typeScriptParser = createFileParser({ async print(file, options = { extname: ".ts" }) {
|
|
146
|
-
const source = file.sources.map((item) => item.value).join("\n\n");
|
|
147
|
-
const importNodes = file.imports.map((item) => {
|
|
148
|
-
const importPath = item.root ? getRelativePath(item.root, item.path) : item.path;
|
|
149
|
-
const hasExtname = !!node_path.default.extname(importPath);
|
|
150
|
-
return createImport({
|
|
151
|
-
name: item.name,
|
|
152
|
-
path: options.extname && hasExtname ? `${trimExtName(importPath)}${options.extname}` : item.root ? trimExtName(importPath) : importPath,
|
|
153
|
-
isTypeOnly: item.isTypeOnly
|
|
154
|
-
});
|
|
155
|
-
}).filter(Boolean);
|
|
156
|
-
const exportNodes = file.exports.map((item) => {
|
|
157
|
-
const exportPath = item.path;
|
|
158
|
-
const hasExtname = !!node_path.default.extname(exportPath);
|
|
159
|
-
return createExport({
|
|
160
|
-
name: item.name,
|
|
161
|
-
path: options.extname && hasExtname ? `${trimExtName(item.path)}${options.extname}` : trimExtName(item.path),
|
|
162
|
-
isTypeOnly: item.isTypeOnly,
|
|
163
|
-
asAlias: item.asAlias
|
|
164
|
-
});
|
|
165
|
-
}).filter(Boolean);
|
|
166
|
-
return [
|
|
167
|
-
file.banner,
|
|
168
|
-
print([...importNodes, ...exportNodes]),
|
|
169
|
-
source,
|
|
170
|
-
file.footer
|
|
171
|
-
].join("\n");
|
|
172
|
-
} });
|
|
173
|
-
|
|
174
|
-
//#endregion
|
|
175
|
-
//#region src/parsers/tsx.ts
|
|
176
|
-
const tsxParser = createFileParser({ async print(file, options = { extname: ".tsx" }) {
|
|
177
|
-
return typeScriptParser.print(file, options);
|
|
178
|
-
} });
|
|
179
|
-
|
|
180
|
-
//#endregion
|
|
181
|
-
//#region src/parsers/parser.ts
|
|
182
|
-
function createFileParser(parser) {
|
|
183
|
-
return parser;
|
|
184
|
-
}
|
|
185
|
-
const defaultParser = createFileParser({ async print(file) {
|
|
186
|
-
return file.sources.map((item) => item.value).join("\n\n");
|
|
187
|
-
} });
|
|
188
|
-
const parsers = {
|
|
189
|
-
".ts": typeScriptParser,
|
|
190
|
-
".js": typeScriptParser,
|
|
191
|
-
".jsx": tsxParser,
|
|
192
|
-
".tsx": tsxParser,
|
|
193
|
-
".json": defaultParser
|
|
194
|
-
};
|
|
195
|
-
async function parseFile(file, { extname } = {}) {
|
|
196
|
-
async function getFileParser(extname$1) {
|
|
197
|
-
if (!extname$1) return defaultParser;
|
|
198
|
-
const parser = parsers[extname$1];
|
|
199
|
-
if (!parser) console.warn(`[parser] No parser found for ${extname$1}, default parser will be used`);
|
|
200
|
-
return parser || defaultParser;
|
|
201
|
-
}
|
|
202
|
-
return (await getFileParser(file.extname)).print(file, { extname });
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
//#endregion
|
|
206
|
-
Object.defineProperty(exports, '__toESM', {
|
|
207
|
-
enumerable: true,
|
|
208
|
-
get: function () {
|
|
209
|
-
return __toESM;
|
|
210
|
-
}
|
|
211
|
-
});
|
|
212
|
-
Object.defineProperty(exports, 'createExport', {
|
|
213
|
-
enumerable: true,
|
|
214
|
-
get: function () {
|
|
215
|
-
return createExport;
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
Object.defineProperty(exports, 'createImport', {
|
|
219
|
-
enumerable: true,
|
|
220
|
-
get: function () {
|
|
221
|
-
return createImport;
|
|
222
|
-
}
|
|
223
|
-
});
|
|
224
|
-
Object.defineProperty(exports, 'parseFile', {
|
|
225
|
-
enumerable: true,
|
|
226
|
-
get: function () {
|
|
227
|
-
return parseFile;
|
|
228
|
-
}
|
|
229
|
-
});
|
|
230
|
-
Object.defineProperty(exports, 'print', {
|
|
231
|
-
enumerable: true,
|
|
232
|
-
get: function () {
|
|
233
|
-
return print;
|
|
234
|
-
}
|
|
235
|
-
});
|
|
236
|
-
Object.defineProperty(exports, 'trimExtName', {
|
|
237
|
-
enumerable: true,
|
|
238
|
-
get: function () {
|
|
239
|
-
return trimExtName;
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
Object.defineProperty(exports, 'tsxParser', {
|
|
243
|
-
enumerable: true,
|
|
244
|
-
get: function () {
|
|
245
|
-
return tsxParser;
|
|
246
|
-
}
|
|
247
|
-
});
|
|
248
|
-
Object.defineProperty(exports, 'typeScriptParser', {
|
|
249
|
-
enumerable: true,
|
|
250
|
-
get: function () {
|
|
251
|
-
return typeScriptParser;
|
|
252
|
-
}
|
|
253
|
-
});
|
|
254
|
-
Object.defineProperty(exports, 'write', {
|
|
255
|
-
enumerable: true,
|
|
256
|
-
get: function () {
|
|
257
|
-
return write;
|
|
258
|
-
}
|
|
259
|
-
});
|
|
260
|
-
//# sourceMappingURL=parser-QF8j8-pj.cjs.map
|
|
@@ -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 '../KubbFile.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,uDA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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,21 +0,0 @@
|
|
|
1
|
-
import { a as ResolvedFile, t as Extname } from "./KubbFile-BzVkcu9M.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
|
-
type GetSourceOptions = {
|
|
14
|
-
extname?: Extname;
|
|
15
|
-
};
|
|
16
|
-
declare function parseFile(file: ResolvedFile, {
|
|
17
|
-
extname
|
|
18
|
-
}?: GetSourceOptions): Promise<string>;
|
|
19
|
-
//#endregion
|
|
20
|
-
export { parseFile as n, ParserModule as t };
|
|
21
|
-
//# sourceMappingURL=parser-yYqnryUV.d.ts.map
|
package/dist/parsers/tsx.cjs
DELETED
package/dist/parsers/tsx.d.cts
DELETED
package/dist/parsers/tsx.d.ts
DELETED
package/dist/parsers/tsx.js
DELETED
package/src/fs.ts
DELETED
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { normalize, relative, resolve } from 'node:path'
|
|
2
|
-
import fs from 'fs-extra'
|
|
3
|
-
import { switcher } from 'js-runtime'
|
|
4
|
-
|
|
5
|
-
type Options = { sanity?: boolean }
|
|
6
|
-
|
|
7
|
-
export async function write(path: string, data: string, options: Options = {}): Promise<string | undefined> {
|
|
8
|
-
if (data.trim() === '') {
|
|
9
|
-
return undefined
|
|
10
|
-
}
|
|
11
|
-
return switcher(
|
|
12
|
-
{
|
|
13
|
-
node: async (path: string, data: string, { sanity }: Options) => {
|
|
14
|
-
try {
|
|
15
|
-
const oldContent = await fs.readFile(resolve(path), {
|
|
16
|
-
encoding: 'utf-8',
|
|
17
|
-
})
|
|
18
|
-
if (oldContent?.toString() === data?.toString()) {
|
|
19
|
-
return
|
|
20
|
-
}
|
|
21
|
-
} catch (_err) {
|
|
22
|
-
/* empty */
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
await fs.outputFile(resolve(path), data, { encoding: 'utf-8' })
|
|
26
|
-
|
|
27
|
-
if (sanity) {
|
|
28
|
-
const savedData = await fs.readFile(resolve(path), {
|
|
29
|
-
encoding: 'utf-8',
|
|
30
|
-
})
|
|
31
|
-
|
|
32
|
-
if (savedData?.toString() !== data?.toString()) {
|
|
33
|
-
throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`)
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return savedData
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
return data
|
|
40
|
-
},
|
|
41
|
-
bun: async (path: string, data: string, { sanity }: Options) => {
|
|
42
|
-
try {
|
|
43
|
-
await Bun.write(resolve(path), data)
|
|
44
|
-
|
|
45
|
-
if (sanity) {
|
|
46
|
-
const file = Bun.file(resolve(path))
|
|
47
|
-
const savedData = await file.text()
|
|
48
|
-
|
|
49
|
-
if (savedData?.toString() !== data?.toString()) {
|
|
50
|
-
throw new Error(`Sanity check failed for ${path}\n\nData[${path.length}]:\n${path}\n\nSaved[${savedData.length}]:\n${savedData}\n`)
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
return savedData
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
return data
|
|
57
|
-
} catch (e) {
|
|
58
|
-
console.error(e)
|
|
59
|
-
}
|
|
60
|
-
},
|
|
61
|
-
},
|
|
62
|
-
'node',
|
|
63
|
-
)(path, data.trim(), options)
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export async function read(path: string): Promise<string> {
|
|
67
|
-
return switcher(
|
|
68
|
-
{
|
|
69
|
-
node: async (path: string) => {
|
|
70
|
-
return fs.readFile(path, { encoding: 'utf8' })
|
|
71
|
-
},
|
|
72
|
-
bun: async (path: string) => {
|
|
73
|
-
const file = Bun.file(path)
|
|
74
|
-
|
|
75
|
-
return file.text()
|
|
76
|
-
},
|
|
77
|
-
},
|
|
78
|
-
'node',
|
|
79
|
-
)(path)
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function readSync(path: string): string {
|
|
83
|
-
return switcher(
|
|
84
|
-
{
|
|
85
|
-
node: (path: string) => {
|
|
86
|
-
return fs.readFileSync(path, { encoding: 'utf8' })
|
|
87
|
-
},
|
|
88
|
-
bun: () => {
|
|
89
|
-
throw new Error('Bun cannot read sync')
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
'node',
|
|
93
|
-
)(path)
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
export async function exists(path: string): Promise<boolean> {
|
|
97
|
-
return switcher(
|
|
98
|
-
{
|
|
99
|
-
node: async (path: string) => {
|
|
100
|
-
return fs.pathExists(path)
|
|
101
|
-
},
|
|
102
|
-
bun: async (path: string) => {
|
|
103
|
-
const file = Bun.file(path)
|
|
104
|
-
|
|
105
|
-
return file.exists()
|
|
106
|
-
},
|
|
107
|
-
},
|
|
108
|
-
'node',
|
|
109
|
-
)(path)
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
export function existsSync(path: string): boolean {
|
|
113
|
-
return switcher(
|
|
114
|
-
{
|
|
115
|
-
node: (path: string) => {
|
|
116
|
-
return fs.pathExistsSync(path)
|
|
117
|
-
},
|
|
118
|
-
bun: () => {
|
|
119
|
-
throw new Error('Bun cannot read sync')
|
|
120
|
-
},
|
|
121
|
-
},
|
|
122
|
-
'node',
|
|
123
|
-
)(path)
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
export async function clean(path: string): Promise<void> {
|
|
127
|
-
return fs.remove(path)
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export async function unlink(path: string): Promise<void> {
|
|
131
|
-
return fs.unlink(path)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function slash(path: string, platform: 'windows' | 'mac' | 'linux' = 'linux') {
|
|
135
|
-
const isWindowsPath = /^\\\\\?\\/.test(path)
|
|
136
|
-
const normalizedPath = normalize(path)
|
|
137
|
-
|
|
138
|
-
if (['linux', 'mac'].includes(platform) && !isWindowsPath) {
|
|
139
|
-
// linux and mac
|
|
140
|
-
return normalizedPath.replaceAll(/\\/g, '/').replace('../', '')
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// windows
|
|
144
|
-
return normalizedPath.replaceAll(/\\/g, '/').replace('../', '')
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export function trimExtName(text: string): string {
|
|
148
|
-
return text.replace(/\.[^/.]+$/, '')
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export function getRelativePath(rootDir?: string | null, filePath?: string | null, platform: 'windows' | 'mac' | 'linux' = 'linux'): string {
|
|
152
|
-
if (!rootDir || !filePath) {
|
|
153
|
-
throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
const relativePath = relative(rootDir, filePath)
|
|
157
|
-
|
|
158
|
-
// On Windows, paths are separated with a "\"
|
|
159
|
-
// However, web browsers use "/" no matter the platform
|
|
160
|
-
const slashedPath = slash(relativePath, platform)
|
|
161
|
-
|
|
162
|
-
if (slashedPath.startsWith('../')) {
|
|
163
|
-
return slashedPath
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
return `./${slashedPath}`
|
|
167
|
-
}
|
package/src/parsers/parser.ts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import type * as KubbFile from '../KubbFile.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
|
-
}
|
package/src/parsers/tsx.ts
DELETED