@remotex-labs/xbuild 1.5.7 → 1.5.8

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/cli.js CHANGED
@@ -8,6 +8,6 @@ __ _| |_/ /_ _ _| | __| |
8
8
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
9
9
  `;function t(r=!0){return`
10
10
  \r${e("\x1B[38;5;208m",i,r)}
11
- \rVersion: ${e("\x1B[38;5;197m","1.5.7",r)}
11
+ \rVersion: ${e("\x1B[38;5;197m","1.5.8",r)}
12
12
  \r`}console.log(t());o(process.argv).catch(r=>{console.error(r.stack),process.exit(1)});
13
13
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/cli.ts", "../src/components/colors.component.ts", "../src/components/banner.component.ts"],
4
- "sourceRoot": "https://github.com/remotex-lab/xBuild/tree/v1.5.7/",
4
+ "sourceRoot": "https://github.com/remotex-lab/xBuild/tree/v1.5.8/",
5
5
  "sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Import will remove at compile time\n */\n\nimport type { xBuildError } from '@errors/xbuild.error';\nimport type { VMRuntimeError } from '@errors/vm-runtime.error';\n\n/**\n * Imports\n */\n\nimport { buildWithArgv } from './index.js';\nimport { bannerComponent } from '@components/banner.component';\n\n/**\n * Banner\n */\n\nconsole.log(bannerComponent());\n\n/**\n * Run entrypoint of xBuild\n */\n\nbuildWithArgv(process.argv).catch((error: VMRuntimeError & xBuildError) => {\n console.error(error.stack);\n process.exit(1);\n});\n", "/**\n * An enumeration of ANSI color codes used for text formatting in the terminal.\n *\n * These colors can be used to format terminal output with various text colors,\n * including different shades of gray, yellow, and orange, among others.\n *\n * Each color code starts with an ANSI escape sequence (`\\u001B`), followed by the color code.\n * The `Reset` option can be used to reset the terminal's text formatting back to the default.\n *\n * @example\n * ```ts\n * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);\n * ```\n */\n\nexport const enum Colors {\n Reset = '\\u001B[0m',\n Red = '\\u001B[38;5;9m',\n Gray = '\\u001B[38;5;243m',\n Cyan = '\\u001B[38;5;81m',\n DarkGray = '\\u001B[38;5;238m',\n LightCoral = '\\u001B[38;5;203m',\n LightOrange = '\\u001B[38;5;215m',\n OliveGreen = '\\u001B[38;5;149m',\n BurntOrange = '\\u001B[38;5;208m',\n LightGoldenrodYellow = '\\u001B[38;5;221m',\n LightYellow = '\\u001B[38;5;230m',\n CanaryYellow = '\\u001B[38;5;227m',\n DeepOrange = '\\u001B[38;5;166m',\n LightGray = '\\u001B[38;5;252m',\n BrightPink = '\\u001B[38;5;197m'\n}\n\n/**\n * Formats a message string with the specified ANSI color and optionally resets it after the message.\n *\n * This function applies an ANSI color code to the provided message,\n * and then appends the reset code to ensure that the color formatting doesn't extend beyond the message.\n * It's useful for outputting colored text in a terminal. If color formatting is not desired,\n * the function can return the message unformatted.\n *\n * @param color - The ANSI color code to apply. This is used only if `activeColor` is true.\n * @param msg - The message to be formatted with the specified color.\n * @param activeColor - A boolean flag indicating whether color formatting should be applied. Default is `__ACTIVE_COLOR`.\n *\n * @returns A string with the specified color applied to the message,\n * followed by a reset sequence if `activeColor` is true.\n *\n * @example\n * ```ts\n * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');\n * console.log(coloredMessage);\n * ```\n *\n * @example\n * ```ts\n * const plainMessage = setColor(Colors.LightOrange, 'This is a light orange message', false);\n * console.log(plainMessage); // Output will be without color formatting\n * ```\n */\n\n\nexport function setColor(color: Colors, msg: string, activeColor: boolean = __ACTIVE_COLOR): string {\n if (!activeColor)\n return msg;\n\n return `${color}${msg}${Colors.Reset}`;\n}\n\n", "/**\n * Imports\n */\n\nimport { Colors, setColor } from '@components/colors.component';\n\n/**\n * ASCII Logo and Version Information\n *\n * @remarks\n * The `asciiLogo` constant stores an ASCII representation of the project logo\n * that will be displayed in the banner. This banner is rendered in a formatted\n * string in the `bannerComponent` function.\n *\n * The `cleanScreen` constant contains an ANSI escape code to clear the terminal screen.\n */\n\nexport const asciiLogo = `\n ______ _ _ _\n | ___ \\\\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\\\ \\\\/ / ___ \\\\ | | | | |/ _\\` |\n > <| |_/ / |_| | | | (_| |\n/_/\\\\_\\\\____/ \\\\__,_|_|_|\\\\__,_|\n`;\n\n// ANSI escape codes for colors\nexport const cleanScreen = '\\x1Bc';\n\n/**\n * Renders the banner with the ASCII logo and version information.\n *\n * This function constructs and returns a formatted banner string that includes an ASCII logo and the version number.\n * The colors used for the ASCII logo and version number can be enabled or disabled based on the `activeColor` parameter.\n * If color formatting is enabled, the ASCII logo will be rendered in burnt orange, and the version number will be in bright pink.\n *\n * @param activeColor - A boolean flag indicating whether ANSI color formatting should be applied. Default is `__ACTIVE_COLOR`.\n *\n * @returns A formatted string containing the ASCII logo, version number, and ANSI color codes if `activeColor` is `true`.\n *\n * @remarks\n * The `bannerComponent` function clears the terminal screen, applies color formatting if enabled, and displays\n * the ASCII logo and version number. The version number is retrieved from the global `__VERSION` variable, and\n * the colors are reset after the text is rendered.\n *\n * @example\n * ```ts\n * console.log(bannerComponent());\n * ```\n *\n * This will output the banner to the console with the ASCII logo, version, and colors.\n *\n * @example\n * ```ts\n * console.log(bannerComponent(false));\n * ```\n *\n * This will output the banner to the console with the ASCII logo and version number without color formatting.\n *\n * @public\n */\n\n// Todo \\r${ activeColor ? cleanScreen : '' }\n\nexport function bannerComponent(activeColor: boolean = true): string {\n return `\n \\r${ setColor(Colors.BurntOrange, asciiLogo, activeColor) }\n \\rVersion: ${ setColor(Colors.BrightPink, __VERSION, activeColor) }\n \\r`;\n}\n\n/**\n * A formatted string prefix used for logging build-related messages.\n * // todo optimize this\n */\n\nexport function prefix() {\n return setColor(Colors.LightCoral, '[xBuild]');\n}\n"],
