susee 0.1.3 → 0.1.5

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/index.cjs CHANGED
@@ -5,1987 +5,4 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
5
  this file except in compliance with the License. You may obtain a copy of the
6
6
  License at http://www.apache.org/licenses/LICENSE-2.0
7
7
  ***************************************************************************** */
8
- "use strict";
9
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- var desc = Object.getOwnPropertyDescriptor(m, k);
12
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
- desc = { enumerable: true, get: function() { return m[k]; } };
14
- }
15
- Object.defineProperty(o, k2, desc);
16
- }) : (function(o, m, k, k2) {
17
- if (k2 === undefined) k2 = k;
18
- o[k2] = m[k];
19
- }));
20
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
- Object.defineProperty(o, "default", { enumerable: true, value: v });
22
- }) : function(o, v) {
23
- o["default"] = v;
24
- });
25
- var __importStar = (this && this.__importStar) || (function () {
26
- var ownKeys = function(o) {
27
- ownKeys = Object.getOwnPropertyNames || function (o) {
28
- var ar = [];
29
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
- return ar;
31
- };
32
- return ownKeys(o);
33
- };
34
- return function (mod) {
35
- if (mod && mod.__esModule) return mod;
36
- var result = {};
37
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
- __setModuleDefault(result, mod);
39
- return result;
40
- };
41
- })();
42
- var __importDefault = (this && this.__importDefault) || function (mod) {
43
- return (mod && mod.__esModule) ? mod : { "default": mod };
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.susee = susee;
47
- const tsconfig_1 = __importDefault(require("@suseejs/tsconfig"));
48
- const dependencies_1 = __importDefault(require("@suseejs/dependencies"));
49
- const node_fs_1 = __importDefault(require("node:fs"));
50
- const node_path_1 = __importDefault(require("node:path"));
51
- const resolves_1 = __importDefault(require("@phothinmaung/resolves"));
52
- const tcolor_1 = __importDefault(require("@suseejs/tcolor"));
53
- const transformer_1 = __importDefault(require("@suseejs/transformer"));
54
- const typescript_1 = __importDefault(require("typescript"));
55
- const utils_1 = __importDefault(require("@suseejs/utils"));
56
- const node_buffer_1 = require("node:buffer");
57
- //src/lib/bundle/bundleCreator.ts
58
- /**
59
- * Creates a BundleCreator function that transforms a DepsFile with a given BundleVisitor and typescript compiler options.
60
- * @param {BundleVisitor} bundleVisitor - a BundleVisitor function that takes a context, depsTree, sourceFile, and any number of arguments.
61
- * @param {ts.CompilerOptions} compilerOptions - typescript compiler options.
62
- * @param {...any} args - any number of arguments to pass to the BundleVisitor function.
63
- * @returns {BundleCreator} a BundleCreator function that takes a DepsFile and returns a transformed DepsFile.
64
- */
65
- const bundleCreator = (bundleVisitor, compilerOptions, ...args) => {
66
- return (depsTree) => {
67
- const sourceFile = typescript_1.default.createSourceFile(depsTree.file, depsTree.content, typescript_1.default.ScriptTarget.Latest, true);
68
- const transformer = (context) => {
69
- const visitor = bundleVisitor(context, depsTree, sourceFile, ...args);
70
- return (rootNode) => typescript_1.default.visitNode(rootNode, visitor);
71
- };
72
- let _content = (0, transformer_1.default)(transformer, sourceFile, compilerOptions);
73
- _content = _content.replace(/^s*;\s*$/gm, "").trim();
74
- const { content, ...rest } = depsTree;
75
- return { content: _content, ...rest };
76
- };
77
- };
78
- //src/lib/bundle/mergeImportsStatement.ts
79
- function mergeImportsStatement(imports) {
80
- const importMap = new Map();
81
- const typeImportMap = new Map();
82
- const defaultImports = new Map();
83
- const typeDefaultImports = new Map();
84
- const namespaceImports = new Map();
85
- // Parse each import statement
86
- for (const importStr of imports) {
87
- const importMatch = importStr.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);
88
- if (!importMatch)
89
- continue;
90
- const [, importClause, _modulePath] = importMatch;
91
- const isTypeImport = importStr.includes("import type");
92
- const modulePath = _modulePath;
93
- if (!importClause) {
94
- // Default import or side-effect import
95
- const defaultMatch = importStr.match(/import\s+(?:type\s+)?(\w+)/);
96
- if (defaultMatch) {
97
- const importName = defaultMatch[1];
98
- const targetMap = isTypeImport ? typeDefaultImports : defaultImports;
99
- if (!targetMap.has(modulePath))
100
- targetMap.set(modulePath, new Set());
101
- targetMap.get(modulePath)?.add(importName);
102
- }
103
- continue;
104
- }
105
- if (importClause.startsWith("{")) {
106
- // Named imports: import { a, b } from 'module'
107
- const targetMap = isTypeImport ? typeImportMap : importMap;
108
- if (!targetMap.has(modulePath))
109
- targetMap.set(modulePath, new Set());
110
- const names = importClause
111
- .replace(/[{}]/g, "")
112
- .split(",")
113
- .map((s) => s.trim())
114
- .filter(Boolean);
115
- // biome-ignore lint/suspicious/useIterableCallbackReturn : just add name for names each
116
- names.forEach((name) => targetMap.get(modulePath)?.add(name));
117
- }
118
- else if (importClause.startsWith("* as")) {
119
- // Namespace import: import * as name from 'module'
120
- const namespaceMatch = importClause.match(/\*\s+as\s+(\w+)/);
121
- if (namespaceMatch) {
122
- const namespaceName = namespaceMatch[1];
123
- if (!namespaceImports.has(modulePath))
124
- namespaceImports.set(modulePath, new Set());
125
- namespaceImports.get(modulePath)?.add(namespaceName);
126
- }
127
- }
128
- else {
129
- // Default import: import name from 'module'
130
- const targetMap = isTypeImport ? typeDefaultImports : defaultImports;
131
- if (!targetMap.has(modulePath))
132
- targetMap.set(modulePath, new Set());
133
- targetMap.get(modulePath)?.add(importClause.trim());
134
- }
135
- }
136
- const mergedImports = [];
137
- // Process named imports - remove type imports that have regular imports
138
- for (const [modulePath, regularNames] of importMap) {
139
- const typeNames = typeImportMap.get(modulePath) || new Set();
140
- // Only include type names that don't have regular imports
141
- const finalNames = new Set([...regularNames]);
142
- for (const typeName of typeNames) {
143
- if (!regularNames.has(typeName)) {
144
- finalNames.add(typeName);
145
- }
146
- }
147
- if (finalNames.size > 0) {
148
- const importNames = Array.from(finalNames).sort().join(", ");
149
- mergedImports.push(`import { ${importNames} } from "${modulePath}";`);
150
- }
151
- }
152
- // Add remaining type-only imports (where no regular imports exist for the module)
153
- for (const [modulePath, typeNames] of typeImportMap) {
154
- if (!importMap.has(modulePath) && typeNames.size > 0) {
155
- const importNames = Array.from(typeNames).sort().join(", ");
156
- mergedImports.push(`import type { ${importNames} } from "${modulePath}";`);
157
- }
158
- }
159
- // Process default imports - remove type default imports that have regular default imports
160
- for (const [modulePath, regularDefaultNames] of defaultImports) {
161
- const typeDefaultNames = typeDefaultImports.get(modulePath) || new Set();
162
- // Only include type default names that don't have regular default imports
163
- const finalNames = new Set([...regularDefaultNames]);
164
- for (const typeName of typeDefaultNames) {
165
- if (!regularDefaultNames.has(typeName)) {
166
- finalNames.add(typeName);
167
- }
168
- }
169
- if (finalNames.size > 0) {
170
- const importNames = Array.from(finalNames).join(", ");
171
- mergedImports.push(`import ${importNames} from "${modulePath}";`);
172
- }
173
- }
174
- // Add remaining type-only default imports
175
- for (const [modulePath, typeDefaultNames] of typeDefaultImports) {
176
- if (!defaultImports.has(modulePath) && typeDefaultNames.size > 0) {
177
- const importNames = Array.from(typeDefaultNames).join(", ");
178
- mergedImports.push(`import type ${importNames} from "${modulePath}";`);
179
- }
180
- }
181
- // Process namespace imports
182
- for (const [modulePath, names] of namespaceImports) {
183
- if (names.size > 0) {
184
- const importNames = Array.from(names).join(", ");
185
- mergedImports.push(`import * as ${importNames} from "${modulePath}";`);
186
- }
187
- }
188
- return mergedImports.sort();
189
- }
190
- //src/lib/bundle/visitors/anonymousCallExpression.ts
191
- /**
192
- * A BundleVisitor that updates the call expression, property access expression, and new expression
193
- * with the anonymous default import name.
194
- */
195
- const anonymousCallExpressionVisitor = (context, depsTree, _sourceFile, exportDefaultImportNameMap) => {
196
- const { factory } = context;
197
- const visit = (node) => {
198
- if (typescript_1.default.isCallExpression(node)) {
199
- if (typescript_1.default.isIdentifier(node.expression)) {
200
- const base = node.expression.text;
201
- const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
202
- if (mapping) {
203
- return factory.updateCallExpression(node, factory.createIdentifier(mapping.newName), node.typeArguments, node.arguments);
204
- }
205
- }
206
- }
207
- else if (typescript_1.default.isPropertyAccessExpression(node)) {
208
- if (typescript_1.default.isIdentifier(node.expression)) {
209
- const base = node.expression.text;
210
- const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
211
- if (mapping) {
212
- return factory.updatePropertyAccessExpression(node, factory.createIdentifier(mapping.newName), node.name);
213
- }
214
- }
215
- }
216
- else if (typescript_1.default.isNewExpression(node)) {
217
- if (typescript_1.default.isIdentifier(node.expression)) {
218
- const base = node.expression.text;
219
- const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
220
- if (mapping) {
221
- return factory.updateNewExpression(node, factory.createIdentifier(mapping.newName), node.typeArguments, node.arguments);
222
- }
223
- }
224
- // for export specifier it is focus on entry file
225
- }
226
- else if (typescript_1.default.isExportSpecifier(node)) {
227
- if (typescript_1.default.isIdentifier(node.name)) {
228
- const base = node.name.text;
229
- const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
230
- if (mapping) {
231
- return factory.updateExportSpecifier(node, node.isTypeOnly, node.propertyName, factory.createIdentifier(mapping.newName));
232
- }
233
- }
234
- }
235
- return typescript_1.default.visitEachChild(node, visit, context);
236
- };
237
- return visit;
238
- };
239
- //src/lib/bundle/visitors/visitorHelpers.ts
240
- const normalizePathKey = (filePath) => {
241
- const parsed = node_path_1.default.parse(filePath);
242
- let noExt = node_path_1.default.join(parsed.dir, parsed.name);
243
- if (parsed.name === "index") {
244
- noExt = parsed.dir;
245
- }
246
- return node_path_1.default.normalize(noExt);
247
- };
248
- const getFileKey = (filePath) => normalizePathKey(filePath);
249
- const getModuleKeyFromSpecifier = (moduleSpecifier, sourceFile, containingFile) => {
250
- let spec = "";
251
- if (typescript_1.default.isStringLiteral(moduleSpecifier)) {
252
- spec = moduleSpecifier.text;
253
- }
254
- else {
255
- spec = moduleSpecifier.getText(sourceFile).replace(/^['"]|['"]$/g, "");
256
- }
257
- if (spec.startsWith(".") || spec.startsWith("/")) {
258
- const baseDir = node_path_1.default.dirname(containingFile);
259
- return normalizePathKey(node_path_1.default.resolve(baseDir, spec));
260
- }
261
- return spec;
262
- };
263
- function uniqueName() {
264
- const storedPrefix = new Map();
265
- const obj = {
266
- setPrefix({ key, value }) {
267
- const names = [];
268
- let _fix;
269
- if (storedPrefix.has(key)) {
270
- console.warn(`${key} already exist`);
271
- throw new Error();
272
- }
273
- else {
274
- _fix = value;
275
- storedPrefix.set(key, value);
276
- }
277
- function getName(input) {
278
- const length = names.length;
279
- const _name = _fix
280
- ? `${_fix}${input}_${length + 1}`
281
- : `$nyein${input}_${length + 1}`;
282
- names.push(_name);
283
- return _name;
284
- }
285
- return { getName };
286
- },
287
- getPrefix(key) {
288
- if (storedPrefix.has(key)) {
289
- return storedPrefix.get(key);
290
- }
291
- },
292
- };
293
- return obj;
294
- }
295
- //src/lib/bundle/visitors/anonymousExport.ts
296
- const prefixKey = "AnonymousName";
297
- const genName = uniqueName().setPrefix({ key: prefixKey, value: "a_" });
298
- /**
299
- * A BundleVisitor that updates the call expression, property access expression, and new expression
300
- * with the anonymous default import name.
301
- */
302
- const anonymousExportVisitor = (context, depsTree, sourceFile, exportDefaultExportNameMap) => {
303
- const { factory } = context;
304
- const visit = (node) => {
305
- const fileName = node_path_1.default.basename(depsTree.file).split(".")[0];
306
- if ((typescript_1.default.isFunctionDeclaration(node) || typescript_1.default.isClassDeclaration(node)) &&
307
- node.name === undefined) {
308
- let exp = false;
309
- let def = false;
310
- node.modifiers?.forEach((mod) => {
311
- if (mod.kind === typescript_1.default.SyntaxKind.ExportKeyword) {
312
- exp = true;
313
- }
314
- if (mod.kind === typescript_1.default.SyntaxKind.DefaultKeyword) {
315
- def = true;
316
- }
317
- });
318
- if (exp && def) {
319
- const base = genName.getName(fileName);
320
- exportDefaultExportNameMap.push({
321
- base,
322
- file: fileName,
323
- newName: base,
324
- isEd: true,
325
- });
326
- if (typescript_1.default.isFunctionDeclaration(node)) {
327
- return factory.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, factory.createIdentifier(base), node.typeParameters, node.parameters, node.type, node.body);
328
- }
329
- else if (typescript_1.default.isClassDeclaration(node)) {
330
- return factory.updateClassDeclaration(node, node.modifiers, factory.createIdentifier(base), node.typeParameters, node.heritageClauses, node.members);
331
- }
332
- }
333
- }
334
- else if (typescript_1.default.isExportAssignment(node) &&
335
- !node.name &&
336
- !node.isExportEquals) {
337
- if (typescript_1.default.isArrowFunction(node.expression)) {
338
- const base = genName.getName(fileName);
339
- const arrowFunctionNode = factory.createArrowFunction(node.expression.modifiers, node.expression.typeParameters, node.expression.parameters, node.expression.type, node.expression.equalsGreaterThanToken, node.expression.body);
340
- const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), node.expression.exclamationToken, node.expression.type, arrowFunctionNode);
341
- const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
342
- const variableStatementNode = factory.createVariableStatement(node.expression.modifiers, variableDeclarationListNode);
343
- const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
344
- exportDefaultExportNameMap.push({
345
- base,
346
- file: fileName,
347
- newName: base,
348
- isEd: true,
349
- });
350
- return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
351
- }
352
- else if (typescript_1.default.isObjectLiteralExpression(node.expression)) {
353
- const base = genName.getName(fileName);
354
- const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, node.expression);
355
- const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
356
- const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
357
- const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
358
- exportDefaultExportNameMap.push({
359
- base,
360
- file: fileName,
361
- newName: base,
362
- isEd: true,
363
- });
364
- return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
365
- }
366
- else if (typescript_1.default.isArrayLiteralExpression(node.expression)) {
367
- const base = genName.getName(fileName);
368
- const arrayLiteralExpressionNode = factory.createArrayLiteralExpression(node.expression.elements, true);
369
- const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, arrayLiteralExpressionNode);
370
- const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
371
- const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
372
- const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
373
- exportDefaultExportNameMap.push({
374
- base,
375
- file: fileName,
376
- newName: base,
377
- isEd: true,
378
- });
379
- return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
380
- }
381
- else if (typescript_1.default.isStringLiteral(node.expression)) {
382
- const base = genName.getName(fileName);
383
- const stringLiteralNode = factory.createStringLiteral(node.expression.text);
384
- const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, stringLiteralNode);
385
- const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
386
- const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
387
- const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
388
- exportDefaultExportNameMap.push({
389
- base,
390
- file: fileName,
391
- newName: base,
392
- isEd: true,
393
- });
394
- return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
395
- }
396
- else if (typescript_1.default.isNumericLiteral(node.expression)) {
397
- const base = genName.getName(fileName);
398
- const numericLiteralNode = factory.createNumericLiteral(node.expression.text);
399
- const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, numericLiteralNode);
400
- const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
401
- const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
402
- const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
403
- exportDefaultExportNameMap.push({
404
- base,
405
- file: fileName,
406
- newName: base,
407
- isEd: true,
408
- });
409
- return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
410
- }
411
- } //
412
- return typescript_1.default.visitEachChild(node, visit, context);
413
- };
414
- return visit;
415
- };
416
- //src/lib/bundle/visitors/anonymousImport.ts
417
- /**
418
- * A BundleVisitor that updates the import declaration, property access expression, and new expression
419
- * with the anonymous default import name.
420
- */
421
- const anonymousImportVisitor = (context, depsTree, sourceFile, exportDefaultExportNameMap, exportDefaultImportNameMap) => {
422
- const { factory } = context;
423
- const visit = (node) => {
424
- if (typescript_1.default.isImportDeclaration(node)) {
425
- const fileName = node.moduleSpecifier.getText(sourceFile);
426
- const _name = node_path_1.default.basename(fileName).split(".")[0].trim();
427
- // check only import default expression
428
- if (node.importClause?.name && typescript_1.default.isIdentifier(node.importClause.name)) {
429
- const base = node.importClause.name.text.trim();
430
- const mapping = exportDefaultExportNameMap.find((v) => v.file === _name);
431
- if (mapping) {
432
- exportDefaultImportNameMap.push({
433
- base,
434
- file: depsTree.file,
435
- newName: mapping.newName,
436
- isEd: true,
437
- });
438
- const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, factory.createIdentifier(mapping.newName), node.importClause.namedBindings);
439
- return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
440
- }
441
- }
442
- }
443
- return typescript_1.default.visitEachChild(node, visit, context);
444
- };
445
- return visit;
446
- };
447
- //src/lib/bundle/visitors/duplicateCallExpression.ts
448
- /**
449
- * A BundleVisitor that updates the call expression, property access expression, and new expression
450
- * with the anonymous default import name.
451
- */
452
- const duplicateCallExpressionVisitor = (context, depsTree, _sourceFile, callNameMap, importNameMap) => {
453
- const { factory } = context;
454
- const visit = (node) => {
455
- if (typescript_1.default.isCallExpression(node)) {
456
- if (typescript_1.default.isIdentifier(node.expression)) {
457
- const base = node.expression.text;
458
- let new_name = null;
459
- const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
460
- const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
461
- if (mapping) {
462
- new_name = mapping.newName;
463
- }
464
- else if (importMapping) {
465
- new_name = importMapping.newName;
466
- //flag.push(new_name);
467
- }
468
- if (new_name) {
469
- return factory.updateCallExpression(node, factory.createIdentifier(new_name), node.typeArguments, node.arguments);
470
- }
471
- }
472
- }
473
- else if (typescript_1.default.isPropertyAccessExpression(node)) {
474
- if (typescript_1.default.isIdentifier(node.expression)) {
475
- const base = node.expression.text;
476
- let new_name = null;
477
- const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
478
- const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
479
- if (mapping) {
480
- new_name = mapping.newName;
481
- }
482
- else if (importMapping) {
483
- new_name = importMapping.newName;
484
- }
485
- if (new_name) {
486
- return factory.updatePropertyAccessExpression(node, factory.createIdentifier(new_name), node.name);
487
- }
488
- }
489
- }
490
- else if (typescript_1.default.isNewExpression(node)) {
491
- if (typescript_1.default.isIdentifier(node.expression)) {
492
- const base = node.expression.text;
493
- let new_name = null;
494
- const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
495
- const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
496
- if (mapping) {
497
- new_name = mapping.newName;
498
- }
499
- else if (importMapping) {
500
- new_name = importMapping.newName;
501
- }
502
- if (new_name) {
503
- return factory.updateNewExpression(node, factory.createIdentifier(new_name), node.typeArguments, node.arguments);
504
- }
505
- }
506
- }
507
- /* ----------------------Returns for visitor function------------------------------- */
508
- return typescript_1.default.visitEachChild(node, visit, context);
509
- };
510
- return visit;
511
- };
512
- //src/lib/bundle/visitors/duplicateCollection.ts
513
- /**
514
- * A BundleVisitor that updates the collection (variable, function, class, etc)
515
- * declaration with the anonymous default import name.
516
- *
517
- * @param {BundleVisitor} context - The BundleVisitor context.
518
- * @param {DepsTree} depsTree - The deps tree object.
519
- * @param {SourceFile} sourceFile - The source file object.
520
- * @param {DuplicatesNameMap} namesMap - The DuplicatesNameMap object.
521
- * @return {NodeVisit} visit - The NodeVisit function.
522
- */
523
- const duplicateCollectionVisitor = (context, depsTree, _sourceFile, namesMap) => {
524
- //const { factory } = context;
525
- const visit = (node, isGlobalScope = true) => {
526
- // Global declarations များကိုသာ collect လုပ်မယ်
527
- if (isGlobalScope) {
528
- // Variable statements (const, let, var)
529
- if (typescript_1.default.isVariableStatement(node)) {
530
- node.declarationList.declarations.forEach((decl) => {
531
- if (typescript_1.default.isIdentifier(decl.name)) {
532
- const $name = decl.name.text;
533
- if (!namesMap.has($name)) {
534
- namesMap.set($name, new Set([{ file: depsTree.file }]));
535
- }
536
- else {
537
- // biome-ignore lint/style/noNonNullAssertion : !namesMap.has($name) before
538
- namesMap.get($name).add({ file: depsTree.file });
539
- }
540
- }
541
- });
542
- }
543
- // Function, Class, Enum, Interface, Type declarations
544
- else if (typescript_1.default.isFunctionDeclaration(node) ||
545
- typescript_1.default.isClassDeclaration(node) ||
546
- typescript_1.default.isEnumDeclaration(node) ||
547
- typescript_1.default.isInterfaceDeclaration(node) ||
548
- typescript_1.default.isTypeAliasDeclaration(node)) {
549
- const $name = node.name?.text;
550
- if ($name) {
551
- if (!namesMap.has($name)) {
552
- namesMap.set($name, new Set([{ file: depsTree.file }]));
553
- }
554
- else {
555
- // biome-ignore lint/style/noNonNullAssertion : !namesMap.has($name) before
556
- namesMap.get($name).add({ file: depsTree.file });
557
- }
558
- }
559
- }
560
- }
561
- // Local scope ထဲရောက်သွားတဲ့ node တွေအတွက် recursive visit
562
- if (typescript_1.default.isBlock(node) ||
563
- typescript_1.default.isFunctionDeclaration(node) ||
564
- typescript_1.default.isFunctionExpression(node) ||
565
- typescript_1.default.isArrowFunction(node) ||
566
- typescript_1.default.isMethodDeclaration(node) ||
567
- typescript_1.default.isClassDeclaration(node)) {
568
- // Local scope ထဲကို ဝင်သွားပြီဆိုတာနဲ့ isGlobalScope = false
569
- if (typescript_1.default.isBlock(node)) {
570
- typescript_1.default.visitNodes(node.statements, (child) => visit(child, false));
571
- }
572
- else {
573
- typescript_1.default.forEachChild(node, (child) => {
574
- visit(child, false);
575
- });
576
- }
577
- }
578
- else {
579
- // Global scope ထဲဆက်ရှိနေတဲ့ node တွေအတွက်
580
- return typescript_1.default.visitEachChild(node, (child) => visit(child, isGlobalScope), context);
581
- }
582
- /* ----------------------Returns for visitNode function------------------------------- */
583
- return node;
584
- };
585
- return visit;
586
- };
587
- //src/lib/bundle/visitors/duplicateExportExpression.ts
588
- /**
589
- * A BundleVisitor that updates the call expression, property access expression, and new expression
590
- * with the anonymous default import name.
591
- */
592
- const duplicateExportExpressionVisitor = (context, depsTree, _sourceFile, callNameMap, importNameMap, exportNameMap) => {
593
- const { factory } = context;
594
- const visit = (node) => {
595
- if (typescript_1.default.isExportSpecifier(node)) {
596
- if (typescript_1.default.isIdentifier(node.name)) {
597
- const base = node.name.text;
598
- let new_name = null;
599
- const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
600
- const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
601
- if (mapping) {
602
- exportNameMap.push({
603
- base,
604
- file: getFileKey(depsTree.file),
605
- newName: mapping.newName,
606
- });
607
- new_name = mapping.newName;
608
- }
609
- else if (importMapping) {
610
- new_name = importMapping.newName;
611
- }
612
- if (new_name) {
613
- return factory.updateExportSpecifier(node, node.isTypeOnly, node.propertyName, factory.createIdentifier(new_name));
614
- }
615
- }
616
- }
617
- else if (typescript_1.default.isExportAssignment(node)) {
618
- const expr = node.expression;
619
- if (typescript_1.default.isIdentifier(expr)) {
620
- const base = expr.text;
621
- let new_name = null;
622
- const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
623
- const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
624
- if (mapping) {
625
- exportNameMap.push({
626
- base,
627
- file: getFileKey(depsTree.file),
628
- newName: mapping.newName,
629
- });
630
- new_name = mapping.newName;
631
- }
632
- else if (importMapping) {
633
- new_name = importMapping.newName;
634
- }
635
- if (new_name) {
636
- return factory.updateExportAssignment(node, node.modifiers, factory.createIdentifier(new_name));
637
- }
638
- }
639
- }
640
- /* ----------------------Returns for visitor function------------------------------- */
641
- return typescript_1.default.visitEachChild(node, visit, context);
642
- };
643
- return visit;
644
- };
645
- //src/lib/bundle/visitors/duplicateImportExpression.ts
646
- /**
647
- * A BundleVisitor that updates the import declaration, property access expression, and new expression
648
- * with the anonymous default import name.
649
- *
650
- * @param {BundleVisitor} context - The BundleVisitor context.
651
- * @param {DepsTree} depsTree - The deps tree object.
652
- * @param {SourceFile} sourceFile - The source file object.
653
- * @param {NamesSets} exportNameMap - The export name map object.
654
- * @param {NamesSets} importNameMap - The import name map object.
655
- * @return {NodeVisit} visit - The NodeVisit function.
656
- */
657
- const duplicateImportExpressionVisitor = (context, depsTree, sourceFile, exportNameMap, importNameMap) => {
658
- const { factory } = context;
659
- const visit = (node) => {
660
- if (typescript_1.default.isImportDeclaration(node)) {
661
- const moduleKey = getModuleKeyFromSpecifier(node.moduleSpecifier, sourceFile, depsTree.file);
662
- let baseNames = [];
663
- if (node.importClause?.namedBindings &&
664
- typescript_1.default.isNamedImports(node.importClause.namedBindings)) {
665
- baseNames = node.importClause.namedBindings.elements.map((el) => el.name.text.trim());
666
- }
667
- // import default expression
668
- if (node.importClause?.name && typescript_1.default.isIdentifier(node.importClause.name)) {
669
- const base = node.importClause.name.text.trim();
670
- const mapping = exportNameMap.find((m) => m.base === base && m.file === moduleKey);
671
- if (mapping) {
672
- importNameMap.push({
673
- base: mapping.base,
674
- file: depsTree.file,
675
- newName: mapping.newName,
676
- });
677
- const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, factory.createIdentifier(mapping.newName), node.importClause.namedBindings);
678
- return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
679
- }
680
- }
681
- // import name , `import{ ... }`
682
- if (baseNames.length > 0 &&
683
- node.importClause &&
684
- node.importClause.namedBindings &&
685
- typescript_1.default.isNamedImports(node.importClause.namedBindings)) {
686
- const updatedElements = node.importClause.namedBindings.elements.map((el) => {
687
- const mapping = exportNameMap.find((m) => m.base === el.name.text.trim() && m.file === moduleKey);
688
- if (mapping) {
689
- importNameMap.push({
690
- base: mapping.base,
691
- file: depsTree.file,
692
- newName: mapping.newName,
693
- });
694
- return factory.updateImportSpecifier(el, el.isTypeOnly, el.propertyName, factory.createIdentifier(mapping.newName));
695
- }
696
- return el;
697
- });
698
- const newNamedImports = factory.updateNamedImports(node.importClause.namedBindings, updatedElements);
699
- const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, node.importClause.name, newNamedImports);
700
- return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
701
- }
702
- } //&&
703
- /* ----------------------Returns for visitor function------------------------------- */
704
- return typescript_1.default.visitEachChild(node, visit, context);
705
- };
706
- return visit;
707
- };
708
- //src/lib/bundle/visitors/duplicateUpdate.ts
709
- const dupName = uniqueName().setPrefix({
710
- key: "DuplicatesNames",
711
- value: "d_",
712
- });
713
- /**
714
- * A BundleVisitor that updates the variable declaration, function declaration, and class declaration
715
- * with the duplicates name.
716
- *
717
- * @param {BundleVisitor} context - The BundleVisitor context.
718
- * @param {DepsTree} depsTree - The deps tree object.
719
- * @param {SourceFile} sourceFile - The source file object.
720
- * @param {DuplicatesNameMap} namesMap - The DuplicatesNameMap object.
721
- * @param {NamesSets} callNameMap - The NamesSets object.
722
- * @return {NodeVisit} visit - The NodeVisit function.
723
- */
724
- const duplicateUpdateVisitor = (context, depsTree, _sourceFile, namesMap, callNameMap) => {
725
- const { factory } = context;
726
- const visit = (node) => {
727
- if (typescript_1.default.isVariableStatement(node)) {
728
- const newDeclarations = node.declarationList.declarations.map((decl) => {
729
- if (typescript_1.default.isIdentifier(decl.name)) {
730
- const base = decl.name.text;
731
- // biome-ignore lint/style/noNonNullAssertion : namesMap.has(base) before that get just only size
732
- if (namesMap.has(base) && namesMap.get(base).size > 1) {
733
- const newName = dupName.getName(base);
734
- callNameMap.push({ base, file: depsTree.file, newName });
735
- return factory.updateVariableDeclaration(decl, factory.createIdentifier(newName), decl.exclamationToken, decl.type, decl.initializer);
736
- }
737
- }
738
- return decl;
739
- });
740
- const newDeclList = factory.updateVariableDeclarationList(node.declarationList, newDeclarations);
741
- return factory.updateVariableStatement(node, node.modifiers, newDeclList);
742
- }
743
- else if (typescript_1.default.isFunctionDeclaration(node)) {
744
- if (node.name && typescript_1.default.isIdentifier(node.name)) {
745
- const base = node.name.text;
746
- // biome-ignore lint/style/noNonNullAssertion : namesMap.has(base) before that get just only size
747
- if (namesMap.has(base) && namesMap.get(base).size > 1) {
748
- const newName = dupName.getName(base);
749
- callNameMap.push({ base, file: depsTree.file, newName });
750
- return factory.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, factory.createIdentifier(newName), node.typeParameters, node.parameters, node.type, node.body);
751
- }
752
- }
753
- }
754
- else if (typescript_1.default.isClassDeclaration(node)) {
755
- if (node.name && typescript_1.default.isIdentifier(node.name)) {
756
- const base = node.name.text;
757
- // biome-ignore lint/style/noNonNullAssertion : namesMap.has(base) before that get just only size
758
- if (namesMap.has(base) && namesMap.get(base).size > 1) {
759
- const newName = dupName.getName(base);
760
- callNameMap.push({ base, file: depsTree.file, newName });
761
- return factory.updateClassDeclaration(node, node.modifiers, factory.createIdentifier(newName), node.typeParameters, node.heritageClauses, node.members);
762
- }
763
- }
764
- }
765
- /* ----------------------Returns for visitor function------------------------------- */
766
- return typescript_1.default.visitEachChild(node, visit, context);
767
- };
768
- return visit;
769
- };
770
- //src/lib/bundle/visitors/removeExports.ts
771
- /**
772
- * A BundleVisitor that removes all exports from the given source file.
773
- * It does so by stripping "export" modifiers from function, class, interface, type alias, enum, and variable declarations,
774
- * and by removing "export { foo }" and "export default" declarations entirely.
775
- */
776
- const removeExportsVisitor = (context) => {
777
- const { factory } = context;
778
- const visit = (node) => {
779
- // --- Case 1: Strip "export" modifiers ---
780
- const inside_nameSpace = utils_1.default.isInsideNamespace(node);
781
- if (!inside_nameSpace) {
782
- if (typescript_1.default.isFunctionDeclaration(node) ||
783
- typescript_1.default.isClassDeclaration(node) ||
784
- typescript_1.default.isInterfaceDeclaration(node) ||
785
- typescript_1.default.isTypeAliasDeclaration(node) ||
786
- typescript_1.default.isEnumDeclaration(node) ||
787
- typescript_1.default.isVariableStatement(node)) {
788
- const modifiers = node.modifiers?.filter((m) => m.kind !== typescript_1.default.SyntaxKind.ExportKeyword &&
789
- m.kind !== typescript_1.default.SyntaxKind.DefaultKeyword);
790
- if (modifiers?.length !== node.modifiers?.length) {
791
- // If the node has an export modifier, remove it.
792
- // If the node is a function, class, interface, type alias, enum or variable declaration,
793
- // update the declaration by removing the export modifier.
794
- if (typescript_1.default.isFunctionDeclaration(node)) {
795
- return factory.updateFunctionDeclaration(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
796
- } // function
797
- if (typescript_1.default.isClassDeclaration(node)) {
798
- return factory.updateClassDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
799
- } // class
800
- if (typescript_1.default.isInterfaceDeclaration(node)) {
801
- return factory.updateInterfaceDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
802
- } // interface
803
- if (typescript_1.default.isTypeAliasDeclaration(node)) {
804
- return factory.updateTypeAliasDeclaration(node, modifiers, node.name, node.typeParameters, node.type);
805
- } // types
806
- if (typescript_1.default.isEnumDeclaration(node)) {
807
- return factory.updateEnumDeclaration(node, modifiers, node.name, node.members);
808
- } //enum
809
- if (typescript_1.default.isVariableStatement(node)) {
810
- return factory.updateVariableStatement(node, modifiers, node.declarationList);
811
- } // vars
812
- } //--
813
- } // --- Case 1
814
- }
815
- // --- Case 2: Remove "export { foo }" entirely ---
816
- if (typescript_1.default.isExportDeclaration(node)) {
817
- // If the node is an export declaration, remove it.
818
- return factory.createEmptyStatement();
819
- }
820
- // --- Case 3: Handle "export default ..." ---
821
- if (typescript_1.default.isExportAssignment(node)) {
822
- const expr = node.expression;
823
- // export default Foo; -> remove line
824
- if (typescript_1.default.isIdentifier(expr)) {
825
- return factory.createEmptyStatement();
826
- }
827
- }
828
- // --------- Visitor Return ------------------//
829
- return typescript_1.default.visitEachChild(node, visit, context);
830
- };
831
- return visit;
832
- };
833
- //src/lib/bundle/visitors/removeImports.ts
834
- let properties = [];
835
- const typeObj = {};
836
- const typesNames = [];
837
- function findProperty(node) {
838
- const properties = [];
839
- if (typescript_1.default.isPropertyAccessExpression(node) && typescript_1.default.isIdentifier(node.expression)) {
840
- properties.push(node.expression.text);
841
- }
842
- node.forEachChild((n) => findProperty(n));
843
- return properties;
844
- }
845
- /**
846
- * A BundleVisitor that removes import declarations and import equals declarations from a TypeScript program.
847
- * The visitor collects the names of type-only import-equals and emits a named/default type import if the type-only import-equals is not a namespace-type alias.
848
- * The visitor also collects the names of type-only imports of namespace-type aliases and emits a namespace type import if the type-only import-equals is not a namespace-type alias.
849
- */
850
- const removeImportsVisitor = (context, depsTree, sourceFile, removedStatements) => {
851
- // Pre-scan: collect names of type-only import-equals (these are namespace-type aliases)
852
- // import type NameSpace = require("foo")
853
- const typeOnlyImportEquals = new Set();
854
- for (const stmt of sourceFile.statements) {
855
- if (typescript_1.default.isImportEqualsDeclaration(stmt) && stmt.isTypeOnly) {
856
- const moduleReference = stmt.moduleReference;
857
- if (typescript_1.default.isExternalModuleReference(moduleReference) &&
858
- typescript_1.default.isStringLiteral(moduleReference.expression)) {
859
- typeOnlyImportEquals.add(stmt.name.text);
860
- }
861
- }
862
- }
863
- const { factory } = context;
864
- const visit = (node) => {
865
- properties = [...properties, ...findProperty(node)];
866
- const obj = {
867
- isNamespace: false,
868
- isTypeOnly: false,
869
- isTypeNamespace: false,
870
- source: "",
871
- importedString: undefined,
872
- importedObject: undefined,
873
- };
874
- // --- Case: TypeReference with QualifiedName (collect type usage)
875
- if (typescript_1.default.isTypeReferenceNode(node) &&
876
- typescript_1.default.isQualifiedName(node.typeName) &&
877
- typescript_1.default.isIdentifier(node.typeName.left) &&
878
- typescript_1.default.isIdentifier(node.typeName.right)) {
879
- const left = node.typeName.left.text;
880
- const right = node.typeName.right.text;
881
- typesNames.push(left);
882
- if (left in typeObj) {
883
- typeObj[left]?.push(right);
884
- }
885
- else {
886
- typeObj[left] = [right];
887
- }
888
- // If this qualified name refers to a type-only import-equals alias, DO NOT rewrite.
889
- // Rewriting (Foo.Bar -> Bar) was intended to support converting to named imports,
890
- // but for type-only namespace imports we will emit `import type * as Foo from "..."`.
891
- if (utils_1.default.checkModuleType(sourceFile, depsTree.file).isCommonJs) {
892
- if (left !== "ts" && !typeOnlyImportEquals.has(left)) {
893
- return factory.updateTypeReferenceNode(node, factory.createIdentifier(right), undefined);
894
- }
895
- }
896
- }
897
- // ------------------------
898
- if (typescript_1.default.isImportDeclaration(node)) {
899
- // --- Case 1: Import declarations
900
- const text = node.getText(sourceFile);
901
- removedStatements.push(text);
902
- return factory.createEmptyStatement();
903
- }
904
- //--- Case 2: Import equals declarations
905
- if (typescript_1.default.isImportEqualsDeclaration(node)) {
906
- const name = node.name.text;
907
- const moduleReference = node.moduleReference;
908
- if (node.isTypeOnly) {
909
- obj.isTypeOnly = true;
910
- }
911
- obj.importedString = name;
912
- if (!obj.isTypeOnly) {
913
- if (properties.includes(name)) {
914
- obj.isNamespace = true;
915
- }
916
- }
917
- if (typescript_1.default.isExternalModuleReference(moduleReference) &&
918
- typescript_1.default.isStringLiteral(moduleReference.expression)) {
919
- obj.source = moduleReference.expression.text;
920
- }
921
- let t;
922
- if (obj.importedString && !obj.importedObject) {
923
- if (obj.isTypeOnly) {
924
- // If this import-equals was a type-only namespace alias, emit a namespace type import
925
- if (typeOnlyImportEquals.has(obj.importedString)) {
926
- t = `import type * as ${obj.importedString} from "${obj.source}";`;
927
- }
928
- else {
929
- // otherwise try to emit a named/default type import (existing behavior)
930
- if (typesNames.includes(obj.importedString)) {
931
- t = `import type { ${typeObj[obj.importedString]?.join(",")} } from "${obj.source}";`;
932
- }
933
- else {
934
- t = `import type ${obj.importedString} from "${obj.source}";`;
935
- }
936
- }
937
- }
938
- else {
939
- if (obj.isNamespace && obj.source && obj.source !== "typescript") {
940
- t = `import * as ${obj.importedString} from "${obj.source}";`;
941
- }
942
- else {
943
- t = `import ${obj.importedString} from "${obj.source}";`;
944
- }
945
- }
946
- }
947
- if (!obj.importedString && obj.importedObject) {
948
- t = `import { ${obj.importedObject.join(", ")} } from "${obj.source}";`;
949
- }
950
- // removed
951
- if (t) {
952
- removedStatements.push(t);
953
- return factory.createEmptyStatement();
954
- }
955
- }
956
- // --- Case 3: Require imports
957
- if (typescript_1.default.isVariableStatement(node)) {
958
- const decls = node.declarationList.declarations;
959
- if (decls.length === 1) {
960
- const decl = decls[0];
961
- if (decl.initializer &&
962
- typescript_1.default.isCallExpression(decl.initializer) &&
963
- typescript_1.default.isIdentifier(decl.initializer.expression) &&
964
- decl.initializer.expression.escapedText === "require") {
965
- // imported from
966
- const arg = decl.initializer.arguments[0];
967
- if (typescript_1.default.isStringLiteral(arg)) {
968
- obj.source = arg.text;
969
- }
970
- if (typescript_1.default.isIdentifier(decl.name)) {
971
- const _n = decl.name.text;
972
- obj.importedString = _n;
973
- if (properties.includes(_n)) {
974
- obj.isNamespace = true;
975
- }
976
- }
977
- else if (typescript_1.default.isObjectBindingPattern(decl.name)) {
978
- const _names = [];
979
- for (const ele of decl.name.elements) {
980
- if (typescript_1.default.isIdentifier(ele.name)) {
981
- _names.push(ele.name.text);
982
- }
983
- }
984
- if (_names.length > 0) {
985
- obj.importedObject = _names;
986
- }
987
- }
988
- let tt;
989
- if (obj.importedString && !obj.importedObject) {
990
- if (obj.isNamespace) {
991
- tt = `import * as ${obj.importedString} from "${obj.source}";`;
992
- }
993
- else {
994
- tt = `import ${obj.importedString} from "${obj.source}";`;
995
- }
996
- }
997
- if (!obj.importedString && obj.importedObject) {
998
- tt = `import { ${obj.importedObject.join(", ")} } from "${obj.source}";`;
999
- }
1000
- if (tt) {
1001
- removedStatements.push(tt);
1002
- return factory.createEmptyStatement();
1003
- }
1004
- }
1005
- }
1006
- }
1007
- // --------- Visitor Return ------------------//
1008
- return typescript_1.default.visitEachChild(node, visit, context);
1009
- };
1010
- return visit;
1011
- };
1012
- //src/lib/bundle/index.ts
1013
- // ------------------------------------------------------------------------------------//
1014
- /**
1015
- * Bundles a TypeScript project into a single file.
1016
- * This function takes a {@link CollatedPoint} object as input and returns a {@link BundleResultPoint} object.
1017
- * The function applies the following steps:
1018
- * 1. Call dependency plugins.
1019
- * 2. Handle duplicates.
1020
- * 3. Handling anonymous imports and exports.
1021
- * 4. Remove Imports.
1022
- * 5. Remove Exports from dependencies only.
1023
- * 6. Handle imported statements.
1024
- * 7. Create final content.
1025
- * 8. Call pre-process plugins.
1026
- * 9. Returns.
1027
- * @param {CollatedPoint} point - A {@link CollatedPoint} object.
1028
- * @returns {Promise<BundleResultPoint>} - A promise resolves with a {@link BundleResultPoint} object.
1029
- */
1030
- async function bundler(point) {
1031
- let depsFiles = point.depFiles;
1032
- const reName = point.rename;
1033
- const compilerOptions = point.tsOptions.default;
1034
- const plugins = point.plugins;
1035
- // construct maps
1036
- const namesMap = new Map();
1037
- const callNameMap = [];
1038
- const importNameMap = [];
1039
- const exportNameMap = [];
1040
- const exportDefaultExportNameMap = [];
1041
- const exportDefaultImportNameMap = [];
1042
- let removedStatements = [];
1043
- const duplicate = async (reName) => {
1044
- if (reName) {
1045
- // order is important here
1046
- const re_name = (0, resolves_1.default)([
1047
- // collector
1048
- [bundleCreator, duplicateCollectionVisitor, compilerOptions, namesMap],
1049
- // update
1050
- [
1051
- bundleCreator,
1052
- duplicateUpdateVisitor,
1053
- compilerOptions,
1054
- namesMap,
1055
- callNameMap,
1056
- ],
1057
- // call exp
1058
- [
1059
- bundleCreator,
1060
- duplicateCallExpressionVisitor,
1061
- compilerOptions,
1062
- callNameMap,
1063
- importNameMap,
1064
- ],
1065
- // export exp
1066
- [
1067
- bundleCreator,
1068
- duplicateExportExpressionVisitor,
1069
- compilerOptions,
1070
- importNameMap,
1071
- exportNameMap,
1072
- ],
1073
- // import exp
1074
- [
1075
- bundleCreator,
1076
- duplicateImportExpressionVisitor,
1077
- compilerOptions,
1078
- exportNameMap,
1079
- importNameMap,
1080
- ],
1081
- // export exp again
1082
- [
1083
- bundleCreator,
1084
- duplicateExportExpressionVisitor,
1085
- compilerOptions,
1086
- importNameMap,
1087
- exportNameMap,
1088
- ],
1089
- // export exp again
1090
- [
1091
- bundleCreator,
1092
- duplicateExportExpressionVisitor,
1093
- compilerOptions,
1094
- importNameMap,
1095
- exportNameMap,
1096
- ],
1097
- ]); // re_name
1098
- const re_name_call = await re_name.concurrent();
1099
- for (const call of re_name_call) {
1100
- await utils_1.default.wait(500);
1101
- depsFiles = depsFiles.map(call);
1102
- }
1103
- }
1104
- else {
1105
- let _err = false;
1106
- const un_rename = (0, resolves_1.default)([
1107
- // collector
1108
- [bundleCreator, duplicateCollectionVisitor, compilerOptions, namesMap],
1109
- ]);
1110
- const un_rename_call = await un_rename.concurrent();
1111
- depsFiles.map(un_rename_call[0]);
1112
- await utils_1.default.wait(1000);
1113
- namesMap.forEach((files, name) => {
1114
- if (files.size > 1) {
1115
- _err = true;
1116
- console.warn(`Name -> ${name} declared in multiple files :`);
1117
- // biome-ignore lint/suspicious/useIterableCallbackReturn : just log warn
1118
- files.forEach((f) => console.warn(` - ${f.file}`));
1119
- }
1120
- });
1121
- await utils_1.default.wait(1000);
1122
- if (_err) {
1123
- process.exit(1);
1124
- }
1125
- }
1126
- };
1127
- // 1. Call dependency plugins
1128
- if (plugins.length) {
1129
- for (let plugin of plugins) {
1130
- plugin = typeof plugin === "function" ? plugin() : plugin;
1131
- if (plugin.type === "dependency") {
1132
- if (plugin.async) {
1133
- depsFiles = await plugin.func(depsFiles);
1134
- }
1135
- else {
1136
- depsFiles = plugin.func(depsFiles);
1137
- }
1138
- }
1139
- }
1140
- } //--
1141
- await utils_1.default.wait(1000);
1142
- // 2. Handle duplicates
1143
- await duplicate(reName);
1144
- // 3. Handling anonymous imports and exports
1145
- const anonymous = (0, resolves_1.default)([
1146
- [
1147
- bundleCreator,
1148
- anonymousExportVisitor,
1149
- compilerOptions,
1150
- exportDefaultExportNameMap,
1151
- ],
1152
- [
1153
- bundleCreator,
1154
- anonymousImportVisitor,
1155
- compilerOptions,
1156
- exportDefaultImportNameMap,
1157
- exportDefaultImportNameMap,
1158
- ],
1159
- [
1160
- bundleCreator,
1161
- anonymousCallExpressionVisitor,
1162
- compilerOptions,
1163
- exportDefaultImportNameMap,
1164
- ],
1165
- ]);
1166
- const anonymousCall = await anonymous.concurrent();
1167
- for (const call of anonymousCall) {
1168
- depsFiles = depsFiles.map(call);
1169
- }
1170
- await utils_1.default.wait(1000);
1171
- // 4. Remove Imports
1172
- const removeImports = (0, resolves_1.default)([
1173
- [bundleCreator, removeImportsVisitor, compilerOptions, removedStatements],
1174
- ]);
1175
- const removeImport = await removeImports.concurrent();
1176
- depsFiles = depsFiles.map(removeImport[0]);
1177
- await utils_1.default.wait(500);
1178
- // 5. Remove Exports from dependencies only
1179
- const removeExports = (0, resolves_1.default)([
1180
- [bundleCreator, removeExportsVisitor, compilerOptions],
1181
- ]);
1182
- const removeExport = await removeExports.concurrent();
1183
- // not remove exports from entry file
1184
- const deps_files = depsFiles.slice(0, -1).map(removeExport[0]);
1185
- const mainFile = depsFiles.slice(-1);
1186
- // 6. Handle imported statements
1187
- // filter removed statements , that not from local like `./` or `../`
1188
- const regexp = /["']((?!\.\/|\.\.\/)[^"']+)["']/;
1189
- removedStatements = removedStatements.filter((i) => regexp.test(i));
1190
- removedStatements = mergeImportsStatement(removedStatements);
1191
- // 7. Create final content
1192
- // make sure all imports are at the top of file
1193
- const importStatements = removedStatements.join("\n").trim();
1194
- const depFilesContent = deps_files
1195
- .map((i) => {
1196
- const file = `//${node_path_1.default.relative(process.cwd(), i.file)}`;
1197
- return `${file}\n${i.content}`;
1198
- })
1199
- .join("\n")
1200
- .trim();
1201
- const mainFileContent = mainFile
1202
- .map((i) => {
1203
- const file = `//${node_path_1.default.relative(process.cwd(), i.file)}`;
1204
- return `${file}\n${i.content}`;
1205
- })
1206
- .join("\n")
1207
- .trim();
1208
- await utils_1.default.wait(1000);
1209
- // text join order is important here
1210
- let content = `${importStatements}\n${depFilesContent}\n${mainFileContent}`;
1211
- // 8. Call pre-process plugins
1212
- if (plugins.length) {
1213
- for (let plugin of plugins) {
1214
- plugin = typeof plugin === "function" ? plugin() : plugin;
1215
- if (plugin.type === "pre-process") {
1216
- if (plugin.async) {
1217
- content = await plugin.func(content);
1218
- }
1219
- else {
1220
- content = plugin.func(content);
1221
- }
1222
- }
1223
- }
1224
- } //--
1225
- // 9. Returns
1226
- return { bundledContent: content, ...point };
1227
- }
1228
- async function bundle(object) {
1229
- const points = [];
1230
- for (const point of object.points) {
1231
- const _point = await bundler(point);
1232
- points.push(_point);
1233
- }
1234
- return {
1235
- points,
1236
- allowUpdatePackageJson: object.allowUpdatePackageJson,
1237
- };
1238
- }
1239
- //src/lib/compile/host.ts
1240
- /**
1241
- * Creates a ts.CompilerHost that can be used with the typescript compiler.
1242
- * This host is designed to be used with in-memory compilation and will
1243
- * return the source file for the given fileName and will write all output
1244
- * files to the createdFiles object.
1245
- * @param {string} sourceCode - the source code to compile
1246
- * @param {string} fileName - the name of the file to compile
1247
- * @returns {{createdFiles: Record<string, string>, host: ts.CompilerHost}}
1248
- */
1249
- function createHost(sourceCode, fileName) {
1250
- const createdFiles = {};
1251
- const host = {
1252
- getSourceFile: (file, languageVersion) => {
1253
- if (file === fileName) {
1254
- return typescript_1.default.createSourceFile(file, sourceCode, languageVersion);
1255
- }
1256
- return undefined;
1257
- },
1258
- writeFile: (fileName, contents) => {
1259
- createdFiles[fileName] = contents;
1260
- },
1261
- getDefaultLibFileName: (options) => typescript_1.default.getDefaultLibFilePath(options),
1262
- getCurrentDirectory: () => "",
1263
- getDirectories: () => [],
1264
- fileExists: (file) => file === fileName,
1265
- readFile: (file) => (file === fileName ? sourceCode : undefined),
1266
- getCanonicalFileName: (file) => file,
1267
- useCaseSensitiveFileNames: () => true,
1268
- getNewLine: () => "\n",
1269
- };
1270
- return { createdFiles, host };
1271
- }
1272
- //src/lib/compile/package.ts
1273
- const isCjs = (files) => files.commonjs && files.commonjsTypes;
1274
- const isEsm = (files) => files.esm && files.esmTypes;
1275
- /**
1276
- * Builds a package exports mapping for the given output files and export path.
1277
- *
1278
- * Produces the appropriate export shape based on whether CommonJS and/or ESM
1279
- * artifacts are present, including their default entry points and type
1280
- * definitions. If neither format is available, returns an empty object.
1281
- *
1282
- * @param files - The build output file paths for CommonJS/ESM and their types.
1283
- * @param exportPath - The subpath export key (e.g. "." or "./feature").
1284
- * @returns A {@link Exports} object describing the package exports map.
1285
- */
1286
- function getExports(files, exportPath) {
1287
- return isCjs(files) && isEsm(files)
1288
- ? {
1289
- [exportPath]: {
1290
- import: {
1291
- types: `./${node_path_1.default.relative(process.cwd(), files.esmTypes)}`,
1292
- default: `./${node_path_1.default.relative(process.cwd(), files.esm)}`,
1293
- },
1294
- require: {
1295
- types: `./${node_path_1.default.relative(process.cwd(), files.commonjsTypes)}`,
1296
- default: `./${node_path_1.default.relative(process.cwd(), files.commonjs)}`,
1297
- },
1298
- },
1299
- }
1300
- : isCjs(files) && !isEsm(files)
1301
- ? {
1302
- [exportPath]: {
1303
- require: {
1304
- types: `./${node_path_1.default.relative(process.cwd(), files.commonjsTypes)}`,
1305
- default: `./${node_path_1.default.relative(process.cwd(), files.commonjs)}`,
1306
- },
1307
- },
1308
- }
1309
- : !isCjs(files) && isEsm(files)
1310
- ? {
1311
- [exportPath]: {
1312
- import: {
1313
- types: `./${node_path_1.default.relative(process.cwd(), files.esmTypes)}`,
1314
- default: `./${node_path_1.default.relative(process.cwd(), files.esm)}`,
1315
- },
1316
- },
1317
- }
1318
- : {};
1319
- }
1320
- /**
1321
- * Writes an updated `package.json` based on output files and export path.
1322
- *
1323
- * Determines module type (ESM/CommonJS), adjusts `main`, `module`, `types`,
1324
- * and `exports` fields, and preserves other existing fields from the
1325
- * current `package.json`.
1326
- *
1327
- * @param files - The generated output files used to populate entry points.
1328
- * @param exportPath - The export path for subpath exports; "." denotes main export.
1329
- */
1330
- async function writePackage(files, exportPath) {
1331
- let isMain = true;
1332
- if (exportPath !== ".") {
1333
- isMain = false;
1334
- }
1335
- const pkgFile = typescript_1.default.sys.resolvePath("package.json");
1336
- const _pkgtext = node_fs_1.default.readFileSync(pkgFile, "utf8");
1337
- const pkgtext = JSON.parse(_pkgtext);
1338
- let { name, version, description, main, module, type, types, exports, ...rest } = pkgtext;
1339
- await utils_1.default.wait(500);
1340
- type = "module";
1341
- let _main = {};
1342
- let _module = {};
1343
- let _types = {};
1344
- let _exports = {};
1345
- if (isMain) {
1346
- _main = files.main
1347
- ? { main: node_path_1.default.relative(process.cwd(), files.main) }
1348
- : {};
1349
- _module = files.module
1350
- ? { module: node_path_1.default.relative(process.cwd(), files.module) }
1351
- : {};
1352
- _types = files.types
1353
- ? { types: node_path_1.default.relative(process.cwd(), files.types) }
1354
- : {};
1355
- _exports = { exports: { ...getExports(files, exportPath) } };
1356
- }
1357
- else {
1358
- _main = main ? { main: main } : {};
1359
- _module = module ? { module: module } : {};
1360
- _types = types ? { types: types } : {};
1361
- const normalizedExports = exports && typeof exports === "object" && !Array.isArray(exports)
1362
- ? { ...exports }
1363
- : {};
1364
- _exports = {
1365
- exports: { ...normalizedExports, ...getExports(files, exportPath) },
1366
- };
1367
- }
1368
- await utils_1.default.wait(1000);
1369
- const pkgJson = {
1370
- name,
1371
- version,
1372
- description,
1373
- type,
1374
- ..._main,
1375
- ..._types,
1376
- ..._module,
1377
- ..._exports,
1378
- ...rest,
1379
- };
1380
- utils_1.default.writeCompileFile(pkgFile, JSON.stringify(pkgJson, null, 2));
1381
- }
1382
- //src/lib/compile/index.ts
1383
- function splitCamelCase(str) {
1384
- const splitString = str
1385
- .replace(/([a-z])([A-Z])/g, "$1 $2")
1386
- .replace(/(_|-|\/)([a-z] || [A-Z])/g, " ")
1387
- .replace(/([A-Z])/g, (match) => match.toLowerCase())
1388
- .replace(/^([a-z])/, (match) => match.toUpperCase());
1389
- return splitString;
1390
- }
1391
- class Compiler {
1392
- constructor(object) {
1393
- this.object = object;
1394
- this.files = {
1395
- commonjs: undefined,
1396
- commonjsTypes: undefined,
1397
- esm: undefined,
1398
- esmTypes: undefined,
1399
- main: undefined,
1400
- module: undefined,
1401
- types: undefined,
1402
- };
1403
- }
1404
- _isUpdate() {
1405
- return this.object.allowUpdatePackageJson;
1406
- }
1407
- async _commonjs(point) {
1408
- const isMain = point.exportPath === ".";
1409
- const _name = isMain ? "Main" : splitCamelCase(point.exportPath.slice(2));
1410
- console.time(tcolor_1.default.cyan(`Compiled commonjs for ${_name} export path`));
1411
- // init
1412
- const fileName = point.fileName;
1413
- const sourceCode = point.bundledContent;
1414
- const format = point.format;
1415
- const plugins = point.plugins;
1416
- const compilerOptions = point.tsOptions.cjs;
1417
- // create host
1418
- const _host = createHost(sourceCode, fileName);
1419
- const createdFiles = _host.createdFiles;
1420
- const host = _host.host;
1421
- const program = typescript_1.default.createProgram([fileName], compilerOptions, host);
1422
- program.emit();
1423
- Object.entries(createdFiles).map(async ([outName, content]) => {
1424
- // ------------------------------------
1425
- if (plugins.length) {
1426
- for (let plugin of plugins) {
1427
- plugin = typeof plugin === "function" ? plugin() : plugin;
1428
- if (plugin.type === "post-process") {
1429
- if (plugin.async) {
1430
- content = await plugin.func(content, outName);
1431
- }
1432
- else {
1433
- content = plugin.func(content, outName);
1434
- }
1435
- }
1436
- }
1437
- }
1438
- if (this._isUpdate()) {
1439
- if (outName.match(/.js/g)) {
1440
- this.files.commonjs = outName.replace(/.js/g, ".cjs");
1441
- }
1442
- if (outName.match(/.d.ts/g)) {
1443
- this.files.commonjsTypes = outName.replace(/.d.ts/g, ".d.cts");
1444
- }
1445
- if (isMain && (format === "both" || format === "commonjs")) {
1446
- if (this.files.commonjs)
1447
- this.files.main = this.files.commonjs;
1448
- if (this.files.commonjsTypes)
1449
- this.files.types = this.files.commonjsTypes;
1450
- }
1451
- }
1452
- outName = outName.replace(/.js/g, ".cjs");
1453
- outName = outName.replace(/.map.js/g, ".map.cjs");
1454
- outName = outName.replace(/.d.ts/g, ".d.cts");
1455
- await utils_1.default.wait(500);
1456
- if (format === "commonjs") {
1457
- await utils_1.default.clearFolder(node_path_1.default.dirname(outName));
1458
- }
1459
- await utils_1.default.writeCompileFile(outName, content);
1460
- });
1461
- console.timeEnd(tcolor_1.default.cyan(`Compiled commonjs for ${_name} export path`));
1462
- }
1463
- async _esm(point) {
1464
- const isMain = point.exportPath === ".";
1465
- const _name = isMain ? "Main" : splitCamelCase(point.exportPath.slice(2));
1466
- console.time(tcolor_1.default.cyan(`Compiled esm for ${_name} export path`));
1467
- // init
1468
- const fileName = point.fileName;
1469
- const sourceCode = point.bundledContent;
1470
- const format = point.format;
1471
- const plugins = point.plugins;
1472
- const compilerOptions = point.tsOptions.esm;
1473
- // create host
1474
- const _host = createHost(sourceCode, fileName);
1475
- const createdFiles = _host.createdFiles;
1476
- const host = _host.host;
1477
- const program = typescript_1.default.createProgram([fileName], compilerOptions, host);
1478
- program.emit();
1479
- Object.entries(createdFiles).map(async ([outName, content]) => {
1480
- if (plugins.length) {
1481
- for (let plugin of plugins) {
1482
- plugin = typeof plugin === "function" ? plugin() : plugin;
1483
- if (plugin.type === "post-process") {
1484
- if (plugin.async) {
1485
- content = await plugin.func(content, outName);
1486
- }
1487
- else {
1488
- content = plugin.func(content, outName);
1489
- }
1490
- }
1491
- }
1492
- }
1493
- // ------------------------------------------
1494
- if (this._isUpdate()) {
1495
- if (outName.match(/.js/g)) {
1496
- this.files.esm = outName.replace(/.js/g, ".mjs");
1497
- }
1498
- if (outName.match(/.d.ts/g)) {
1499
- this.files.esmTypes = outName.replace(/.d.ts/g, ".d.mts");
1500
- }
1501
- if (isMain && format === "both" && this.files.esm) {
1502
- this.files.module = this.files.esm;
1503
- }
1504
- }
1505
- outName = outName.replace(/.js/g, ".mjs");
1506
- outName = outName.replace(/.map.js/g, ".map.mjs");
1507
- outName = outName.replace(/.d.ts/g, ".d.mts");
1508
- await utils_1.default.wait(500);
1509
- if (format !== "commonjs") {
1510
- await utils_1.default.clearFolder(node_path_1.default.dirname(outName));
1511
- }
1512
- await utils_1.default.writeCompileFile(outName, content);
1513
- });
1514
- console.timeEnd(tcolor_1.default.cyan(`Compiled esm for ${_name} export path`));
1515
- }
1516
- /**
1517
- * Compile bundled code for each entry point.
1518
- * This function will iterate through each entry point and compile code according to the format specified.
1519
- * If the format is "commonjs", it will compile the code into commonjs format.
1520
- * If the format is "esm", it will compile the code into esm format.
1521
- * If the format is "both", it will compile the code into both commonjs and esm formats.
1522
- * If the allowUpdatePackageJson flag is set to true, it will update the package.json according to the compiled file paths.
1523
- */
1524
- async compile() {
1525
- for (const point of this.object.points) {
1526
- await utils_1.default.wait(500);
1527
- switch (point.format) {
1528
- case "commonjs":
1529
- await this._commonjs(point);
1530
- if (this._isUpdate()) {
1531
- await writePackage(this.files, point.exportPath);
1532
- }
1533
- break;
1534
- case "esm":
1535
- await this._esm(point);
1536
- if (this._isUpdate()) {
1537
- await writePackage(this.files, point.exportPath);
1538
- }
1539
- break;
1540
- case "both":
1541
- await this._esm(point);
1542
- await utils_1.default.wait(1000);
1543
- await this._commonjs(point);
1544
- if (this._isUpdate()) {
1545
- await writePackage(this.files, point.exportPath);
1546
- }
1547
- break;
1548
- }
1549
- await utils_1.default.wait(500);
1550
- }
1551
- }
1552
- }
1553
- //src/lib/init/checks.ts
1554
- var checks;
1555
- (function (checks) {
1556
- /**
1557
- * Checks the given dependencies for type errors. If any type errors are found,
1558
- * an error message is printed to the console and the process exits with a code of 1.
1559
- * @param dep The dependencies to check for type errors
1560
- * @param compilerOptions The compiler options to use when checking for type errors
1561
- * @returns true if no type errors are found, false otherwise
1562
- */
1563
- function typesCheck(dep, compilerOptions) {
1564
- if (!compilerOptions.noCheck) {
1565
- const filePaths = dep.map((i) => i.file);
1566
- let _err = false;
1567
- // Create program
1568
- const program = typescript_1.default.createProgram(filePaths, compilerOptions);
1569
- // Check each file individually for immediate feedback
1570
- for (const filePath of filePaths) {
1571
- const sourceFile = program.getSourceFile(filePath);
1572
- if (!sourceFile) {
1573
- console.error(tcolor_1.default.magenta(`File not found: ${filePath}`));
1574
- typescript_1.default.sys.exit(1);
1575
- }
1576
- const diagnostics = [
1577
- ...program.getSyntacticDiagnostics(sourceFile),
1578
- ...program.getSemanticDiagnostics(sourceFile),
1579
- ...program.getDeclarationDiagnostics(sourceFile),
1580
- ];
1581
- if (diagnostics.length > 0) {
1582
- const formatHost = {
1583
- getCurrentDirectory: () => process.cwd(),
1584
- getCanonicalFileName: (fileName) => fileName,
1585
- getNewLine: () => typescript_1.default.sys.newLine,
1586
- };
1587
- console.error(typescript_1.default.formatDiagnosticsWithColorAndContext(diagnostics, formatHost));
1588
- _err = true;
1589
- }
1590
- }
1591
- if (_err) {
1592
- typescript_1.default.sys.exit(1);
1593
- }
1594
- else {
1595
- return true;
1596
- }
1597
- }
1598
- }
1599
- /**
1600
- * Check the module type of the given dependencies.
1601
- * @param _dep The dependencies to check for module type
1602
- * @returns true if all dependencies are ESM, false otherwise
1603
- */
1604
- function moduleType(_dep) {
1605
- let _esmCount = 0;
1606
- let cjsCount = 0;
1607
- let unknownCount = 0;
1608
- for (const dep of _dep) {
1609
- try {
1610
- // Create a TypeScript source file
1611
- const sourceFile = typescript_1.default.createSourceFile(dep.file, dep.content, typescript_1.default.ScriptTarget.Latest, true);
1612
- let hasESMImports = false;
1613
- let hasCommonJS = false;
1614
- // Walk through the AST to detect module syntax
1615
- function walk(node) {
1616
- // Check for ESM import/export syntax
1617
- if (typescript_1.default.isImportDeclaration(node) ||
1618
- typescript_1.default.isImportEqualsDeclaration(node) ||
1619
- typescript_1.default.isExportDeclaration(node) ||
1620
- typescript_1.default.isExportSpecifier(node) ||
1621
- typescript_1.default.isExportAssignment(node)) {
1622
- hasESMImports = true;
1623
- }
1624
- // Check for export modifier on declarations
1625
- if ((typescript_1.default.isVariableStatement(node) ||
1626
- typescript_1.default.isFunctionDeclaration(node) ||
1627
- typescript_1.default.isInterfaceDeclaration(node) ||
1628
- typescript_1.default.isTypeAliasDeclaration(node) ||
1629
- typescript_1.default.isEnumDeclaration(node) ||
1630
- typescript_1.default.isClassDeclaration(node)) &&
1631
- node.modifiers?.some((mod) => mod.kind === typescript_1.default.SyntaxKind.ExportKeyword)) {
1632
- hasESMImports = true;
1633
- }
1634
- // Check for CommonJS require/exports
1635
- if (typescript_1.default.isCallExpression(node)) {
1636
- if (typescript_1.default.isIdentifier(node.expression) &&
1637
- node.expression.text === "require" &&
1638
- node.arguments.length > 0) {
1639
- hasCommonJS = true;
1640
- }
1641
- }
1642
- // Check for module.exports or exports.xxx
1643
- if (typescript_1.default.isPropertyAccessExpression(node)) {
1644
- const text = node.getText(sourceFile);
1645
- if (text.startsWith("module.exports") ||
1646
- text.startsWith("exports.")) {
1647
- hasCommonJS = true;
1648
- }
1649
- }
1650
- // Continue walking the AST
1651
- typescript_1.default.forEachChild(node, walk);
1652
- }
1653
- walk(sourceFile);
1654
- // Determine the module format based on what we found
1655
- if (hasESMImports && !hasCommonJS) {
1656
- _esmCount++;
1657
- }
1658
- else if (hasCommonJS && !hasESMImports) {
1659
- cjsCount++;
1660
- }
1661
- else if (hasESMImports && hasCommonJS) {
1662
- // Mixed - probably ESM with dynamic imports or similar
1663
- _esmCount++;
1664
- }
1665
- }
1666
- catch (error) {
1667
- console.error(tcolor_1.default.magenta(`Error checking module format for ${dep.file} : \n ${error}`));
1668
- unknownCount++;
1669
- }
1670
- }
1671
- if (unknownCount) {
1672
- console.error(tcolor_1.default.magenta("Unknown error when checking module types in the dependencies tree."));
1673
- typescript_1.default.sys.exit(1);
1674
- }
1675
- if (cjsCount) {
1676
- console.error(tcolor_1.default.magenta("The package detects CommonJs format in the dependencies tree, that unsupported."));
1677
- typescript_1.default.sys.exit(1);
1678
- }
1679
- return true;
1680
- }
1681
- function ext(_dep) {
1682
- const tsExt = new Set([".ts", ".mts", ".cts", ".tsx"]);
1683
- for (const dep of _dep) {
1684
- const ext = node_path_1.default.extname(dep.file);
1685
- if (!tsExt.has(ext)) {
1686
- console.error(tcolor_1.default.magenta(`${dep.file} has no valid TypeScript extension`));
1687
- typescript_1.default.sys.exit(1);
1688
- }
1689
- }
1690
- return true;
1691
- }
1692
- async function init(_dep, options) {
1693
- const res = (0, resolves_1.default)([
1694
- [ext, _dep],
1695
- [moduleType, _dep],
1696
- [typesCheck, _dep, options],
1697
- ]);
1698
- const results = await res.concurrent();
1699
- return results.every((r) => r === true);
1700
- }
1701
- checks.init = init;
1702
- })(checks || (checks = {}));
1703
- //src/lib/init/config.ts
1704
- // -------------
1705
- const getConfigPath = () => {
1706
- const fileNames = ["susee.config.ts", "susee.config.js", "susee.config.mjs"];
1707
- let configFile;
1708
- for (const file of fileNames) {
1709
- const _file = typescript_1.default.sys.resolvePath(file);
1710
- if (typescript_1.default.sys.fileExists(_file)) {
1711
- configFile = _file;
1712
- break;
1713
- }
1714
- }
1715
- return configFile;
1716
- };
1717
- //---------
1718
- function checkEntries(entries) {
1719
- if (entries.length < 1) {
1720
- console.error(tcolor_1.default.magenta(`No entry found in susee.config file, at least one entry required`));
1721
- typescript_1.default.sys.exit(1);
1722
- }
1723
- const objectStore = {};
1724
- const duplicateExportPaths = [];
1725
- for (const obj of entries) {
1726
- const value = obj.exportPath;
1727
- if (objectStore[value]) {
1728
- duplicateExportPaths.push(`"${value}"`);
1729
- }
1730
- else {
1731
- objectStore[value] = true;
1732
- }
1733
- }
1734
- if (duplicateExportPaths.length > 0) {
1735
- console.error(tcolor_1.default.magenta(`Duplicate export paths/path (${duplicateExportPaths.join(",")}) found in your susee.config file , that will error for bundled output`));
1736
- typescript_1.default.sys.exit(1);
1737
- }
1738
- for (const obj of entries) {
1739
- if (!typescript_1.default.sys.fileExists(typescript_1.default.sys.resolvePath(obj.entry))) {
1740
- console.error(tcolor_1.default.magenta(`Entry file ${obj.entry} dose not exists.`));
1741
- typescript_1.default.sys.exit(1);
1742
- }
1743
- }
1744
- }
1745
- /**
1746
- * Get SuSee configuration from susee.config file (susee.config.ts, susee.config.js, susee.config.mjs)
1747
- * @returns {Promise<ConfigReturns>} - SuSee configuration
1748
- * @throws {Error} - when no susee.config file found
1749
- */
1750
- async function getConfig() {
1751
- const configPath = getConfigPath();
1752
- if (configPath === undefined) {
1753
- console.error(tcolor_1.default.magenta(`No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found`));
1754
- typescript_1.default.sys.exit(1);
1755
- }
1756
- const _default = await Promise.resolve(`${configPath}`).then(s => __importStar(require(s)));
1757
- const config = _default.default;
1758
- const entryCheck = (0, resolves_1.default)([[checkEntries, config.entryPoints]]);
1759
- await entryCheck.series();
1760
- await utils_1.default.wait(1000);
1761
- const points = [];
1762
- for (const ent of config.entryPoints) {
1763
- const point = {
1764
- entry: ent.entry,
1765
- exportPath: ent.exportPath,
1766
- format: ent.format ?? "esm",
1767
- tsconfigFilePath: ent.tsconfigFilePath ?? undefined,
1768
- renameDuplicates: ent.renameDuplicates ?? true,
1769
- // TODO check for defined out dir here or in config.ts
1770
- outDir: config.outDir ?? "dist",
1771
- };
1772
- points.push(point);
1773
- }
1774
- return {
1775
- points,
1776
- plugins: config.plugins ?? [],
1777
- allowUpdatePackageJson: config.allowUpdatePackageJson ?? true,
1778
- };
1779
- }
1780
- //src/lib/init/deps.ts
1781
- //---------------
1782
- async function fileSizes(path) {
1783
- const s = await node_fs_1.default.promises.stat(path);
1784
- const logical = s.size; // bytes in file
1785
- const allocated = s.blocks !== null ? s.blocks * 512 : null; // bytes actually allocated (POSIX)
1786
- return { logical, allocated };
1787
- }
1788
- const checkExport = (str, file) => {
1789
- const esmRex = /export default .*/gm;
1790
- const cjsRex = /export = .*/gm;
1791
- const ctsRex = /.cts/g;
1792
- if (str.match(esmRex) || (str.match(cjsRex) && file.match(ctsRex))) {
1793
- return true;
1794
- }
1795
- else {
1796
- return false;
1797
- }
1798
- };
1799
- /**
1800
- * Generate dependencies graph for given entry file.
1801
- *
1802
- * This function will return an array of dependencies file objects.
1803
- * Each object will contain the following properties:
1804
- * - file: path to the file
1805
- * - content: content of the file
1806
- * - length: length of the content in bytes
1807
- * - includeDefExport: whether the file includes export default or export = statement
1808
- * - size: an object containing the following properties:
1809
- * - logical: size of the file in bytes
1810
- * - allocated: size of the file in bytes on disk
1811
- * - utf8: size of the file in bytes when encoded in utf8
1812
- * - buffBytes: size of the file in bytes when encoded in buffer
1813
- *
1814
- * @param {string} entryFile - path to the entry file
1815
- * @param {SuseePlugins} plugins - array of plugins
1816
- * @returns {Promise<DepsFiles>}
1817
- */
1818
- async function generateDependencies(entryFile, plugins) {
1819
- const deps = await (0, dependencies_1.default)(entryFile);
1820
- const sorted = deps.sort(); // get dependencies graph
1821
- let depsFiles = [];
1822
- await utils_1.default.wait(1000);
1823
- for (const dep of sorted) {
1824
- const file = typescript_1.default.sys.resolvePath(dep);
1825
- const content = await node_fs_1.default.promises.readFile(file, "utf8");
1826
- const s = await fileSizes(file);
1827
- const length = content.length;
1828
- const includeDefExport = checkExport(content, file);
1829
- const _files = {
1830
- file,
1831
- content,
1832
- length,
1833
- includeDefExport,
1834
- size: {
1835
- logical: s.logical,
1836
- allocated: s.allocated,
1837
- utf8: new TextEncoder().encode(content).length,
1838
- buffBytes: node_buffer_1.Buffer.byteLength(content, "utf8"),
1839
- },
1840
- };
1841
- depsFiles.push(_files);
1842
- }
1843
- // call dependency plugins
1844
- if (plugins.length) {
1845
- for (const plugin of plugins) {
1846
- const _plug = typeof plugin === "function" ? plugin() : plugin;
1847
- if (_plug.type === "dependency") {
1848
- if (_plug.async) {
1849
- depsFiles = await _plug.func(depsFiles);
1850
- }
1851
- else {
1852
- depsFiles = _plug.func(depsFiles);
1853
- }
1854
- await utils_1.default.wait(1000);
1855
- }
1856
- }
1857
- }
1858
- return depsFiles;
1859
- }
1860
- //src/lib/init/tsCompilerOptions.ts
1861
- class GetOptions {
1862
- constructor(point) {
1863
- this._point = point;
1864
- this._options = {};
1865
- }
1866
- __init() {
1867
- const __opts = new tsconfig_1.default(this._point.tsconfigFilePath);
1868
- const __outDir = this._point.exportPath === "."
1869
- ? this._point.outDir
1870
- : `${this._point.outDir}/${this._point.exportPath.slice(2)}`;
1871
- __opts.removeCompilerOption("rootDir");
1872
- __opts.removeCompilerOption("module");
1873
- __opts.editCompilerOptions({
1874
- moduleResolution: typescript_1.default.ModuleResolutionKind.NodeNext,
1875
- outDir: __outDir,
1876
- });
1877
- this._options = __opts.getCompilerOptions();
1878
- }
1879
- __init2() {
1880
- this.__init();
1881
- let { types, lib, ...restOptions } = this._options;
1882
- // normalize types into an array
1883
- if (types) {
1884
- if (!types.includes("node")) {
1885
- types = ["node", ...types];
1886
- }
1887
- }
1888
- else {
1889
- types = ["node"];
1890
- }
1891
- if (lib) {
1892
- lib = [...new Set(["ESNext", ...lib])];
1893
- }
1894
- else {
1895
- lib = ["ESNext"];
1896
- }
1897
- return { types, lib, ...restOptions };
1898
- }
1899
- get commonjs() {
1900
- const opts = this.__init2();
1901
- const { module, ...rest } = opts;
1902
- return { module: typescript_1.default.ModuleKind.CommonJS, ...rest };
1903
- }
1904
- get esm() {
1905
- const opts = this.__init2();
1906
- const { module, ...rest } = opts;
1907
- return { module: typescript_1.default.ModuleKind.ES2020, ...rest };
1908
- }
1909
- get default() {
1910
- return this.__init2();
1911
- }
1912
- }
1913
- /**
1914
- * Returns an instance of GetOptions, which provides various methods
1915
- * to generate different sets of compiler options based on the
1916
- * given Point.
1917
- *
1918
- * @param {Point} point - The point to generate compiler options for.
1919
- * @returns {GetOptions}
1920
- */
1921
- function getOptions(point) {
1922
- return new GetOptions(point);
1923
- }
1924
- //src/lib/init/index.ts
1925
- /**
1926
- * This function takes a susee configuration object and returns a promise that resolves with a `CollatedReturn` object.
1927
- * The function iterates over the `points` array in the susee configuration object.
1928
- * For each point, it generates the dependencies using the `generateDependencies` function.
1929
- * It then checks if the dependencies are valid using the `checks.init` function.
1930
- * If the dependencies are invalid, it exits the process with code 1.
1931
- * If the dependencies are valid, it constructs a `CollatedPoint` object and adds it to the result array.
1932
- * Finally, it returns a `CollatedReturn` object with the result array and the `allowUpdatePackageJson` flag.
1933
- */
1934
- async function collections() {
1935
- const __config = await getConfig();
1936
- const points = __config.points;
1937
- const result = [];
1938
- for (const point of points) {
1939
- const __opts = getOptions(point);
1940
- const __deps = await generateDependencies(point.entry, __config.plugins);
1941
- const checked = await checks.init(__deps, __opts.esm);
1942
- if (!checked) {
1943
- typescript_1.default.sys.exit(1);
1944
- }
1945
- const c = {
1946
- fileName: point.entry,
1947
- exportPath: point.exportPath,
1948
- format: point.format,
1949
- rename: point.renameDuplicates,
1950
- outDir: point.outDir,
1951
- tsOptions: {
1952
- cjs: __opts.commonjs,
1953
- esm: __opts.esm,
1954
- default: __opts.default,
1955
- },
1956
- depFiles: __deps,
1957
- plugins: __config.plugins,
1958
- };
1959
- result.push(c);
1960
- }
1961
- return {
1962
- points: result,
1963
- allowUpdatePackageJson: __config.allowUpdatePackageJson,
1964
- };
1965
- }
1966
- //src/index.ts
1967
- /**
1968
- * Bundles a TypeScript project into a single file.
1969
- * The function takes a {@link SuSeeConfig} object as input and returns a promise resolves with a bundled result.
1970
- * The function applies the following steps:
1971
- * 1. Call dependency plugins.
1972
- * 2. Handle duplicates.
1973
- * 3. Handling anonymous imports and exports.
1974
- * 4. Remove Imports.
1975
- * 5. Remove Exports from dependencies only.
1976
- * 6. Handle imported statements.
1977
- * 7. Create final content.
1978
- * 8. Call pre-process plugins.
1979
- * 9. Returns.
1980
- */
1981
- async function susee() {
1982
- console.info(`${tcolor_1.default.green("Start")} : ${tcolor_1.default.cyan("bundling")}`);
1983
- const collected = await collections();
1984
- await utils_1.default.wait(1000);
1985
- const bundled = await bundle(collected);
1986
- await utils_1.default.wait(1000);
1987
- const compiler = new Compiler(bundled);
1988
- await compiler.compile();
1989
- console.info(`${tcolor_1.default.green("End")} : ${tcolor_1.default.cyan("bundling")}`);
1990
- }
1991
- //# sourceMappingURL=index.js.map
8
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,r)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(null!=t)for(var a=e(t),r=0;r<a.length;r++)"default"!==a[r]&&__createBinding(i,t,a[r]);return __setModuleDefault(i,t),i}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.susee=susee;const tsconfig_1=__importDefault(require("@suseejs/tsconfig")),dependencies_1=__importDefault(require("@suseejs/dependencies")),node_fs_1=__importDefault(require("node:fs")),node_path_1=__importDefault(require("node:path")),resolves_1=__importDefault(require("@phothinmaung/resolves")),tcolor_1=__importDefault(require("@suseejs/tcolor")),transformer_1=__importDefault(require("@suseejs/transformer")),typescript_1=__importDefault(require("typescript")),utils_1=__importDefault(require("@suseejs/utils")),node_buffer_1=require("node:buffer");function splitCamelCase(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/(_|-|\/)([a-z] || [A-Z])/g," ").replace(/([A-Z])/g,e=>e.toLowerCase()).replace(/^([a-z])/,e=>e.toUpperCase())}function uniqueName(){const e=new Map,t={setPrefix({key:i,value:a}){if(e.has(i))throw console.warn(`${i} already exist`),new Error;return e.set(i,[a,0]),t},getName(t,i){const[a,r]=e.get(t)||[],s=a?`${a}${i}_${(r??0)+1}`:`$nyein${i}_${(r??0)+1}`;return e.set(t,[a??"$nyein",(r??0)+1]),s},getPrefix(t){const[i]=e.get(t)||[];return i}};return t}const exportDefaultExportNameMap=[],exportDefaultImportNameMap=[],prefixKey="AnonymousName",genName=uniqueName().setPrefix({key:prefixKey,value:"__anonymous__"});function anonymousCallExpressionHandler(e){return({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=r=>{if(typescript_1.default.isCallExpression(r)){if(typescript_1.default.isIdentifier(r.expression)){const e=r.expression.text,a=exportDefaultImportNameMap.find(i=>i.base===e&&i.file===t);if(a)return i.updateCallExpression(r,i.createIdentifier(a.newName),r.typeArguments,r.arguments)}}else if(typescript_1.default.isPropertyAccessExpression(r)){if(typescript_1.default.isIdentifier(r.expression)){const e=r.expression.text,a=exportDefaultImportNameMap.find(i=>i.base===e&&i.file===t);if(a)return i.updatePropertyAccessExpression(r,i.createIdentifier(a.newName),r.name)}}else if(typescript_1.default.isNewExpression(r)){if(typescript_1.default.isIdentifier(r.expression)){const e=r.expression.text,a=exportDefaultImportNameMap.find(i=>i.base===e&&i.file===t);if(a)return i.updateNewExpression(r,i.createIdentifier(a.newName),r.typeArguments,r.arguments)}}else if(typescript_1.default.isExportSpecifier(r)&&typescript_1.default.isIdentifier(r.name)){const e=r.name.text,a=exportDefaultImportNameMap.find(i=>i.base===e&&i.file===t);if(a)return i.updateExportSpecifier(r,r.isTypeOnly,r.propertyName,i.createIdentifier(a.newName))}return typescript_1.default.visitEachChild(r,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}}}function anonymousExportHandler(e){return({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=s=>{const n=node_path_1.default.basename(t).split(".")[0];if((typescript_1.default.isFunctionDeclaration(s)||typescript_1.default.isClassDeclaration(s))&&void 0===s.name){let e=!1,t=!1;if(s.modifiers?.forEach(i=>{i.kind===typescript_1.default.SyntaxKind.ExportKeyword&&(e=!0),i.kind===typescript_1.default.SyntaxKind.DefaultKeyword&&(t=!0)}),e&&t){const e=genName.getName(prefixKey,n);if(exportDefaultExportNameMap.push({base:e,file:n,newName:e,isEd:!0}),typescript_1.default.isFunctionDeclaration(s))return i.updateFunctionDeclaration(s,s.modifiers,s.asteriskToken,i.createIdentifier(e),s.typeParameters,s.parameters,s.type,s.body);if(typescript_1.default.isClassDeclaration(s))return i.updateClassDeclaration(s,s.modifiers,i.createIdentifier(e),s.typeParameters,s.heritageClauses,s.members)}}else if(typescript_1.default.isExportAssignment(s)&&!s.name&&!s.isExportEquals){if(typescript_1.default.isArrowFunction(s.expression)){const e=genName.getName(prefixKey,n),t=i.createArrowFunction(s.expression.modifiers,s.expression.typeParameters,s.expression.parameters,s.expression.type,s.expression.equalsGreaterThanToken,s.expression.body),a=i.createVariableDeclaration(i.createIdentifier(e),s.expression.exclamationToken,s.expression.type,t),o=i.createVariableDeclarationList([a],typescript_1.default.NodeFlags.Const),p=i.createVariableStatement(s.expression.modifiers,o),c=i.createExportAssignment(void 0,void 0,i.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:n,newName:e,isEd:!0}),i.updateSourceFile(r,[p,c],r.isDeclarationFile,r.referencedFiles,r.typeReferenceDirectives,r.hasNoDefaultLib,r.libReferenceDirectives)}if(typescript_1.default.isObjectLiteralExpression(s.expression)){const e=genName.getName(prefixKey,n),t=i.createVariableDeclaration(i.createIdentifier(e),void 0,void 0,s.expression),a=i.createVariableDeclarationList([t],typescript_1.default.NodeFlags.Const),o=i.createVariableStatement(void 0,a),p=i.createExportAssignment(void 0,void 0,i.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:n,newName:e,isEd:!0}),i.updateSourceFile(r,[o,p],r.isDeclarationFile,r.referencedFiles,r.typeReferenceDirectives,r.hasNoDefaultLib,r.libReferenceDirectives)}if(typescript_1.default.isArrayLiteralExpression(s.expression)){const e=genName.getName(prefixKey,n),t=i.createArrayLiteralExpression(s.expression.elements,!0),a=i.createVariableDeclaration(i.createIdentifier(e),void 0,void 0,t),o=i.createVariableDeclarationList([a],typescript_1.default.NodeFlags.Const),p=i.createVariableStatement(void 0,o),c=i.createExportAssignment(void 0,void 0,i.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:n,newName:e,isEd:!0}),i.updateSourceFile(r,[p,c],r.isDeclarationFile,r.referencedFiles,r.typeReferenceDirectives,r.hasNoDefaultLib,r.libReferenceDirectives)}if(typescript_1.default.isStringLiteral(s.expression)){const e=genName.getName(prefixKey,n),t=i.createStringLiteral(s.expression.text),a=i.createVariableDeclaration(i.createIdentifier(e),void 0,void 0,t),o=i.createVariableDeclarationList([a],typescript_1.default.NodeFlags.Const),p=i.createVariableStatement(void 0,o),c=i.createExportAssignment(void 0,void 0,i.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:n,newName:e,isEd:!0}),i.updateSourceFile(r,[p,c],r.isDeclarationFile,r.referencedFiles,r.typeReferenceDirectives,r.hasNoDefaultLib,r.libReferenceDirectives)}if(typescript_1.default.isNumericLiteral(s.expression)){const e=genName.getName(prefixKey,n),t=i.createNumericLiteral(s.expression.text),a=i.createVariableDeclaration(i.createIdentifier(e),void 0,void 0,t),o=i.createVariableDeclarationList([a],typescript_1.default.NodeFlags.Const),p=i.createVariableStatement(void 0,o),c=i.createExportAssignment(void 0,void 0,i.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:n,newName:e,isEd:!0}),i.updateSourceFile(r,[p,c],r.isDeclarationFile,r.referencedFiles,r.typeReferenceDirectives,r.hasNoDefaultLib,r.libReferenceDirectives)}}return typescript_1.default.visitEachChild(s,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}}}function anonymousImportHandler(e){return({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=s=>{if(typescript_1.default.isImportDeclaration(s)){const e=s.moduleSpecifier.getText(r),a=node_path_1.default.basename(e).split(".")[0].trim();if(s.importClause?.name&&typescript_1.default.isIdentifier(s.importClause.name)){const e=s.importClause.name.text.trim(),r=exportDefaultExportNameMap.find(e=>e.file===a);if(r){exportDefaultImportNameMap.push({base:e,file:t,newName:r.newName,isEd:!0});const a=i.updateImportClause(s.importClause,s.importClause.phaseModifier,i.createIdentifier(r.newName),s.importClause.namedBindings);return i.updateImportDeclaration(s,s.modifiers,a,s.moduleSpecifier,s.attributes)}}}return typescript_1.default.visitEachChild(s,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}}}const anonymousHandler=async(e,t)=>{const i=(0,resolves_1.default)([[anonymousExportHandler,t],[anonymousImportHandler,t],[anonymousCallExpressionHandler,t]]),a=await i.concurrent();for(const t of a)e=e.map(t);return e},namesMap=new Map,callNameMap=[],importNameMap=[],exportNameMap=[];function __uniqueName(){const e=new Map;return{setPrefix({key:t,value:i}){const a=[];let r;if(e.has(t))throw console.warn(`${t} already exist`),new Error;return r=i,e.set(t,i),{getName:function(e){const t=a.length,i=r?`${r}${e}_${t+1}`:`$nyein${e}_${t+1}`;return a.push(i),i}}},getPrefix(t){if(e.has(t))return e.get(t)}}}const dupName=__uniqueName().setPrefix({key:"DuplicatesNames",value:"__duplicatesNames__"}),normalizePathKey=e=>{const t=node_path_1.default.parse(e);let i=node_path_1.default.join(t.dir,t.name);return"index"===t.name&&(i=t.dir),node_path_1.default.normalize(i)},getFileKey=e=>normalizePathKey(e),getModuleKeyFromSpecifier=(e,t,i)=>{let a="";if(a=typescript_1.default.isStringLiteral(e)?e.text:e.getText(t).replace(/^['"]|['"]$/g,""),a.startsWith(".")||a.startsWith("/")){const e=node_path_1.default.dirname(i);return normalizePathKey(node_path_1.default.resolve(e,a))}return a},callExpression=e=>({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=r=>{if(typescript_1.default.isCallExpression(r)){if(typescript_1.default.isIdentifier(r.expression)){const e=r.expression.text;let a=null;const s=callNameMap.find(i=>i.base===e&&i.file===t),n=importNameMap.find(i=>i.base===e&&i.file===t);if(s?a=s.newName:n&&(a=n.newName),a)return i.updateCallExpression(r,i.createIdentifier(a),r.typeArguments,r.arguments)}}else if(typescript_1.default.isPropertyAccessExpression(r)){if(typescript_1.default.isIdentifier(r.expression)){const e=r.expression.text;let a=null;const s=callNameMap.find(i=>i.base===e&&i.file===t),n=importNameMap.find(i=>i.base===e&&i.file===t);if(s?a=s.newName:n&&(a=n.newName),a)return i.updatePropertyAccessExpression(r,i.createIdentifier(a),r.name)}}else if(typescript_1.default.isNewExpression(r)&&typescript_1.default.isIdentifier(r.expression)){const e=r.expression.text;let a=null;const s=callNameMap.find(i=>i.base===e&&i.file===t),n=importNameMap.find(i=>i.base===e&&i.file===t);if(s?a=s.newName:n&&(a=n.newName),a)return i.updateNewExpression(r,i.createIdentifier(a),r.typeArguments,r.arguments)}return typescript_1.default.visitEachChild(r,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}},exportExpression=e=>({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=r=>{if(typescript_1.default.isExportSpecifier(r)){if(typescript_1.default.isIdentifier(r.name)){const e=r.name.text;let a=null;const s=callNameMap.find(i=>i.base===e&&i.file===t),n=importNameMap.find(i=>i.base===e&&i.file===t);if(s?(exportNameMap.push({base:e,file:getFileKey(t),newName:s.newName}),a=s.newName):n&&(a=n.newName),a)return i.updateExportSpecifier(r,r.isTypeOnly,r.propertyName,i.createIdentifier(a))}}else if(typescript_1.default.isExportAssignment(r)){const e=r.expression;if(typescript_1.default.isIdentifier(e)){const a=e.text;let s=null;const n=callNameMap.find(e=>e.base===a&&e.file===t),o=importNameMap.find(e=>e.base===a&&e.file===t);if(n?(exportNameMap.push({base:a,file:getFileKey(t),newName:n.newName}),s=n.newName):o&&(s=o.newName),s)return i.updateExportAssignment(r,r.modifiers,i.createIdentifier(s))}}return typescript_1.default.visitEachChild(r,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}},importExpression=e=>({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=s=>{if(typescript_1.default.isImportDeclaration(s)){const e=getModuleKeyFromSpecifier(s.moduleSpecifier,r,t);let a=[];if(s.importClause?.namedBindings&&typescript_1.default.isNamedImports(s.importClause.namedBindings)&&(a=s.importClause.namedBindings.elements.map(e=>e.name.text.trim())),s.importClause?.name&&typescript_1.default.isIdentifier(s.importClause.name)){const a=s.importClause.name.text.trim(),r=exportNameMap.find(t=>t.base===a&&t.file===e);if(r){importNameMap.push({base:r.base,file:t,newName:r.newName});const e=i.updateImportClause(s.importClause,s.importClause.phaseModifier,i.createIdentifier(r.newName),s.importClause.namedBindings);return i.updateImportDeclaration(s,s.modifiers,e,s.moduleSpecifier,s.attributes)}}if(a.length>0&&s.importClause&&s.importClause.namedBindings&&typescript_1.default.isNamedImports(s.importClause.namedBindings)){const a=s.importClause.namedBindings.elements.map(a=>{const r=exportNameMap.find(t=>t.base===a.name.text.trim()&&t.file===e);return r?(importNameMap.push({base:r.base,file:t,newName:r.newName}),i.updateImportSpecifier(a,a.isTypeOnly,a.propertyName,i.createIdentifier(r.newName))):a}),r=i.updateNamedImports(s.importClause.namedBindings,a),n=i.updateImportClause(s.importClause,s.importClause.phaseModifier,s.importClause.name,r);return i.updateImportDeclaration(s,s.modifiers,n,s.moduleSpecifier,s.attributes)}}return typescript_1.default.visitEachChild(s,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}},collector=e=>({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{function i(a,r=!0){if(r)if(typescript_1.default.isVariableStatement(a))a.declarationList.declarations.forEach(e=>{if(typescript_1.default.isIdentifier(e.name)){const i=e.name.text;namesMap.has(i)?namesMap.get(i).add({file:t}):namesMap.set(i,new Set([{file:t}]))}});else if(typescript_1.default.isFunctionDeclaration(a)||typescript_1.default.isClassDeclaration(a)||typescript_1.default.isEnumDeclaration(a)||typescript_1.default.isInterfaceDeclaration(a)||typescript_1.default.isTypeAliasDeclaration(a)){const e=a.name?.text;e&&(namesMap.has(e)?namesMap.get(e).add({file:t}):namesMap.set(e,new Set([{file:t}])))}return typescript_1.default.isBlock(a)||typescript_1.default.isFunctionDeclaration(a)||typescript_1.default.isFunctionExpression(a)||typescript_1.default.isArrowFunction(a)||typescript_1.default.isMethodDeclaration(a)||typescript_1.default.isClassDeclaration(a)?(typescript_1.default.isBlock(a)?typescript_1.default.visitNodes(a.statements,e=>i(e,!1)):typescript_1.default.forEachChild(a,e=>{i(e,!1)}),a):typescript_1.default.visitEachChild(a,e=>i(e,r),e)}return e=>i(e,!0)},r,e);return{file:t,content:s,...a}},updater=e=>({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0),s=(0,transformer_1.default)(e=>{const{factory:i}=e,a=r=>{if(typescript_1.default.isVariableStatement(r)){const e=r.declarationList.declarations.map(e=>{if(typescript_1.default.isIdentifier(e.name)){const a=e.name.text;if(namesMap.has(a)&&namesMap.get(a).size>1){const r=dupName.getName(a);return callNameMap.push({base:a,file:t,newName:r}),i.updateVariableDeclaration(e,i.createIdentifier(r),e.exclamationToken,e.type,e.initializer)}}return e}),a=i.updateVariableDeclarationList(r.declarationList,e);return i.updateVariableStatement(r,r.modifiers,a)}if(typescript_1.default.isFunctionDeclaration(r)){if(r.name&&typescript_1.default.isIdentifier(r.name)){const e=r.name.text;if(namesMap.has(e)&&namesMap.get(e).size>1){const a=dupName.getName(e);return callNameMap.push({base:e,file:t,newName:a}),i.updateFunctionDeclaration(r,r.modifiers,r.asteriskToken,i.createIdentifier(a),r.typeParameters,r.parameters,r.type,r.body)}}}else if(typescript_1.default.isClassDeclaration(r)&&r.name&&typescript_1.default.isIdentifier(r.name)){const e=r.name.text;if(namesMap.has(e)&&namesMap.get(e).size>1){const a=dupName.getName(e);return callNameMap.push({base:e,file:t,newName:a}),i.updateClassDeclaration(r,r.modifiers,i.createIdentifier(a),r.typeParameters,r.heritageClauses,r.members)}}return typescript_1.default.visitEachChild(r,a,e)};return e=>typescript_1.default.visitNode(e,a)},r,e);return{file:t,content:s,...a}},duplicateHandlers={renamed:async(e,t)=>{const i=(0,resolves_1.default)([[collector,t],[updater,t],[callExpression,t],[exportExpression,t],[importExpression,t],[callExpression,t],[exportExpression,t]]),a=await i.concurrent();for(const t of a)e=e.map(t);return e},notRenamed:async(e,t)=>{let i=!1;const a=(0,resolves_1.default)([[collector,namesMap,t]]),r=await a.concurrent();return e.map(r[0]),await utils_1.default.wait(1e3),namesMap.forEach((e,t)=>{e.size>1&&(i=!0,console.warn(`Name -> ${t} declared in multiple files :`),e.forEach(e=>console.warn(` - ${e.file}`)))}),await utils_1.default.wait(500),i&&process.exit(1),e}};function mergeImportsStatement(e){const t=new Map,i=new Map,a=new Map,r=new Map,s=new Map;for(const n of e){const e=n.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);if(!e)continue;const[,o,p]=e,c=n.includes("import type"),l=p;if(!o){const e=n.match(/import\s+(?:type\s+)?(\w+)/);if(e){const t=e[1],i=c?r:a;i.has(l)||i.set(l,new Set),i.get(l)?.add(t)}continue}if(o.startsWith("{")){const e=c?i:t;e.has(l)||e.set(l,new Set);o.replace(/[{}]/g,"").split(",").map(e=>e.trim()).filter(Boolean).forEach(t=>e.get(l)?.add(t))}else if(o.startsWith("* as")){const e=o.match(/\*\s+as\s+(\w+)/);if(e){const t=e[1];s.has(l)||s.set(l,new Set),s.get(l)?.add(t)}}else{const e=c?r:a;e.has(l)||e.set(l,new Set),e.get(l)?.add(o.trim())}}const n=[];for(const[e,a]of t){const t=i.get(e)||new Set,r=new Set([...a]);for(const e of t)a.has(e)||r.add(e);if(r.size>0){const t=Array.from(r).sort().join(", ");n.push(`import { ${t} } from "${e}";`)}}for(const[e,a]of i)if(!t.has(e)&&a.size>0){const t=Array.from(a).sort().join(", ");n.push(`import type { ${t} } from "${e}";`)}for(const[e,t]of a){const i=r.get(e)||new Set,a=new Set([...t]);for(const e of i)t.has(e)||a.add(e);if(a.size>0){const t=Array.from(a).join(", ");n.push(`import ${t} from "${e}";`)}}for(const[e,t]of r)if(!a.has(e)&&t.size>0){const i=Array.from(t).join(", ");n.push(`import type ${i} from "${e}";`)}for(const[e,t]of s)if(t.size>0){const i=Array.from(t).join(", ");n.push(`import * as ${i} from "${e}";`)}return n.sort()}function esmExportRemoveHandler(e){return({file:t,content:i,...a})=>{const r=typescript_1.default.createSourceFile(t,i,typescript_1.default.ScriptTarget.Latest,!0);return{file:t,content:(0,transformer_1.default)(e=>{const{factory:t}=e,i=a=>{if(!utils_1.default.isInsideNamespace(a)&&(typescript_1.default.isFunctionDeclaration(a)||typescript_1.default.isClassDeclaration(a)||typescript_1.default.isInterfaceDeclaration(a)||typescript_1.default.isTypeAliasDeclaration(a)||typescript_1.default.isEnumDeclaration(a)||typescript_1.default.isVariableStatement(a))){const e=a.modifiers?.filter(e=>e.kind!==typescript_1.default.SyntaxKind.ExportKeyword&&e.kind!==typescript_1.default.SyntaxKind.DefaultKeyword);if(e?.length!==a.modifiers?.length){if(typescript_1.default.isFunctionDeclaration(a))return t.updateFunctionDeclaration(a,e,a.asteriskToken,a.name,a.typeParameters,a.parameters,a.type,a.body);if(typescript_1.default.isClassDeclaration(a))return t.updateClassDeclaration(a,e,a.name,a.typeParameters,a.heritageClauses,a.members);if(typescript_1.default.isInterfaceDeclaration(a))return t.updateInterfaceDeclaration(a,e,a.name,a.typeParameters,a.heritageClauses,a.members);if(typescript_1.default.isTypeAliasDeclaration(a))return t.updateTypeAliasDeclaration(a,e,a.name,a.typeParameters,a.type);if(typescript_1.default.isEnumDeclaration(a))return t.updateEnumDeclaration(a,e,a.name,a.members);if(typescript_1.default.isVariableStatement(a))return t.updateVariableStatement(a,e,a.declarationList)}}if(typescript_1.default.isExportDeclaration(a))return t.createEmptyStatement();if(typescript_1.default.isExportAssignment(a)){const e=a.expression;if(typescript_1.default.isIdentifier(e))return t.createEmptyStatement()}return typescript_1.default.visitEachChild(a,i,e)};return e=>typescript_1.default.visitNode(e,i)},r,e),...a}}}let properties=[];const typeObj={},typesNames=[];function findProperty(e){const t=[];return typescript_1.default.isPropertyAccessExpression(e)&&typescript_1.default.isIdentifier(e.expression)&&t.push(e.expression.text),e.forEachChild(e=>findProperty(e)),t}function importAllRemoveHandler(e,t){return({file:i,content:a,...r})=>{const s=typescript_1.default.createSourceFile(i,a,typescript_1.default.ScriptTarget.Latest,!0),n=new Set;for(const e of s.statements)if(typescript_1.default.isImportEqualsDeclaration(e)&&e.isTypeOnly){const t=e.moduleReference;typescript_1.default.isExternalModuleReference(t)&&typescript_1.default.isStringLiteral(t.expression)&&n.add(e.name.text)}const o=(0,transformer_1.default)(t=>{const{factory:a}=t,r=o=>{properties=[...properties,...findProperty(o)];const p={isNamespace:!1,isTypeOnly:!1,isTypeNamespace:!1,source:"",importedString:void 0,importedObject:void 0};if(typescript_1.default.isTypeReferenceNode(o)&&typescript_1.default.isQualifiedName(o.typeName)&&typescript_1.default.isIdentifier(o.typeName.left)&&typescript_1.default.isIdentifier(o.typeName.right)){const e=o.typeName.left.text,t=o.typeName.right.text;if(typesNames.push(e),e in typeObj?typeObj[e]?.push(t):typeObj[e]=[t],utils_1.default.checkModuleType(s,i).isCommonJs&&"ts"!==e&&!n.has(e))return a.updateTypeReferenceNode(o,a.createIdentifier(t),void 0)}if(typescript_1.default.isImportDeclaration(o)){const t=o.getText(s);return e.push(t),a.createEmptyStatement()}if(typescript_1.default.isImportEqualsDeclaration(o)){const t=o.name.text,i=o.moduleReference;let r;if(o.isTypeOnly&&(p.isTypeOnly=!0),p.importedString=t,p.isTypeOnly||properties.includes(t)&&(p.isNamespace=!0),typescript_1.default.isExternalModuleReference(i)&&typescript_1.default.isStringLiteral(i.expression)&&(p.source=i.expression.text),p.importedString&&!p.importedObject&&(r=p.isTypeOnly?n.has(p.importedString)?`import type * as ${p.importedString} from "${p.source}";`:typesNames.includes(p.importedString)?`import type { ${typeObj[p.importedString]?.join(",")} } from "${p.source}";`:`import type ${p.importedString} from "${p.source}";`:p.isNamespace&&p.source&&"typescript"!==p.source?`import * as ${p.importedString} from "${p.source}";`:`import ${p.importedString} from "${p.source}";`),!p.importedString&&p.importedObject&&(r=`import { ${p.importedObject.join(", ")} } from "${p.source}";`),r)return e.push(r),a.createEmptyStatement()}if(typescript_1.default.isVariableStatement(o)){const t=o.declarationList.declarations;if(1===t.length){const i=t[0];if(i.initializer&&typescript_1.default.isCallExpression(i.initializer)&&typescript_1.default.isIdentifier(i.initializer.expression)&&"require"===i.initializer.expression.escapedText){const t=i.initializer.arguments[0];if(typescript_1.default.isStringLiteral(t)&&(p.source=t.text),typescript_1.default.isIdentifier(i.name)){const e=i.name.text;p.importedString=e,properties.includes(e)&&(p.isNamespace=!0)}else if(typescript_1.default.isObjectBindingPattern(i.name)){const e=[];for(const t of i.name.elements)typescript_1.default.isIdentifier(t.name)&&e.push(t.name.text);e.length>0&&(p.importedObject=e)}let r;if(p.importedString&&!p.importedObject&&(r=p.isNamespace?`import * as ${p.importedString} from "${p.source}";`:`import ${p.importedString} from "${p.source}";`),!p.importedString&&p.importedObject&&(r=`import { ${p.importedObject.join(", ")} } from "${p.source}";`),r)return e.push(r),a.createEmptyStatement()}}}return typescript_1.default.visitEachChild(o,r,t)};return e=>typescript_1.default.visitNode(e,r)},s,t);return{file:i,content:o,...r}}}const removeHandlers=async(e,t)=>{const i=(0,resolves_1.default)([[importAllRemoveHandler,e,t],[esmExportRemoveHandler,t]]);return await i.series()};function collectBindingNames(e,t){typescript_1.default.isIdentifier(e)?t.push(e.text):(typescript_1.default.isObjectBindingPattern(e)||typescript_1.default.isArrayBindingPattern(e))&&e.elements.forEach(e=>{typescript_1.default.isBindingElement(e)&&e.name&&collectBindingNames(e.name,t)})}function clearUnusedCode(e,t,i,a={treatExportsAsUsed:!0}){const r=typescript_1.default.createSourceFile(t,e,typescript_1.default.ScriptTarget.Latest,!0),s=new Map,n=new Set,o=(e,t=!1)=>{const i=s.get(e);s.set(e,{exported:!!i?.exported||t})},p=e=>{if(typescript_1.default.isImportDeclaration(e)&&e.importClause){const t=e.importClause;t.name&&typescript_1.default.isIdentifier(t.name)&&o(t.name.text,!1),t.namedBindings&&(typescript_1.default.isNamedImports(t.namedBindings)?t.namedBindings.elements.forEach(e=>{typescript_1.default.isImportSpecifier(e)&&typescript_1.default.isIdentifier(e.name)&&o(e.name.text,!1)}):typescript_1.default.isNamespaceImport(t.namedBindings)&&typescript_1.default.isIdentifier(t.namedBindings.name)&&o(t.namedBindings.name.text,!1))}else if(typescript_1.default.isImportEqualsDeclaration(e)&&typescript_1.default.isIdentifier(e.name))o(e.name.text,!1);else if(typescript_1.default.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===typescript_1.default.SyntaxKind.ExportKeyword)??!1;e.declarationList.declarations.forEach(e=>{collectBindingNames(e.name,[]);const i=[];collectBindingNames(e.name,i),i.forEach(e=>o(e,t))})}else if(typescript_1.default.isFunctionDeclaration(e)&&e.name&&typescript_1.default.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===typescript_1.default.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}else if(typescript_1.default.isClassDeclaration(e)&&e.name&&typescript_1.default.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===typescript_1.default.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}if(typescript_1.default.isIdentifier(e)){const t=e.parent;typescript_1.default.isVariableDeclaration(t)&&t.name===e||typescript_1.default.isFunctionDeclaration(t)&&t.name===e||typescript_1.default.isClassDeclaration(t)&&t.name===e||typescript_1.default.isImportClause(t)&&t.name===e||typescript_1.default.isImportSpecifier(t)&&t.name===e||typescript_1.default.isNamespaceImport(t)&&t.name===e||typescript_1.default.isBindingElement(t)&&t.name===e||typescript_1.default.isParameter(t)&&t.name===e||n.add(e.text)}typescript_1.default.forEachChild(e,p)};p(r);const c=new Set;s.forEach((e,t)=>{n.has(t)||a.treatExportsAsUsed&&e.exported||c.add(t)});return(0,transformer_1.default)(e=>{const t=i=>{if(typescript_1.default.isImportDeclaration(i)&&i.importClause){const e=i.importClause,t=e.name&&typescript_1.default.isIdentifier(e.name)?e.name.text:void 0;let a;const r=[];e.namedBindings&&(typescript_1.default.isNamedImports(e.namedBindings)?e.namedBindings.elements.forEach(e=>{typescript_1.default.isImportSpecifier(e)&&typescript_1.default.isIdentifier(e.name)&&r.push(e)}):typescript_1.default.isNamespaceImport(e.namedBindings)&&typescript_1.default.isIdentifier(e.namedBindings.name)&&(a=e.namedBindings.name.text));const s=!!t&&!c.has(t),n=!!a&&!c.has(a),o=r.filter(e=>!c.has(e.name.text));if(!s&&!n&&0===o.length)return typescript_1.default.factory.createNotEmittedStatement(i);if(!s&&!!e.name||void 0!==a&&!n||o.length!==r.length){let e;e=o.length>0?typescript_1.default.factory.createNamedImports(o):n&&a?typescript_1.default.factory.createNamespaceImport(typescript_1.default.factory.createIdentifier(a)):void 0;const r=s&&t?typescript_1.default.factory.createIdentifier(t):void 0,p=typescript_1.default.factory.createImportClause(!1,r,e);return typescript_1.default.factory.updateImportDeclaration(i,i.modifiers,p,i.moduleSpecifier,i.assertClause)}return i}if((typescript_1.default.isFunctionDeclaration(i)||typescript_1.default.isClassDeclaration(i))&&i.name&&typescript_1.default.isIdentifier(i.name))return c.has(i.name.text)?typescript_1.default.factory.createNotEmittedStatement(i):i;if(typescript_1.default.isVariableStatement(i)){const e=[];i.declarationList.declarations.forEach(t=>collectBindingNames(t.name,e));return e.some(e=>!c.has(e))?i:typescript_1.default.factory.createNotEmittedStatement(i)}return typescript_1.default.visitEachChild(i,t,e)};return e=>typescript_1.default.visitNode(e,t)},r,i)}async function bundler(e){const t="."===e.exportPath?"Main":splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor_1.default.cyan("Bundled")} -> ${tcolor_1.default.brightCyan(t)} ${tcolor_1.default.cyan("export path")}`);let i=e.depFiles;const a=e.rename,r=e.tsOptions.default,s=e.plugins;let n=[];if(s.length)for(let e of s)e="function"==typeof e?e():e,"dependency"===e.type&&(i=e.async?await e.func(i):e.func(i));i=a?await duplicateHandlers.renamed(i,r):await duplicateHandlers.notRenamed(i,r),i=await anonymousHandler(i,r);const o=await removeHandlers(n,r);i=i.map(o[0]);const p=i.slice(0,-1).map(o[1]),c=i.slice(-1),l=/["']((?!\.\/|\.\.\/)[^"']+)["']/;n=n.filter(e=>l.test(e)),n=mergeImportsStatement(n);let f=`${n.join("\n").trim()}\n${p.map(e=>`${`//${node_path_1.default.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}\n${c.map(e=>`${`//${node_path_1.default.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}`;if(f=f.replace(/^s*;\s*$/gm,"").trim(),f=clearUnusedCode(f,e.fileName,r),s.length)for(let e of s)e="function"==typeof e?e():e,"pre-process"===e.type&&(f=e.async?await e.func(f):e.func(f));return console.timeEnd(`${tcolor_1.default.cyan("Bundled")} -> ${tcolor_1.default.brightCyan(t)} ${tcolor_1.default.cyan("export path")}`),{bundledContent:f,...e}}async function bundle(e){const t=[];for(const i of e.points){const e=await bundler(i);t.push(e)}return{points:t,allowUpdatePackageJson:e.allowUpdatePackageJson}}function createHost(e,t){const i={},a={getSourceFile:(i,a)=>{if(i===t)return typescript_1.default.createSourceFile(i,e,a)},writeFile:(e,t)=>{i[e]=t},getDefaultLibFileName:e=>typescript_1.default.getDefaultLibFilePath(e),getCurrentDirectory:()=>"",getDirectories:()=>[],fileExists:e=>e===t,readFile:i=>i===t?e:void 0,getCanonicalFileName:e=>e,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n"};return{createdFiles:i,host:a}}const isCjs=e=>e.commonjs&&e.commonjsTypes,isEsm=e=>e.esm&&e.esmTypes;function getExports(e,t){return isCjs(e)&&isEsm(e)?{[t]:{import:{types:`./${node_path_1.default.relative(process.cwd(),e.esmTypes)}`,default:`./${node_path_1.default.relative(process.cwd(),e.esm)}`},require:{types:`./${node_path_1.default.relative(process.cwd(),e.commonjsTypes)}`,default:`./${node_path_1.default.relative(process.cwd(),e.commonjs)}`}}}:isCjs(e)&&!isEsm(e)?{[t]:{require:{types:`./${node_path_1.default.relative(process.cwd(),e.commonjsTypes)}`,default:`./${node_path_1.default.relative(process.cwd(),e.commonjs)}`}}}:!isCjs(e)&&isEsm(e)?{[t]:{import:{types:`./${node_path_1.default.relative(process.cwd(),e.esmTypes)}`,default:`./${node_path_1.default.relative(process.cwd(),e.esm)}`}}}:{}}async function writePackage(e,t){let i=!0;"."!==t&&(i=!1);const a=typescript_1.default.sys.resolvePath("package.json"),r=node_fs_1.default.readFileSync(a,"utf8"),s=JSON.parse(r);let{name:n,version:o,description:p,main:c,module:l,type:f,types:d,exports:u,...m}=s;await utils_1.default.wait(500),f="module";let y={},_={},h={},g={};if(i)y=e.main?{main:node_path_1.default.relative(process.cwd(),e.main)}:{},_=e.module?{module:node_path_1.default.relative(process.cwd(),e.module)}:{},h=e.types?{types:node_path_1.default.relative(process.cwd(),e.types)}:{},g={exports:{...getExports(e,t)}};else{y=c?{main:c}:{},_=l?{module:l}:{},h=d?{types:d}:{};g={exports:{...u&&"object"==typeof u&&!Array.isArray(u)?{...u}:{},...getExports(e,t)}}}await utils_1.default.wait(1e3);const x={name:n,version:o,description:p,type:f,...y,...h,..._,...g,...m};utils_1.default.writeCompileFile(a,JSON.stringify(x,null,2))}class Compiler{constructor(e){this.object=e,this.files={commonjs:void 0,commonjsTypes:void 0,esm:void 0,esmTypes:void 0,main:void 0,module:void 0,types:void 0}}_isUpdate(){return this.object.allowUpdatePackageJson}async _commonjs(e){const t="."===e.exportPath,i=t?"Main":splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor_1.default.cyan("Compiled CJS")} -> ${tcolor_1.default.brightCyan(i)} ${tcolor_1.default.cyan("export path")}`);const a=e.fileName,r=e.bundledContent,s=e.format,n=e.plugins,o=e.tsOptions.cjs,p=createHost(r,a),c=p.createdFiles,l=p.host;typescript_1.default.createProgram([a],o,l).emit(),Object.entries(c).map(async([e,i])=>{if(".js"===node_path_1.default.extname(e)&&n.length)for(let t of n)t="function"==typeof t?t():t,"post-process"===t.type&&(i=t.async?await t.func(i,e):t.func(i,e));this._isUpdate()&&(e.match(/.js/g)&&(this.files.commonjs=e.replace(/.js/g,".cjs")),e.match(/.d.ts/g)&&(this.files.commonjsTypes=e.replace(/.d.ts/g,".d.cts")),!t||"both"!==s&&"commonjs"!==s||(this.files.commonjs&&(this.files.main=this.files.commonjs),this.files.commonjsTypes&&(this.files.types=this.files.commonjsTypes))),e=(e=(e=e.replace(/.js/g,".cjs")).replace(/.map.js/g,".map.cjs")).replace(/.d.ts/g,".d.cts"),await utils_1.default.wait(500),"commonjs"===s&&await utils_1.default.clearFolder(node_path_1.default.dirname(e)),await utils_1.default.writeCompileFile(e,i)}),console.timeEnd(`${tcolor_1.default.cyan("Compiled CJS")} -> ${tcolor_1.default.brightCyan(i)} ${tcolor_1.default.cyan("export path")}`)}async _esm(e){const t="."===e.exportPath,i=t?"Main":splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor_1.default.cyan("Compiled ESM")} -> ${tcolor_1.default.brightCyan(i)} ${tcolor_1.default.cyan("export path")}`);const a=e.fileName,r=e.bundledContent,s=e.format,n=e.plugins,o=e.tsOptions.esm,p=createHost(r,a),c=p.createdFiles,l=p.host;typescript_1.default.createProgram([a],o,l).emit(),Object.entries(c).map(async([e,i])=>{if(".js"===node_path_1.default.extname(e)&&n.length)for(let t of n)t="function"==typeof t?t():t,"post-process"===t.type&&(i=t.async?await t.func(i,e):t.func(i,e));this._isUpdate()&&(e.match(/.js/g)&&(this.files.esm=e.replace(/.js/g,".mjs")),e.match(/.d.ts/g)&&(this.files.esmTypes=e.replace(/.d.ts/g,".d.mts")),t&&"both"===s&&this.files.esm&&(this.files.module=this.files.esm)),e=(e=(e=e.replace(/.js/g,".mjs")).replace(/.map.js/g,".map.mjs")).replace(/.d.ts/g,".d.mts"),await utils_1.default.wait(500),"commonjs"!==s&&await utils_1.default.clearFolder(node_path_1.default.dirname(e)),await utils_1.default.writeCompileFile(e,i)}),console.timeEnd(`${tcolor_1.default.cyan("Compiled ESM")} -> ${tcolor_1.default.brightCyan(i)} ${tcolor_1.default.cyan("export path")}`)}async compile(){for(const e of this.object.points){switch(await utils_1.default.wait(500),e.format){case"commonjs":await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath);break;case"esm":await this._esm(e),this._isUpdate()&&await writePackage(this.files,e.exportPath);break;case"both":await this._esm(e),await utils_1.default.wait(1e3),await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath)}await utils_1.default.wait(500)}}}var checks;!function(e){function t(e,t){if(!t.noCheck){const i=e.map(e=>e.file);let a=!1;const r=typescript_1.default.createProgram(i,t);for(const e of i){const t=r.getSourceFile(e);t||(console.error(tcolor_1.default.magenta(`File not found: ${e}`)),typescript_1.default.sys.exit(1));const i=[...r.getSyntacticDiagnostics(t),...r.getSemanticDiagnostics(t),...r.getDeclarationDiagnostics(t)];if(i.length>0){const e={getCurrentDirectory:()=>process.cwd(),getCanonicalFileName:e=>e,getNewLine:()=>typescript_1.default.sys.newLine};console.error(typescript_1.default.formatDiagnosticsWithColorAndContext(i,e)),a=!0}}if(!a)return!0;typescript_1.default.sys.exit(1)}}function i(e){let t=0,i=0;for(const a of e)try{const r=typescript_1.default.createSourceFile(a.file,a.content,typescript_1.default.ScriptTarget.Latest,!0);let s=!1,n=!1;function o(e){if((typescript_1.default.isImportDeclaration(e)||typescript_1.default.isImportEqualsDeclaration(e)||typescript_1.default.isExportDeclaration(e)||typescript_1.default.isExportSpecifier(e)||typescript_1.default.isExportAssignment(e))&&(s=!0),(typescript_1.default.isVariableStatement(e)||typescript_1.default.isFunctionDeclaration(e)||typescript_1.default.isInterfaceDeclaration(e)||typescript_1.default.isTypeAliasDeclaration(e)||typescript_1.default.isEnumDeclaration(e)||typescript_1.default.isClassDeclaration(e))&&e.modifiers?.some(e=>e.kind===typescript_1.default.SyntaxKind.ExportKeyword)&&(s=!0),typescript_1.default.isCallExpression(e)&&typescript_1.default.isIdentifier(e.expression)&&"require"===e.expression.text&&e.arguments.length>0&&(n=!0),typescript_1.default.isPropertyAccessExpression(e)){const t=e.getText(r);(t.startsWith("module.exports")||t.startsWith("exports."))&&(n=!0)}typescript_1.default.forEachChild(e,o)}o(r),s&&!n?0:n&&!s?t++:s&&n&&0}catch(p){console.error(tcolor_1.default.magenta(`Error checking module format for ${a.file} : \n ${p}`)),i++}return i&&(console.error(tcolor_1.default.magenta("Unknown error when checking module types in the dependencies tree.")),typescript_1.default.sys.exit(1)),t&&(console.error(tcolor_1.default.magenta("The package detects CommonJs format in the dependencies tree, that unsupported.")),typescript_1.default.sys.exit(1)),!0}function a(e){const t=new Set([".ts",".mts",".cts",".tsx"]);for(const i of e){const e=node_path_1.default.extname(i.file);t.has(e)||(console.error(tcolor_1.default.magenta(`${i.file} has no valid TypeScript extension`)),typescript_1.default.sys.exit(1))}return!0}e.types=async function(e,i){const a=(0,resolves_1.default)([[t,e,i]]);return(await a.series())[0]},e.moduleAndExtension=async function(e){const t=(0,resolves_1.default)([[i,e],[a,e]]);return(await t.concurrent()).every(e=>!0===e)}}(checks||(checks={}));const getConfigPath=()=>{const e=["susee.config.ts","susee.config.js","susee.config.mjs"];let t;for(const i of e){const e=typescript_1.default.sys.resolvePath(i);if(typescript_1.default.sys.fileExists(e)){t=e;break}}return t};function checkEntries(e){e.length<1&&(console.error(tcolor_1.default.magenta("No entry found in susee.config file, at least one entry required")),typescript_1.default.sys.exit(1));const t={},i=[];for(const a of e){const e=a.exportPath;t[e]?i.push(`"${e}"`):t[e]=!0}i.length>0&&(console.error(tcolor_1.default.magenta(`Duplicate export paths/path (${i.join(",")}) found in your susee.config file , that will error for bundled output`)),typescript_1.default.sys.exit(1));for(const t of e)typescript_1.default.sys.fileExists(typescript_1.default.sys.resolvePath(t.entry))||(console.error(tcolor_1.default.magenta(`Entry file ${t.entry} dose not exists.`)),typescript_1.default.sys.exit(1))}async function getConfig(){const e=getConfigPath();void 0===e&&(console.error(tcolor_1.default.magenta('No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found')),typescript_1.default.sys.exit(1));const t=(await Promise.resolve(`${e}`).then(e=>__importStar(require(e)))).default,i=(0,resolves_1.default)([[checkEntries,t.entryPoints]]);await i.series(),await utils_1.default.wait(1e3);const a=[];for(const e of t.entryPoints){const i={entry:e.entry,exportPath:e.exportPath,format:e.format??"esm",tsconfigFilePath:e.tsconfigFilePath??void 0,renameDuplicates:e.renameDuplicates??!0,outDir:t.outDir??"dist"};a.push(i)}return{points:a,plugins:t.plugins??[],allowUpdatePackageJson:t.allowUpdatePackageJson??!0}}async function fileSizes(e){const t=await node_fs_1.default.promises.stat(e);return{logical:t.size,allocated:null!==t.blocks?512*t.blocks:null}}const checkExport=(e,t)=>!!(e.match(/export default .*/gm)||e.match(/export = .*/gm)&&t.match(/.cts/g));async function generateDependencies(e){const t=(await(0,dependencies_1.default)(e)).sort(),i=[];await utils_1.default.wait(1e3);for(const e of t){const t=typescript_1.default.sys.resolvePath(e),a=await node_fs_1.default.promises.readFile(t,"utf8"),r=await fileSizes(t),s=a.length,n=checkExport(a,t),o=typescript_1.default.createSourceFile(t,a,typescript_1.default.ScriptTarget.Latest,!0),p=utils_1.default.checkModuleType(o,t).isCommonJs?"cjs":"esm",c={file:t,content:a,length:s,includeDefExport:n,size:{logical:r.logical,allocated:r.allocated,utf8:(new TextEncoder).encode(a).length,buffBytes:node_buffer_1.Buffer.byteLength(a,"utf8")},type:p};i.push(c)}return i}class GetOptions{constructor(e){this._point=e,this._options={}}__init(){const e=new tsconfig_1.default(this._point.tsconfigFilePath),t="."===this._point.exportPath?this._point.outDir:`${this._point.outDir}/${this._point.exportPath.slice(2)}`;e.removeCompilerOption("rootDir"),e.removeCompilerOption("module"),e.editCompilerOptions({moduleResolution:typescript_1.default.ModuleResolutionKind.NodeNext,outDir:t}),this._options=e.getCompilerOptions()}__init2(){this.__init();let{types:e,lib:t,...i}=this._options;return e?e.includes("node")||(e=["node",...e]):e=["node"],t=t?[...new Set(["ESNext",...t])]:["ESNext"],{types:e,lib:t,...i}}get commonjs(){const e=this.__init2(),{module:t,...i}=e;return{module:typescript_1.default.ModuleKind.CommonJS,...i}}get esm(){const e=this.__init2(),{module:t,...i}=e;return{module:typescript_1.default.ModuleKind.ES2020,...i}}get default(){return this.__init2()}}function getOptions(e){return new GetOptions(e)}async function collections(){console.time(`${tcolor_1.default.cyan("Collected Data")} :`);const e=await getConfig(),t=e.points,i=e.plugins,a=[];for(const e of t){const t=getOptions(e);let r=await generateDependencies(e.entry);await checks.types(r,t.esm)||typescript_1.default.sys.exit(1);let s=!1;if(i.length)for(const e of i){const t="function"==typeof e?e():e;"dependency"===t.type&&(t.name&&"@suseejs/plugin-commonjs"===t.name&&(s=!0),r=t.async?await t.func(r):t.func(r))}if(!s){await checks.moduleAndExtension(r)||typescript_1.default.sys.exit(1)}const n={fileName:e.entry,exportPath:e.exportPath,format:e.format,rename:e.renameDuplicates,outDir:e.outDir,tsOptions:{cjs:t.commonjs,esm:t.esm,default:t.default},depFiles:r,plugins:i};a.push(n)}return console.timeEnd(`${tcolor_1.default.cyan("Collected Data")} :`),{points:a,allowUpdatePackageJson:e.allowUpdatePackageJson}}async function susee(){console.info(`${tcolor_1.default.cyan("Started")} : `),console.time(`${tcolor_1.default.cyan("Done")}`);const e=await collections();await utils_1.default.wait(1e3);const t=await bundle(e);await utils_1.default.wait(1e3);const i=new Compiler(t);await i.compile(),console.timeEnd(`${tcolor_1.default.cyan("Done")}`)}