susee 1.0.0 → 1.0.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.d.cts CHANGED
@@ -1,4 +1,78 @@
1
- import type { SuSeeConfig } from "@suseejs/types";
1
+ import type { SuseePlugin, SuseePluginFunction } from "@suseejs/types";
2
+ /**
3
+ * Entry point for SuSee configuration
4
+ */
5
+ interface EntryPoint {
6
+ /**
7
+ * Entry of file path of package
8
+ *
9
+ * required
10
+ */
11
+ entry: string;
12
+ /**
13
+ * Info for output
14
+ *
15
+ * required
16
+ */
17
+ /**
18
+ * path for package
19
+ *
20
+ * required
21
+ */
22
+ exportPath: "." | `./${string}`;
23
+ /**
24
+ * Output module type of package , commonjs,esm or both esm and commonjs
25
+ *
26
+ * default - esm
27
+ */
28
+ format?: "commonjs" | "esm" | "both";
29
+ /**
30
+ * Custom tsconfig.json path for package typescript compiler options
31
+ *
32
+ * Priority -
33
+ * 1. this custom tsconfig.json
34
+ * 2. tsconfig.json at root directory
35
+ * 3. default compiler options of susee
36
+ *
37
+ * default - undefined
38
+ */
39
+ tsconfigFilePath?: string | undefined;
40
+ /**
41
+ * When bundling , if there are duplicate declared names , susee will auto rename , if renameDuplicates = false exist with code 1.
42
+ *
43
+ * default - true
44
+ */
45
+ renameDuplicates?: boolean;
46
+ }
47
+ /**
48
+ * Configuration for Susee Bundler
49
+ */
50
+ interface SuSeeConfig {
51
+ /**
52
+ * Array of entry points object
53
+ *
54
+ * required
55
+ */
56
+ entryPoints: EntryPoint[];
57
+ /**
58
+ * Out directory
59
+ *
60
+ * default - dist
61
+ */
62
+ outDir?: string;
63
+ /**
64
+ * Array of susee extension
65
+ *
66
+ * default - []
67
+ */
68
+ plugins?: (SuseePlugin | SuseePluginFunction)[];
69
+ /**
70
+ * Allow bundler to update your package.json.
71
+ *
72
+ * default - true
73
+ */
74
+ allowUpdatePackageJson?: boolean;
75
+ }
2
76
  /**
3
77
  * Main entry point for susee.
4
78
  * It will:
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAA4L,WAAW,EAAW,MAAM,gBAAgB,CAAC;AAm6DrP;;;;;;;GAOG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAUpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAiH,WAAW,EAAE,mBAAmB,EAAW,MAAM,gBAAgB,CAAC;AAI/L;;GAEG;AACH,UAAU,UAAU;IAChB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH;;;;OAIG;IACH,UAAU,EAAE,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;IACrC;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC9B;AACD;;GAEG;AACH,UAAU,WAAW;IACjB;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,mBAAmB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AA08DD;;;;;;;GAOG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAUpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,78 @@
1
- import type { SuSeeConfig } from "@suseejs/types";
1
+ import type { SuseePlugin, SuseePluginFunction } from "@suseejs/types";
2
+ /**
3
+ * Entry point for SuSee configuration
4
+ */
5
+ interface EntryPoint {
6
+ /**
7
+ * Entry of file path of package
8
+ *
9
+ * required
10
+ */
11
+ entry: string;
12
+ /**
13
+ * Info for output
14
+ *
15
+ * required
16
+ */
17
+ /**
18
+ * path for package
19
+ *
20
+ * required
21
+ */
22
+ exportPath: "." | `./${string}`;
23
+ /**
24
+ * Output module type of package , commonjs,esm or both esm and commonjs
25
+ *
26
+ * default - esm
27
+ */
28
+ format?: "commonjs" | "esm" | "both";
29
+ /**
30
+ * Custom tsconfig.json path for package typescript compiler options
31
+ *
32
+ * Priority -
33
+ * 1. this custom tsconfig.json
34
+ * 2. tsconfig.json at root directory
35
+ * 3. default compiler options of susee
36
+ *
37
+ * default - undefined
38
+ */
39
+ tsconfigFilePath?: string | undefined;
40
+ /**
41
+ * When bundling , if there are duplicate declared names , susee will auto rename , if renameDuplicates = false exist with code 1.
42
+ *
43
+ * default - true
44
+ */
45
+ renameDuplicates?: boolean;
46
+ }
47
+ /**
48
+ * Configuration for Susee Bundler
49
+ */
50
+ interface SuSeeConfig {
51
+ /**
52
+ * Array of entry points object
53
+ *
54
+ * required
55
+ */
56
+ entryPoints: EntryPoint[];
57
+ /**
58
+ * Out directory
59
+ *
60
+ * default - dist
61
+ */
62
+ outDir?: string;
63
+ /**
64
+ * Array of susee extension
65
+ *
66
+ * default - []
67
+ */
68
+ plugins?: (SuseePlugin | SuseePluginFunction)[];
69
+ /**
70
+ * Allow bundler to update your package.json.
71
+ *
72
+ * default - true
73
+ */
74
+ allowUpdatePackageJson?: boolean;
75
+ }
2
76
  /**
3
77
  * Main entry point for susee.
4
78
  * It will:
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAA4L,WAAW,EAAW,MAAM,gBAAgB,CAAC;AAm6DrP;;;;;;;GAOG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAUpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAiH,WAAW,EAAE,mBAAmB,EAAW,MAAM,gBAAgB,CAAC;AAI/L;;GAEG;AACH,UAAU,UAAU;IAChB;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH;;;;OAIG;IACH,UAAU,EAAE,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;IACrC;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC9B;AACD;;GAEG;AACH,UAAU,WAAW;IACjB;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,mBAAmB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AA08DD;;;;;;;GAOG;AACH,iBAAe,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAUpC;AACD,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,CAAC"}
package/dist/index.mjs CHANGED
@@ -5,4 +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
- import TsConfig from"@suseejs/tsconfig";import dependencies from"@suseejs/dependencies";import fs from"node:fs";import path from"node:path";import resolves from"@phothinmaung/resolves";import tcolor from"@suseejs/tcolor";import transformFunction from"@suseejs/transformer";import ts from"typescript";import utilities from"@suseejs/utils";import{Buffer}from"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:s,value:i}){if(e.has(s))throw console.warn(`${s} already exist`),new Error;return e.set(s,[i,0]),t},getName(t,s){const[i,n]=e.get(t)||[],r=i?`${i}${s}_${(n??0)+1}`:`$nyein${s}_${(n??0)+1}`;return e.set(t,[i??"$nyein",(n??0)+1]),r},getPrefix(t){const[s]=e.get(t)||[];return s}};return t}const exportDefaultExportNameMap=[],exportDefaultImportNameMap=[],prefixKey="AnonymousName",genName=uniqueName().setPrefix({key:prefixKey,value:"__anonymous__"});function anonymousCallExpressionHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=n=>{if(ts.isCallExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateCallExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isPropertyAccessExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updatePropertyAccessExpression(n,s.createIdentifier(i.newName),n.name)}}else if(ts.isNewExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateNewExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isExportSpecifier(n)&&ts.isIdentifier(n.name)){const e=n.name.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i.newName))}return ts.visitEachChild(n,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousExportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{const o=path.basename(t).split(".")[0];if((ts.isFunctionDeclaration(r)||ts.isClassDeclaration(r))&&void 0===r.name){let e=!1,t=!1;if(r.modifiers?.forEach(s=>{s.kind===ts.SyntaxKind.ExportKeyword&&(e=!0),s.kind===ts.SyntaxKind.DefaultKeyword&&(t=!0)}),e&&t){const e=genName.getName(prefixKey,o);if(exportDefaultExportNameMap.push({base:e,file:o,newName:e,isEd:!0}),ts.isFunctionDeclaration(r))return s.updateFunctionDeclaration(r,r.modifiers,r.asteriskToken,s.createIdentifier(e),r.typeParameters,r.parameters,r.type,r.body);if(ts.isClassDeclaration(r))return s.updateClassDeclaration(r,r.modifiers,s.createIdentifier(e),r.typeParameters,r.heritageClauses,r.members)}}else if(ts.isExportAssignment(r)&&!r.name&&!r.isExportEquals){if(ts.isArrowFunction(r.expression)){const e=genName.getName(prefixKey,o),t=s.createArrowFunction(r.expression.modifiers,r.expression.typeParameters,r.expression.parameters,r.expression.type,r.expression.equalsGreaterThanToken,r.expression.body),i=s.createVariableDeclaration(s.createIdentifier(e),r.expression.exclamationToken,r.expression.type,t),a=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(r.expression.modifiers,a),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:o,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isObjectLiteralExpression(r.expression)){const e=genName.getName(prefixKey,o),t=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,r.expression),i=s.createVariableDeclarationList([t],ts.NodeFlags.Const),a=s.createVariableStatement(void 0,i),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:o,newName:e,isEd:!0}),s.updateSourceFile(n,[a,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isArrayLiteralExpression(r.expression)){const e=genName.getName(prefixKey,o),t=s.createArrayLiteralExpression(r.expression.elements,!0),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),a=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,a),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:o,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isStringLiteral(r.expression)){const e=genName.getName(prefixKey,o),t=s.createStringLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),a=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,a),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:o,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isNumericLiteral(r.expression)){const e=genName.getName(prefixKey,o),t=s.createNumericLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),a=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,a),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:o,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousImportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{if(ts.isImportDeclaration(r)){const e=r.moduleSpecifier.getText(n),i=path.basename(e).split(".")[0].trim();if(r.importClause?.name&&ts.isIdentifier(r.importClause.name)){const e=r.importClause.name.text.trim(),n=exportDefaultExportNameMap.find(e=>e.file===i);if(n){exportDefaultImportNameMap.push({base:e,file:t,newName:n.newName,isEd:!0});const i=s.updateImportClause(r.importClause,r.importClause.phaseModifier,s.createIdentifier(n.newName),r.importClause.namedBindings);return s.updateImportDeclaration(r,r.modifiers,i,r.moduleSpecifier,r.attributes)}}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}const anonymousHandler=async(e,t)=>{const s=resolves([[anonymousExportHandler,t],[anonymousImportHandler,t],[anonymousCallExpressionHandler,t]]),i=await s.concurrent();for(const t of i)e=e.map(t);return e};function duplicates(e,t,s){const i=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),n=new Map;for(const e of i.statements){if(!ts.isImportDeclaration(e)||!e.importClause)continue;const t=e.importClause;if(t.name&&ts.isIdentifier(t.name)){const e=t.name.text;n.set(e,(n.get(e)||[]).concat({name:e,node:t}))}else if(t.namedBindings&&ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)){const e=t.namedBindings.name.text;n.set(e,(n.get(e)||[]).concat({name:e,node:t.namedBindings}))}else if(t.namedBindings&&ts.isNamedImports(t.namedBindings))for(const e of t.namedBindings.elements)if(ts.isIdentifier(e.name)){const t=e.name.text;n.set(t,(n.get(t)||[]).concat({name:t,node:e}))}}const r=new Map,o=uniqueName();o.setPrefix({key:"DuplicateImport",value:"__dup__"});for(const[e,t]of n.entries())if(t.length>1)for(let s=1;s<t.length;s++){const t=o.getName("DuplicateImport",`${e}_`);r.set(`${e}::${s}`,t),r.set(`${e}::occurrence_${s}`,t)}const a=new Map;for(const[e,t]of n.entries())if(t.length>1)for(let s=1;s<t.length;s++){const i=t[s];i?.node&&a.set(i.node.pos,r.get(`${e}::${s}`))}return transformFunction(e=>{const{factory:t}=e,s=i=>{if(ts.isImportDeclaration(i)&&i.importClause){const e=i.importClause;let s=!1,n=e;if(e.name&&ts.isIdentifier(e.name)){e.pos;const i=a.get(e.pos);i&&(n=t.updateImportClause(e,e.isTypeOnly,t.createIdentifier(i),e.namedBindings),s=!0)}if(e.namedBindings&&ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)){const i=a.get(e.namedBindings.pos);if(i){const e=t.createNamespaceImport(t.createIdentifier(i));n=t.updateImportClause(n,n.isTypeOnly,n.name,e),s=!0}}if(e.namedBindings&&ts.isNamedImports(e.namedBindings)){const i=e.namedBindings.elements.map(e=>{if(ts.isIdentifier(e.name)){const i=a.get(e.pos);if(i)return s=!0,t.updateImportSpecifier(e,e.isTypeOnly,e.propertyName,t.createIdentifier(i))}return e});if(s){const e=t.createNamedImports(i);n=t.updateImportClause(n,n.isTypeOnly,n.name,e)}}if(s)return t.updateImportDeclaration(i,i.modifiers,n,i.moduleSpecifier,i.assertClause)}if(ts.isIdentifier(i)){const e=i.text;if(!(e=>{const t=e.parent;if(!t)return!1;switch(t.kind){case ts.SyntaxKind.ImportSpecifier:case ts.SyntaxKind.NamespaceImport:case ts.SyntaxKind.ImportClause:case ts.SyntaxKind.VariableDeclaration:case ts.SyntaxKind.FunctionDeclaration:case ts.SyntaxKind.ClassDeclaration:case ts.SyntaxKind.InterfaceDeclaration:case ts.SyntaxKind.TypeAliasDeclaration:case ts.SyntaxKind.EnumDeclaration:case ts.SyntaxKind.Parameter:case ts.SyntaxKind.PropertyDeclaration:case ts.SyntaxKind.MethodDeclaration:case ts.SyntaxKind.BindingElement:return!0;default:return!1}})(i)){if(i.parent&&ts.isPropertyAccessExpression(i.parent)&&i.parent.name===i)return i;const s=n.get(e);if(s&&s.length>1)for(let i=1;i<s.length;i++){const s=r.get(`${e}::occurrence_${i}`)||r.get(`${e}::${i}`);if(s)return t.createIdentifier(s)}}}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},i,s)}function mergeImportsStatement(e){const t=new Map,s=new Map,i=new Map,n=new Map,r=new Map;for(const o of e){const e=o.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);if(!e)continue;const[,a,c]=e,l=o.includes("import type"),m=c;if(!a){const e=o.match(/import\s+(?:type\s+)?(\w+)/);if(e){const t=e[1],s=l?n:i;s.has(m)||s.set(m,new Set),s.get(m)?.add(t)}continue}if(a.startsWith("{")){const e=l?s:t;e.has(m)||e.set(m,new Set);a.replace(/[{}]/g,"").split(",").map(e=>e.trim()).filter(Boolean).forEach(t=>e.get(m)?.add(t))}else if(a.startsWith("* as")){const e=a.match(/\*\s+as\s+(\w+)/);if(e){const t=e[1];r.has(m)||r.set(m,new Set),r.get(m)?.add(t)}}else{const e=l?n:i;e.has(m)||e.set(m,new Set),e.get(m)?.add(a.trim())}}const o=[];for(const[e,i]of t){const t=s.get(e)||new Set,n=new Set([...i]);for(const e of t)i.has(e)||n.add(e);if(n.size>0){const t=Array.from(n).sort().join(", ");o.push(`import { ${t} } from "${e}";`)}}for(const[e,i]of s)if(!t.has(e)&&i.size>0){const t=Array.from(i).sort().join(", ");o.push(`import type { ${t} } from "${e}";`)}for(const[e,t]of i){const s=n.get(e)||new Set,i=new Set([...t]);for(const e of s)t.has(e)||i.add(e);if(i.size>0){const t=Array.from(i).join(", ");o.push(`import ${t} from "${e}";`)}}for(const[e,t]of n)if(!i.has(e)&&t.size>0){const s=Array.from(t).join(", ");o.push(`import type ${s} from "${e}";`)}for(const[e,t]of r)if(t.size>0){const s=Array.from(t).join(", ");o.push(`import * as ${s} from "${e}";`)}return o.sort()}function esmExportRemoveHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0);return{file:t,content:transformFunction(e=>{const{factory:t}=e,s=i=>{if(!utilities.isInsideNamespace(i)&&(ts.isFunctionDeclaration(i)||ts.isClassDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)||ts.isEnumDeclaration(i)||ts.isVariableStatement(i))){const e=i.modifiers?.filter(e=>e.kind!==ts.SyntaxKind.ExportKeyword&&e.kind!==ts.SyntaxKind.DefaultKeyword);if(e?.length!==i.modifiers?.length){if(ts.isFunctionDeclaration(i))return t.updateFunctionDeclaration(i,e,i.asteriskToken,i.name,i.typeParameters,i.parameters,i.type,i.body);if(ts.isClassDeclaration(i))return t.updateClassDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isInterfaceDeclaration(i))return t.updateInterfaceDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isTypeAliasDeclaration(i))return t.updateTypeAliasDeclaration(i,e,i.name,i.typeParameters,i.type);if(ts.isEnumDeclaration(i))return t.updateEnumDeclaration(i,e,i.name,i.members);if(ts.isVariableStatement(i))return t.updateVariableStatement(i,e,i.declarationList)}}if(ts.isExportDeclaration(i))return t.createEmptyStatement();if(ts.isExportAssignment(i)){const e=i.expression;if(ts.isIdentifier(e))return t.createEmptyStatement()}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},n,e),...i}}}let properties=[];const typeObj={},typesNames=[];function findProperty(e){const t=[];return ts.isPropertyAccessExpression(e)&&ts.isIdentifier(e.expression)&&t.push(e.expression.text),e.forEachChild(e=>findProperty(e)),t}function importAllRemoveHandler(e,t){return({file:s,content:i,...n})=>{const r=ts.createSourceFile(s,i,ts.ScriptTarget.Latest,!0),o=new Set;for(const e of r.statements)if(ts.isImportEqualsDeclaration(e)&&e.isTypeOnly){const t=e.moduleReference;ts.isExternalModuleReference(t)&&ts.isStringLiteral(t.expression)&&o.add(e.name.text)}const a=transformFunction(t=>{const{factory:i}=t,n=a=>{properties=[...properties,...findProperty(a)];const c={isNamespace:!1,isTypeOnly:!1,isTypeNamespace:!1,source:"",importedString:void 0,importedObject:void 0};if(ts.isTypeReferenceNode(a)&&ts.isQualifiedName(a.typeName)&&ts.isIdentifier(a.typeName.left)&&ts.isIdentifier(a.typeName.right)){const e=a.typeName.left.text,t=a.typeName.right.text;if(typesNames.push(e),e in typeObj?typeObj[e]?.push(t):typeObj[e]=[t],utilities.checkModuleType(r,s).isCommonJs&&"ts"!==e&&!o.has(e))return i.updateTypeReferenceNode(a,i.createIdentifier(t),void 0)}if(ts.isImportDeclaration(a)){const t=a.getText(r);return e.push(t),i.createEmptyStatement()}if(ts.isImportEqualsDeclaration(a)){const t=a.name.text,s=a.moduleReference;let n;if(a.isTypeOnly&&(c.isTypeOnly=!0),c.importedString=t,c.isTypeOnly||properties.includes(t)&&(c.isNamespace=!0),ts.isExternalModuleReference(s)&&ts.isStringLiteral(s.expression)&&(c.source=s.expression.text),c.importedString&&!c.importedObject&&(n=c.isTypeOnly?o.has(c.importedString)?`import type * as ${c.importedString} from "${c.source}";`:typesNames.includes(c.importedString)?`import type { ${typeObj[c.importedString]?.join(",")} } from "${c.source}";`:`import type ${c.importedString} from "${c.source}";`:c.isNamespace&&c.source&&"typescript"!==c.source?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}if(ts.isVariableStatement(a)){const t=a.declarationList.declarations;if(1===t.length){const s=t[0];if(s.initializer&&ts.isCallExpression(s.initializer)&&ts.isIdentifier(s.initializer.expression)&&"require"===s.initializer.expression.escapedText){const t=s.initializer.arguments[0];if(ts.isStringLiteral(t)&&(c.source=t.text),ts.isIdentifier(s.name)){const e=s.name.text;c.importedString=e,properties.includes(e)&&(c.isNamespace=!0)}else if(ts.isObjectBindingPattern(s.name)){const e=[];for(const t of s.name.elements)ts.isIdentifier(t.name)&&e.push(t.name.text);e.length>0&&(c.importedObject=e)}let n;if(c.importedString&&!c.importedObject&&(n=c.isNamespace?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}}}return ts.visitEachChild(a,n,t)};return e=>ts.visitNode(e,n)},r,t);return{file:s,content:a,...n}}}const removeHandlers=async(e,t)=>{const s=resolves([[importAllRemoveHandler,e,t],[esmExportRemoveHandler,t]]);return await s.series()};function collectBindingNames(e,t){ts.isIdentifier(e)?t.push(e.text):(ts.isObjectBindingPattern(e)||ts.isArrayBindingPattern(e))&&e.elements.forEach(e=>{ts.isBindingElement(e)&&e.name&&collectBindingNames(e.name,t)})}function clearUnusedCode(e,t,s,i={treatExportsAsUsed:!0}){const n=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),r=new Map,o=new Set,a=(e,t=!1)=>{const s=r.get(e);r.set(e,{exported:!!s?.exported||t})},c=e=>{if(ts.isImportDeclaration(e)&&e.importClause){const t=e.importClause;t.name&&ts.isIdentifier(t.name)&&a(t.name.text,!1),t.namedBindings&&(ts.isNamedImports(t.namedBindings)?t.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&a(e.name.text,!1)}):ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)&&a(t.namedBindings.name.text,!1))}else if(ts.isImportEqualsDeclaration(e)&&ts.isIdentifier(e.name))a(e.name.text,!1);else if(ts.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;e.declarationList.declarations.forEach(e=>{collectBindingNames(e.name,[]);const s=[];collectBindingNames(e.name,s),s.forEach(e=>a(e,t))})}else if(ts.isFunctionDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;a(e.name.text,t)}else if(ts.isClassDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;a(e.name.text,t)}if(ts.isIdentifier(e)){const t=e.parent;ts.isVariableDeclaration(t)&&t.name===e||ts.isFunctionDeclaration(t)&&t.name===e||ts.isClassDeclaration(t)&&t.name===e||ts.isImportClause(t)&&t.name===e||ts.isImportSpecifier(t)&&t.name===e||ts.isNamespaceImport(t)&&t.name===e||ts.isBindingElement(t)&&t.name===e||ts.isParameter(t)&&t.name===e||o.add(e.text)}ts.forEachChild(e,c)};c(n);const l=new Set;r.forEach((e,t)=>{o.has(t)||i.treatExportsAsUsed&&e.exported||l.add(t)});return transformFunction(e=>{const t=s=>{if(ts.isImportDeclaration(s)&&s.importClause){const e=s.importClause,t=e.name&&ts.isIdentifier(e.name)?e.name.text:void 0;let i;const n=[];e.namedBindings&&(ts.isNamedImports(e.namedBindings)?e.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&n.push(e)}):ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)&&(i=e.namedBindings.name.text));const r=!!t&&!l.has(t),o=!!i&&!l.has(i),a=n.filter(e=>!l.has(e.name.text));if(!r&&!o&&0===a.length)return ts.factory.createNotEmittedStatement(s);if(!r&&!!e.name||void 0!==i&&!o||a.length!==n.length){let e;e=a.length>0?ts.factory.createNamedImports(a):o&&i?ts.factory.createNamespaceImport(ts.factory.createIdentifier(i)):void 0;const n=r&&t?ts.factory.createIdentifier(t):void 0,c=ts.factory.createImportClause(!1,n,e);return ts.factory.updateImportDeclaration(s,s.modifiers,c,s.moduleSpecifier,s.assertClause)}return s}if((ts.isFunctionDeclaration(s)||ts.isClassDeclaration(s))&&s.name&&ts.isIdentifier(s.name))return l.has(s.name.text)?ts.factory.createNotEmittedStatement(s):s;if(ts.isVariableStatement(s)){const e=[];s.declarationList.declarations.forEach(t=>collectBindingNames(t.name,e));return e.some(e=>!l.has(e))?s:ts.factory.createNotEmittedStatement(s)}return ts.visitEachChild(s,t,e)};return e=>ts.visitNode(e,t)},n,s)}async function bundler(e){const t="."===e.exportPath?"Main":splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Bundled")} -> ${tcolor.brightCyan(t)} ${tcolor.cyan("export path")}`);let s=e.depFiles;const i=e.rename,n=e.tsOptions.default,r=e.plugins;let o=[];if(r.length)for(let e of r)e="function"==typeof e?e():e,"dependency"===e.type&&(e.async?(s=await e.func(s,n),await utilities.wait(1e3)):s=e.func(s,n));s=await anonymousHandler(s,n);const a=await removeHandlers(o,n);s=s.map(a[0]);const c=s.slice(0,-1).map(a[1]),l=s.slice(-1),m=/["']((?!\.\/|\.\.\/)[^"']+)["']/;o=o.filter(e=>m.test(e)),o=mergeImportsStatement(o);let p=`${o.join("\n").trim()}\n${c.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}\n${l.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}`;if(p=p.replace(/^s*;\s*$/gm,"").trim(),i&&(p=duplicates(p,e.fileName,n)),p=clearUnusedCode(p,e.fileName,n),r.length)for(let e of r)e="function"==typeof e?e():e,"pre-process"===e.type&&(p=e.async?await e.func(p):e.func(p));return console.timeEnd(`${tcolor.cyan("Bundled")} -> ${tcolor.brightCyan(t)} ${tcolor.cyan("export path")}`),{bundledContent:p,...e}}async function bundle(e){const t=[];for(const s of e.points){const e=await bundler(s);t.push(e)}return{points:t,allowUpdatePackageJson:e.allowUpdatePackageJson}}function createHost(e,t){const s={},i={getSourceFile:(s,i)=>{if(s===t)return ts.createSourceFile(s,e,i)},writeFile:(e,t)=>{s[e]=t},getDefaultLibFileName:e=>ts.getDefaultLibFilePath(e),getCurrentDirectory:()=>"",getDirectories:()=>[],fileExists:e=>e===t,readFile:s=>s===t?e:void 0,getCanonicalFileName:e=>e,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n"};return{createdFiles:s,host:i}}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:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`},require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:isCjs(e)&&!isEsm(e)?{[t]:{require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:!isCjs(e)&&isEsm(e)?{[t]:{import:{types:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`}}}:{}}async function writePackage(e,t){let s=!0;"."!==t&&(s=!1);const i=ts.sys.resolvePath("package.json"),n=fs.readFileSync(i,"utf8"),r=JSON.parse(n);let{name:o,version:a,description:c,main:l,module:m,type:p,types:f,exports:d,...u}=r;await utilities.wait(500),p="module";let y={},g={},h={},x={};if(s)y=e.main?{main:path.relative(process.cwd(),e.main)}:{},g=e.module?{module:path.relative(process.cwd(),e.module)}:{},h=e.types?{types:path.relative(process.cwd(),e.types)}:{},x={exports:{...getExports(e,t)}};else{y=l?{main:l}:{},g=m?{module:m}:{},h=f?{types:f}:{};x={exports:{...d&&"object"==typeof d&&!Array.isArray(d)?{...d}:{},...getExports(e,t)}}}await utilities.wait(1e3);const w={name:o,version:a,description:c,type:p,...y,...h,...g,...x,...u};utilities.writeCompileFile(i,JSON.stringify(w,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,s=t?"Main":splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Compiled CJS")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`);const i=e.fileName,n=e.bundledContent,r=e.format,o=e.plugins,a=e.tsOptions.cjs,c=createHost(n,i),l=c.createdFiles,m=c.host;ts.createProgram([i],a,m).emit(),Object.entries(l).map(async([e,s])=>{if(".js"===path.extname(e)&&o.length)for(let t of o)t="function"==typeof t?t():t,"post-process"===t.type&&(s=t.async?await t.func(s,e):t.func(s,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"!==r&&"commonjs"!==r||(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 utilities.wait(500),"commonjs"===r&&await utilities.clearFolder(path.dirname(e)),await utilities.writeCompileFile(e,s)}),console.timeEnd(`${tcolor.cyan("Compiled CJS")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`)}async _esm(e){const t="."===e.exportPath,s=t?"Main":splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Compiled ESM")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`);const i=e.fileName,n=e.bundledContent,r=e.format,o=e.plugins,a=e.tsOptions.esm,c=createHost(n,i),l=c.createdFiles,m=c.host;ts.createProgram([i],a,m).emit(),Object.entries(l).map(async([e,s])=>{if(".js"===path.extname(e)&&o.length)for(let t of o)t="function"==typeof t?t():t,"post-process"===t.type&&(s=t.async?await t.func(s,e):t.func(s,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"===r&&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 utilities.wait(500),"commonjs"!==r&&await utilities.clearFolder(path.dirname(e)),await utilities.writeCompileFile(e,s)}),console.timeEnd(`${tcolor.cyan("Compiled ESM")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`)}async compile(){for(const e of this.object.points){switch(await utilities.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 utilities.wait(1e3),await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath)}await utilities.wait(500)}}}var checks;!function(e){function t(e,t){if(!t.noCheck){const s=e.map(e=>e.file);let i=!1;const n=ts.createProgram(s,t);for(const e of s){const t=n.getSourceFile(e);t||(console.error(tcolor.magenta(`File not found: ${e}`)),ts.sys.exit(1));const s=[...n.getSyntacticDiagnostics(t),...n.getSemanticDiagnostics(t),...n.getDeclarationDiagnostics(t)];if(s.length>0){const e={getCurrentDirectory:()=>process.cwd(),getCanonicalFileName:e=>e,getNewLine:()=>ts.sys.newLine};console.error(ts.formatDiagnosticsWithColorAndContext(s,e)),i=!0}}if(!i)return!0;ts.sys.exit(1)}}function s(e){let t=0,s=0;for(const n of e)try{const r=ts.createSourceFile(n.file,n.content,ts.ScriptTarget.Latest,!0);let o=!1,a=!1;function i(e){if((ts.isImportDeclaration(e)||ts.isImportEqualsDeclaration(e)||ts.isExportDeclaration(e)||ts.isExportSpecifier(e)||ts.isExportAssignment(e))&&(o=!0),(ts.isVariableStatement(e)||ts.isFunctionDeclaration(e)||ts.isInterfaceDeclaration(e)||ts.isTypeAliasDeclaration(e)||ts.isEnumDeclaration(e)||ts.isClassDeclaration(e))&&e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)&&(o=!0),ts.isCallExpression(e)&&ts.isIdentifier(e.expression)&&"require"===e.expression.text&&e.arguments.length>0&&(a=!0),ts.isPropertyAccessExpression(e)){const t=e.getText(r);(t.startsWith("module.exports")||t.startsWith("exports."))&&(a=!0)}ts.forEachChild(e,i)}i(r),o&&!a?0:a&&!o?t++:o&&a&&0}catch(c){console.error(tcolor.magenta(`Error checking module format for ${n.file} : \n ${c}`)),s++}return s&&(console.error(tcolor.magenta("Unknown error when checking module types in the dependencies tree.")),ts.sys.exit(1)),t&&(console.error(tcolor.magenta("The package detects CommonJs format in the dependencies tree, that unsupported.")),ts.sys.exit(1)),!0}function i(e){const t=new Set([".ts",".mts",".cts",".tsx"]);for(const s of e){const e=path.extname(s.file);t.has(e)||(console.error(tcolor.magenta(`${s.file} has no valid TypeScript extension`)),ts.sys.exit(1))}return!0}e.types=async function(e,s){const i=resolves([[t,e,s]]);return(await i.series())[0]},e.moduleAndExtension=async function(e){const t=resolves([[s,e],[i,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 s of e){const e=ts.sys.resolvePath(s);if(ts.sys.fileExists(e)){t=e;break}}return t};function checkEntries(e){e.length<1&&(console.error(tcolor.magenta("No entry found in susee.config file, at least one entry required")),ts.sys.exit(1));const t={},s=[];for(const i of e){const e=i.exportPath;t[e]?s.push(`"${e}"`):t[e]=!0}s.length>0&&(console.error(tcolor.magenta(`Duplicate export paths/path (${s.join(",")}) found in your susee.config file , that will error for bundled output`)),ts.sys.exit(1));for(const t of e)ts.sys.fileExists(ts.sys.resolvePath(t.entry))||(console.error(tcolor.magenta(`Entry file ${t.entry} dose not exists.`)),ts.sys.exit(1))}async function getConfig(){const e=getConfigPath();void 0===e&&(console.error(tcolor.magenta('No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found')),ts.sys.exit(1));const t=(await import(e)).default,s=resolves([[checkEntries,t.entryPoints]]);await s.series(),await utilities.wait(1e3);const i=[];for(const e of t.entryPoints){const s={entry:e.entry,exportPath:e.exportPath,format:e.format??"esm",tsconfigFilePath:e.tsconfigFilePath??void 0,renameDuplicates:e.renameDuplicates??!0,outDir:t.outDir??"dist"};i.push(s)}return{points:i,plugins:t.plugins??[],allowUpdatePackageJson:t.allowUpdatePackageJson??!0}}async function fileSizes(e){const t=await fs.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 dependencies(e)).sort(),s=[];await utilities.wait(1e3);for(const e of t){const t=ts.sys.resolvePath(e),i=await fs.promises.readFile(t,"utf8"),n=await fileSizes(t),r=i.length,o=checkExport(i,t),a=ts.createSourceFile(t,i,ts.ScriptTarget.Latest,!0),c=utilities.checkModuleType(a,t).isCommonJs?"cjs":"esm",l={file:t,content:i,length:r,includeDefExport:o,size:{logical:n.logical,allocated:n.allocated,utf8:(new TextEncoder).encode(i).length,buffBytes:Buffer.byteLength(i,"utf8")},type:c};s.push(l)}return s}class GetOptions{constructor(e){this._point=e,this._options={}}__init(){const e=new TsConfig(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:ts.ModuleResolutionKind.NodeNext,outDir:t}),this._options=e.getCompilerOptions()}__init2(){this.__init();let{types:e,lib:t,...s}=this._options;return e?e.includes("node")||(e=["node",...e]):e=["node"],t=t?[...new Set(["ESNext",...t])]:["ESNext"],{types:e,lib:t,...s}}get commonjs(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.CommonJS,...s}}get esm(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.ES2020,...s}}get default(){return this.__init2()}}function getOptions(e){return new GetOptions(e)}async function collections(){console.time(`${tcolor.cyan("Collected Data")}`);const e=await getConfig(),t=e.points,s=e.plugins,i=[];for(const e of t){const t=getOptions(e),n=await generateDependencies(e.entry);await checks.types(n,t.esm)||ts.sys.exit(1);let r=!1;if(s.length)for(const e of s){const t="function"==typeof e?e():e;"dependency"===t.type&&t.name&&"@suseejs/plugin-commonjs"===t.name&&(r=!0)}if(!r){await checks.moduleAndExtension(n)||ts.sys.exit(1)}const o={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:n,plugins:s};i.push(o)}return console.timeEnd(`${tcolor.cyan("Collected Data")}`),{points:i,allowUpdatePackageJson:e.allowUpdatePackageJson}}async function susee(){console.info(`${tcolor.cyan("Susee Started")} : `),console.time(`${tcolor.cyan("Susee Done")}`);const e=await collections();await utilities.wait(1e3);const t=await bundle(e);await utilities.wait(1e3);const s=new Compiler(t);await s.compile(),console.timeEnd(`${tcolor.cyan("Susee Done")}`)}export{susee};
8
+ import TsConfig from"@suseejs/tsconfig";import fs from"node:fs";import mhaehko from"mhaehko";import path from"node:path";import resolves from"@phothinmaung/resolves";import tcolor from"@suseejs/tcolor";import transformFunction from"@suseejs/transformer";import ts from"typescript";import{Buffer}from"node:buffer";var utilities;!function(e){e.splitCamelCase=function(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())},e.wait=e=>new Promise(t=>setTimeout(t,e)),e.checkModuleType=(e,t)=>{let s=0,i=0,n=0;try{let t=!1,n=!1;!function s(i){if((ts.isImportDeclaration(i)||ts.isImportEqualsDeclaration(i)||ts.isExportDeclaration(i)||ts.isExportSpecifier(i)||ts.isExportAssignment(i))&&(t=!0),(ts.isVariableStatement(i)||ts.isFunctionDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)||ts.isEnumDeclaration(i)||ts.isClassDeclaration(i))&&i.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)&&(t=!0),ts.isCallExpression(i)&&ts.isIdentifier(i.expression)&&"require"===i.expression.text&&i.arguments.length>0&&(n=!0),ts.isPropertyAccessExpression(i)){const t=i.getText(e);(t.startsWith("module.exports")||t.startsWith("exports."))&&(n=!0)}ts.forEachChild(i,s)}(e),t&&!n?s++:n&&!t?i++:t&&n&&s++}catch(e){console.error(tcolor.magenta(`Error checking module format for ${t} : \n ${e}`)),n++}return n>0&&(console.error(tcolor.magenta("Error checking module format.")),ts.sys.exit(1)),{isCommonJs:i>0,isEsm:s>0}},e.isJsxContent=function(e){const t=ts.createSourceFile("file.tsx",e,ts.ScriptTarget.Latest,!0,ts.ScriptKind.TSX);let s=!1;return function e(t){ts.isJsxElement(t)||ts.isJsxSelfClosingElement(t)||ts.isJsxFragment(t)?s=!0:ts.forEachChild(t,e)}(t),s},e.writeCompileFile=async function(t,s){const i=ts.sys.resolvePath(t),n=path.dirname(i);ts.sys.directoryExists(n)||await fs.promises.mkdir(n,{recursive:!0}),await e.wait(500),await fs.promises.writeFile(i,s)},e.isInsideNamespace=e=>{let t=e.parent;for(;t;){if(ts.isModuleDeclaration(t)&&t.flags===ts.NodeFlags.Namespace)return!0;t=t.parent}return!1},e.clearFolder=async function(e){e=path.resolve(process.cwd(),e);try{const t=await fs.promises.readdir(e,{withFileTypes:!0});await Promise.all(t.map(t=>fs.promises.rm(path.join(e,t.name),{recursive:!0})))}catch(e){if("ENOENT"!==e.code)throw e}}}(utilities||(utilities={}));const getConfigPath=()=>{const e=["susee.config.ts","susee.config.js","susee.config.mjs"];let t;for(const s of e){const e=ts.sys.resolvePath(s);if(ts.sys.fileExists(e)){t=e;break}}return t};function checkEntries(e){e.length<1&&(console.error(tcolor.magenta("No entry found in susee.config file, at least one entry required")),ts.sys.exit(1));const t={},s=[];for(const i of e){const e=i.exportPath;t[e]?s.push(`"${e}"`):t[e]=!0}s.length>0&&(console.error(tcolor.magenta(`Duplicate export paths/path (${s.join(",")}) found in your susee.config file , that will error for bundled output`)),ts.sys.exit(1));for(const t of e)ts.sys.fileExists(ts.sys.resolvePath(t.entry))||(console.error(tcolor.magenta(`Entry file ${t.entry} dose not exists.`)),ts.sys.exit(1))}async function finalSuseeConfig(){const e=getConfigPath();void 0===e&&(console.error(tcolor.magenta('No susee.config file ("susee.config.ts", "susee.config.js", "susee.config.mjs") found')),ts.sys.exit(1));const t=(await import(e)).default,s=resolves([[checkEntries,t.entryPoints]]);await s.series(),await utilities.wait(1e3);const i=t.outDir??"dist",n=[];for(const e of t.entryPoints){const t={entry:e.entry,exportPath:e.exportPath,format:e.format??"esm",tsconfigFilePath:e.tsconfigFilePath??void 0,renameDuplicates:e.renameDuplicates??!0,outDirPath:"."===e.exportPath?i:`${i}${e.exportPath.slice(1)}`};n.push(t)}return{points:n,plugins:t.plugins??[],allowUpdatePackageJson:t.allowUpdatePackageJson??!0,outDir:i}}class CompilerOptions{constructor(e){this._point=e,this._options={}}__init(){const e=new TsConfig(this._point.tsconfigFilePath);e.removeCompilerOption("rootDir"),e.removeCompilerOption("module"),e.editCompilerOptions({moduleResolution:ts.ModuleResolutionKind.NodeNext,outDir:this._point.outDirPath}),this._options=e.getCompilerOptions()}__init2(){this.__init();let{types:e,lib:t,...s}=this._options;return e?e.includes("node")||(e=["node",...e]):e=["node"],t=t?[...new Set(["ESNext",...t])]:["ESNext"],{types:e,lib:t,...s}}get commonjs(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.CommonJS,...s}}get esm(){const e=this.__init2(),{module:t,...s}=e;return{module:ts.ModuleKind.ES2020,...s}}get default(){return this.__init2()}}function compilerOptions(e){return new CompilerOptions(e)}async function fileSizes(e){const t=await fs.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 mhaehko(e)).sort(),s=[];for(const e of t){const t=ts.sys.resolvePath(e),i=await fs.promises.readFile(t,"utf8"),n=path.extname(t),r=await fileSizes(t),a=i.length,o=checkExport(i,t),c=ts.createSourceFile(t,i,ts.ScriptTarget.Latest,!0),l=utilities.checkModuleType(c,t).isCommonJs?"cjs":"esm",m={file:t,content:i,length:a,includeDefExport:o,size:{logical:r.logical,allocated:r.allocated,utf8:(new TextEncoder).encode(i).length,buffBytes:Buffer.byteLength(i,"utf8")},moduleType:l,fileExt:n,isJsx:utilities.isJsxContent(i)};s.push(m)}return s}function _typesCheck(e,t){if(!t.noCheck){const s=e.map(e=>e.file);let i=!1;const n=ts.createProgram(s,t);for(const e of s){const t=n.getSourceFile(e);t||(console.error(tcolor.magenta(`File not found: ${e}`)),ts.sys.exit(1));const s=[...n.getSyntacticDiagnostics(t),...n.getSemanticDiagnostics(t),...n.getDeclarationDiagnostics(t)];if(s.length>0){const e={getCurrentDirectory:()=>process.cwd(),getCanonicalFileName:e=>e,getNewLine:()=>ts.sys.newLine};console.error(ts.formatDiagnosticsWithColorAndContext(s,e)),i=!0}}if(!i)return!0;ts.sys.exit(1)}}async function typeCheck(e,t){const s=resolves([[_typesCheck,e,t]]);return(await s.series())[0]}async function initializer(){console.time(`${tcolor.cyan("Collected Data")}`);const e=await finalSuseeConfig(),t=e.points,s=e.plugins,i=[];for(const e of t){const t=compilerOptions(e);let n=await generateDependencies(e.entry);if(await typeCheck(n,t.esm)||ts.sys.exit(1),s.length)for(const e of s){const s="function"==typeof e?e():e;"dependency"===s.type&&(n=s.async?await s.func(n,t.default):s.func(n,t.default))}const r={fileName:e.entry,exportPath:e.exportPath,format:e.format,rename:e.renameDuplicates,outDir:e.outDirPath,tsOptions:{cjs:t.commonjs,esm:t.esm,default:t.default},depFiles:n,plugins:s};i.push(r)}return console.timeEnd(`${tcolor.cyan("Collected Data")}`),{points:i,allowUpdatePackageJson:e.allowUpdatePackageJson}}function uniqueName(){const e=new Map,t={setPrefix({key:s,value:i}){if(e.has(s))throw console.warn(`${s} already exist`),new Error;return e.set(s,[i,0]),t},getName(t,s){const[i,n]=e.get(t)||[],r=i?`${i}${s}_${(n??0)+1}`:`$nyein${s}_${(n??0)+1}`;return e.set(t,[i??"$nyein",(n??0)+1]),r},getPrefix(t){const[s]=e.get(t)||[];return s}};return t}const exportDefaultExportNameMap=[],exportDefaultImportNameMap=[],prefixKey="AnonymousName",genName=uniqueName().setPrefix({key:prefixKey,value:"__anonymous__"});function anonymousCallExpressionHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=n=>{if(ts.isCallExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateCallExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isPropertyAccessExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updatePropertyAccessExpression(n,s.createIdentifier(i.newName),n.name)}}else if(ts.isNewExpression(n)){if(ts.isIdentifier(n.expression)){const e=n.expression.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateNewExpression(n,s.createIdentifier(i.newName),n.typeArguments,n.arguments)}}else if(ts.isExportSpecifier(n)&&ts.isIdentifier(n.name)){const e=n.name.text,i=exportDefaultImportNameMap.find(s=>s.base===e&&s.file===t);if(i)return s.updateExportSpecifier(n,n.isTypeOnly,n.propertyName,s.createIdentifier(i.newName))}return ts.visitEachChild(n,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousExportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{const a=path.basename(t).split(".")[0];if((ts.isFunctionDeclaration(r)||ts.isClassDeclaration(r))&&void 0===r.name){let e=!1,t=!1;if(r.modifiers?.forEach(s=>{s.kind===ts.SyntaxKind.ExportKeyword&&(e=!0),s.kind===ts.SyntaxKind.DefaultKeyword&&(t=!0)}),e&&t){const e=genName.getName(prefixKey,a);if(exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),ts.isFunctionDeclaration(r))return s.updateFunctionDeclaration(r,r.modifiers,r.asteriskToken,s.createIdentifier(e),r.typeParameters,r.parameters,r.type,r.body);if(ts.isClassDeclaration(r))return s.updateClassDeclaration(r,r.modifiers,s.createIdentifier(e),r.typeParameters,r.heritageClauses,r.members)}}else if(ts.isExportAssignment(r)&&!r.name&&!r.isExportEquals){if(ts.isArrowFunction(r.expression)){const e=genName.getName(prefixKey,a),t=s.createArrowFunction(r.expression.modifiers,r.expression.typeParameters,r.expression.parameters,r.expression.type,r.expression.equalsGreaterThanToken,r.expression.body),i=s.createVariableDeclaration(s.createIdentifier(e),r.expression.exclamationToken,r.expression.type,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(r.expression.modifiers,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isObjectLiteralExpression(r.expression)){const e=genName.getName(prefixKey,a),t=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,r.expression),i=s.createVariableDeclarationList([t],ts.NodeFlags.Const),o=s.createVariableStatement(void 0,i),c=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[o,c],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isArrayLiteralExpression(r.expression)){const e=genName.getName(prefixKey,a),t=s.createArrayLiteralExpression(r.expression.elements,!0),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isStringLiteral(r.expression)){const e=genName.getName(prefixKey,a),t=s.createStringLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}if(ts.isNumericLiteral(r.expression)){const e=genName.getName(prefixKey,a),t=s.createNumericLiteral(r.expression.text),i=s.createVariableDeclaration(s.createIdentifier(e),void 0,void 0,t),o=s.createVariableDeclarationList([i],ts.NodeFlags.Const),c=s.createVariableStatement(void 0,o),l=s.createExportAssignment(void 0,void 0,s.createIdentifier(e));return exportDefaultExportNameMap.push({base:e,file:a,newName:e,isEd:!0}),s.updateSourceFile(n,[c,l],n.isDeclarationFile,n.referencedFiles,n.typeReferenceDirectives,n.hasNoDefaultLib,n.libReferenceDirectives)}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}function anonymousImportHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0),r=transformFunction(e=>{const{factory:s}=e,i=r=>{if(ts.isImportDeclaration(r)){const e=r.moduleSpecifier.getText(n),i=path.basename(e).split(".")[0].trim();if(r.importClause?.name&&ts.isIdentifier(r.importClause.name)){const e=r.importClause.name.text.trim(),n=exportDefaultExportNameMap.find(e=>e.file===i);if(n){exportDefaultImportNameMap.push({base:e,file:t,newName:n.newName,isEd:!0});const i=s.updateImportClause(r.importClause,r.importClause.phaseModifier,s.createIdentifier(n.newName),r.importClause.namedBindings);return s.updateImportDeclaration(r,r.modifiers,i,r.moduleSpecifier,r.attributes)}}}return ts.visitEachChild(r,i,e)};return e=>ts.visitNode(e,i)},n,e);return{file:t,content:r,...i}}}const anonymousHandler=async(e,t)=>{const s=resolves([[anonymousExportHandler,t],[anonymousImportHandler,t],[anonymousCallExpressionHandler,t]]),i=await s.concurrent();for(const t of i)e=e.map(t);return e};function duplicates(e,t,s){const i=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),n=new Map;for(const e of i.statements){if(!ts.isImportDeclaration(e)||!e.importClause)continue;const t=e.importClause;if(t.name&&ts.isIdentifier(t.name)){const e=t.name.text;n.set(e,(n.get(e)||[]).concat({name:e,node:t}))}else if(t.namedBindings&&ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)){const e=t.namedBindings.name.text;n.set(e,(n.get(e)||[]).concat({name:e,node:t.namedBindings}))}else if(t.namedBindings&&ts.isNamedImports(t.namedBindings))for(const e of t.namedBindings.elements)if(ts.isIdentifier(e.name)){const t=e.name.text;n.set(t,(n.get(t)||[]).concat({name:t,node:e}))}}const r=new Map,a=uniqueName();a.setPrefix({key:"DuplicateImport",value:"__dup__"});for(const[e,t]of n.entries())if(t.length>1)for(let s=1;s<t.length;s++){const t=a.getName("DuplicateImport",`${e}_`);r.set(`${e}::${s}`,t),r.set(`${e}::occurrence_${s}`,t)}const o=new Map;for(const[e,t]of n.entries())if(t.length>1)for(let s=1;s<t.length;s++){const i=t[s];i?.node&&o.set(i.node.pos,r.get(`${e}::${s}`))}return transformFunction(e=>{const{factory:t}=e,s=i=>{if(ts.isImportDeclaration(i)&&i.importClause){const e=i.importClause;let s=!1,n=e;if(e.name&&ts.isIdentifier(e.name)){e.pos;const i=o.get(e.pos);i&&(n=t.updateImportClause(e,e.isTypeOnly,t.createIdentifier(i),e.namedBindings),s=!0)}if(e.namedBindings&&ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)){const i=o.get(e.namedBindings.pos);if(i){const e=t.createNamespaceImport(t.createIdentifier(i));n=t.updateImportClause(n,n.isTypeOnly,n.name,e),s=!0}}if(e.namedBindings&&ts.isNamedImports(e.namedBindings)){const i=e.namedBindings.elements.map(e=>{if(ts.isIdentifier(e.name)){const i=o.get(e.pos);if(i)return s=!0,t.updateImportSpecifier(e,e.isTypeOnly,e.propertyName,t.createIdentifier(i))}return e});if(s){const e=t.createNamedImports(i);n=t.updateImportClause(n,n.isTypeOnly,n.name,e)}}if(s)return t.updateImportDeclaration(i,i.modifiers,n,i.moduleSpecifier,i.assertClause)}if(ts.isIdentifier(i)){const e=i.text;if(!(e=>{const t=e.parent;if(!t)return!1;switch(t.kind){case ts.SyntaxKind.ImportSpecifier:case ts.SyntaxKind.NamespaceImport:case ts.SyntaxKind.ImportClause:case ts.SyntaxKind.VariableDeclaration:case ts.SyntaxKind.FunctionDeclaration:case ts.SyntaxKind.ClassDeclaration:case ts.SyntaxKind.InterfaceDeclaration:case ts.SyntaxKind.TypeAliasDeclaration:case ts.SyntaxKind.EnumDeclaration:case ts.SyntaxKind.Parameter:case ts.SyntaxKind.PropertyDeclaration:case ts.SyntaxKind.MethodDeclaration:case ts.SyntaxKind.BindingElement:return!0;default:return!1}})(i)){if(i.parent&&ts.isPropertyAccessExpression(i.parent)&&i.parent.name===i)return i;const s=n.get(e);if(s&&s.length>1)for(let i=1;i<s.length;i++){const s=r.get(`${e}::occurrence_${i}`)||r.get(`${e}::${i}`);if(s)return t.createIdentifier(s)}}}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},i,s)}function mergeImportsStatement(e){const t=new Map,s=new Map,i=new Map,n=new Map,r=new Map;for(const a of e){const e=a.match(/import\s+(?:type\s+)?(?:(.*?)\s+from\s+)?["']([^"']+)["'];?/);if(!e)continue;const[,o,c]=e,l=a.includes("import type"),m=c;if(!o){const e=a.match(/import\s+(?:type\s+)?(\w+)/);if(e){const t=e[1],s=l?n:i;s.has(m)||s.set(m,new Set),s.get(m)?.add(t)}continue}if(o.startsWith("{")){const e=l?s:t;e.has(m)||e.set(m,new Set);o.replace(/[{}]/g,"").split(",").map(e=>e.trim()).filter(Boolean).forEach(t=>e.get(m)?.add(t))}else if(o.startsWith("* as")){const e=o.match(/\*\s+as\s+(\w+)/);if(e){const t=e[1];r.has(m)||r.set(m,new Set),r.get(m)?.add(t)}}else{const e=l?n:i;e.has(m)||e.set(m,new Set),e.get(m)?.add(o.trim())}}const a=[];for(const[e,i]of t){const t=s.get(e)||new Set,n=new Set([...i]);for(const e of t)i.has(e)||n.add(e);if(n.size>0){const t=Array.from(n).sort().join(", ");a.push(`import { ${t} } from "${e}";`)}}for(const[e,i]of s)if(!t.has(e)&&i.size>0){const t=Array.from(i).sort().join(", ");a.push(`import type { ${t} } from "${e}";`)}for(const[e,t]of i){const s=n.get(e)||new Set,i=new Set([...t]);for(const e of s)t.has(e)||i.add(e);if(i.size>0){const t=Array.from(i).join(", ");a.push(`import ${t} from "${e}";`)}}for(const[e,t]of n)if(!i.has(e)&&t.size>0){const s=Array.from(t).join(", ");a.push(`import type ${s} from "${e}";`)}for(const[e,t]of r)if(t.size>0){const s=Array.from(t).join(", ");a.push(`import * as ${s} from "${e}";`)}return a.sort()}function esmExportRemoveHandler(e){return({file:t,content:s,...i})=>{const n=ts.createSourceFile(t,s,ts.ScriptTarget.Latest,!0);return{file:t,content:transformFunction(e=>{const{factory:t}=e,s=i=>{if(!utilities.isInsideNamespace(i)&&(ts.isFunctionDeclaration(i)||ts.isClassDeclaration(i)||ts.isInterfaceDeclaration(i)||ts.isTypeAliasDeclaration(i)||ts.isEnumDeclaration(i)||ts.isVariableStatement(i))){const e=i.modifiers?.filter(e=>e.kind!==ts.SyntaxKind.ExportKeyword&&e.kind!==ts.SyntaxKind.DefaultKeyword);if(e?.length!==i.modifiers?.length){if(ts.isFunctionDeclaration(i))return t.updateFunctionDeclaration(i,e,i.asteriskToken,i.name,i.typeParameters,i.parameters,i.type,i.body);if(ts.isClassDeclaration(i))return t.updateClassDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isInterfaceDeclaration(i))return t.updateInterfaceDeclaration(i,e,i.name,i.typeParameters,i.heritageClauses,i.members);if(ts.isTypeAliasDeclaration(i))return t.updateTypeAliasDeclaration(i,e,i.name,i.typeParameters,i.type);if(ts.isEnumDeclaration(i))return t.updateEnumDeclaration(i,e,i.name,i.members);if(ts.isVariableStatement(i))return t.updateVariableStatement(i,e,i.declarationList)}}if(ts.isExportDeclaration(i))return t.createEmptyStatement();if(ts.isExportAssignment(i)){const e=i.expression;if(ts.isIdentifier(e))return t.createEmptyStatement()}return ts.visitEachChild(i,s,e)};return e=>ts.visitNode(e,s)},n,e),...i}}}let properties=[];const typeObj={},typesNames=[];function findProperty(e){const t=[];return ts.isPropertyAccessExpression(e)&&ts.isIdentifier(e.expression)&&t.push(e.expression.text),e.forEachChild(e=>findProperty(e)),t}function importAllRemoveHandler(e,t){return({file:s,content:i,...n})=>{const r=ts.createSourceFile(s,i,ts.ScriptTarget.Latest,!0),a=new Set;for(const e of r.statements)if(ts.isImportEqualsDeclaration(e)&&e.isTypeOnly){const t=e.moduleReference;ts.isExternalModuleReference(t)&&ts.isStringLiteral(t.expression)&&a.add(e.name.text)}const o=transformFunction(t=>{const{factory:i}=t,n=o=>{properties=[...properties,...findProperty(o)];const c={isNamespace:!1,isTypeOnly:!1,isTypeNamespace:!1,source:"",importedString:void 0,importedObject:void 0};if(ts.isTypeReferenceNode(o)&&ts.isQualifiedName(o.typeName)&&ts.isIdentifier(o.typeName.left)&&ts.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],utilities.checkModuleType(r,s).isCommonJs&&"ts"!==e&&!a.has(e))return i.updateTypeReferenceNode(o,i.createIdentifier(t),void 0)}if(ts.isImportDeclaration(o)){const t=o.getText(r);return e.push(t),i.createEmptyStatement()}if(ts.isImportEqualsDeclaration(o)){const t=o.name.text,s=o.moduleReference;let n;if(o.isTypeOnly&&(c.isTypeOnly=!0),c.importedString=t,c.isTypeOnly||properties.includes(t)&&(c.isNamespace=!0),ts.isExternalModuleReference(s)&&ts.isStringLiteral(s.expression)&&(c.source=s.expression.text),c.importedString&&!c.importedObject&&(n=c.isTypeOnly?a.has(c.importedString)?`import type * as ${c.importedString} from "${c.source}";`:typesNames.includes(c.importedString)?`import type { ${typeObj[c.importedString]?.join(",")} } from "${c.source}";`:`import type ${c.importedString} from "${c.source}";`:c.isNamespace&&c.source&&"typescript"!==c.source?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}if(ts.isVariableStatement(o)){const t=o.declarationList.declarations;if(1===t.length){const s=t[0];if(s.initializer&&ts.isCallExpression(s.initializer)&&ts.isIdentifier(s.initializer.expression)&&"require"===s.initializer.expression.escapedText){const t=s.initializer.arguments[0];if(ts.isStringLiteral(t)&&(c.source=t.text),ts.isIdentifier(s.name)){const e=s.name.text;c.importedString=e,properties.includes(e)&&(c.isNamespace=!0)}else if(ts.isObjectBindingPattern(s.name)){const e=[];for(const t of s.name.elements)ts.isIdentifier(t.name)&&e.push(t.name.text);e.length>0&&(c.importedObject=e)}let n;if(c.importedString&&!c.importedObject&&(n=c.isNamespace?`import * as ${c.importedString} from "${c.source}";`:`import ${c.importedString} from "${c.source}";`),!c.importedString&&c.importedObject&&(n=`import { ${c.importedObject.join(", ")} } from "${c.source}";`),n)return e.push(n),i.createEmptyStatement()}}}return ts.visitEachChild(o,n,t)};return e=>ts.visitNode(e,n)},r,t);return{file:s,content:o,...n}}}const removeHandlers=async(e,t)=>{const s=resolves([[importAllRemoveHandler,e,t],[esmExportRemoveHandler,t]]);return await s.series()};function collectBindingNames(e,t){ts.isIdentifier(e)?t.push(e.text):(ts.isObjectBindingPattern(e)||ts.isArrayBindingPattern(e))&&e.elements.forEach(e=>{ts.isBindingElement(e)&&e.name&&collectBindingNames(e.name,t)})}function clearUnusedCode(e,t,s,i={treatExportsAsUsed:!0}){const n=ts.createSourceFile(t,e,ts.ScriptTarget.Latest,!0),r=new Map,a=new Set,o=(e,t=!1)=>{const s=r.get(e);r.set(e,{exported:!!s?.exported||t})},c=e=>{if(ts.isImportDeclaration(e)&&e.importClause){const t=e.importClause;t.name&&ts.isIdentifier(t.name)&&o(t.name.text,!1),t.namedBindings&&(ts.isNamedImports(t.namedBindings)?t.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&o(e.name.text,!1)}):ts.isNamespaceImport(t.namedBindings)&&ts.isIdentifier(t.namedBindings.name)&&o(t.namedBindings.name.text,!1))}else if(ts.isImportEqualsDeclaration(e)&&ts.isIdentifier(e.name))o(e.name.text,!1);else if(ts.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;e.declarationList.declarations.forEach(e=>{collectBindingNames(e.name,[]);const s=[];collectBindingNames(e.name,s),s.forEach(e=>o(e,t))})}else if(ts.isFunctionDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}else if(ts.isClassDeclaration(e)&&e.name&&ts.isIdentifier(e.name)){const t=e.modifiers?.some(e=>e.kind===ts.SyntaxKind.ExportKeyword)??!1;o(e.name.text,t)}if(ts.isIdentifier(e)){const t=e.parent;ts.isVariableDeclaration(t)&&t.name===e||ts.isFunctionDeclaration(t)&&t.name===e||ts.isClassDeclaration(t)&&t.name===e||ts.isImportClause(t)&&t.name===e||ts.isImportSpecifier(t)&&t.name===e||ts.isNamespaceImport(t)&&t.name===e||ts.isBindingElement(t)&&t.name===e||ts.isParameter(t)&&t.name===e||a.add(e.text)}ts.forEachChild(e,c)};c(n);const l=new Set;r.forEach((e,t)=>{a.has(t)||i.treatExportsAsUsed&&e.exported||l.add(t)});return transformFunction(e=>{const t=s=>{if(ts.isImportDeclaration(s)&&s.importClause){const e=s.importClause,t=e.name&&ts.isIdentifier(e.name)?e.name.text:void 0;let i;const n=[];e.namedBindings&&(ts.isNamedImports(e.namedBindings)?e.namedBindings.elements.forEach(e=>{ts.isImportSpecifier(e)&&ts.isIdentifier(e.name)&&n.push(e)}):ts.isNamespaceImport(e.namedBindings)&&ts.isIdentifier(e.namedBindings.name)&&(i=e.namedBindings.name.text));const r=!!t&&!l.has(t),a=!!i&&!l.has(i),o=n.filter(e=>!l.has(e.name.text));if(!r&&!a&&0===o.length)return ts.factory.createNotEmittedStatement(s);if(!r&&!!e.name||void 0!==i&&!a||o.length!==n.length){let e;e=o.length>0?ts.factory.createNamedImports(o):a&&i?ts.factory.createNamespaceImport(ts.factory.createIdentifier(i)):void 0;const n=r&&t?ts.factory.createIdentifier(t):void 0,c=ts.factory.createImportClause(!1,n,e);return ts.factory.updateImportDeclaration(s,s.modifiers,c,s.moduleSpecifier,s.assertClause)}return s}if((ts.isFunctionDeclaration(s)||ts.isClassDeclaration(s))&&s.name&&ts.isIdentifier(s.name))return l.has(s.name.text)?ts.factory.createNotEmittedStatement(s):s;if(ts.isVariableStatement(s)){const e=[];s.declarationList.declarations.forEach(t=>collectBindingNames(t.name,e));return e.some(e=>!l.has(e))?s:ts.factory.createNotEmittedStatement(s)}return ts.visitEachChild(s,t,e)};return e=>ts.visitNode(e,t)},n,s)}async function bundler(e){const t="."===e.exportPath?"Main":utilities.splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Bundled")} -> ${tcolor.brightCyan(t)} ${tcolor.cyan("export path")}`);let s=e.depFiles;const i=e.rename,n=e.tsOptions.default,r=e.plugins;let a=[];s=await anonymousHandler(s,n);const o=await removeHandlers(a,n);s=s.map(o[0]);const c=s.slice(0,-1).map(o[1]),l=s.slice(-1),m=/["']((?!\.\/|\.\.\/)[^"']+)["']/;a=a.filter(e=>m.test(e)),a=mergeImportsStatement(a);let p=`${a.join("\n").trim()}\n${c.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}\n${l.map(e=>`${`//${path.relative(process.cwd(),e.file)}`}\n${e.content}`).join("\n").trim()}`;if(p=p.replace(/^s*;\s*$/gm,"").trim(),i&&(p=duplicates(p,e.fileName,n)),p=clearUnusedCode(p,e.fileName,n),r.length)for(let e of r)e="function"==typeof e?e():e,"pre-process"===e.type&&(p=e.async?await e.func(p):e.func(p));return console.timeEnd(`${tcolor.cyan("Bundled")} -> ${tcolor.brightCyan(t)} ${tcolor.cyan("export path")}`),{bundledContent:p,...e}}async function bundle(e){const t=[];for(const s of e.points){const e=await bundler(s);t.push(e)}return{points:t,allowUpdatePackageJson:e.allowUpdatePackageJson}}function createHost(e,t){const s={},i={getSourceFile:(s,i)=>{if(s===t)return ts.createSourceFile(s,e,i)},writeFile:(e,t)=>{s[e]=t},getDefaultLibFileName:e=>ts.getDefaultLibFilePath(e),getCurrentDirectory:()=>"",getDirectories:()=>[],fileExists:e=>e===t,readFile:s=>s===t?e:void 0,getCanonicalFileName:e=>e,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n"};return{createdFiles:s,host:i}}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:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`},require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:isCjs(e)&&!isEsm(e)?{[t]:{require:{types:`./${path.relative(process.cwd(),e.commonjsTypes)}`,default:`./${path.relative(process.cwd(),e.commonjs)}`}}}:!isCjs(e)&&isEsm(e)?{[t]:{import:{types:`./${path.relative(process.cwd(),e.esmTypes)}`,default:`./${path.relative(process.cwd(),e.esm)}`}}}:{}}async function writePackage(e,t){let s=!0;"."!==t&&(s=!1);const i=ts.sys.resolvePath("package.json"),n=fs.readFileSync(i,"utf8"),r=JSON.parse(n);let{name:a,version:o,description:c,main:l,module:m,type:p,types:f,exports:d,...u}=r;await utilities.wait(500),p="module";let y={},g={},h={},x={};if(s)y=e.main?{main:path.relative(process.cwd(),e.main)}:{},g=e.module?{module:path.relative(process.cwd(),e.module)}:{},h=e.types?{types:path.relative(process.cwd(),e.types)}:{},x={exports:{...getExports(e,t)}};else{y=l?{main:l}:{},g=m?{module:m}:{},h=f?{types:f}:{};x={exports:{...d&&"object"==typeof d&&!Array.isArray(d)?{...d}:{},...getExports(e,t)}}}await utilities.wait(1e3);const w={name:a,version:o,description:c,type:p,...y,...h,...g,...x,...u};utilities.writeCompileFile(i,JSON.stringify(w,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,s=t?"Main":utilities.splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Compiled CJS")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`);const i=e.fileName,n=e.bundledContent,r=e.format,a=e.plugins,o=e.tsOptions.cjs,c=createHost(n,i),l=c.createdFiles,m=c.host;ts.createProgram([i],o,m).emit(),Object.entries(l).map(async([e,s])=>{if(".js"===path.extname(e)&&a.length)for(let t of a)t="function"==typeof t?t():t,"post-process"===t.type&&(s=t.async?await t.func(s,e):t.func(s,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"!==r&&"commonjs"!==r||(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 utilities.wait(500),"commonjs"===r&&await utilities.clearFolder(path.dirname(e)),await utilities.writeCompileFile(e,s)}),console.timeEnd(`${tcolor.cyan("Compiled CJS")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`)}async _esm(e){const t="."===e.exportPath,s=t?"Main":utilities.splitCamelCase(e.exportPath.slice(2));console.time(`${tcolor.cyan("Compiled ESM")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`);const i=e.fileName,n=e.bundledContent,r=e.format,a=e.plugins,o=e.tsOptions.esm,c=createHost(n,i),l=c.createdFiles,m=c.host;ts.createProgram([i],o,m).emit(),Object.entries(l).map(async([e,s])=>{if(".js"===path.extname(e)&&a.length)for(let t of a)t="function"==typeof t?t():t,"post-process"===t.type&&(s=t.async?await t.func(s,e):t.func(s,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"===r&&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 utilities.wait(500),"commonjs"!==r&&await utilities.clearFolder(path.dirname(e)),await utilities.writeCompileFile(e,s)}),console.timeEnd(`${tcolor.cyan("Compiled ESM")} -> ${tcolor.brightCyan(s)} ${tcolor.cyan("export path")}`)}async compile(){for(const e of this.object.points){switch(await utilities.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 utilities.wait(1e3),await this._commonjs(e),this._isUpdate()&&await writePackage(this.files,e.exportPath)}await utilities.wait(500)}}}async function susee(){console.info(`${tcolor.cyan("Susee Started")} : `),console.time(`${tcolor.cyan("Susee Done")}`);const e=await collections();await utilities.wait(1e3);const t=await bundle(e);await utilities.wait(1e3);const s=new Compiler(t);await s.compile(),console.timeEnd(`${tcolor.cyan("Susee Done")}`)}export{susee};