6
6
  "mappings": ";AAaA,OAAS,iBAAAA,MAAqB,aCiDvB,SAASC,EAASC,EAAeC,EAAaC,EAAuB,eAAwB,CAChG,OAAKA,EAGE,GAAGF,CAAK,GAAGC,CAAG,UAFVA,CAGf,CClDO,IAAME,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;EA+ClB,SAASC,EAAgBC,EAAuB,GAAc,CACjE,MAAO;AAAA,YACEC,mBAA6BC,EAAWF,CAAW,CAAE;AAAA,qBAC5CC,mBAA4B,QAAWD,CAAW,CAAE;AAAA,OAE1E,CFjDA,QAAQ,IAAIG,EAAgB,CAAC,EAM7BC,EAAc,QAAQ,IAAI,EAAE,MAAOC,GAAwC,CACvE,QAAQ,MAAMA,EAAM,KAAK,EACzB,QAAQ,KAAK,CAAC,CAClB,CAAC",
7
7
  "names": ["buildWithArgv", "setColor", "color", "msg", "activeColor", "asciiLogo", "bannerComponent", "activeColor", "setColor", "asciiLogo", "bannerComponent", "buildWithArgv", "error"]
package/dist/index.js CHANGED
@@ -76,7 +76,7 @@ ${this.name}: ${this.applyColor("\x1B[38;5;243m",r?.file??"")}
76
76
  </body>
77
77
  </html>
