susee 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -45,9 +45,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
45
45
  Object.defineProperty(exports, "__esModule", { value: true });
46
46
  exports.susee = susee;
47
47
  const tsconfig_1 = __importDefault(require("@suseejs/tsconfig"));
48
- const anonymous_1 = __importDefault(require("@suseejs/anonymous"));
49
48
  const dependencies_1 = __importDefault(require("@suseejs/dependencies"));
50
- const duplicates_1 = __importDefault(require("@suseejs/duplicates"));
51
49
  const node_fs_1 = __importDefault(require("node:fs"));
52
50
  const node_path_1 = __importDefault(require("node:path"));
53
51
  const resolves_1 = __importDefault(require("@phothinmaung/resolves"));
@@ -55,85 +53,21 @@ const tcolor_1 = __importDefault(require("@suseejs/tcolor"));
55
53
  const transformer_1 = __importDefault(require("@suseejs/transformer"));
56
54
  const typescript_1 = __importDefault(require("typescript"));
57
55
  const utils_1 = __importDefault(require("@suseejs/utils"));
58
- function removeExportExpressionHandler(compilerOptions) {
59
- return ({ file, content }) => {
60
- const sourceFile = typescript_1.default.createSourceFile(file, content, typescript_1.default.ScriptTarget.Latest, true);
56
+ const node_buffer_1 = require("node:buffer");
57
+ const bundleCreator = (bundleVisitor, compilerOptions, ...args) => {
58
+ return (depsTree) => {
59
+ const sourceFile = typescript_1.default.createSourceFile(depsTree.file, depsTree.content, typescript_1.default.ScriptTarget.Latest, true);
61
60
  const transformer = (context) => {
62
- const { factory } = context;
63
- const visitor = (node) => {
64
- if (typescript_1.default.isFunctionDeclaration(node) ||
65
- typescript_1.default.isClassDeclaration(node) ||
66
- typescript_1.default.isInterfaceDeclaration(node) ||
67
- typescript_1.default.isTypeAliasDeclaration(node) ||
68
- typescript_1.default.isEnumDeclaration(node) ||
69
- typescript_1.default.isVariableStatement(node)) {
70
- const modifiers = node.modifiers?.filter((m) => m.kind !== typescript_1.default.SyntaxKind.ExportKeyword &&
71
- m.kind !== typescript_1.default.SyntaxKind.DefaultKeyword);
72
- if (modifiers?.length !== node.modifiers?.length) {
73
- if (typescript_1.default.isFunctionDeclaration(node)) {
74
- return factory.updateFunctionDeclaration(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
75
- }
76
- if (typescript_1.default.isClassDeclaration(node)) {
77
- return factory.updateClassDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
78
- }
79
- if (typescript_1.default.isInterfaceDeclaration(node)) {
80
- return factory.updateInterfaceDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
81
- }
82
- if (typescript_1.default.isTypeAliasDeclaration(node)) {
83
- return factory.updateTypeAliasDeclaration(node, modifiers, node.name, node.typeParameters, node.type);
84
- }
85
- if (typescript_1.default.isEnumDeclaration(node)) {
86
- return factory.updateEnumDeclaration(node, modifiers, node.name, node.members);
87
- }
88
- if (typescript_1.default.isVariableStatement(node)) {
89
- return factory.updateVariableStatement(node, modifiers, node.declarationList);
90
- }
91
- }
92
- }
93
- if (typescript_1.default.isExportDeclaration(node)) {
94
- return factory.createEmptyStatement();
95
- }
96
- if (typescript_1.default.isExportAssignment(node)) {
97
- const expr = node.expression;
98
- if (typescript_1.default.isIdentifier(expr)) {
99
- return factory.createEmptyStatement();
100
- }
101
- }
102
- return typescript_1.default.visitEachChild(node, visitor, context);
103
- };
104
- return (rootNode) => typescript_1.default.visitNode(rootNode, visitor);
105
- };
106
- let _content = (0, transformer_1.default)(transformer, sourceFile, compilerOptions);
107
- _content = _content.replace(/^s*;\s*$/gm, "").trim();
108
- return { file, content: _content };
109
- };
110
- }
111
- function removeImportExpressionHandler(removedStatements, compilerOptions) {
112
- return ({ file, content }) => {
113
- const sourceFile = typescript_1.default.createSourceFile(file, content, typescript_1.default.ScriptTarget.Latest, true);
114
- const transformer = (context) => {
115
- const { factory } = context;
116
- const visitor = (node) => {
117
- if (typescript_1.default.isImportDeclaration(node)) {
118
- const text = node.getText(sourceFile);
119
- removedStatements.push(text);
120
- return factory.createEmptyStatement();
121
- }
122
- if (typescript_1.default.isImportEqualsDeclaration(node)) {
123
- const text = node.getText(sourceFile);
124
- removedStatements.push(text);
125
- return factory.createEmptyStatement();
126
- }
127
- return typescript_1.default.visitEachChild(node, visitor, context);
128
- };
61
+ const visitor = bundleVisitor(context, depsTree, sourceFile, ...args);
129
62
  return (rootNode) => typescript_1.default.visitNode(rootNode, visitor);
130
63
  };
131
64
  let _content = (0, transformer_1.default)(transformer, sourceFile, compilerOptions);
132
65
  _content = _content.replace(/^s*;\s*$/gm, "").trim();
133
- return { file, content: _content };
66
+ const { content, ...rest } = depsTree;
67
+ return { content: _content, ...rest };
134
68
  };
135
- }
136
- function mergeImports(imports) {
69
+ };
70
+ function mergeImportsStatement(imports) {
137
71
  const importMap = new Map();
138
72
  const typeImportMap = new Map();
139
73
  const defaultImports = new Map();
@@ -231,8 +165,714 @@ function mergeImports(imports) {
231
165
  }
232
166
  return mergedImports.sort();
233
167
  }
234
- async function bundler({ depsFiles, compilerOptions, renameDuplicates, }) {
235
- const reName = renameDuplicates ?? true;
168
+ const anonymousCallExpressionVisitor = (context, depsTree, _sourceFile, exportDefaultImportNameMap) => {
169
+ const { factory } = context;
170
+ const visit = (node) => {
171
+ if (typescript_1.default.isCallExpression(node)) {
172
+ if (typescript_1.default.isIdentifier(node.expression)) {
173
+ const base = node.expression.text;
174
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
175
+ if (mapping) {
176
+ return factory.updateCallExpression(node, factory.createIdentifier(mapping.newName), node.typeArguments, node.arguments);
177
+ }
178
+ }
179
+ }
180
+ else if (typescript_1.default.isPropertyAccessExpression(node)) {
181
+ if (typescript_1.default.isIdentifier(node.expression)) {
182
+ const base = node.expression.text;
183
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
184
+ if (mapping) {
185
+ return factory.updatePropertyAccessExpression(node, factory.createIdentifier(mapping.newName), node.name);
186
+ }
187
+ }
188
+ }
189
+ else if (typescript_1.default.isNewExpression(node)) {
190
+ if (typescript_1.default.isIdentifier(node.expression)) {
191
+ const base = node.expression.text;
192
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
193
+ if (mapping) {
194
+ return factory.updateNewExpression(node, factory.createIdentifier(mapping.newName), node.typeArguments, node.arguments);
195
+ }
196
+ }
197
+ }
198
+ else if (typescript_1.default.isExportSpecifier(node)) {
199
+ if (typescript_1.default.isIdentifier(node.name)) {
200
+ const base = node.name.text;
201
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
202
+ if (mapping) {
203
+ return factory.updateExportSpecifier(node, node.isTypeOnly, node.propertyName, factory.createIdentifier(mapping.newName));
204
+ }
205
+ }
206
+ }
207
+ return typescript_1.default.visitEachChild(node, visit, context);
208
+ };
209
+ return visit;
210
+ };
211
+ const normalizePathKey = (filePath) => {
212
+ const parsed = node_path_1.default.parse(filePath);
213
+ let noExt = node_path_1.default.join(parsed.dir, parsed.name);
214
+ if (parsed.name === "index") {
215
+ noExt = parsed.dir;
216
+ }
217
+ return node_path_1.default.normalize(noExt);
218
+ };
219
+ const getFileKey = (filePath) => normalizePathKey(filePath);
220
+ const getModuleKeyFromSpecifier = (moduleSpecifier, sourceFile, containingFile) => {
221
+ let spec = "";
222
+ if (typescript_1.default.isStringLiteral(moduleSpecifier)) {
223
+ spec = moduleSpecifier.text;
224
+ }
225
+ else {
226
+ spec = moduleSpecifier.getText(sourceFile).replace(/^['"]|['"]$/g, "");
227
+ }
228
+ if (spec.startsWith(".") || spec.startsWith("/")) {
229
+ const baseDir = node_path_1.default.dirname(containingFile);
230
+ return normalizePathKey(node_path_1.default.resolve(baseDir, spec));
231
+ }
232
+ return spec;
233
+ };
234
+ function uniqueName() {
235
+ const storedPrefix = new Map();
236
+ const obj = {
237
+ setPrefix({ key, value }) {
238
+ const names = [];
239
+ let _fix;
240
+ if (storedPrefix.has(key)) {
241
+ console.warn(`${key} already exist`);
242
+ throw new Error();
243
+ }
244
+ else {
245
+ _fix = value;
246
+ storedPrefix.set(key, value);
247
+ }
248
+ function getName(input) {
249
+ const length = names.length;
250
+ const _name = _fix
251
+ ? `${_fix}${input}_${length + 1}`
252
+ : `$nyein${input}_${length + 1}`;
253
+ names.push(_name);
254
+ return _name;
255
+ }
256
+ return { getName };
257
+ },
258
+ getPrefix(key) {
259
+ if (storedPrefix.has(key)) {
260
+ return storedPrefix.get(key);
261
+ }
262
+ },
263
+ };
264
+ return obj;
265
+ }
266
+ const prefixKey = "AnonymousName";
267
+ const genName = uniqueName().setPrefix({ key: prefixKey, value: "a_" });
268
+ const anonymousExportVisitor = (context, depsTree, sourceFile, exportDefaultExportNameMap) => {
269
+ const { factory } = context;
270
+ const visit = (node) => {
271
+ const fileName = node_path_1.default.basename(depsTree.file).split(".")[0];
272
+ if ((typescript_1.default.isFunctionDeclaration(node) || typescript_1.default.isClassDeclaration(node)) &&
273
+ node.name === undefined) {
274
+ let exp = false;
275
+ let def = false;
276
+ node.modifiers?.forEach((mod) => {
277
+ if (mod.kind === typescript_1.default.SyntaxKind.ExportKeyword) {
278
+ exp = true;
279
+ }
280
+ if (mod.kind === typescript_1.default.SyntaxKind.DefaultKeyword) {
281
+ def = true;
282
+ }
283
+ });
284
+ if (exp && def) {
285
+ const base = genName.getName(fileName);
286
+ exportDefaultExportNameMap.push({
287
+ base,
288
+ file: fileName,
289
+ newName: base,
290
+ isEd: true,
291
+ });
292
+ if (typescript_1.default.isFunctionDeclaration(node)) {
293
+ return factory.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, factory.createIdentifier(base), node.typeParameters, node.parameters, node.type, node.body);
294
+ }
295
+ else if (typescript_1.default.isClassDeclaration(node)) {
296
+ return factory.updateClassDeclaration(node, node.modifiers, factory.createIdentifier(base), node.typeParameters, node.heritageClauses, node.members);
297
+ }
298
+ }
299
+ }
300
+ else if (typescript_1.default.isExportAssignment(node) &&
301
+ !node.name &&
302
+ !node.isExportEquals) {
303
+ if (typescript_1.default.isArrowFunction(node.expression)) {
304
+ const base = genName.getName(fileName);
305
+ const arrowFunctionNode = factory.createArrowFunction(node.expression.modifiers, node.expression.typeParameters, node.expression.parameters, node.expression.type, node.expression.equalsGreaterThanToken, node.expression.body);
306
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), node.expression.exclamationToken, node.expression.type, arrowFunctionNode);
307
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
308
+ const variableStatementNode = factory.createVariableStatement(node.expression.modifiers, variableDeclarationListNode);
309
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
310
+ exportDefaultExportNameMap.push({
311
+ base,
312
+ file: fileName,
313
+ newName: base,
314
+ isEd: true,
315
+ });
316
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
317
+ }
318
+ else if (typescript_1.default.isObjectLiteralExpression(node.expression)) {
319
+ const base = genName.getName(fileName);
320
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, node.expression);
321
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
322
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
323
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
324
+ exportDefaultExportNameMap.push({
325
+ base,
326
+ file: fileName,
327
+ newName: base,
328
+ isEd: true,
329
+ });
330
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
331
+ }
332
+ else if (typescript_1.default.isArrayLiteralExpression(node.expression)) {
333
+ const base = genName.getName(fileName);
334
+ const arrayLiteralExpressionNode = factory.createArrayLiteralExpression(node.expression.elements, true);
335
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, arrayLiteralExpressionNode);
336
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
337
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
338
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
339
+ exportDefaultExportNameMap.push({
340
+ base,
341
+ file: fileName,
342
+ newName: base,
343
+ isEd: true,
344
+ });
345
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
346
+ }
347
+ else if (typescript_1.default.isStringLiteral(node.expression)) {
348
+ const base = genName.getName(fileName);
349
+ const stringLiteralNode = factory.createStringLiteral(node.expression.text);
350
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, stringLiteralNode);
351
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
352
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
353
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
354
+ exportDefaultExportNameMap.push({
355
+ base,
356
+ file: fileName,
357
+ newName: base,
358
+ isEd: true,
359
+ });
360
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
361
+ }
362
+ else if (typescript_1.default.isNumericLiteral(node.expression)) {
363
+ const base = genName.getName(fileName);
364
+ const numericLiteralNode = factory.createNumericLiteral(node.expression.text);
365
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, numericLiteralNode);
366
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], typescript_1.default.NodeFlags.Const);
367
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
368
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
369
+ exportDefaultExportNameMap.push({
370
+ base,
371
+ file: fileName,
372
+ newName: base,
373
+ isEd: true,
374
+ });
375
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
376
+ }
377
+ }
378
+ return typescript_1.default.visitEachChild(node, visit, context);
379
+ };
380
+ return visit;
381
+ };
382
+ const anonymousImportVisitor = (context, depsTree, sourceFile, exportDefaultExportNameMap, exportDefaultImportNameMap) => {
383
+ const { factory } = context;
384
+ const visit = (node) => {
385
+ if (typescript_1.default.isImportDeclaration(node)) {
386
+ const fileName = node.moduleSpecifier.getText(sourceFile);
387
+ const _name = node_path_1.default.basename(fileName).split(".")[0].trim();
388
+ if (node.importClause?.name && typescript_1.default.isIdentifier(node.importClause.name)) {
389
+ const base = node.importClause.name.text.trim();
390
+ const mapping = exportDefaultExportNameMap.find((v) => v.file === _name);
391
+ if (mapping) {
392
+ exportDefaultImportNameMap.push({
393
+ base,
394
+ file: depsTree.file,
395
+ newName: mapping.newName,
396
+ isEd: true,
397
+ });
398
+ const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, factory.createIdentifier(mapping.newName), node.importClause.namedBindings);
399
+ return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
400
+ }
401
+ }
402
+ }
403
+ return typescript_1.default.visitEachChild(node, visit, context);
404
+ };
405
+ return visit;
406
+ };
407
+ const duplicateCallExpressionVisitor = (context, depsTree, _sourceFile, callNameMap, importNameMap) => {
408
+ const { factory } = context;
409
+ const visit = (node) => {
410
+ if (typescript_1.default.isCallExpression(node)) {
411
+ if (typescript_1.default.isIdentifier(node.expression)) {
412
+ const base = node.expression.text;
413
+ let new_name = null;
414
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
415
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
416
+ if (mapping) {
417
+ new_name = mapping.newName;
418
+ }
419
+ else if (importMapping) {
420
+ new_name = importMapping.newName;
421
+ }
422
+ if (new_name) {
423
+ return factory.updateCallExpression(node, factory.createIdentifier(new_name), node.typeArguments, node.arguments);
424
+ }
425
+ }
426
+ }
427
+ else if (typescript_1.default.isPropertyAccessExpression(node)) {
428
+ if (typescript_1.default.isIdentifier(node.expression)) {
429
+ const base = node.expression.text;
430
+ let new_name = null;
431
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
432
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
433
+ if (mapping) {
434
+ new_name = mapping.newName;
435
+ }
436
+ else if (importMapping) {
437
+ new_name = importMapping.newName;
438
+ }
439
+ if (new_name) {
440
+ return factory.updatePropertyAccessExpression(node, factory.createIdentifier(new_name), node.name);
441
+ }
442
+ }
443
+ }
444
+ else if (typescript_1.default.isNewExpression(node)) {
445
+ if (typescript_1.default.isIdentifier(node.expression)) {
446
+ const base = node.expression.text;
447
+ let new_name = null;
448
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
449
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
450
+ if (mapping) {
451
+ new_name = mapping.newName;
452
+ }
453
+ else if (importMapping) {
454
+ new_name = importMapping.newName;
455
+ }
456
+ if (new_name) {
457
+ return factory.updateNewExpression(node, factory.createIdentifier(new_name), node.typeArguments, node.arguments);
458
+ }
459
+ }
460
+ }
461
+ return typescript_1.default.visitEachChild(node, visit, context);
462
+ };
463
+ return visit;
464
+ };
465
+ const duplicateCollectionVisitor = (context, depsTree, _sourceFile, namesMap) => {
466
+ const visit = (node, isGlobalScope = true) => {
467
+ if (isGlobalScope) {
468
+ if (typescript_1.default.isVariableStatement(node)) {
469
+ node.declarationList.declarations.forEach((decl) => {
470
+ if (typescript_1.default.isIdentifier(decl.name)) {
471
+ const $name = decl.name.text;
472
+ if (!namesMap.has($name)) {
473
+ namesMap.set($name, new Set([{ file: depsTree.file }]));
474
+ }
475
+ else {
476
+ namesMap.get($name).add({ file: depsTree.file });
477
+ }
478
+ }
479
+ });
480
+ }
481
+ else if (typescript_1.default.isFunctionDeclaration(node) ||
482
+ typescript_1.default.isClassDeclaration(node) ||
483
+ typescript_1.default.isEnumDeclaration(node) ||
484
+ typescript_1.default.isInterfaceDeclaration(node) ||
485
+ typescript_1.default.isTypeAliasDeclaration(node)) {
486
+ const $name = node.name?.text;
487
+ if ($name) {
488
+ if (!namesMap.has($name)) {
489
+ namesMap.set($name, new Set([{ file: depsTree.file }]));
490
+ }
491
+ else {
492
+ namesMap.get($name).add({ file: depsTree.file });
493
+ }
494
+ }
495
+ }
496
+ }
497
+ if (typescript_1.default.isBlock(node) ||
498
+ typescript_1.default.isFunctionDeclaration(node) ||
499
+ typescript_1.default.isFunctionExpression(node) ||
500
+ typescript_1.default.isArrowFunction(node) ||
501
+ typescript_1.default.isMethodDeclaration(node) ||
502
+ typescript_1.default.isClassDeclaration(node)) {
503
+ if (typescript_1.default.isBlock(node)) {
504
+ typescript_1.default.visitNodes(node.statements, (child) => visit(child, false));
505
+ }
506
+ else {
507
+ typescript_1.default.forEachChild(node, (child) => {
508
+ visit(child, false);
509
+ });
510
+ }
511
+ }
512
+ else {
513
+ return typescript_1.default.visitEachChild(node, (child) => visit(child, isGlobalScope), context);
514
+ }
515
+ return node;
516
+ };
517
+ return visit;
518
+ };
519
+ const duplicateExportExpressionVisitor = (context, depsTree, _sourceFile, callNameMap, importNameMap, exportNameMap) => {
520
+ const { factory } = context;
521
+ const visit = (node) => {
522
+ if (typescript_1.default.isExportSpecifier(node)) {
523
+ if (typescript_1.default.isIdentifier(node.name)) {
524
+ const base = node.name.text;
525
+ let new_name = null;
526
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
527
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
528
+ if (mapping) {
529
+ exportNameMap.push({
530
+ base,
531
+ file: getFileKey(depsTree.file),
532
+ newName: mapping.newName,
533
+ });
534
+ new_name = mapping.newName;
535
+ }
536
+ else if (importMapping) {
537
+ new_name = importMapping.newName;
538
+ }
539
+ if (new_name) {
540
+ return factory.updateExportSpecifier(node, node.isTypeOnly, node.propertyName, factory.createIdentifier(new_name));
541
+ }
542
+ }
543
+ }
544
+ else if (typescript_1.default.isExportAssignment(node)) {
545
+ const expr = node.expression;
546
+ if (typescript_1.default.isIdentifier(expr)) {
547
+ const base = expr.text;
548
+ let new_name = null;
549
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
550
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
551
+ if (mapping) {
552
+ exportNameMap.push({
553
+ base,
554
+ file: getFileKey(depsTree.file),
555
+ newName: mapping.newName,
556
+ });
557
+ new_name = mapping.newName;
558
+ }
559
+ else if (importMapping) {
560
+ new_name = importMapping.newName;
561
+ }
562
+ if (new_name) {
563
+ return factory.updateExportAssignment(node, node.modifiers, factory.createIdentifier(new_name));
564
+ }
565
+ }
566
+ }
567
+ return typescript_1.default.visitEachChild(node, visit, context);
568
+ };
569
+ return visit;
570
+ };
571
+ const duplicateImportExpressionVisitor = (context, depsTree, sourceFile, exportNameMap, importNameMap) => {
572
+ const { factory } = context;
573
+ const visit = (node) => {
574
+ if (typescript_1.default.isImportDeclaration(node)) {
575
+ const moduleKey = getModuleKeyFromSpecifier(node.moduleSpecifier, sourceFile, depsTree.file);
576
+ let baseNames = [];
577
+ if (node.importClause?.namedBindings &&
578
+ typescript_1.default.isNamedImports(node.importClause.namedBindings)) {
579
+ baseNames = node.importClause.namedBindings.elements.map((el) => el.name.text.trim());
580
+ }
581
+ if (node.importClause?.name && typescript_1.default.isIdentifier(node.importClause.name)) {
582
+ const base = node.importClause.name.text.trim();
583
+ const mapping = exportNameMap.find((m) => m.base === base && m.file === moduleKey);
584
+ if (mapping) {
585
+ importNameMap.push({
586
+ base: mapping.base,
587
+ file: depsTree.file,
588
+ newName: mapping.newName,
589
+ });
590
+ const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, factory.createIdentifier(mapping.newName), node.importClause.namedBindings);
591
+ return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
592
+ }
593
+ }
594
+ if (baseNames.length > 0 &&
595
+ node.importClause &&
596
+ node.importClause.namedBindings &&
597
+ typescript_1.default.isNamedImports(node.importClause.namedBindings)) {
598
+ const updatedElements = node.importClause.namedBindings.elements.map((el) => {
599
+ const mapping = exportNameMap.find((m) => m.base === el.name.text.trim() && m.file === moduleKey);
600
+ if (mapping) {
601
+ importNameMap.push({
602
+ base: mapping.base,
603
+ file: depsTree.file,
604
+ newName: mapping.newName,
605
+ });
606
+ return factory.updateImportSpecifier(el, el.isTypeOnly, el.propertyName, factory.createIdentifier(mapping.newName));
607
+ }
608
+ return el;
609
+ });
610
+ const newNamedImports = factory.updateNamedImports(node.importClause.namedBindings, updatedElements);
611
+ const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, node.importClause.name, newNamedImports);
612
+ return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
613
+ }
614
+ }
615
+ return typescript_1.default.visitEachChild(node, visit, context);
616
+ };
617
+ return visit;
618
+ };
619
+ const dupName = uniqueName().setPrefix({
620
+ key: "DuplicatesNames",
621
+ value: "d_",
622
+ });
623
+ const duplicateUpdateVisitor = (context, depsTree, _sourceFile, namesMap, callNameMap) => {
624
+ const { factory } = context;
625
+ const visit = (node) => {
626
+ if (typescript_1.default.isVariableStatement(node)) {
627
+ const newDeclarations = node.declarationList.declarations.map((decl) => {
628
+ if (typescript_1.default.isIdentifier(decl.name)) {
629
+ const base = decl.name.text;
630
+ if (namesMap.has(base) && namesMap.get(base).size > 1) {
631
+ const newName = dupName.getName(base);
632
+ callNameMap.push({ base, file: depsTree.file, newName });
633
+ return factory.updateVariableDeclaration(decl, factory.createIdentifier(newName), decl.exclamationToken, decl.type, decl.initializer);
634
+ }
635
+ }
636
+ return decl;
637
+ });
638
+ const newDeclList = factory.updateVariableDeclarationList(node.declarationList, newDeclarations);
639
+ return factory.updateVariableStatement(node, node.modifiers, newDeclList);
640
+ }
641
+ else if (typescript_1.default.isFunctionDeclaration(node)) {
642
+ if (node.name && typescript_1.default.isIdentifier(node.name)) {
643
+ const base = node.name.text;
644
+ if (namesMap.has(base) && namesMap.get(base).size > 1) {
645
+ const newName = dupName.getName(base);
646
+ callNameMap.push({ base, file: depsTree.file, newName });
647
+ return factory.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, factory.createIdentifier(newName), node.typeParameters, node.parameters, node.type, node.body);
648
+ }
649
+ }
650
+ }
651
+ else if (typescript_1.default.isClassDeclaration(node)) {
652
+ if (node.name && typescript_1.default.isIdentifier(node.name)) {
653
+ const base = node.name.text;
654
+ if (namesMap.has(base) && namesMap.get(base).size > 1) {
655
+ const newName = dupName.getName(base);
656
+ callNameMap.push({ base, file: depsTree.file, newName });
657
+ return factory.updateClassDeclaration(node, node.modifiers, factory.createIdentifier(newName), node.typeParameters, node.heritageClauses, node.members);
658
+ }
659
+ }
660
+ }
661
+ return typescript_1.default.visitEachChild(node, visit, context);
662
+ };
663
+ return visit;
664
+ };
665
+ const removeExportsVisitor = (context) => {
666
+ const { factory } = context;
667
+ const visit = (node) => {
668
+ const inside_nameSpace = utils_1.default.isInsideNamespace(node);
669
+ if (!inside_nameSpace) {
670
+ if (typescript_1.default.isFunctionDeclaration(node) ||
671
+ typescript_1.default.isClassDeclaration(node) ||
672
+ typescript_1.default.isInterfaceDeclaration(node) ||
673
+ typescript_1.default.isTypeAliasDeclaration(node) ||
674
+ typescript_1.default.isEnumDeclaration(node) ||
675
+ typescript_1.default.isVariableStatement(node)) {
676
+ const modifiers = node.modifiers?.filter((m) => m.kind !== typescript_1.default.SyntaxKind.ExportKeyword &&
677
+ m.kind !== typescript_1.default.SyntaxKind.DefaultKeyword);
678
+ if (modifiers?.length !== node.modifiers?.length) {
679
+ if (typescript_1.default.isFunctionDeclaration(node)) {
680
+ return factory.updateFunctionDeclaration(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
681
+ }
682
+ if (typescript_1.default.isClassDeclaration(node)) {
683
+ return factory.updateClassDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
684
+ }
685
+ if (typescript_1.default.isInterfaceDeclaration(node)) {
686
+ return factory.updateInterfaceDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
687
+ }
688
+ if (typescript_1.default.isTypeAliasDeclaration(node)) {
689
+ return factory.updateTypeAliasDeclaration(node, modifiers, node.name, node.typeParameters, node.type);
690
+ }
691
+ if (typescript_1.default.isEnumDeclaration(node)) {
692
+ return factory.updateEnumDeclaration(node, modifiers, node.name, node.members);
693
+ }
694
+ if (typescript_1.default.isVariableStatement(node)) {
695
+ return factory.updateVariableStatement(node, modifiers, node.declarationList);
696
+ }
697
+ }
698
+ }
699
+ }
700
+ if (typescript_1.default.isExportDeclaration(node)) {
701
+ return factory.createEmptyStatement();
702
+ }
703
+ if (typescript_1.default.isExportAssignment(node)) {
704
+ const expr = node.expression;
705
+ if (typescript_1.default.isIdentifier(expr)) {
706
+ return factory.createEmptyStatement();
707
+ }
708
+ }
709
+ return typescript_1.default.visitEachChild(node, visit, context);
710
+ };
711
+ return visit;
712
+ };
713
+ let properties = [];
714
+ const typeObj = {};
715
+ const typesNames = [];
716
+ function findProperty(node) {
717
+ const properties = [];
718
+ if (typescript_1.default.isPropertyAccessExpression(node) && typescript_1.default.isIdentifier(node.expression)) {
719
+ properties.push(node.expression.text);
720
+ }
721
+ node.forEachChild((n) => findProperty(n));
722
+ return properties;
723
+ }
724
+ const removeImportsVisitor = (context, depsTree, sourceFile, removedStatements) => {
725
+ const typeOnlyImportEquals = new Set();
726
+ for (const stmt of sourceFile.statements) {
727
+ if (typescript_1.default.isImportEqualsDeclaration(stmt) && stmt.isTypeOnly) {
728
+ const moduleReference = stmt.moduleReference;
729
+ if (typescript_1.default.isExternalModuleReference(moduleReference) &&
730
+ typescript_1.default.isStringLiteral(moduleReference.expression)) {
731
+ typeOnlyImportEquals.add(stmt.name.text);
732
+ }
733
+ }
734
+ }
735
+ const { factory } = context;
736
+ const visit = (node) => {
737
+ properties = [...properties, ...findProperty(node)];
738
+ const obj = {
739
+ isNamespace: false,
740
+ isTypeOnly: false,
741
+ isTypeNamespace: false,
742
+ source: "",
743
+ importedString: undefined,
744
+ importedObject: undefined,
745
+ };
746
+ if (typescript_1.default.isTypeReferenceNode(node) &&
747
+ typescript_1.default.isQualifiedName(node.typeName) &&
748
+ typescript_1.default.isIdentifier(node.typeName.left) &&
749
+ typescript_1.default.isIdentifier(node.typeName.right)) {
750
+ const left = node.typeName.left.text;
751
+ const right = node.typeName.right.text;
752
+ typesNames.push(left);
753
+ if (left in typeObj) {
754
+ typeObj[left]?.push(right);
755
+ }
756
+ else {
757
+ typeObj[left] = [right];
758
+ }
759
+ if (utils_1.default.checkModuleType(sourceFile, depsTree.file).isCommonJs) {
760
+ if (left !== "ts" && !typeOnlyImportEquals.has(left)) {
761
+ return factory.updateTypeReferenceNode(node, factory.createIdentifier(right), undefined);
762
+ }
763
+ }
764
+ }
765
+ if (typescript_1.default.isImportDeclaration(node)) {
766
+ const text = node.getText(sourceFile);
767
+ removedStatements.push(text);
768
+ return factory.createEmptyStatement();
769
+ }
770
+ if (typescript_1.default.isImportEqualsDeclaration(node)) {
771
+ const name = node.name.text;
772
+ const moduleReference = node.moduleReference;
773
+ if (node.isTypeOnly) {
774
+ obj.isTypeOnly = true;
775
+ }
776
+ obj.importedString = name;
777
+ if (!obj.isTypeOnly) {
778
+ if (properties.includes(name)) {
779
+ obj.isNamespace = true;
780
+ }
781
+ }
782
+ if (typescript_1.default.isExternalModuleReference(moduleReference) &&
783
+ typescript_1.default.isStringLiteral(moduleReference.expression)) {
784
+ obj.source = moduleReference.expression.text;
785
+ }
786
+ let t;
787
+ if (obj.importedString && !obj.importedObject) {
788
+ if (obj.isTypeOnly) {
789
+ if (typeOnlyImportEquals.has(obj.importedString)) {
790
+ t = `import type * as ${obj.importedString} from "${obj.source}";`;
791
+ }
792
+ else {
793
+ if (typesNames.includes(obj.importedString)) {
794
+ t = `import type { ${typeObj[obj.importedString]?.join(",")} } from "${obj.source}";`;
795
+ }
796
+ else {
797
+ t = `import type ${obj.importedString} from "${obj.source}";`;
798
+ }
799
+ }
800
+ }
801
+ else {
802
+ if (obj.isNamespace && obj.source && obj.source !== "typescript") {
803
+ t = `import * as ${obj.importedString} from "${obj.source}";`;
804
+ }
805
+ else {
806
+ t = `import ${obj.importedString} from "${obj.source}";`;
807
+ }
808
+ }
809
+ }
810
+ if (!obj.importedString && obj.importedObject) {
811
+ t = `import { ${obj.importedObject.join(", ")} } from "${obj.source}";`;
812
+ }
813
+ if (t) {
814
+ removedStatements.push(t);
815
+ return factory.createEmptyStatement();
816
+ }
817
+ }
818
+ if (typescript_1.default.isVariableStatement(node)) {
819
+ const decls = node.declarationList.declarations;
820
+ if (decls.length === 1) {
821
+ const decl = decls[0];
822
+ if (decl.initializer &&
823
+ typescript_1.default.isCallExpression(decl.initializer) &&
824
+ typescript_1.default.isIdentifier(decl.initializer.expression) &&
825
+ decl.initializer.expression.escapedText === "require") {
826
+ const arg = decl.initializer.arguments[0];
827
+ if (typescript_1.default.isStringLiteral(arg)) {
828
+ obj.source = arg.text;
829
+ }
830
+ if (typescript_1.default.isIdentifier(decl.name)) {
831
+ const _n = decl.name.text;
832
+ obj.importedString = _n;
833
+ if (properties.includes(_n)) {
834
+ obj.isNamespace = true;
835
+ }
836
+ }
837
+ else if (typescript_1.default.isObjectBindingPattern(decl.name)) {
838
+ const _names = [];
839
+ for (const ele of decl.name.elements) {
840
+ if (typescript_1.default.isIdentifier(ele.name)) {
841
+ _names.push(ele.name.text);
842
+ }
843
+ }
844
+ if (_names.length > 0) {
845
+ obj.importedObject = _names;
846
+ }
847
+ }
848
+ let tt;
849
+ if (obj.importedString && !obj.importedObject) {
850
+ if (obj.isNamespace) {
851
+ tt = `import * as ${obj.importedString} from "${obj.source}";`;
852
+ }
853
+ else {
854
+ tt = `import ${obj.importedString} from "${obj.source}";`;
855
+ }
856
+ }
857
+ if (!obj.importedString && obj.importedObject) {
858
+ tt = `import { ${obj.importedObject.join(", ")} } from "${obj.source}";`;
859
+ }
860
+ if (tt) {
861
+ removedStatements.push(tt);
862
+ return factory.createEmptyStatement();
863
+ }
864
+ }
865
+ }
866
+ }
867
+ return typescript_1.default.visitEachChild(node, visit, context);
868
+ };
869
+ return visit;
870
+ };
871
+ async function bundler(point) {
872
+ let depsFiles = point.depFiles;
873
+ const reName = point.rename;
874
+ const compilerOptions = point.tsOptions.default;
875
+ const plugins = point.plugins;
236
876
  const namesMap = new Map();
237
877
  const callNameMap = [];
238
878
  const importNameMap = [];
@@ -240,30 +880,136 @@ async function bundler({ depsFiles, compilerOptions, renameDuplicates, }) {
240
880
  const exportDefaultExportNameMap = [];
241
881
  const exportDefaultImportNameMap = [];
242
882
  let removedStatements = [];
243
- if (reName) {
244
- depsFiles = await duplicates_1.default.renamed(depsFiles, namesMap, callNameMap, importNameMap, exportNameMap, compilerOptions);
245
- }
246
- else {
247
- depsFiles = await duplicates_1.default.notRenamed(depsFiles, namesMap, compilerOptions);
883
+ const duplicate = async (reName) => {
884
+ if (reName) {
885
+ const re_name = (0, resolves_1.default)([
886
+ [bundleCreator, duplicateCollectionVisitor, compilerOptions, namesMap],
887
+ [
888
+ bundleCreator,
889
+ duplicateUpdateVisitor,
890
+ compilerOptions,
891
+ namesMap,
892
+ callNameMap,
893
+ ],
894
+ [
895
+ bundleCreator,
896
+ duplicateCallExpressionVisitor,
897
+ compilerOptions,
898
+ callNameMap,
899
+ importNameMap,
900
+ ],
901
+ [
902
+ bundleCreator,
903
+ duplicateExportExpressionVisitor,
904
+ compilerOptions,
905
+ importNameMap,
906
+ exportNameMap,
907
+ ],
908
+ [
909
+ bundleCreator,
910
+ duplicateImportExpressionVisitor,
911
+ compilerOptions,
912
+ exportNameMap,
913
+ importNameMap,
914
+ ],
915
+ [
916
+ bundleCreator,
917
+ duplicateExportExpressionVisitor,
918
+ compilerOptions,
919
+ importNameMap,
920
+ exportNameMap,
921
+ ],
922
+ [
923
+ bundleCreator,
924
+ duplicateExportExpressionVisitor,
925
+ compilerOptions,
926
+ importNameMap,
927
+ exportNameMap,
928
+ ],
929
+ ]);
930
+ const re_name_call = await re_name.concurrent();
931
+ for (const call of re_name_call) {
932
+ await utils_1.default.wait(500);
933
+ depsFiles = depsFiles.map(call);
934
+ }
935
+ }
936
+ else {
937
+ let _err = false;
938
+ const un_rename = (0, resolves_1.default)([
939
+ [bundleCreator, duplicateCollectionVisitor, compilerOptions, namesMap],
940
+ ]);
941
+ const un_rename_call = await un_rename.concurrent();
942
+ depsFiles.map(un_rename_call[0]);
943
+ await utils_1.default.wait(1000);
944
+ namesMap.forEach((files, name) => {
945
+ if (files.size > 1) {
946
+ _err = true;
947
+ console.warn(`Name -> ${name} declared in multiple files :`);
948
+ files.forEach((f) => console.warn(` - ${f.file}`));
949
+ }
950
+ });
951
+ await utils_1.default.wait(1000);
952
+ if (_err) {
953
+ process.exit(1);
954
+ }
955
+ }
956
+ };
957
+ if (plugins.length) {
958
+ for (let plugin of plugins) {
959
+ plugin = typeof plugin === "function" ? plugin() : plugin;
960
+ if (plugin.type === "dependency") {
961
+ if (plugin.async) {
962
+ depsFiles = await plugin.func(depsFiles);
963
+ }
964
+ else {
965
+ depsFiles = plugin.func(depsFiles);
966
+ }
967
+ }
968
+ }
248
969
  }
249
970
  await utils_1.default.wait(1000);
250
- depsFiles = await (0, anonymous_1.default)(depsFiles, exportDefaultExportNameMap, exportDefaultImportNameMap, compilerOptions);
971
+ await duplicate(reName);
972
+ const anonymous = (0, resolves_1.default)([
973
+ [
974
+ bundleCreator,
975
+ anonymousExportVisitor,
976
+ compilerOptions,
977
+ exportDefaultExportNameMap,
978
+ ],
979
+ [
980
+ bundleCreator,
981
+ anonymousImportVisitor,
982
+ compilerOptions,
983
+ exportDefaultImportNameMap,
984
+ exportDefaultImportNameMap,
985
+ ],
986
+ [
987
+ bundleCreator,
988
+ anonymousCallExpressionVisitor,
989
+ compilerOptions,
990
+ exportDefaultImportNameMap,
991
+ ],
992
+ ]);
993
+ const anonymousCall = await anonymous.concurrent();
994
+ for (const call of anonymousCall) {
995
+ depsFiles = depsFiles.map(call);
996
+ }
251
997
  await utils_1.default.wait(1000);
252
998
  const removeImports = (0, resolves_1.default)([
253
- [removeImportExpressionHandler, removedStatements, compilerOptions],
999
+ [bundleCreator, removeImportsVisitor, compilerOptions, removedStatements],
254
1000
  ]);
255
1001
  const removeImport = await removeImports.concurrent();
256
1002
  depsFiles = depsFiles.map(removeImport[0]);
257
- await utils_1.default.wait(1000);
1003
+ await utils_1.default.wait(500);
258
1004
  const removeExports = (0, resolves_1.default)([
259
- [removeExportExpressionHandler, compilerOptions],
1005
+ [bundleCreator, removeExportsVisitor, compilerOptions],
260
1006
  ]);
261
1007
  const removeExport = await removeExports.concurrent();
262
1008
  const deps_files = depsFiles.slice(0, -1).map(removeExport[0]);
263
1009
  const mainFile = depsFiles.slice(-1);
264
1010
  const regexp = /["']((?!\.\/|\.\.\/)[^"']+)["']/;
265
1011
  removedStatements = removedStatements.filter((i) => regexp.test(i));
266
- removedStatements = mergeImports(removedStatements);
1012
+ removedStatements = mergeImportsStatement(removedStatements);
267
1013
  const importStatements = removedStatements.join("\n").trim();
268
1014
  const depFilesContent = deps_files
269
1015
  .map((i) => {
@@ -280,79 +1026,34 @@ async function bundler({ depsFiles, compilerOptions, renameDuplicates, }) {
280
1026
  .join("\n")
281
1027
  .trim();
282
1028
  await utils_1.default.wait(1000);
283
- const content = `${importStatements}\n${depFilesContent}\n${mainFileContent}`;
284
- return content;
285
- }
286
- function checkExports(file, str) {
287
- const sourceFile = typescript_1.default.createSourceFile(file, str, typescript_1.default.ScriptTarget.Latest, true);
288
- let nameExport = false;
289
- let defExport = false;
290
- const transformer = (context) => {
291
- const visitor = (node) => {
292
- if (typescript_1.default.isExportAssignment(node) &&
293
- !node.isExportEquals &&
294
- node.modifiers === undefined &&
295
- typescript_1.default.isIdentifier(node.expression)) {
296
- defExport = true;
297
- }
298
- else if (typescript_1.default.isFunctionDeclaration(node) ||
299
- typescript_1.default.isClassDeclaration(node)) {
300
- let exp = false;
301
- let def = false;
302
- node.modifiers?.forEach((mod) => {
303
- if (mod.kind === typescript_1.default.SyntaxKind.ExportKeyword) {
304
- exp = true;
305
- }
306
- if (mod.kind === typescript_1.default.SyntaxKind.DefaultKeyword) {
307
- def = true;
308
- }
309
- });
310
- if (exp && def)
311
- defExport = true;
312
- }
313
- else if (typescript_1.default.isExportAssignment(node) &&
314
- typescript_1.default.isObjectLiteralExpression(node.expression)) {
315
- const pros = node.expression.properties;
316
- for (const pro of pros) {
317
- if (pro.name && typescript_1.default.isIdentifier(pro.name)) {
318
- defExport = true;
319
- }
1029
+ let content = `${importStatements}\n${depFilesContent}\n${mainFileContent}`;
1030
+ if (plugins.length) {
1031
+ for (let plugin of plugins) {
1032
+ plugin = typeof plugin === "function" ? plugin() : plugin;
1033
+ if (plugin.type === "pre-process") {
1034
+ if (plugin.async) {
1035
+ content = await plugin.func(content);
1036
+ }
1037
+ else {
1038
+ content = plugin.func(content);
320
1039
  }
321
1040
  }
322
- else if (typescript_1.default.isNamedExports(node)) {
323
- nameExport = true;
324
- }
325
- else if (typescript_1.default.isVariableStatement(node) ||
326
- typescript_1.default.isFunctionDeclaration(node) ||
327
- typescript_1.default.isInterfaceDeclaration(node) ||
328
- typescript_1.default.isTypeAliasDeclaration(node)) {
329
- const isInsideNamespace = (n) => {
330
- let current = n.parent;
331
- while (current) {
332
- if (typescript_1.default.isModuleDeclaration(current) &&
333
- current.flags === typescript_1.default.NodeFlags.Namespace) {
334
- return true;
335
- }
336
- current = current.parent;
337
- }
338
- return false;
339
- };
340
- node?.modifiers?.forEach((mod) => {
341
- if (mod.kind === typescript_1.default.SyntaxKind.ExportKeyword) {
342
- if (!isInsideNamespace(node)) {
343
- nameExport = true;
344
- }
345
- }
346
- });
347
- }
348
- return typescript_1.default.visitEachChild(node, visitor, context);
349
- };
350
- return (rootNode) => typescript_1.default.visitNode(rootNode, visitor);
1041
+ }
1042
+ }
1043
+ return { bundledContent: content, ...point };
1044
+ }
1045
+ async function bundle(object) {
1046
+ const points = [];
1047
+ for (const point of object.points) {
1048
+ const _point = await bundler(point);
1049
+ points.push(_point);
1050
+ }
1051
+ return {
1052
+ points,
1053
+ allowUpdatePackageJson: object.allowUpdatePackageJson,
351
1054
  };
352
- typescript_1.default.transform(sourceFile, [transformer]);
353
- return { nameExport, defExport };
354
1055
  }
355
- const createHost = (sourceCode, fileName) => {
1056
+ function createHost(sourceCode, fileName) {
356
1057
  const createdFiles = {};
357
1058
  const host = {
358
1059
  getSourceFile: (file, languageVersion) => {
@@ -374,80 +1075,106 @@ const createHost = (sourceCode, fileName) => {
374
1075
  getNewLine: () => "\n",
375
1076
  };
376
1077
  return { createdFiles, host };
377
- };
378
- function replaceInJs(fileName, sourceCode, compilerOptions) {
379
- const sourceFile = typescript_1.default.createSourceFile(fileName, sourceCode, typescript_1.default.ScriptTarget.Latest, true);
380
- const transformer = (context) => {
381
- const { factory } = context;
382
- const visitor = (node) => {
383
- if (typescript_1.default.isExpressionStatement(node)) {
384
- const expr = node.expression;
385
- if (typescript_1.default.isBinaryExpression(expr) &&
386
- typescript_1.default.isPropertyAccessExpression(expr.left) &&
387
- typescript_1.default.isIdentifier(expr.left.expression) &&
388
- expr.left.expression.escapedText === "exports" &&
389
- typescript_1.default.isIdentifier(expr.left.name) &&
390
- expr.left.name.escapedText === "default" &&
391
- expr.operatorToken.kind === typescript_1.default.SyntaxKind.EqualsToken &&
392
- typescript_1.default.isIdentifier(expr.right)) {
393
- const newLeftExpr = factory.createIdentifier("module");
394
- const newName = factory.createIdentifier("exports");
395
- const newLeft = factory.updatePropertyAccessExpression(expr.left, newLeftExpr, newName);
396
- const newExpr = factory.updateBinaryExpression(expr, newLeft, expr.operatorToken, expr.right);
397
- return factory.updateExpressionStatement(node, newExpr);
398
- }
399
- }
400
- return typescript_1.default.visitEachChild(node, visitor, context);
401
- };
402
- return (rootNode) => typescript_1.default.visitNode(rootNode, visitor);
403
- };
404
- return (0, transformer_1.default)(transformer, sourceFile, compilerOptions);
405
- }
406
- function replaceInTs(fileName, sourceCode, compilerOptions) {
407
- const sourceFile = typescript_1.default.createSourceFile(fileName, sourceCode, typescript_1.default.ScriptTarget.Latest, true);
408
- const transformer = (context) => {
409
- const { factory } = context;
410
- const visitor = (node) => {
411
- if (typescript_1.default.isExportAssignment(node) &&
412
- node.modifiers === undefined &&
413
- !node.isExportEquals) {
414
- return factory.createExportAssignment(node.modifiers, true, node.expression);
415
- }
416
- return typescript_1.default.visitEachChild(node, visitor, context);
417
- };
418
- return (rootNode) => typescript_1.default.visitNode(rootNode, visitor);
419
- };
420
- return (0, transformer_1.default)(transformer, sourceFile, compilerOptions);
421
1078
  }
422
- async function clearFolder(folderPath) {
423
- folderPath = node_path_1.default.resolve(process.cwd(), folderPath);
424
- try {
425
- const entries = await node_fs_1.default.promises.readdir(folderPath, {
426
- withFileTypes: true,
427
- });
428
- await Promise.all(entries.map((entry) => node_fs_1.default.promises.rm(node_path_1.default.join(folderPath, entry.name), {
429
- recursive: true,
430
- })));
431
- }
432
- catch (error) {
433
- if (error.code !== "ENOENT") {
434
- throw error;
1079
+ const isCjs = (files) => files.commonjs && files.commonjsTypes;
1080
+ const isEsm = (files) => files.esm && files.esmTypes;
1081
+ function getExports(files, exportPath) {
1082
+ return isCjs(files) && isEsm(files)
1083
+ ? {
1084
+ [exportPath]: {
1085
+ import: {
1086
+ default: `./${node_path_1.default.relative(process.cwd(), files.esm)}`,
1087
+ types: `./${node_path_1.default.relative(process.cwd(), files.esmTypes)}`,
1088
+ },
1089
+ require: {
1090
+ default: `./${node_path_1.default.relative(process.cwd(), files.commonjs)}`,
1091
+ types: `./${node_path_1.default.relative(process.cwd(), files.commonjsTypes)}`,
1092
+ },
1093
+ },
435
1094
  }
436
- }
1095
+ : isCjs(files) && !isEsm(files)
1096
+ ? {
1097
+ [exportPath]: {
1098
+ require: {
1099
+ default: `./${node_path_1.default.relative(process.cwd(), files.commonjs)}`,
1100
+ types: `./${node_path_1.default.relative(process.cwd(), files.commonjsTypes)}`,
1101
+ },
1102
+ },
1103
+ }
1104
+ : !isCjs(files) && isEsm(files)
1105
+ ? {
1106
+ [exportPath]: {
1107
+ import: {
1108
+ default: `./${node_path_1.default.relative(process.cwd(), files.esm)}`,
1109
+ types: `./${node_path_1.default.relative(process.cwd(), files.esmTypes)}`,
1110
+ },
1111
+ },
1112
+ }
1113
+ : {};
437
1114
  }
438
- async function writeCompileFile(file, content) {
439
- const filePath = typescript_1.default.sys.resolvePath(file);
440
- const dir = node_path_1.default.dirname(filePath);
441
- if (!typescript_1.default.sys.directoryExists(dir)) {
442
- await node_fs_1.default.promises.mkdir(dir, { recursive: true });
1115
+ async function writePackage(files, exportPath) {
1116
+ let isMain = true;
1117
+ if (exportPath !== ".") {
1118
+ isMain = false;
443
1119
  }
1120
+ const pkgFile = typescript_1.default.sys.resolvePath("package.json");
1121
+ const _pkgtext = node_fs_1.default.readFileSync(pkgFile, "utf8");
1122
+ const pkgtext = JSON.parse(_pkgtext);
1123
+ let { name, version, description, main, module, type, types, exports, ...rest } = pkgtext;
444
1124
  await utils_1.default.wait(500);
445
- await node_fs_1.default.promises.writeFile(filePath, content);
1125
+ type = "module";
1126
+ let _main = {};
1127
+ let _module = {};
1128
+ let _types = {};
1129
+ let _exports = {};
1130
+ if (isMain) {
1131
+ _main = files.main
1132
+ ? { main: node_path_1.default.relative(process.cwd(), files.main) }
1133
+ : {};
1134
+ _module = files.module
1135
+ ? { module: node_path_1.default.relative(process.cwd(), files.module) }
1136
+ : {};
1137
+ _types = files.types
1138
+ ? { types: node_path_1.default.relative(process.cwd(), files.types) }
1139
+ : {};
1140
+ _exports = { exports: { ...getExports(files, exportPath) } };
1141
+ }
1142
+ else {
1143
+ _main = main ? { main: main } : {};
1144
+ _module = module ? { module: module } : {};
1145
+ _types = types ? { types: types } : {};
1146
+ const normalizedExports = exports && typeof exports === "object" && !Array.isArray(exports)
1147
+ ? { ...exports }
1148
+ : {};
1149
+ _exports = {
1150
+ exports: { ...normalizedExports, ...getExports(files, exportPath) },
1151
+ };
1152
+ }
1153
+ await utils_1.default.wait(1000);
1154
+ const pkgJson = {
1155
+ name,
1156
+ version,
1157
+ description,
1158
+ type,
1159
+ ..._main,
1160
+ ..._types,
1161
+ ..._module,
1162
+ ..._exports,
1163
+ ...rest,
1164
+ };
1165
+ utils_1.default.writeCompileFile(pkgFile, JSON.stringify(pkgJson, null, 2));
446
1166
  }
447
- class Compilers {
448
- constructor(options) {
449
- this._target = options?.target ?? "both";
450
- this._configPath = options?.configPath;
1167
+ function splitCamelCase(str) {
1168
+ const splitString = str
1169
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
1170
+ .replace(/(_|-|\/)([a-z] || [A-Z])/g, " ")
1171
+ .replace(/([A-Z])/g, (match) => match.toLowerCase())
1172
+ .replace(/^([a-z])/, (match) => match.toUpperCase());
1173
+ return splitString;
1174
+ }
1175
+ class Compiler {
1176
+ constructor(object) {
1177
+ this.object = object;
451
1178
  this.files = {
452
1179
  commonjs: undefined,
453
1180
  commonjsTypes: undefined,
@@ -457,48 +1184,46 @@ class Compilers {
457
1184
  module: undefined,
458
1185
  types: undefined,
459
1186
  };
460
- this.outDir = "";
461
1187
  }
462
- async commonjs(sourceCode, fileName, compilerOptions, isMain, hooks, isUpdate = true) {
463
- console.time(tcolor_1.default.green("Compiled Commonjs"));
464
- const ck = checkExports(fileName, sourceCode);
465
- if (ck.defExport && ck.nameExport) {
466
- console.warn(tcolor_1.default.yellow("Both name export and default export are exported from your project,that will effect on default export for commonjs output"));
467
- }
1188
+ _isUpdate() {
1189
+ return this.object.allowUpdatePackageJson;
1190
+ }
1191
+ async _commonjs(point) {
1192
+ const isMain = point.exportPath === ".";
1193
+ const _name = isMain ? "Main" : splitCamelCase(point.exportPath.slice(2));
1194
+ console.time(tcolor_1.default.cyan(`Compiled commonjs for ${_name} export path`));
1195
+ const fileName = point.fileName;
1196
+ const sourceCode = point.bundledContent;
1197
+ const format = point.format;
1198
+ const plugins = point.plugins;
1199
+ const compilerOptions = point.tsOptions.cjs;
468
1200
  const _host = createHost(sourceCode, fileName);
469
1201
  const createdFiles = _host.createdFiles;
470
1202
  const host = _host.host;
471
1203
  const program = typescript_1.default.createProgram([fileName], compilerOptions, host);
472
1204
  program.emit();
473
1205
  Object.entries(createdFiles).map(async ([outName, content]) => {
474
- if (ck.defExport && !ck.nameExport) {
475
- const ext = utils_1.default.extname(outName);
476
- if (ext === ".js") {
477
- content = replaceInJs(fileName, content, compilerOptions);
478
- }
479
- if (ext === ".ts") {
480
- content = replaceInTs(fileName, content, compilerOptions);
481
- }
482
- }
483
- if (hooks?.length) {
484
- for (const hook of hooks) {
485
- if (hook.async) {
486
- content = await hook.func(content, outName);
487
- }
488
- else {
489
- content = hook.func(content, outName);
1206
+ if (plugins.length) {
1207
+ for (let plugin of plugins) {
1208
+ plugin = typeof plugin === "function" ? plugin() : plugin;
1209
+ if (plugin.type === "post-process") {
1210
+ if (plugin.async) {
1211
+ content = await plugin.func(content, outName);
1212
+ }
1213
+ else {
1214
+ content = plugin.func(content, outName);
1215
+ }
490
1216
  }
491
1217
  }
492
1218
  }
493
- if (isUpdate) {
1219
+ if (this._isUpdate()) {
494
1220
  if (outName.match(/.js/g)) {
495
1221
  this.files.commonjs = outName.replace(/.js/g, ".cjs");
496
1222
  }
497
1223
  if (outName.match(/.d.ts/g)) {
498
1224
  this.files.commonjsTypes = outName.replace(/.d.ts/g, ".d.cts");
499
1225
  }
500
- if (isMain &&
501
- (this._target === "both" || this._target === "commonjs")) {
1226
+ if (isMain && (format === "both" || format === "commonjs")) {
502
1227
  if (this.files.commonjs)
503
1228
  this.files.main = this.files.commonjs;
504
1229
  if (this.files.commonjsTypes)
@@ -509,39 +1234,49 @@ class Compilers {
509
1234
  outName = outName.replace(/.map.js/g, ".map.cjs");
510
1235
  outName = outName.replace(/.d.ts/g, ".d.cts");
511
1236
  await utils_1.default.wait(500);
512
- if (this._target !== "both" && this._target !== "esm") {
513
- await clearFolder(utils_1.default.dirname(outName));
1237
+ if (format === "commonjs") {
1238
+ await utils_1.default.clearFolder(node_path_1.default.dirname(outName));
514
1239
  }
515
- await writeCompileFile(outName, content);
1240
+ await utils_1.default.writeCompileFile(outName, content);
516
1241
  });
517
- console.timeEnd(tcolor_1.default.green("Compiled Commonjs"));
1242
+ console.timeEnd(tcolor_1.default.cyan(`Compiled commonjs for ${_name} export path`));
518
1243
  }
519
- async esm(sourceCode, fileName, compilerOptions, isMain, hooks, isUpdate = true) {
520
- console.time(tcolor_1.default.green("Compiled ESM"));
1244
+ async _esm(point) {
1245
+ const isMain = point.exportPath === ".";
1246
+ const _name = isMain ? "Main" : splitCamelCase(point.exportPath.slice(2));
1247
+ console.time(tcolor_1.default.cyan(`Compiled esm for ${_name} export path`));
1248
+ const fileName = point.fileName;
1249
+ const sourceCode = point.bundledContent;
1250
+ const format = point.format;
1251
+ const plugins = point.plugins;
1252
+ const compilerOptions = point.tsOptions.esm;
521
1253
  const _host = createHost(sourceCode, fileName);
522
1254
  const createdFiles = _host.createdFiles;
523
1255
  const host = _host.host;
524
1256
  const program = typescript_1.default.createProgram([fileName], compilerOptions, host);
525
1257
  program.emit();
526
1258
  Object.entries(createdFiles).map(async ([outName, content]) => {
527
- if (hooks?.length) {
528
- for (const hook of hooks) {
529
- if (hook.async) {
530
- content = await hook.func(content, outName);
531
- }
532
- else {
533
- content = hook.func(content, outName);
1259
+ if (plugins.length) {
1260
+ for (let plugin of plugins) {
1261
+ plugin = typeof plugin === "function" ? plugin() : plugin;
1262
+ if (plugin.type === "post-process") {
1263
+ if (plugin.async) {
1264
+ content = await plugin.func(content, outName);
1265
+ }
1266
+ else {
1267
+ content = plugin.func(content, outName);
1268
+ }
534
1269
  }
535
1270
  }
536
1271
  }
537
- if (isUpdate) {
1272
+ if (this._isUpdate()) {
538
1273
  if (outName.match(/.js/g)) {
539
1274
  this.files.esm = outName.replace(/.js/g, ".mjs");
540
1275
  }
541
1276
  if (outName.match(/.d.ts/g)) {
542
1277
  this.files.esmTypes = outName.replace(/.d.ts/g, ".d.mts");
543
1278
  }
544
- if (isMain && this._target === "both" && this.files.esm) {
1279
+ if (isMain && format === "both" && this.files.esm) {
545
1280
  this.files.module = this.files.esm;
546
1281
  }
547
1282
  }
@@ -549,18 +1284,47 @@ class Compilers {
549
1284
  outName = outName.replace(/.map.js/g, ".map.mjs");
550
1285
  outName = outName.replace(/.d.ts/g, ".d.mts");
551
1286
  await utils_1.default.wait(500);
552
- if (this._target !== "commonjs") {
553
- await clearFolder(utils_1.default.dirname(outName));
1287
+ if (format !== "commonjs") {
1288
+ await utils_1.default.clearFolder(node_path_1.default.dirname(outName));
554
1289
  }
555
- await writeCompileFile(outName, content);
1290
+ await utils_1.default.writeCompileFile(outName, content);
556
1291
  });
557
- console.timeEnd(tcolor_1.default.green("Compiled ESM"));
1292
+ console.timeEnd(tcolor_1.default.cyan(`Compiled esm for ${_name} export path`));
1293
+ }
1294
+ async compile() {
1295
+ for (const point of this.object.points) {
1296
+ await utils_1.default.wait(500);
1297
+ switch (point.format) {
1298
+ case "commonjs":
1299
+ await this._commonjs(point);
1300
+ if (this._isUpdate()) {
1301
+ await writePackage(this.files, point.exportPath);
1302
+ }
1303
+ break;
1304
+ case "esm":
1305
+ await this._esm(point);
1306
+ if (this._isUpdate()) {
1307
+ await writePackage(this.files, point.exportPath);
1308
+ }
1309
+ break;
1310
+ case "both":
1311
+ await this._esm(point);
1312
+ await utils_1.default.wait(1000);
1313
+ await this._commonjs(point);
1314
+ if (this._isUpdate()) {
1315
+ await writePackage(this.files, point.exportPath);
1316
+ }
1317
+ break;
1318
+ }
1319
+ await utils_1.default.wait(500);
1320
+ }
558
1321
  }
559
1322
  }
560
- const depsCheck = {
561
- types(deps, compilerOptions) {
1323
+ var checks;
1324
+ (function (checks) {
1325
+ function typesCheck(dep, compilerOptions) {
562
1326
  if (!compilerOptions.noCheck) {
563
- const filePaths = deps.map((i) => i.file);
1327
+ const filePaths = dep.map((i) => i.file);
564
1328
  let _err = false;
565
1329
  const program = typescript_1.default.createProgram(filePaths, compilerOptions);
566
1330
  for (const filePath of filePaths) {
@@ -591,23 +1355,12 @@ const depsCheck = {
591
1355
  return true;
592
1356
  }
593
1357
  }
594
- },
595
- ext(deps) {
596
- const tsExt = new Set([".ts", ".mts", ".cts", ".tsx"]);
597
- for (const dep of deps) {
598
- const ext = utils_1.default.extname(dep.file);
599
- if (!tsExt.has(ext)) {
600
- console.error(tcolor_1.default.magenta(`${dep.file} has no valid TypeScript extension`));
601
- typescript_1.default.sys.exit(1);
602
- }
603
- }
604
- return true;
605
- },
606
- moduleType(deps) {
1358
+ }
1359
+ function moduleType(_dep) {
607
1360
  let _esmCount = 0;
608
1361
  let cjsCount = 0;
609
- let unknowCount = 0;
610
- for (const dep of deps) {
1362
+ let unknownCount = 0;
1363
+ for (const dep of _dep) {
611
1364
  try {
612
1365
  const sourceFile = typescript_1.default.createSourceFile(dep.file, dep.content, typescript_1.default.ScriptTarget.Latest, true);
613
1366
  let hasESMImports = false;
@@ -658,10 +1411,10 @@ const depsCheck = {
658
1411
  }
659
1412
  catch (error) {
660
1413
  console.error(tcolor_1.default.magenta(`Error checking module format for ${dep.file} : \n ${error}`));
661
- unknowCount++;
1414
+ unknownCount++;
662
1415
  }
663
1416
  }
664
- if (unknowCount) {
1417
+ if (unknownCount) {
665
1418
  console.error(tcolor_1.default.magenta("Unknown error when checking module types in the dependencies tree."));
666
1419
  typescript_1.default.sys.exit(1);
667
1420
  }
@@ -670,126 +1423,29 @@ const depsCheck = {
670
1423
  typescript_1.default.sys.exit(1);
671
1424
  }
672
1425
  return true;
673
- },
674
- nodeCheck(nodeEnvOption, nodeModules) {
675
- if (!nodeEnvOption && nodeModules.length > 0) {
676
- console.error();
677
- typescript_1.default.sys.exit(1);
1426
+ }
1427
+ function ext(_dep) {
1428
+ const tsExt = new Set([".ts", ".mts", ".cts", ".tsx"]);
1429
+ for (const dep of _dep) {
1430
+ const ext = node_path_1.default.extname(dep.file);
1431
+ if (!tsExt.has(ext)) {
1432
+ console.error(tcolor_1.default.magenta(`${dep.file} has no valid TypeScript extension`));
1433
+ typescript_1.default.sys.exit(1);
1434
+ }
678
1435
  }
679
1436
  return true;
680
- },
681
- async make(deps, compilerOptions, nodeModules, nodeEnv = true) {
1437
+ }
1438
+ async function init(_dep, options) {
682
1439
  const res = (0, resolves_1.default)([
683
- [depsCheck.ext, deps],
684
- [depsCheck.nodeCheck, nodeEnv, nodeModules],
685
- [depsCheck.moduleType, deps],
686
- [depsCheck.types, deps, compilerOptions],
1440
+ [ext, _dep],
1441
+ [moduleType, _dep],
1442
+ [typesCheck, _dep, options],
687
1443
  ]);
688
1444
  const results = await res.concurrent();
689
1445
  return results.every((r) => r === true);
690
- },
691
- };
692
- async function getDependencies(entry) {
693
- const deps = await (0, dependencies_1.default)(entry);
694
- const sorted = deps.sort();
695
- const circularMessages = [];
696
- const nodeModules = deps.node();
697
- const depFiles = [];
698
- await utils_1.default.wait(100);
699
- for (const dep of sorted) {
700
- const file = utils_1.default.resolvePath(dep);
701
- const content = utils_1.default.readFile(file);
702
- depFiles.push({ file, content });
703
- }
704
- const circular = deps
705
- .mutual()
706
- .map((i) => `${i[0]} -> ${i[1]} \n ${i[1]} -> ${i[0]} \n`);
707
- const unknown = deps.warn().map((i) => `${i}\n`);
708
- if (circular.length)
709
- circularMessages.push(circular.join(""));
710
- if (unknown.length)
711
- circularMessages.push(unknown.join(""));
712
- return {
713
- depFiles,
714
- sorted,
715
- circularMessages,
716
- nodeModules,
717
- };
718
- }
719
- const getCompilerOptions = (exportPath, configPath) => {
720
- const config = new tsconfig_1.default(configPath);
721
- const generalOptions = () => config.getCompilerOptions();
722
- const commonjs = () => {
723
- const _config = new tsconfig_1.default(configPath);
724
- _config.addCompilerOptions({ outDir: "dist" });
725
- _config.removeCompilerOption("rootDir");
726
- _config.removeCompilerOption("module");
727
- const _options = _config.getCompilerOptions();
728
- let out_dir = _options.outDir;
729
- let isMain = true;
730
- if (exportPath !== ".") {
731
- out_dir = `${out_dir}/${exportPath.slice(2)}`;
732
- isMain = false;
733
- }
734
- const { outDir, module, ...restOptions } = _options;
735
- const compilerOptions = {
736
- outDir: out_dir,
737
- module: typescript_1.default.ModuleKind.CommonJS,
738
- ...restOptions,
739
- };
740
- return {
741
- isMain,
742
- compilerOptions,
743
- out_dir,
744
- };
745
- };
746
- const esm = () => {
747
- const __config = new tsconfig_1.default(configPath);
748
- __config.addCompilerOptions({ outDir: "dist" });
749
- __config.removeCompilerOption("rootDir");
750
- const _options = __config.getCompilerOptions();
751
- let out_dir = _options.outDir;
752
- let isMain = true;
753
- if (exportPath !== ".") {
754
- out_dir = `${out_dir}/${exportPath.slice(2)}`;
755
- isMain = false;
756
- }
757
- const { outDir, module, ...restOptions } = _options;
758
- const compilerOptions = {
759
- outDir: out_dir,
760
- module: typescript_1.default.ModuleKind.ES2022,
761
- ...restOptions,
762
- };
763
- return {
764
- isMain,
765
- compilerOptions,
766
- out_dir,
767
- };
768
- };
769
- return { commonjs, esm, generalOptions };
770
- };
771
- async function entry({ entryPath, exportPath, configPath, nodeEnv, }) {
772
- const deps = await getDependencies(entryPath);
773
- const depFiles = deps.depFiles;
774
- const nodeModules = deps.nodeModules;
775
- await utils_1.default.wait(1000);
776
- const opts = getCompilerOptions(exportPath, configPath);
777
- const generalOptions = opts.generalOptions();
778
- const modOpts = {
779
- commonjs: () => opts.commonjs(),
780
- esm: () => opts.esm(),
781
- };
782
- await utils_1.default.wait(1000);
783
- const checked = await depsCheck.make(depFiles, generalOptions, nodeModules, nodeEnv);
784
- if (!checked) {
785
- typescript_1.default.sys.exit(1);
786
1446
  }
787
- return {
788
- depFiles,
789
- modOpts,
790
- generalOptions,
791
- };
792
- }
1447
+ checks.init = init;
1448
+ })(checks || (checks = {}));
793
1449
  const getConfigPath = () => {
794
1450
  const fileNames = ["susee.config.ts", "susee.config.js", "susee.config.mjs"];
795
1451
  let configFile;
@@ -808,18 +1464,18 @@ function checkEntries(entries) {
808
1464
  typescript_1.default.sys.exit(1);
809
1465
  }
810
1466
  const objectStore = {};
811
- const duplicates = [];
1467
+ const duplicateExportPaths = [];
812
1468
  for (const obj of entries) {
813
1469
  const value = obj.exportPath;
814
1470
  if (objectStore[value]) {
815
- duplicates.push(`"${value}"`);
1471
+ duplicateExportPaths.push(`"${value}"`);
816
1472
  }
817
1473
  else {
818
1474
  objectStore[value] = true;
819
1475
  }
820
1476
  }
821
- if (duplicates.length > 0) {
822
- console.error(tcolor_1.default.magenta(`Duplicate export paths/path (${duplicates.join(",")}) found in your susee.config file , that will error for bundled output`));
1477
+ if (duplicateExportPaths.length > 0) {
1478
+ console.error(tcolor_1.default.magenta(`Duplicate export paths/path (${duplicateExportPaths.join(",")}) found in your susee.config file , that will error for bundled output`));
823
1479
  typescript_1.default.sys.exit(1);
824
1480
  }
825
1481
  for (const obj of entries) {
@@ -840,149 +1496,176 @@ async function getConfig() {
840
1496
  const entryCheck = (0, resolves_1.default)([[checkEntries, config.entryPoints]]);
841
1497
  await entryCheck.series();
842
1498
  await utils_1.default.wait(1000);
1499
+ const points = [];
1500
+ for (const ent of config.entryPoints) {
1501
+ const point = {
1502
+ entry: ent.entry,
1503
+ exportPath: ent.exportPath,
1504
+ format: ent.format ?? "esm",
1505
+ tsconfigFilePath: ent.tsconfigFilePath ?? undefined,
1506
+ renameDuplicates: ent.renameDuplicates ?? true,
1507
+ outDir: config.outDir ?? "dist",
1508
+ };
1509
+ points.push(point);
1510
+ }
843
1511
  return {
844
- entryPoints: config.entryPoints,
845
- postProcessHooks: config.postProcessHooks ?? [],
1512
+ points,
1513
+ plugins: config.plugins ?? [],
846
1514
  allowUpdatePackageJson: config.allowUpdatePackageJson ?? true,
847
- nodeEnv: config.nodeEnv ?? true,
848
- renameDuplicates: config.renameDuplicates ?? true,
849
1515
  };
850
1516
  }
851
- const isCjs = (files) => files.commonjs && files.commonjsTypes;
852
- const isEsm = (files) => files.esm && files.esmTypes;
853
- function getExports(files, exportPath) {
854
- return isCjs(files) && isEsm(files)
855
- ? {
856
- [exportPath]: {
857
- import: {
858
- default: `./${node_path_1.default.relative(process.cwd(), files.esm)}`,
859
- types: `./${node_path_1.default.relative(process.cwd(), files.esmTypes)}`,
860
- },
861
- require: {
862
- default: `./${node_path_1.default.relative(process.cwd(), files.commonjs)}`,
863
- types: `./${node_path_1.default.relative(process.cwd(), files.commonjsTypes)}`,
864
- },
865
- },
866
- }
867
- : isCjs(files) && !isEsm(files)
868
- ? {
869
- [exportPath]: {
870
- require: {
871
- default: `./${node_path_1.default.relative(process.cwd(), files.commonjs)}`,
872
- types: `./${node_path_1.default.relative(process.cwd(), files.commonjsTypes)}`,
873
- },
874
- },
875
- }
876
- : !isCjs(files) && isEsm(files)
877
- ? {
878
- [exportPath]: {
879
- import: {
880
- default: `./${node_path_1.default.relative(process.cwd(), files.esm)}`,
881
- types: `./${node_path_1.default.relative(process.cwd(), files.esmTypes)}`,
882
- },
883
- },
884
- }
885
- : {};
1517
+ async function fileSizes(path) {
1518
+ const s = await node_fs_1.default.promises.stat(path);
1519
+ const logical = s.size;
1520
+ const allocated = s.blocks !== null ? s.blocks * 512 : null;
1521
+ return { logical, allocated };
886
1522
  }
887
- async function writePackage(files, exportPath) {
888
- let isMain = true;
889
- if (exportPath !== ".") {
890
- isMain = false;
891
- }
892
- const pkgFile = utils_1.default.resolvePath("package.json");
893
- const _pkgtext = utils_1.default.readFile(pkgFile);
894
- const pkgtext = JSON.parse(_pkgtext);
895
- let { name, version, description, main, module, type, types, exports, ...rest } = pkgtext;
896
- await utils_1.default.wait(500);
897
- type = isEsm(files) ? "module" : "commonjs";
898
- let _main = {};
899
- let _module = {};
900
- let _types = {};
901
- let _exports = {};
902
- if (isMain) {
903
- _main = files.main
904
- ? { main: node_path_1.default.relative(process.cwd(), files.main) }
905
- : {};
906
- _module = files.module
907
- ? { module: node_path_1.default.relative(process.cwd(), files.module) }
908
- : {};
909
- _types = files.types
910
- ? { types: node_path_1.default.relative(process.cwd(), files.types) }
911
- : {};
912
- _exports = { exports: { ...getExports(files, exportPath) } };
1523
+ const checkExport = (str, file) => {
1524
+ const esmRex = /export default .*/gm;
1525
+ const cjsRex = /export = .*/gm;
1526
+ const ctsRex = /.cts/g;
1527
+ if (str.match(esmRex) || (str.match(cjsRex) && file.match(ctsRex))) {
1528
+ return true;
913
1529
  }
914
1530
  else {
915
- _main = main ? { main: main } : {};
916
- _module = module ? { module: module } : {};
917
- _types = types ? { types: types } : {};
918
- const normalizedExports = exports && typeof exports === "object" && !Array.isArray(exports)
919
- ? { ...exports }
920
- : {};
921
- _exports = {
922
- exports: { ...normalizedExports, ...getExports(files, exportPath) },
923
- };
1531
+ return false;
924
1532
  }
1533
+ };
1534
+ async function generateDependencies(entryFile, plugins) {
1535
+ const deps = await (0, dependencies_1.default)(entryFile);
1536
+ const sorted = deps.sort();
1537
+ let depsFiles = [];
925
1538
  await utils_1.default.wait(1000);
926
- const pkgJson = {
927
- name,
928
- version,
929
- description,
930
- type,
931
- ..._main,
932
- ..._types,
933
- ..._module,
934
- ..._exports,
935
- ...rest,
936
- };
937
- utils_1.default.writeFile(pkgFile, JSON.stringify(pkgJson, null, 2));
1539
+ for (const dep of sorted) {
1540
+ const file = typescript_1.default.sys.resolvePath(dep);
1541
+ const content = await node_fs_1.default.promises.readFile(file, "utf8");
1542
+ const s = await fileSizes(file);
1543
+ const length = content.length;
1544
+ const includeDefExport = checkExport(content, file);
1545
+ const _files = {
1546
+ file,
1547
+ content,
1548
+ length,
1549
+ includeDefExport,
1550
+ size: {
1551
+ logical: s.logical,
1552
+ allocated: s.allocated,
1553
+ utf8: new TextEncoder().encode(content).length,
1554
+ buffBytes: node_buffer_1.Buffer.byteLength(content, "utf8"),
1555
+ },
1556
+ };
1557
+ depsFiles.push(_files);
1558
+ }
1559
+ if (plugins.length) {
1560
+ for (const plugin of plugins) {
1561
+ const _plug = typeof plugin === "function" ? plugin() : plugin;
1562
+ if (_plug.type === "dependency") {
1563
+ if (_plug.async) {
1564
+ depsFiles = await _plug.func(depsFiles);
1565
+ }
1566
+ else {
1567
+ depsFiles = _plug.func(depsFiles);
1568
+ }
1569
+ await utils_1.default.wait(1000);
1570
+ }
1571
+ }
1572
+ }
1573
+ return depsFiles;
938
1574
  }
939
- async function susee() {
940
- const config = await getConfig();
941
- console.info(tcolor_1.default.cyan("Start Bundle"));
942
- const compile = async (e) => {
943
- const target = e.moduleType ? e.moduleType : "esm";
944
- const configPath = e.tsconfigFilePath;
945
- const ent = await entry({
946
- entryPath: e.entry,
947
- exportPath: e.exportPath,
948
- configPath: e.tsconfigFilePath,
949
- nodeEnv: config.nodeEnv,
950
- });
951
- const sourceCode = await bundler({
952
- depsFiles: ent.depFiles,
953
- compilerOptions: ent.generalOptions,
954
- renameDuplicates: config.renameDuplicates,
1575
+ class GetOptions {
1576
+ constructor(point) {
1577
+ this._point = point;
1578
+ this._options = {};
1579
+ }
1580
+ __init() {
1581
+ const __opts = new tsconfig_1.default(this._point.tsconfigFilePath);
1582
+ const __outDir = this._point.exportPath === "."
1583
+ ? this._point.outDir
1584
+ : `${this._point.outDir}/${this._point.exportPath.slice(2)}`;
1585
+ __opts.removeCompilerOption("rootDir");
1586
+ __opts.removeCompilerOption("module");
1587
+ __opts.editCompilerOptions({
1588
+ moduleResolution: typescript_1.default.ModuleResolutionKind.NodeNext,
1589
+ outDir: __outDir,
955
1590
  });
956
- const mdOpts = ent.modOpts;
957
- const cjsOpts = mdOpts.commonjs();
958
- const esmOpts = mdOpts.esm();
959
- const compiler = new Compilers({ target, configPath });
960
- if (target === "commonjs") {
961
- await compiler.commonjs(sourceCode, e.entry, cjsOpts.compilerOptions, cjsOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
962
- }
963
- else if (target === "esm") {
964
- await compiler.esm(sourceCode, e.entry, esmOpts.compilerOptions, esmOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
965
- }
966
- else if (target === "both") {
967
- await compiler.esm(sourceCode, e.entry, esmOpts.compilerOptions, esmOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
968
- await utils_1.default.wait(1000);
969
- await compiler.commonjs(sourceCode, e.entry, cjsOpts.compilerOptions, cjsOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
1591
+ this._options = __opts.getCompilerOptions();
1592
+ }
1593
+ __init2() {
1594
+ this.__init();
1595
+ let { types, lib, ...restOptions } = this._options;
1596
+ if (types) {
1597
+ if (!types.includes("node")) {
1598
+ types = ["node", ...types];
1599
+ }
970
1600
  }
971
- await utils_1.default.wait(1000);
972
- if (config.allowUpdatePackageJson) {
973
- await writePackage(compiler.files, e.exportPath);
1601
+ else {
1602
+ types = ["node"];
974
1603
  }
975
- };
976
- for (const entry of config.entryPoints) {
977
- const entName = entry.exportPath === "." ? "main" : entry.exportPath.slice(2);
978
- await utils_1.default.wait(1000);
979
- console.info(tcolor_1.default.cyan(`Start ${tcolor_1.default.green("->")} "${entName}" export path`));
980
- await compile(entry);
981
- console.info(tcolor_1.default.cyan(`End ${tcolor_1.default.green("->")} "${entName}" export path`));
982
- if (config.entryPoints.indexOf(entry) + 1 < config.entryPoints.length) {
983
- console.info("-----------------------------------");
1604
+ if (lib) {
1605
+ lib = [...new Set(["ESNext", ...lib])];
1606
+ }
1607
+ else {
1608
+ lib = ["ESNext"];
984
1609
  }
1610
+ return { types, lib, ...restOptions };
985
1611
  }
986
- console.info(tcolor_1.default.cyan("Finished Bundle"));
1612
+ get commonjs() {
1613
+ const opts = this.__init2();
1614
+ const { module, ...rest } = opts;
1615
+ return { module: typescript_1.default.ModuleKind.CommonJS, ...rest };
1616
+ }
1617
+ get esm() {
1618
+ const opts = this.__init2();
1619
+ const { module, ...rest } = opts;
1620
+ return { module: typescript_1.default.ModuleKind.ES2020, ...rest };
1621
+ }
1622
+ get default() {
1623
+ return this.__init2();
1624
+ }
1625
+ }
1626
+ function getOptions(point) {
1627
+ return new GetOptions(point);
1628
+ }
1629
+ async function collections() {
1630
+ const __config = await getConfig();
1631
+ const points = __config.points;
1632
+ const result = [];
1633
+ for (const point of points) {
1634
+ const __opts = getOptions(point);
1635
+ const __deps = await generateDependencies(point.entry, __config.plugins);
1636
+ const checked = await checks.init(__deps, __opts.esm);
1637
+ if (!checked) {
1638
+ typescript_1.default.sys.exit(1);
1639
+ }
1640
+ const c = {
1641
+ fileName: point.entry,
1642
+ exportPath: point.exportPath,
1643
+ format: point.format,
1644
+ rename: point.renameDuplicates,
1645
+ outDir: point.outDir,
1646
+ tsOptions: {
1647
+ cjs: __opts.commonjs,
1648
+ esm: __opts.esm,
1649
+ default: __opts.default,
1650
+ },
1651
+ depFiles: __deps,
1652
+ plugins: __config.plugins,
1653
+ };
1654
+ result.push(c);
1655
+ }
1656
+ return {
1657
+ points: result,
1658
+ allowUpdatePackageJson: __config.allowUpdatePackageJson,
1659
+ };
1660
+ }
1661
+ async function susee() {
1662
+ console.info(`${tcolor_1.default.green("Start")} : ${tcolor_1.default.cyan("bundling")}`);
1663
+ const collected = await collections();
1664
+ await utils_1.default.wait(1000);
1665
+ const bundled = await bundle(collected);
1666
+ await utils_1.default.wait(1000);
1667
+ const compiler = new Compiler(bundled);
1668
+ await compiler.compile();
1669
+ console.info(`${tcolor_1.default.green("End")} : ${tcolor_1.default.cyan("bundling")}`);
987
1670
  }
988
1671
  //# sourceMappingURL=index.js.map