78
78
  `;import{extname as q,join as Y,resolve as Ve}from"path";import{existsSync as Z,readdir as Ue,readFile as Je,readFileSync as X,stat as ze}from"fs";var Q={html:{icon:"fa-file-code",color:"#d1a65f"},css:{icon:"fa-file-css",color:"#264de4"},js:{icon:"fa-file-code",color:"#f7df1e"},json:{icon:"fa-file-json",color:"#b41717"},png:{icon:"fa-file-image",color:"#53a8e4"},jpg:{icon:"fa-file-image",color:"#53a8e4"},jpeg:{icon:"fa-file-image",color:"#53a8e4"},gif:{icon:"fa-file-image",color:"#53a8e4"},txt:{icon:"fa-file-alt",color:"#8e8e8e"},folder:{icon:"fa-folder",color:"#ffb800"}},T=class{rootDir;isHttps;config;constructor(e,t){this.rootDir=Ve(t),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?Z(this.config.keyfile)&&Z(this.config.certfile):!1}start(){if(this.config.onStart&&this.config.onStart(),this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){ee.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}).listen(this.config.port,this.config.host,()=>{console.log(`${d()} HTTP/S server is running at http://${this.config.host}:${this.config.port}`)})}startHttpsServer(){let e={key:X(this.config.keyfile),cert:X(this.config.certfile)};te.createServer(e,(r,i)=>{this.handleRequest(r,i,()=>this.defaultResponse(r,i))}).listen(this.config.port,this.config.host,()=>{let r=u("\x1B[38;5;227m",`https://${this.config.host}:${this.config.port}`);console.log(`${d()} HTTPS server is running at ${r}`)})}handleRequest(e,t,r){try{this.config.onRequest?this.config.onRequest(e,t,r):r()}catch(i){this.sendError(t,i)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",ts:"text/plain",map:"application/json",json:"application/json",png:"image/png",jpg:"image/jpeg",gif:"image/gif",txt:"text/plain"}[e]||"application/octet-stream"}async defaultResponse(e,t){let r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",i=Y(this.rootDir,r);if(!i.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await this.promisifyStat(i);n.isDirectory()?this.handleDirectory(i,r,t):n.isFile()&&this.handleFile(i,t)}catch(n){let a=n.message;a.includes("favicon")||console.log(d(),a),this.sendNotFound(t)}}promisifyStat(e){return new Promise((t,r)=>{ze(e,(i,n)=>i?r(i):t(n))})}handleDirectory(e,t,r){Ue(e,(i,n)=>{if(i)return this.sendError(r,i);let a=n.map(l=>{if(l.match(/[^A-Za-z0-9_\/\\.-]/))return;let c=Y(t,l);if(c.match(/[^A-Za-z0-9_\/\\.-]/))return;let f=q(l).slice(1)||"folder",{icon:m,color:x}=Q[f]||Q.folder;return`<li><i class="fas ${m}" style="color: ${x};"></i> <a href="/${c}">${l}</a></li>`}).join("");r.writeHead(200,{"Content-Type":"text/html"}),r.end(G.replace("${ fileList }",a))})}handleFile(e,t){let r=q(e).slice(1)||"txt",i=this.getContentType(r);Je(e,(n,a)=>{if(n)return this.sendError(t,n);t.writeHead(200,{"Content-Type":i}),t.end(a)})}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(`${d()}`,t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{promises as Ge}from"fs";import{resolve as qe}from"path";var k=class{buildState={};onEndHooks=[];onSuccess=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnSuccess(e){e&&this.onSuccess.push(e)}registerOnResolve(e){e&&this.onResolveHooks.push(e)}registerOnLoad(e){e&&this.onLoadHooks.push(e)}setup(){return{name:"middleware-plugin",setup:e=>{e.initialOptions.metafile=!0,e.onEnd(this.handleOnEnd.bind(this)),e.onStart(this.handleOnStart.bind(this,e)),e.onLoad({filter:/.*/},this.handleOnLoad.bind(this)),e.onResolve({filter:/.*/},this.handleOnResolve.bind(this))}}}async handleOnStart(e){this.buildState={};let t={errors:[],warnings:[]};for(let r of this.onStartHooks){let i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}return t}async handleOnEnd(e){let t={errors:e.errors??[],warnings:e.warnings??[]};for(let r of this.onEndHooks){e.errors=t.errors,e.warnings=t.warnings;let i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}if(t.errors.length<1)for(let r of this.onSuccess)await r(e,this.buildState);return t}async handleOnResolve(e){let t={};for(let r of this.onResolveHooks){let i=await r(e,this.buildState);i&&(t={...t,...i,path:i.path||t.path})}return t.path?t:null}async handleOnLoad(e){let t={contents:void 0,loader:"default"},r=qe(e.path);t.contents||(t.contents=await Ge.readFile(r,"utf8"));for(let i of this.onLoadHooks){let n=await i(t.contents??"",t.loader,e,this.buildState);n&&(t={...t,...n,contents:n.contents||t.contents,loader:n.loader||t.loader})}return t.contents?t:null}};function re(o,e){return o.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(t,r,i)=>e[r]?i:`
79
- `.repeat((i.match(/\n/g)||[]).length))}import{relative as Ye}from"path";function ie(o,e,t,r){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in t){let a=Ye(e,t[n]).replace(/\\/g,"/");a.startsWith("..")||(a=`./${a}`),o=o.replaceAll(n,`${a}/`),r&&(o=o.replace(i,(l,c)=>(c.startsWith("../")||c.startsWith("./"))&&!c.endsWith(".js")?l.replace(c,`${c}.js`):l))}return o}import*as s from"typescript";var P=class o extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),t?.cause&&(this.cause=t.cause)}};import{dirname as Ze,join as Xe,parse as oe,relative as ne,resolve as O,normalize as se}from"path";var Qe={ClassDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateClassDeclaration(o,i,o.name,o.typeParameters,o.heritageClauses,o.members)},InterfaceDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=e?[t,...e]:[t];return s.factory.updateInterfaceDeclaration(o,r,o.name,o.typeParameters,o.heritageClauses,o.members)},EnumDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateEnumDeclaration(o,i,o.name,o.members)},FunctionDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateFunctionDeclaration(o,i,o.asteriskToken,o.name,o.typeParameters,o.parameters,o.type,o.body)},TypeAliasDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=e?[t,...e]:[t];return s.factory.updateTypeAliasDeclaration(o,r,o.name,o.typeParameters,o.type)},VariableStatement:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateVariableStatement(o,i,o.declarationList)},ModuleDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=e?[t,...e]:[t];return s.factory.updateModuleDeclaration(o,r,o.name,o.body)}},D=class{constructor(e,t,r=!0){this.tsConfig=e;this.outDir=t;this.activeColor=r;this.options={...this.tsConfig.options,outDir:this.outDir}}options;typeCheck(e=!1){let t=s.createProgram(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0,emitDeclarationOnly:!0});this.handleDiagnostics(s.getPreEmitDiagnostics(t),e)}generateBundleDeclarations(e,t=!1,r=!1){let i={...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0},n=this.tsConfig.fileNames;!this.tsConfig.raw.include&&!this.tsConfig.raw.files&&(n=[]),Object.entries(e).forEach(([a,l])=>{i.outFile=Xe(this.outDir,a);let c=s.createProgram(n.concat(l),i),f={afterDeclarations:[this.cleanupDeclarations()]},m=s.getPreEmitDiagnostics(c);!t&&m.some(x=>x.category===s.DiagnosticCategory.Error)&&this.handleDiagnostics(m,r),c.emit(void 0,void 0,void 0,void 0,f)})}generateDeclarations(e,t=!1,r=!1){let i=s.createProgram([...this.tsConfig.fileNames,...Object.values(e)],{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),n=s.getPreEmitDiagnostics(i);!t&&n.some(a=>a.category===s.DiagnosticCategory.Error)&&this.handleDiagnostics(n,r),i.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return s.isImportDeclaration(e)||s.isExportDeclaration(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&s.isStringLiteral(e.moduleSpecifier)}resolveModuleFileName(e,t){let r,i=s.resolveModuleName(e,t.baseUrl,t,s.sys);if(i.resolvedModule&&t.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return r;r=O(i.resolvedModule.resolvedFileName).replace(O(t.baseUrl),".")}return r}getRelativePathToOutDir(e,t){e=O(e).replace(O(this.options.baseUrl??""),".");let r=ne(Ze(e),t).replace(/\\/g,"/"),i=oe(r);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,t){let r=s.factory.createStringLiteral(t);return s.isImportDeclaration(e)?s.factory.updateImportDeclaration(e,e.modifiers,e.importClause,r,void 0):s.isExportDeclaration(e)?s.factory.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,r,void 0):e}createVisitor(e,t){let r=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,a=this.resolveModuleFileName(n,this.options);if(a){let l=this.getRelativePathToOutDir(e.fileName,a);return this.updateModuleSpecifier(i,l)}}return s.visitEachChild(i,r,t)};return r}createTransformerFactory(){return e=>({transformSourceFile:t=>s.visitEachChild(t,this.createVisitor(t,e),e),transformBundle:t=>t})}handleDiagnostics(e,t=!1){if(e.length!==0&&(e.forEach(r=>{if(r.file&&r.start!==void 0){let{line:i,character:n}=r.file.getLineAndCharacterOfPosition(r.start),a=s.flattenDiagnosticMessageText(r.messageText,`
79
+ `.repeat((i.match(/\n/g)||[]).length))}import{relative as Ye}from"path";function ie(o,e,t,r){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in t){let a=Ye(e,t[n]).replace(/\\/g,"/");a.startsWith("..")||(a=`./${a}`),o=o.replaceAll(n,`${a}/`),r&&(o=o.replace(i,(l,c)=>(c.startsWith("../")||c.startsWith("./"))&&!c.endsWith(".js")?l.replace(c,`${c}.js`):l))}return o}import*as s from"typescript";var P=class o extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),t?.cause&&(this.cause=t.cause)}};import{dirname as Ze,join as Xe,parse as oe,relative as ne,resolve as O,normalize as se}from"path";var Qe={ClassDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateClassDeclaration(o,i,o.name,o.typeParameters,o.heritageClauses,o.members)},InterfaceDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=e?[t,...e]:[t];return s.factory.updateInterfaceDeclaration(o,r,o.name,o.typeParameters,o.heritageClauses,o.members)},EnumDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateEnumDeclaration(o,i,o.name,o.members)},FunctionDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateFunctionDeclaration(o,i,o.asteriskToken,o.name,o.typeParameters,o.parameters,o.type,o.body)},TypeAliasDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=e?[t,...e]:[t];return s.factory.updateTypeAliasDeclaration(o,r,o.name,o.typeParameters,o.type)},VariableStatement:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=s.factory.createModifier(s.SyntaxKind.DeclareKeyword),i=e?[t,r,...e]:[t,r];return s.factory.updateVariableStatement(o,i,o.declarationList)},ModuleDeclaration:(o,e)=>{let t=s.factory.createModifier(s.SyntaxKind.ExportKeyword),r=e?[t,...e]:[t];return s.factory.updateModuleDeclaration(o,r,o.name,o.body)}},D=class{constructor(e,t,r=!0){this.tsConfig=e;this.outDir=t;this.activeColor=r;this.options={...this.tsConfig.options,outDir:this.outDir}}options;typeCheck(e=!1){let t=s.createProgram(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0,emitDeclarationOnly:!0});this.handleDiagnostics(s.getPreEmitDiagnostics(t),e)}generateBundleDeclarations(e,t=!1,r=!1){let i={...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0},n=this.tsConfig.fileNames;!this.tsConfig.raw.include&&!this.tsConfig.raw.files&&(n=[]),n=n.filter(a=>a.endsWith(".d.ts")),Object.entries(e).forEach(([a,l])=>{i.outFile=Xe(this.outDir,a);let c=s.createProgram(n.concat(l),i),f={afterDeclarations:[this.cleanupDeclarations()]},m=s.getPreEmitDiagnostics(c);!t&&m.some(x=>x.category===s.DiagnosticCategory.Error)&&this.handleDiagnostics(m,r),c.emit(void 0,void 0,void 0,void 0,f)})}generateDeclarations(e,t=!1,r=!1){let i=s.createProgram([...this.tsConfig.fileNames,...Object.values(e)],{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),n=s.getPreEmitDiagnostics(i);!t&&n.some(a=>a.category===s.DiagnosticCategory.Error)&&this.handleDiagnostics(n,r),i.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return s.isImportDeclaration(e)||s.isExportDeclaration(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&s.isStringLiteral(e.moduleSpecifier)}resolveModuleFileName(e,t){let r,i=s.resolveModuleName(e,t.baseUrl,t,s.sys);if(i.resolvedModule&&t.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return r;r=O(i.resolvedModule.resolvedFileName).replace(O(t.baseUrl),".")}return r}getRelativePathToOutDir(e,t){e=O(e).replace(O(this.options.baseUrl??""),".");let r=ne(Ze(e),t).replace(/\\/g,"/"),i=oe(r);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,t){let r=s.factory.createStringLiteral(t);return s.isImportDeclaration(e)?s.factory.updateImportDeclaration(e,e.modifiers,e.importClause,r,void 0):s.isExportDeclaration(e)?s.factory.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,r,void 0):e}createVisitor(e,t){let r=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,a=this.resolveModuleFileName(n,this.options);if(a){let l=this.getRelativePathToOutDir(e.fileName,a);return this.updateModuleSpecifier(i,l)}}return s.visitEachChild(i,r,t)};return r}createTransformerFactory(){return e=>({transformSourceFile:t=>s.visitEachChild(t,this.createVisitor(t,e),e),transformBundle:t=>t})}handleDiagnostics(e,t=!1){if(e.length!==0&&(e.forEach(r=>{if(r.file&&r.start!==void 0){let{line:i,character:n}=r.file.getLineAndCharacterOfPosition(r.start),a=s.flattenDiagnosticMessageText(r.messageText,`
80
80
  `),l=u("\x1B[38;5;81m",r.file.fileName,this.activeColor),c=u("\x1B[38;5;230m",`${i+1}:${n+1}`,this.activeColor),f=u("\x1B[38;5;9m","error",this.activeColor),m=u("\x1B[38;5;243m",`TS${r.code}`,this.activeColor);console.error(`${d()} ${l}:${c} - ${f} ${m}:${a}`)}else console.error(s.flattenDiagnosticMessageText(r.messageText,`
81
81
  `))}),console.log(`
82
82
  `),!t))throw new P("Type checking failed due to errors.")}isNodeWithModifiers(e){return s.isClassDeclaration(e)||s.isInterfaceDeclaration(e)||s.isEnumDeclaration(e)||s.isFunctionDeclaration(e)||s.isTypeAliasDeclaration(e)||s.isVariableStatement(e)||s.isModuleDeclaration(e)}removeExportModifiers(e){if(!e)return;let t=e.filter(r=>r.kind!==s.SyntaxKind.ExportKeyword&&r.kind!==s.SyntaxKind.DefaultKeyword);return t.length?t:void 0}updateNodeWithoutExports(e){let t=this.removeExportModifiers(e.modifiers);for(let[r,i]of Object.entries(Qe)){let n=s[`is${r}`];if(typeof n=="function"&&n(e))return i(e,t)}return e}visitNode(e,t){return this.isNodeWithModifiers(t)&&t.modifiers&&t.modifiers.some(i=>i.kind===s.SyntaxKind.ExportKeyword||i.kind===s.SyntaxKind.DefaultKeyword)?this.updateNodeWithoutExports(t):s.visitEachChild(t,r=>this.visitNode(e,r),e)}visitTopLevelStatement(e,t,r,i){if(s.isImportDeclaration(e)){if(e.moduleSpecifier&&s.isStringLiteral(e.moduleSpecifier)){let n=e.moduleSpecifier.text;if(r.includes(se(n)))return[];e.importClause&&(t.has(n)||t.set(n,[]),t.get(n).push(e.importClause))}return[]}return s.isImportEqualsDeclaration(e)?[]:s.isExportDeclaration(e)?[]:s.isModuleDeclaration(e)?e.modifiers?.some(n=>n.kind===s.SyntaxKind.DeclareKeyword)?e.body&&s.isModuleBlock(e.body)?e.body.statements.flatMap(n=>this.visitTopLevelStatement(n,t,r,i)):[]:[this.visitNode(i,e)]:[this.visitNode(i,e)]}visitSourceFile(e,t,r,i){let n=e.statements.flatMap(a=>this.visitTopLevelStatement(a,t,r,i));return s.factory.updateSourceFile(e,n,e.isDeclarationFile,e.referencedFiles,e.typeReferenceDirectives,e.hasNoDefaultLib,e.libReferenceDirectives)}mergeImportClauses(e,t=!0){if(e.length===0)return;if(e.length===1&&!t)return e[0];let r,i=t;t||(i=e.some(c=>c.isTypeOnly));let n=new Map,a;for(let c of e){if(c.name&&!r&&(r=c.name),c.namedBindings&&s.isNamedImports(c.namedBindings))for(let f of c.namedBindings.elements){let m=f.name.text;n.has(m)||n.set(m,f)}c.namedBindings&&s.isNamespaceImport(c.namedBindings)&&!a&&(a=c.namedBindings)}let l;return n.size>0?l=s.factory.createNamedImports(Array.from(n.values())):a&&(l=a),s.factory.createImportClause(i,r,l)}cleanupDeclarations(){return e=>t=>{if(!s.isBundle(t))throw new Error("Cannot process a single file, expected a bundle");let r=new Map,i=t.sourceFiles.map(c=>{let f=oe(ne(this.options.baseUrl??"",c.fileName));return se(`${f.dir?f.dir+"/":""}${f.name}`)}),n=t.sourceFiles.map(c=>this.visitSourceFile(c,r,i,e)),a=Array.from(r.entries()).map(([c,f])=>s.factory.createImportDeclaration(void 0,this.mergeImportClauses(f),s.factory.createStringLiteral(c))),l=s.factory.createSourceFile(a,s.factory.createToken(s.SyntaxKind.EndOfFileToken),s.NodeFlags.None);return s.factory.createBundle([l,...n])}}};import h from"typescript";import{dirname as at}from"path";import{existsSync as le,readFileSync as ct}from"fs";import{cwd as et}from"process";var R={dev:!1,watch:!1,declaration:!1,buildOnError:!1,noTypeChecker:!1,bundleDeclaration:!1,define:{},esbuild:{write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:et(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as it}from"module";import{SourceService as ot}from"@remotex-labs/xmap";import{Script as tt,createContext as rt}from"vm";function ae(o,e={}){e.RegExp=RegExp,e.console=console;let t=new tt(o),r=rt(e);return t.runInContext(r,{breakOnSigint:!0})}function ce(o,e){for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let r=o[t];typeof r=="function"?o[t]=nt(r,e):typeof r=="object"&&r!==null&&ce(r,e)}return o}function nt(o,e){return(...t)=>{try{return o(...t)}catch(r){throw new v(r,e)}}}function st(o,e){return ce(o,e)}async function M(o){let{code:e,sourceMap:t}=await J(o,{banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),r={exports:{}},i=it(import.meta.url),n=new ot(JSON.parse(atob(t)));try{await ae(e,{require:i,module:r})}catch(a){throw new v(a,n)}return st(r.exports.default,n)}var lt=JSON.stringify({compilerOptions:{strict:!0,target:"ESNext",module:"ESNext",outDir:"dist",skipLibCheck:!0,isolatedModules:!1,esModuleInterop:!1,moduleDetection:"force",moduleResolution:"node",resolveJsonModule:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0}});function ft(o){let e=o.argv,t=i=>Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0)),r=t({bundle:e.bundle,minify:e.minify,outdir:e.outdir,tsconfig:e.tsconfig,entryPoints:e.file?[e.file]:void 0,target:e.node?[`node${process.version.slice(1)}`]:void 0,platform:e.node?"node":void 0,format:e.format});return{...t({dev:e.dev,watch:e.watch,declaration:e.declaration,serve:e.serve?{active:e.serve}:{undefined:void 0}}),esbuild:r}}function fe(o){let e=o.tsconfig??"tsconfig.json",t=le(e)?ct(e,"utf8"):JSON.stringify(lt),r=h.parseConfigFileTextToJson(e,t);if(r.error)throw new g(h.formatDiagnosticsWithColorAndContext([r.error],{getCurrentDirectory:h.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>h.sys.newLine}));let i=h.parseJsonConfigFileContent(r.config,h.sys,at(e));if(i.errors.length>0)throw new g(h.formatDiagnosticsWithColorAndContext(i.errors,{getCurrentDirectory:h.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>h.sys.newLine}));return i}async function I(o,e={}){let t=Array.isArray(o)?o:[o],r=t[0];return t.flatMap(i=>{let n={...R,...r,...i,...e,esbuild:{...R.esbuild,...r?.esbuild,...i?.esbuild,...e.esbuild},serve:{...R.serve,...r.serve,...i.serve,...e.serve}};if(!n.esbuild.entryPoints)throw new g("entryPoints cannot be undefined.");return n})}async function ue(o,e){let t=ft(e),r=le(o)?await M(o):{};return I(r,t)}function ut(o){let e={};return o.forEach(t=>{let r=t.substring(0,t.lastIndexOf("."));e[r]=t}),e}function B(o){if(Array.isArray(o)){let e={};return o.length>0&&typeof o[0]=="object"?o.forEach(t=>{e[t.out]=t.in}):typeof o[0]=="string"&&(e=ut(o)),e}else if(o&&typeof o=="object")return o;throw new g("Unsupported entry points format")}import{join as pt}from"path";import{mkdirSync as dt,writeFileSync as mt}from"fs";function pe(o){let e=o.moduleTypeOutDir??o.esbuild.outdir??"dist",t=o.esbuild.format==="esm"?"module":"commonjs";dt(e,{recursive:!0}),mt(pt(e,"package.json"),`{"type": "${t}"}`)}var S=class{constructor(e){this.config=e;let t=fe(this.config.esbuild);this.config.esbuild.logLevel="silent",this.pluginsProvider=new k,this.typeScriptProvider=new D(t,this.config.declarationOutDir??t.options.outDir??this.config.esbuild.outdir),this.configureDevelopmentMode(),this.setupPlugins()}typeScriptProvider;activePossess=[];pluginsProvider;async run(){return await this.execute(async()=>{let e=await this.build();return(this.config.watch||this.config.dev)&&await e.watch(),e})}async runDebug(e){return await this.execute(async()=>{this.config.dev=!1,this.config.watch=!1;let t=await this.build();this.spawnDev(t.metafile,e,!0)})}async serve(){let e=new T(this.config.serve,this.config.esbuild.outdir??"");return await this.execute(async()=>{e.start(),await(await this.build()).watch()})}async execute(e){try{return await e()}catch(t){let r=t;Array.isArray(r.errors)&&(!this.config.watch||!this.config.dev||!this.config.serve.active)?this.handleErrors(r):console.error(new v(t).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=C(this.typeScriptProvider.options.baseUrl??""),t=this.generatePathAlias(e);this.registerPluginHooks(t,e),this.pluginsProvider.registerOnLoad(async(r,i,n,a)=>await z(r,i,n,a,this.config))}registerPluginHooks(e,t){this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((r,i,n)=>{if(n.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let a=gt(C(n.path).replace(t,"."));r=ie(r.toString(),a,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:re(r.toString(),this.config.define)}}})}generatePathAlias(e){let t=this.typeScriptProvider.options.paths,r={};for(let i in t){let n=t[i];if(n.length>0){let a=i.replace(/\*/g,"");r[a]=C(n[0].replace(/\*/g,"")).replace(e,".")}}return r}handleErrors(e){let t=e.errors??[];for(let r of t){if(!r.detail){console.error(new E(r).stack);continue}if(r.detail.name!=="TypesError"){if(r.detail.name){if(r.detail.name==="VMRuntimeError"){console.error(r.detail.stack);continue}if(r.detail instanceof Error){console.error(new v(r.detail).stack);continue}}return console.error(r.text)}}}injects(e,t,r){if(!t)return;e[r]||(e[r]={});let i=e[r];for(let n in t)if(t.hasOwnProperty(n)){let a=t[n];if(typeof a=="function"){console.log(`${d()} trigger ${r} function`),i[n]=a();continue}i[n]=a}}async build(){pe(this.config);let e=this.config.esbuild;this.config.hooks&&(this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd),this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad),this.pluginsProvider.registerOnEnd(this.config.hooks.onSuccess),this.pluginsProvider.registerOnStart(this.config.hooks.onStart),this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve)),e.define||(e.define={});for(let t in this.config.define)e.define[t]=JSON.stringify(this.config.define[t]);return this.config.esbuild.bundle||await this.processEntryPoints(),e.plugins=[this.pluginsProvider.setup()],this.injects(this.config.esbuild,this.config.banner,"banner"),this.injects(this.config.esbuild,this.config.footer,"footer"),this.config.watch||this.config.dev||this.config.serve.active?await yt(e):await ht(e)}spawnDev(e,t,r=!1){if(Array.isArray(t))for(let i in e.outputs)i.includes("map")||!t.some(n=>i.includes(`/${n}.`))||this.activePossess.push(V(i,r))}async start(e,t){try{t.startTime=Date.now(),console.log(`${d()} StartBuild ${e.initialOptions.outdir}`),this.config.bundleDeclaration?this.typeScriptProvider.generateBundleDeclarations(B(this.config.esbuild.entryPoints),this.config.noTypeChecker,this.config.buildOnError):this.config.declaration?this.typeScriptProvider.generateDeclarations(B(this.config.esbuild.entryPoints),this.config.noTypeChecker,this.config.buildOnError):this.config.noTypeChecker||this.typeScriptProvider.typeCheck(this.config.buildOnError)}finally{for(;this.activePossess.length>0;){let r=this.activePossess.pop();r&&r.kill("SIGTERM")}}}async end(e,t){if(e.errors.length>0){this.handleErrors(e),!this.config.serve.active&&!this.config.dev&&!this.config.watch&&de.exit(1);return}let r=Date.now()-t.startTime;console.log(`