@remotex-labs/xbuild 1.3.2 → 1.3.3
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.js +14 -14
- package/dist/index.js.map +5 -5
- package/dist/providers/typescript.provider.d.ts +1 -8
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{cwd as me}from"process";import{readFileSync as ge}from"fs";import{fileURLToPath as he}from"url";import{dirname as
|
|
2
|
+
import{cwd as me}from"process";import{readFileSync as ge}from"fs";import{fileURLToPath as he}from"url";import{dirname as $,join as ye,resolve as B}from"path";function c(o,e,r=__ACTIVE_COLOR){return r?`${o}${e}\x1B[0m`:e}import{SourceService as ve,formatErrorCode as Se,highlightCode as be}from"@remotex-labs/xmap";var I=me(),R=$(he(import.meta.url)),Ce=$(R),L=(()=>{let o;return{get service(){if(!o){let e=ge(ye(R,"index.js.map"));o=new ve(e.toString(),import.meta.url)}return o}}})();global.__ACTIVE_COLOR||(global.__ACTIVE_COLOR=!0);function xe(o,e,r,t){return`${o.replace(`${t}\\`,e).replace(/\\/g,"/")}#L${r}`}function O(o,e,r,t,i){if(i.isPromiseAll())return`at async Promise.all (index: ${i.getPromiseIndex()})`;let n=i.isAsync()?"async":"",s=o?`${n} ${o}`:n,a=r>=0&&t>=0?c("\x1B[38;5;243m",`[${r}:${t}]`):"";return`at ${s} ${c("\x1B[38;5;238m",e)} ${a}`.replace(/\s{2,}/g," ").trim()}function we(o){let e=o.getLineNumber()||-1,r=o.getColumnNumber()||-1,t=o.getFileName()||"<anonymous>",i=o.getTypeName()||"",n=o.getFunctionName()||"",s=o.isNative()?"<native>":n;return i&&(s=`${i}.${s}`),{functionName:s,source:t,line:e,column:r}}function Ee(o,e){let r=__ACTIVE_COLOR?be(o.code):o.code;return o.name&&e.name=="TypeError"&&(e.message=e.message.replace(/^\S+/,o.name)),Se({...o,code:r},{color:__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:__ACTIVE_COLOR?"\x1B[0m":""})}function ke(o,e){let{functionName:r,source:t,line:i,column:n}=we(o);if(o.isPromiseAll()||o.isEval()||o.isNative())return O(r,t,i,n,o);let s=null,a=t===L.service.file;if(a?s=L.service.getPositionWithCode(i,n):e.error.sourceMap&&(s=e.error.sourceMap.getPositionWithCode(i,n)),s){let l=a?R:I,{line:g,column:h,name:T}=s,A=B(l,s.source);return e.blockCode||(e.blockCode=Ee(s,e.error)),s.sourceRoot&&(A=xe(B(l,s.source),s.sourceRoot,s.line,a?Ce:I)),O(T||r,A,g,h,o)}return t==="evalmachine.<anonymous>"?"":O(r,t,i,n,o)}function Pe(o,e){return e.map(r=>ke(r,o)).filter(Boolean)}function N(o,e){let r={error:o,blockCode:null,formattedError:global.__ACTIVE_COLOR?"\x1B[0m":""},t=Pe(r,e);return r.formattedError+=`
|
|
3
3
|
${o.name}:
|
|
4
4
|
${c("\x1B[38;5;203m",o.message)}
|
|
5
5
|
|
|
6
|
-
`,
|
|
6
|
+
`,r.blockCode&&(r.formattedError+=`${r.blockCode}
|
|
7
7
|
|
|
8
|
-
`),
|
|
9
|
-
${
|
|
8
|
+
`),t.length>0&&(r.formattedError+=`Enhanced Stack Trace:
|
|
9
|
+
${t.join(`
|
|
10
10
|
`)}
|
|
11
|
-
`),
|
|
11
|
+
`),r.formattedError}var _=Error.prepareStackTrace;Error.prepareStackTrace=(o,e)=>(o.callStacks=e,_?_(o,e):"");process.on("uncaughtException",o=>{console.error(o.stack)});process.on("unhandledRejection",o=>{console.error(o.stack)});import Te from"yargs";import{hideBin as Oe}from"yargs/helpers";function M(o){let e=Te(Oe(o)).command("$0 [file]","A versatile JavaScript and TypeScript toolchain build system.",r=>{r.positional("entryPoints",{describe:"The file entryPoints to build",type:"string"}).option("typeCheck",{describe:"Perform type checking",alias:"tc",type:"boolean"}).option("node",{alias:"n",describe:"Build for node platform",type:"boolean"}).option("dev",{alias:"d",describe:"Array entryPoints to run as development in Node.js",type:"array"}).option("debug",{alias:"db",describe:"Array entryPoints to run in Node.js with debug state",type:"array"}).option("serve",{alias:"s",describe:"Serve the build folder over HTTP",type:"boolean"}).option("outdir",{alias:"o",describe:"Output directory",type:"string"}).option("declaration",{alias:"de",describe:"Add TypeScript declarations",type:"boolean"}).option("watch",{alias:"w",describe:"Watch for file changes",type:"boolean"}).option("config",{alias:"c",describe:"Build configuration file (js/ts)",type:"string",default:"xbuild.config.ts"}).option("tsconfig",{alias:"tsc",describe:"Set TypeScript configuration file to use",type:"string",default:"tsconfig.json"}).option("minify",{alias:"m",describe:"Minify the code",type:"boolean"}).option("bundle",{alias:"b",describe:"Bundle the code",type:"boolean"}).option("noTypeChecker",{alias:"ntc",describe:"Skip TypeScript type checking",type:"boolean"}).option("buildOnError",{alias:"boe",describe:"Continue building even if there are TypeScript type errors",type:"boolean"}).option("format",{alias:"f",describe:"Defines the format for the build output ('cjs' | 'esm' | 'iif').",type:"string"}).option("version",{alias:"v",describe:"Show version number",type:"boolean",default:!1,conflicts:"help"})}).help().alias("help","h").version(!1).middleware(r=>{r.version&&process.exit(0)});return e.showHelp(r=>{(process.argv.includes("--help")||process.argv.includes("-h"))&&(console.log(r+`
|
|
12
12
|
|
|
13
|
-
`),process.exit(0))}),e}import{dirname as
|
|
13
|
+
`),process.exit(0))}),e}import{dirname as fr,resolve as y}from"path";import{build as pr,context as ur}from"esbuild";import{spawn as Re}from"child_process";function F(o,e=!1){let r=["--enable-source-maps",o];e&&r.unshift("--inspect-brk=0.0.0.0:0");let t=Re("node",r);return t.stdout.on("data",i=>{console.log(i.toString())}),t.stderr.on("data",i=>{console.error(i.toString())}),t}var d=class o extends Error{constructor(r,t){super(r);this.sourceMap=t;Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="xBuildBaseError"}callStacks=[];reformatStack(r){return r.callStacks?N(this,r.callStacks):r.stack??""}};var S=class o extends d{constructor(e){super(e.text),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="EsbuildError",e.location}};var De=`
|
|
14
14
|
______ _ _ _
|
|
15
15
|
| ___ \\ (_) | | |
|
|
16
16
|
__ _| |_/ /_ _ _| | __| |
|
|
17
17
|
\\ \\/ / ___ \\ | | | | |/ _\` |
|
|
18
18
|
> <| |_/ / |_| | | | (_| |
|
|
19
19
|
/_/\\_\\____/ \\__,_|_|_|\\__,_|
|
|
20
|
-
`;function
|
|
20
|
+
`;function j(o=!0){return`
|
|
21
21
|
\r${c("\x1B[38;5;208m",De,o)}
|
|
22
|
-
\rVersion: ${c("\x1B[38;5;197m","1.3.
|
|
23
|
-
\r`}function f(){return c("\x1B[38;5;203m","[xBuild]")}var m=class o extends d{originalError;originalErrorStack;constructor(e,
|
|
22
|
+
\rVersion: ${c("\x1B[38;5;197m","1.3.3",o)}
|
|
23
|
+
\r`}function f(){return c("\x1B[38;5;203m","[xBuild]")}var m=class o extends d{originalError;originalErrorStack;constructor(e,r){super(e.message,r),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.originalError=e,this.originalErrorStack=e.stack,this.name="VMRuntimeError",this.stack=this.reformatStack(e)}};import*as G from"http";import*as z from"https";var H=`<!DOCTYPE html>
|
|
24
24
|
<html>
|
|
25
25
|
<head>
|
|
26
26
|
<meta charset="UTF-8">
|
|
@@ -77,10 +77,10 @@ __ _| |_/ /_ _ _| | __| |
|
|
|
77
77
|
<ul>\${ fileList }</ul>
|
|
78
78
|
</body>
|
|
79
79
|
</html>
|
|
80
|
-
`;import{extname as
|
|
81
|
-
`),a=c("\x1B[38;5;81m",
|
|
80
|
+
`;import{extname as W,join as V,resolve as Be}from"path";import{existsSync as J,readdir as Ie,readFile as Le,readFileSync as U,stat as _e}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"}},b=class{rootDir;isHttps;config;constructor(e,r){this.rootDir=Be(r),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?J(this.config.keyfile)&&J(this.config.certfile):!1}start(){if(this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){G.createServer((r,t)=>{this.handleRequest(r,t,()=>this.defaultResponse(r,t))}).listen(this.config.port,this.config.host,()=>{console.log(`${f()} HTTP/S server is running at http://${this.config.host}:${this.config.port}`)})}startHttpsServer(){let e={key:U(this.config.keyfile),cert:U(this.config.certfile)};z.createServer(e,(t,i)=>{this.handleRequest(t,i,()=>this.defaultResponse(t,i))}).listen(this.config.port,this.config.host,()=>{let t=c("\x1B[38;5;227m",`https://${this.config.host}:${this.config.port}`);console.log(`${f()} HTTPS server is running at ${t}`)})}handleRequest(e,r,t){try{this.config.onRequest?this.config.onRequest(e,r,t):t()}catch(i){this.sendError(r,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,r){let t=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",i=V(this.rootDir,t);if(!i.startsWith(this.rootDir)){r.statusCode=403,r.end();return}try{let n=await this.promisifyStat(i);n.isDirectory()?this.handleDirectory(i,t,r):n.isFile()&&this.handleFile(i,r)}catch(n){let s=n.message;s.includes("favicon")||console.log(f(),s),this.sendNotFound(r)}}promisifyStat(e){return new Promise((r,t)=>{_e(e,(i,n)=>i?t(i):r(n))})}handleDirectory(e,r,t){Ie(e,(i,n)=>{if(i)return this.sendError(t,i);let s=n.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let l=V(r,a);if(l.match(/[^A-Za-z0-9_\/\\.-]/))return;let g=W(a).slice(1)||"folder",{icon:h,color:T}=q[g]||q.folder;return`<li><i class="fas ${h}" style="color: ${T};"></i> <a href="/${l}">${a}</a></li>`}).join("");t.writeHead(200,{"Content-Type":"text/html"}),t.end(H.replace("${ fileList }",s))})}handleFile(e,r){let t=W(e).slice(1)||"txt",i=this.getContentType(t);Le(e,(n,s)=>{if(n)return this.sendError(r,n);r.writeHead(200,{"Content-Type":i}),r.end(s)})}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,r){console.error(`${f()}`,r.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{promises as $e}from"fs";import{resolve as Ne}from"path";var C=class{buildState={};onEndHooks=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.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 r={errors:[],warnings:[]};for(let t of this.onStartHooks){let i=await t(e,this.buildState);i&&(i.errors?.length&&r.errors.push(...i.errors),i.warnings?.length&&r.warnings.push(...i.warnings))}return r}async handleOnEnd(e){let r={errors:e.errors??[],warnings:e.warnings??[]};for(let t of this.onEndHooks){e.errors=r.errors,e.warnings=r.warnings;let i=await t(e,this.buildState);i&&(i.errors?.length&&r.errors.push(...i.errors),i.warnings?.length&&r.warnings.push(...i.warnings))}return r}async handleOnResolve(e){let r={};for(let t of this.onResolveHooks){let i=await t(e,this.buildState);i&&(r={...r,...i,path:i.path||r.path})}return r.path?r:null}async handleOnLoad(e){let r={contents:void 0,loader:"default"},t=Ne(e.path);r.contents||(r.contents=await $e.readFile(t,"utf8"));for(let i of this.onLoadHooks){let n=await i(r.contents??"",r.loader,e,this.buildState);n&&(r={...r,...n,contents:n.contents||r.contents,loader:n.loader||r.loader})}return r.contents?r:null}};function Y(o,e){return o.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(r,t,i)=>e[t]?i:"")}import{relative as Me}from"path";function Z(o,e,r,t){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in r){let s=Me(e,r[n]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),o=o.replaceAll(n,`${s}/`),t&&(o=o.replace(i,(a,l)=>(l.startsWith("../")||l.startsWith("./"))&&!l.endsWith(".js")?a.replace(l,`${l}.js`):a))}return o}import{cwd as Fe}from"process";import{build as K}from"esbuild";var p=class o extends d{originalErrorStack;constructor(e,r){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,o),r&&Object.assign(this,r),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var je={write:!1,bundle:!0,minify:!1,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function He(o){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,r=o.match(e);if(!r||!r[1])throw new p("Source map URL not found in the output.");let t=r[1];return{code:o.replace(e,""),sourceMap:t}}async function X(o,e={}){let r={absWorkingDir:Fe(),...je,...e,entryPoints:[o]},i=(await K(r)).outputFiles?.pop()?.text??"";return He(i)}async function Q(o,e="browser"){return(await K({entryPoints:o,bundle:!0,write:!1,metafile:!0,platform:e,packages:"external",logLevel:"silent",outdir:"dist"})).metafile}var x=class o extends Error{constructor(e,r){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),r?.cause&&(this.cause=r.cause)}};import{resolve as w,relative as We,dirname as Ve,parse as Je}from"path";import{sys as Ue,factory as D,createProgram as ee,visitEachChild as re,isStringLiteral as qe,resolveModuleName as Ge,DiagnosticCategory as ze,isImportDeclaration as te,isExportDeclaration as oe,getPreEmitDiagnostics as ie,flattenDiagnosticMessageText as ne}from"typescript";var E=class{constructor(e,r,t=!0){this.tsConfig=e;this.outDir=r;this.activeColor=t;this.options={...this.tsConfig.options,outDir:this.outDir}}options;typeCheck(e=!1){let r=ee(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0});this.handleDiagnostics(ie(r),e)}generateDeclarations(e=!1,r=!1){let t=ee(this.tsConfig.fileNames,{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),i=ie(t);!e&&i.some(n=>n.category===ze.Error)&&this.handleDiagnostics(i,r),t.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return te(e)||oe(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&qe(e.moduleSpecifier)}resolveModuleFileName(e,r){let t,i=Ge(e,r.baseUrl,r,Ue);if(i.resolvedModule&&r.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return t;t=w(i.resolvedModule.resolvedFileName).replace(w(r.baseUrl),".")}return t}getRelativePathToOutDir(e,r){e=w(e).replace(w(this.options.baseUrl??""),".");let t=We(Ve(e),r).replace(/\\/g,"/"),i=Je(t);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,r){let t=D.createStringLiteral(r);return te(e)?D.updateImportDeclaration(e,e.modifiers,e.importClause,t,void 0):oe(e)?D.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,t,void 0):e}createVisitor(e,r){let t=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,s=this.resolveModuleFileName(n,this.options);if(s){let a=this.getRelativePathToOutDir(e.fileName,s);return this.updateModuleSpecifier(i,a)}}return re(i,t,r)};return t}createTransformerFactory(){return e=>({transformSourceFile:r=>re(r,this.createVisitor(r,e),e),transformBundle:r=>r})}handleDiagnostics(e,r=!1){if(e.length!==0&&(e.forEach(t=>{if(t.file&&t.start!==void 0){let{line:i,character:n}=t.file.getLineAndCharacterOfPosition(t.start),s=ne(t.messageText,`
|
|
81
|
+
`),a=c("\x1B[38;5;81m",t.file.fileName,this.activeColor),l=c("\x1B[38;5;230m",`${i+1}:${n+1}`,this.activeColor),g=c("\x1B[38;5;9m","error",this.activeColor),h=c("\x1B[38;5;243m",`TS${t.code}`,this.activeColor);console.error(`${f()} ${a}:${l} - ${g} ${h}:${s}`)}else console.error(ne(t.messageText,`
|
|
82
82
|
`))}),console.log(`
|
|
83
|
-
`),!
|
|
84
|
-
${f()} ${c("\x1B[38;5;166m",`Build completed! in ${
|
|
85
|
-
`),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,
|
|
83
|
+
`),!r))throw new x("Type checking failed due to errors.")}};import u from"typescript";import{dirname as tr}from"path";import{existsSync as le,readFileSync as or}from"fs";import{cwd as Ye}from"process";var k={dev:!1,watch:!1,declaration:!1,buildOnError:!1,noTypeChecker:!1,define:{},esbuild:{write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:Ye(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as Xe}from"module";import{SourceService as Qe}from"@remotex-labs/xmap";import{Script as Ze,createContext as Ke}from"vm";function se(o,e={}){e.console=console;let r=new Ze(o),t=Ke(e);return r.runInContext(t,{breakOnSigint:!0})}function ae(o,e){for(let r in o)if(Object.prototype.hasOwnProperty.call(o,r)){let t=o[r];typeof t=="function"?o[r]=er(t,e):typeof t=="object"&&t!==null&&ae(t,e)}return o}function er(o,e){return(...r)=>{try{return o(...r)}catch(t){throw new m(t,e)}}}function rr(o,e){return ae(o,e)}async function ce(o){let{code:e,sourceMap:r}=await X(o,{banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),t={exports:{}},i=Xe(import.meta.url),n=new Qe(JSON.parse(atob(r)));try{await se(e,{require:i,module:t})}catch(s){throw new m(s,n)}return rr(t.exports.default,n)}var ir=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 nr(o){let e=o.argv,r=i=>Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0)),t=r({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{...r({dev:e.dev,watch:e.watch,declaration:e.declaration,serve:e.serve?{active:e.serve}:{undefined:void 0}}),esbuild:t}}function fe(o){let e=o.tsconfig??"",r=le(e)?or(e,"utf8"):JSON.stringify(ir),t=u.parseConfigFileTextToJson(e,r);if(t.error)throw new p(u.formatDiagnosticsWithColorAndContext([t.error],{getCurrentDirectory:u.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>u.sys.newLine}));let i=u.parseJsonConfigFileContent(t.config,u.sys,tr(e));if(i.errors.length>0)throw new p(u.formatDiagnosticsWithColorAndContext(i.errors,{getCurrentDirectory:u.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>u.sys.newLine}));return i}async function pe(o,e){let r=nr(e),t=le(o)?await ce(o):{},i=Array.isArray(t)?t:[t],n=i[0];return i.flatMap(s=>{let a={...k,...n,...s,...r,esbuild:{...k.esbuild,...n?.esbuild,...s?.esbuild,...r.esbuild},serve:{...k.serve,...n.serve,...s.serve,...r.serve}};if(!a.esbuild.entryPoints)throw new p("entryPoints cannot be undefined.");return a})}function sr(o){let e={};return o.forEach(r=>{let t=r.substring(0,r.lastIndexOf("."));e[t]=r}),e}function ue(o){if(Array.isArray(o)){let e={};return o.length>0&&typeof o[0]=="object"?o.forEach(r=>{e[r.out]=r.in}):typeof o[0]=="string"&&(e=sr(o)),e}else if(o&&typeof o=="object")return o;throw new p("Unsupported entry points format")}import{join as ar}from"path";import{mkdirSync as cr,writeFileSync as lr}from"fs";function de(o){let e=o.moduleTypeOutDir??o.esbuild.outdir??"dist",r=o.esbuild.format==="esm"?"module":"commonjs";cr(e,{recursive:!0}),lr(ar(e,"package.json"),`{"type": "${r}"}`)}var P=class{constructor(e){this.config=e;let r=fe(this.config.esbuild);this.config.esbuild.logLevel="silent",this.pluginsProvider=new C,this.typeScriptProvider=new E(r,this.config.declarationOutDir??r.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();(this.config.watch||this.config.dev)&&await e.watch()})}async runDebug(e){return await this.execute(async()=>{this.config.dev=!1,this.config.watch=!1;let r=await this.build();this.spawnDev(r.metafile,e,!0)})}async serve(){let e=new b(this.config.serve,this.config.esbuild.outdir??"");return await this.execute(async()=>{e.start(),await(await this.build()).watch()})}async execute(e){try{await e()}catch(r){let t=r;Array.isArray(t.errors)||console.error(new m(r).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=y(this.typeScriptProvider.options.baseUrl??""),r=this.generatePathAlias(e);this.registerPluginHooks(r,e)}registerPluginHooks(e,r){this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((t,i,n)=>{if(n.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let s=fr(y(n.path).replace(r,"."));t=Z(t.toString(),s,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:Y(t.toString(),this.config.define)}}})}generatePathAlias(e){let r=this.typeScriptProvider.options.paths,t={};for(let i in r){let n=r[i];if(n.length>0){let s=i.replace(/\*/g,"");t[s]=y(n[0].replace(/\*/g,"")).replace(e,".")}}return t}handleErrors(e){let r=e.errors??[];for(let t of r){if(!t.detail){console.error(new S(t).stack);continue}if(t.detail.name!=="TypesError"){if(t.detail.name){if(t.detail.name==="VMRuntimeError"){console.error(t.detail.stack);continue}if(t.detail instanceof Error){console.error(new m(t.detail).originalErrorStack);continue}}return console.error(t.text)}}}async build(){de(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.registerOnStart(this.config.hooks.onStart),this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve)),e.define||(e.define={});for(let r in this.config.define)e.define[r]=JSON.stringify(this.config.define[r]);return this.config.esbuild.bundle||await this.processEntryPoints(),e.plugins=[this.pluginsProvider.setup()],this.config.watch||this.config.dev||this.config.serve.active?await ur(e):await pr(e)}spawnDev(e,r,t=!1){if(Array.isArray(r))for(let i in e.outputs)i.includes("map")||!r.some(n=>i.includes(`/${n}.`))||this.activePossess.push(F(i,t))}async start(e,r){try{r.startTime=Date.now(),console.log(`${f()} StartBuild ${e.initialOptions.outdir}`),this.config.declaration?this.typeScriptProvider.generateDeclarations(this.config.noTypeChecker,this.config.buildOnError):this.config.noTypeChecker||this.typeScriptProvider.typeCheck(this.config.buildOnError)}finally{for(;this.activePossess.length>0;){let t=this.activePossess.pop();t&&t.kill("SIGTERM")}}}async end(e,r){if(e.errors.length>0)return this.handleErrors(e);let t=Date.now()-r.startTime;console.log(`
|
|
84
|
+
${f()} ${c("\x1B[38;5;166m",`Build completed! in ${t} ms`)}`),console.log(`${f()} ${Object.keys(e.metafile.outputs).length} Modules:`),Object.keys(e.metafile.outputs).forEach(i=>{let n=e.metafile.outputs[i].bytes;console.log(`${f()} ${c("\x1B[38;5;227m",i)}: ${c("\x1B[38;5;208m",n.toString())} bytes`)}),console.log(`
|
|
85
|
+
`),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,r=await Q(e.entryPoints,e.platform),t=y(this.typeScriptProvider.options.baseUrl??""),i=ue(e.entryPoints),n=Object.values(i);Array.isArray(e.entryPoints)&&typeof e.entryPoints[0]=="string"&&(i={},n=[]);for(let s in r.inputs){if(n.includes(s))continue;let a=y(s).replace(t,"."),l=a.substring(0,a.lastIndexOf("."));i[l]=s}e.entryPoints=i}};global.__ACTIVE_COLOR=!0;console.log(j());async function dr(){let o=M(process.argv),e=o.argv,t=(await pe(e.config,o)).map(async i=>{let n=new P(i);if(e.typeCheck)return n.typeScriptProvider.typeCheck(!0);if(e.serve||i.serve.active)return await n.serve();if(Array.isArray(e.debug))return e.debug.length<1&&(e.debug=["index"]),await n.runDebug(e.debug);await n.run()});await Promise.all(t)}dr().catch(o=>{console.error(o.stack)});
|
|
86
86
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/errors/stack.error.ts", "../src/components/colors.component.ts", "../src/errors/uncaught.error.ts", "../src/services/cli.service.ts", "../src/services/build.service.ts", "../src/services/process.service.ts", "../src/errors/base.error.ts", "../src/errors/esbuild.error.ts", "../src/components/banner.component.ts", "../src/errors/vm-runtime.error.ts", "../src/providers/server.provider.ts", "../src/providers/html/server.html", "../src/providers/plugins.provider.ts", "../src/plugins/ifdef.plugin.ts", "../src/plugins/resolve-alias.plugin.ts", "../src/services/transpiler.service.ts", "../src/errors/xbuild.error.ts", "../src/errors/types.error.ts", "../src/providers/typescript.provider.ts", "../src/
|
|
4
|
-
"sourceRoot": "https://github.com/remotex-lab/xBuild/tree/v1.3.
|
|
5
|
-
"sourcesContent": ["/**\n * Import will remove at compile time\n */\n\nimport type { BaseError } from '@errors/base.error';\nimport type { PositionWithCodeInterface } from '@remotex-labs/xmap';\nimport type { ErrorType, FrameDetailsInterface, StackTraceStateInterface } from '@errors/interfaces/stack.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join, resolve } from 'path';\nimport { Colors, setColor } from '@components/colors.component';\nimport { SourceService, formatErrorCode, highlightCode } from '@remotex-labs/xmap';\n\n/**\n * Defines\n */\n\nconst cliPath = cwd();\nconst distPath = dirname(fileURLToPath(import.meta.url));\nconst rootPath = dirname(distPath);\nexport const xBuildLazy = (() => {\n let cachedSourceService: SourceService;\n\n return {\n get service() {\n if (!cachedSourceService) {\n // Lazy loading the sourceMap\n const sourceMapData = readFileSync(join(distPath, 'index.js.map'));\n cachedSourceService = new SourceService(sourceMapData.toString(), import.meta.url);\n }\n\n return cachedSourceService;\n }\n };\n})();\n\nif (!global.__ACTIVE_COLOR) {\n global.__ACTIVE_COLOR = true;\n}\n\n/**\n * Modifies the file path by applying the source root and appending the line number.\n *\n * @param source - The original full file path.\n * @param sourceRoot - The source root to be applied to the file path.\n * @param line - The line number point ot in the file.\n * @param rootPath - The project root directory to remove from the path.\n * @returns The modified file path with the source root applied and line number appended.\n */\n\nfunction modifyFilePathWithSourceRoot(source: string, sourceRoot: string, line: number, rootPath: string): string {\n return `${ source.replace(`${ rootPath }\\\\`, sourceRoot).replace(/\\\\/g, '/') }#L${ line }`;\n}\n\n/**\n * Formats a single error line for the stack trace.\n *\n * @param name - The name of the function.\n * @param file - The file name.\n * @param line - The line number.\n * @param column - The column number.\n * @param frame - The frame call stack\n * @returns The formatted error line as a string.\n */\n\nfunction formatErrorLine(name: string, file: string, line: number, column: number, frame: NodeJS.CallSite): string {\n if (frame.isPromiseAll())\n return `at async Promise.all (index: ${ frame.getPromiseIndex() })`;\n\n const asyncPrefix = frame.isAsync() ? 'async' : '';\n const formattedName = name ? `${ asyncPrefix } ${ name }` : asyncPrefix;\n const position = (line >= 0 && column >= 0) ? setColor(Colors.Gray, `[${ line }:${ column }]`) : '';\n\n return `at ${ formattedName } ${ setColor(Colors.DarkGray, file) } ${ position }`\n .replace(/\\s{2,}/g, ' ').trim();\n}\n\n/**\n * Extracts details such as function name, file name, line, and column from a stack frame.\n *\n * @param frame - The call site from the stack trace.\n * @returns An object containing function name, file name, line number, and column number.\n */\n\nfunction extractFrameDetails(frame: NodeJS.CallSite): FrameDetailsInterface {\n const line = frame.getLineNumber() || -1;\n const column = frame.getColumnNumber() || -1;\n const source = frame.getFileName() || '<anonymous>';\n const typeName = frame.getTypeName() || '';\n const functionName = frame.getFunctionName() || '';\n\n let name = frame.isNative() ? '<native>' : functionName;\n if (typeName)\n name = `${ typeName }.${ name }`;\n\n return { functionName: name, source, line, column };\n}\n\n/**\n * Highlights the code at a given position and formats it for display.\n *\n * @param position - The position containing the code to be highlighted. It must implement the `PositionWithCodeInterface`.\n * @param error - The error object that may be modified if a TypeError is detected. It should be of type `ErrorType`.\n * @returns The formatted highlighted code as a string, incorporating any modifications based on the error type.\n */\n\nfunction highlightPositionCode(position: PositionWithCodeInterface, error: ErrorType): string {\n const highlightedCode = __ACTIVE_COLOR ? highlightCode(position.code) : position.code;\n if (position.name && error.name == 'TypeError') {\n error.message = error.message.replace(/^\\S+/, position.name);\n }\n\n return formatErrorCode({ ...position, code: highlightedCode }, {\n color: __ACTIVE_COLOR ? Colors.BrightPink : '',\n reset: __ACTIVE_COLOR ? Colors.Reset : ''\n });\n}\n\n/**\n * Formats a single stack entry from the call stack.\n *\n * @param frame - The call site from the stack trace.\n * @param state - The current state containing error and formatting information.\n * @returns The formatted stack entry as a string.\n */\n\nfunction formatStackEntry(frame: NodeJS.CallSite, state: StackTraceStateInterface): string {\n const { functionName, source, line, column } = extractFrameDetails(frame);\n\n if (frame.isPromiseAll() || frame.isEval() || frame.isNative())\n return formatErrorLine(functionName, source, line, column, frame);\n\n let position: PositionWithCodeInterface | null = null;\n const isXBuildService = source === xBuildLazy.service.file;\n\n if (isXBuildService)\n position = xBuildLazy.service.getPositionWithCode(line, column);\n else if (state.error.sourceMap)\n position = state.error.sourceMap.getPositionWithCode(line, column);\n\n if (position) {\n const dirPath = isXBuildService ? distPath : cliPath;\n const { line: posLine, column: posColumn, name } = position;\n let source = resolve(dirPath, position.source);\n\n if (!state.blockCode)\n state.blockCode = highlightPositionCode(position, state.error);\n\n if (position.sourceRoot)\n source = modifyFilePathWithSourceRoot(\n resolve(dirPath, position.source),\n position.sourceRoot,\n position.line,\n isXBuildService ? rootPath : cliPath\n );\n\n return formatErrorLine(name || functionName, source, posLine, posColumn, frame);\n }\n\n if (source === 'evalmachine.<anonymous>')\n return '';\n\n return formatErrorLine(functionName, source, line, column, frame);\n}\n\n/**\n * Formats all stack entries into an array of strings for display.\n *\n * @param state - The current state containing error and formatting information.\n * @param stackEntries - The array of stack entries from the call stack.\n * @returns An array of formatted stack entry strings.\n */\n\nfunction formattedStackEntries(state: StackTraceStateInterface, stackEntries: Array<NodeJS.CallSite>): Array<string> {\n return stackEntries.map((frame) => formatStackEntry(frame, state)).filter(Boolean);\n}\n\n/**\n * Prepares the error stack trace for display.\n *\n * This function overrides the default stack trace preparation to provide a custom format,\n * including enhanced stack trace information and error details.\n *\n * @param error - The error object (Error or BaseError).\n * @param stackEntries - The array of stack entries from the call stack.\n * @returns The formatted stack trace as a string.\n */\n\nexport function formatStackTrace(error: ErrorType & BaseError, stackEntries: Array<NodeJS.CallSite>): string {\n const state: StackTraceStateInterface = {\n error: error,\n blockCode: null,\n formattedError: global.__ACTIVE_COLOR ? Colors.Reset : ''\n };\n\n const stackTrace = formattedStackEntries(state, stackEntries);\n state.formattedError += `\\n${ error.name }: \\n${ setColor(Colors.LightCoral, error.message) }\\n\\n`;\n\n if (state.blockCode)\n state.formattedError += `${ state.blockCode }\\n\\n`;\n\n if (stackTrace.length > 0)\n state.formattedError += `Enhanced Stack Trace:\\n${ stackTrace.join('\\n') }\\n`;\n\n return state.formattedError;\n}\n\n// Preserve the original Error.prepareStackTrace function\nconst originalPrepareStackTrace = Error.prepareStackTrace;\n\n/**\n * Custom Error.prepareStackTrace to capture CallSite objects in the error.\n *\n * @param error - The error object being processed.\n * @param stackEntries - An array of CallSite objects representing the stack trace.\n * @returns A string stack trace generated by the original prepareStackTrace function.\n */\n\nError.prepareStackTrace = (error: ErrorType, stackEntries: Array<NodeJS.CallSite>): string => {\n // Attach the stack entries (CallSite objects) to the error object\n error.callStacks = stackEntries;\n\n // Call the original prepareStackTrace to return the standard string representation of the stack\n return originalPrepareStackTrace ? originalPrepareStackTrace(error, stackEntries) : '';\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 * ```typescript\n * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);\n * ```\n *\n * @enum {string}\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 {string} A string with the specified color applied to the message,\n * followed by a reset sequence if `activeColor` is true.\n *\n * @example\n * ```typescript\n * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');\n * console.log(coloredMessage);\n * ```\n *\n * @example\n * ```typescript\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 * Handles uncaught exceptions in the Node.js process.\n *\n * This handler is triggered when an error is thrown that is not caught by any try-catch blocks.\n * It captures such exceptions and logs them to the console. If the exception is an instance of `Error`,\n * its string representation is logged. Otherwise, the raw error object is logged.\n *\n * This setup helps in debugging by ensuring that all uncaught exceptions are logged, providing visibility\n * into errors that might otherwise go unnoticed.\n *\n * @example\n * ```ts\n * process.on('uncaughtException', (error) => {\n * if (error instanceof Error) {\n * console.error(error.toString());\n * } else {\n * console.error(error);\n * }\n * });\n * ```\n *\n * @throws Will log uncaught exceptions to the console.\n * Custom handling logic should be added if additional error handling or logging is required.\n */\n\nprocess.on('uncaughtException', (error: Error) => {\n console.error(error.stack);\n});\n\n/**\n * Handles unhandled promise rejections in the Node.js process.\n *\n * This handler is triggered when a promise is rejected, and no rejection handler is attached to it.\n * It captures such rejections and logs them to the console. If the rejection reason is an instance of `Error`,\n * its string representation is logged. Otherwise, the raw rejection reason is logged.\n *\n * This setup helps in debugging by ensuring that all unhandled promise rejections are logged, providing visibility\n * into issues related to unhandled promises that might otherwise go unnoticed.\n *\n * @example\n * ```ts\n * process.on('unhandledRejection', (reason) => {\n * if (reason instanceof Error) {\n * console.error(reason.toString());\n * } else {\n * console.error(reason);\n * }\n * });\n * ```\n *\n * @throws Will log unhandled promise rejections to the console.\n * Custom handling logic should be added if additional handling or logging is required.\n */\n\nprocess.on('unhandledRejection', (reason: Error) => {\n console.error(reason.stack);\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Argv } from 'yargs';\nimport type { ArgvInterface } from '@services/interfaces/cli.interface';\n\n/**\n * Imports\n */\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\n\n/**\n * Parses command-line arguments into an `ArgvInterface` object using `yargs`.\n *\n * This function configures `yargs` to handle various build-related options for a JavaScript and TypeScript toolchain.\n * It returns an object that adheres to the `ArgvInterface` structure based on the parsed arguments.\n *\n * @param argv - An array of command-line arguments (e.g., `process.argv`).\n * @returns An object representing the parsed command-line arguments.\n *\n * @see {@link ArgvInterface} for the structure of the returned object.\n *\n * @example\n * // Example usage:\n * const args = argvParser(process.argv);\n * console.log(args.file); // Output: the file to build\n * console.log(args.dev); // Output: true or false based on the --dev flag\n */\n\nexport function argvParser(argv: Array<string>): Argv<ArgvInterface> {\n const cli = yargs(hideBin(argv))\n .command('$0 [file]', 'A versatile JavaScript and TypeScript toolchain build system.', (yargs) => {\n yargs\n .positional('entryPoints', {\n describe: 'The file entryPoints to build',\n type: 'string'\n })\n .option('typeCheck', {\n describe: 'Perform type checking',\n alias: 'tc',\n type: 'boolean'\n })\n .option('node', {\n alias: 'n',\n describe: 'Build for node platform',\n type: 'boolean'\n })\n .option('dev', {\n alias: 'd',\n describe: 'Array entryPoints to run as development in Node.js',\n type: 'array'\n })\n .option('debug', {\n alias: 'db',\n describe: 'Array entryPoints to run in Node.js with debug state',\n type: 'array'\n })\n .option('serve', {\n alias: 's',\n describe: 'Serve the build folder over HTTP',\n type: 'boolean'\n })\n .option('outdir', {\n alias: 'o',\n describe: 'Output directory',\n type: 'string'\n })\n .option('declaration', {\n alias: 'de',\n describe: 'Add TypeScript declarations',\n type: 'boolean'\n })\n .option('watch', {\n alias: 'w',\n describe: 'Watch for file changes',\n type: 'boolean'\n })\n .option('config', {\n alias: 'c',\n describe: 'Build configuration file (js/ts)',\n type: 'string',\n default: 'xbuild.config.ts'\n })\n .option('tsconfig', {\n alias: 'tsc',\n describe: 'Set TypeScript configuration file to use',\n type: 'string',\n default: 'tsconfig.json'\n })\n .option('minify', {\n alias: 'm',\n describe: 'Minify the code',\n type: 'boolean'\n })\n .option('bundle', {\n alias: 'b',\n describe: 'Bundle the code',\n type: 'boolean'\n })\n .option('noTypeChecker', {\n alias: 'ntc',\n describe: 'Skip TypeScript type checking',\n type: 'boolean'\n })\n .option('buildOnError', {\n alias: 'boe',\n describe: 'Continue building even if there are TypeScript type errors',\n type: 'boolean'\n })\n .option('format', {\n alias: 'f',\n describe: 'Defines the format for the build output (\\'cjs\\' | \\'esm\\' | \\'iif\\').',\n type: 'string'\n })\n .option('version', {\n alias: 'v',\n describe: 'Show version number',\n type: 'boolean',\n default: false,\n conflicts: 'help'\n });\n })\n .help()\n .alias('help', 'h')\n .version(false) // Disable the default version behavior\n .middleware((argv) => {\n if (argv.version) {\n // todo fix the banner and color\n process.exit(0);\n }\n });\n\n // Custom help message with version info at the top\n cli.showHelp((helpText) => {\n if (process.argv.includes('--help') || process.argv.includes('-h')) {\n console.log(helpText + '\\n\\n');\n process.exit(0); // Ensure the process exits after showing help\n }\n });\n\n return <Argv<ArgvInterface>> cli;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { ConfigurationInterface } from '@configuration/interfaces/configuration.interface';\nimport type { BuildContext, BuildResult, Message, Metafile, OnEndResult, PluginBuild, SameShape } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { dirname, resolve } from 'path';\nimport { build, context } from 'esbuild';\nimport { spawn } from '@services/process.service';\nimport { esBuildError } from '@errors/esbuild.error';\nimport { prefix } from '@components/banner.component';\nimport { VMRuntimeError } from '@errors/vm-runtime.error';\nimport { ServerProvider } from '@providers/server.provider';\nimport { PluginsProvider } from '@providers/plugins.provider';\nimport { parseIfDefConditionals } from '@plugins/ifdef.plugin';\nimport { Colors, setColor } from '@components/colors.component';\nimport { resolveAliasPlugin } from '@plugins/resolve-alias.plugin';\nimport { analyzeDependencies } from '@services/transpiler.service';\nimport { TypeScriptProvider } from '@providers/typescript.provider';\nimport { tsConfiguration } from '@providers/configuration.provider';\nimport { extractEntryPoints } from '@components/entry-points.component';\nimport { packageTypeComponent } from '@components/package-type.component';\nimport type { BuildState } from '@providers/interfaces/plugins.interfaces';\n\n/**\n * Manages the build process for a TypeScript project using esbuild.\n *\n * The `BuildService` class orchestrates the build process, including TypeScript compilation, handling of build errors,\n * and lifecycle management of the build. It can operate in various modes, such as watching for file changes or running\n * in development mode. It also provides functionality for spawning development processes and processing entry points.\n *\n * @remarks\n * - The build process can be configured using the provided `ConfigurationInterface`.\n * - Errors related to TypeScript are handled separately and are not logged by default.\n * - The class supports various build modes, including watch mode and development mode, and handles different scenarios\n * based on the configuration.\n *\n * @public\n * @category Services\n */\n\nexport class BuildService {\n /**\n * Provides TypeScript-related functionality for the build process.\n */\n\n readonly typeScriptProvider: TypeScriptProvider;\n\n /**\n * Keeps track of active development processes spawned during the build.\n * This property holds an array of `ChildProcessWithoutNullStreams` instances that represent Node.js processes spawned\n * for running development tasks. These processes are used to handle development builds or runtime tasks and are managed\n * by the `BuildService` class to ensure they are properly started and stopped.\n *\n * @private\n * @type {Array<ChildProcessWithoutNullStreams>}\n *\n * @remarks\n * - The array is populated when development processes are spawned, such as when specific development files are\n * processed or when running in development mode.\n * - The processes are terminated gracefully at the end of the build to avoid leaving orphaned processes running.\n * - It is important to manage these processes correctly to avoid resource leaks and ensure proper cleanup.\n */\n\n private activePossess: Array<ChildProcessWithoutNullStreams> = [];\n\n /**\n * Plugin provider\n *\n * @private\n */\n\n private pluginsProvider: PluginsProvider;\n\n /**\n * Initializes the build service with the provided configuration.\n *\n * The constructor configures the TypeScript provider, suppresses esbuild logging,\n * sets up development modes, and registers the necessary plugins.\n *\n * Declaration files will be output based on the following order of precedence:\n * 1. If `declarationOutDir` is set in the configuration, it will be used.\n * 2. If `declarationOutDir` is not provided, it will use the `outDir` value from the tsconfig.\n * 3. If neither of the above is available, it falls back to using the `outdir` specified in the esbuild configuration.\n *\n * @param config - The configuration object for the build process, including esbuild and TypeScript settings.\n */\n\n constructor(private config: ConfigurationInterface) {\n const tsConfig = tsConfiguration(this.config.esbuild);\n\n this.config.esbuild.logLevel = 'silent';\n this.pluginsProvider = new PluginsProvider();\n this.typeScriptProvider = new TypeScriptProvider(\n tsConfig, this.config.declarationOutDir ?? tsConfig.options.outDir ?? this.config.esbuild.outdir!\n );\n\n this.configureDevelopmentMode();\n this.setupPlugins();\n }\n\n /**\n * Executes the build process.\n * This method performs the build and handles any errors that occur. If watching or development mode is enabled,\n * it starts watching for changes. It logs errors that are not related to TypeScript.\n *\n * @returns A promise that resolves when the build process is complete.\n *\n * @throws {Error} Throws an error if the build process encounters issues not related to TypeScript.\n *\n * @example\n * ```typescript\n * import { BuildService } from './build-service';\n *\n * const buildService = new BuildService(config);\n * buildService.run().then(() => {\n * console.log('Build process completed successfully.');\n * }).catch((error) => {\n * console.error('Build process failed:', error);\n * });\n * ```\n *\n * In this example, the `run` method is used to execute the build process. It handles both successful completion\n * and errors.\n */\n\n async run(): Promise<void> {\n return await this.execute(async () => {\n const result = await this.build();\n if (this.config.watch || this.config.dev) {\n await (<BuildContext> result).watch();\n }\n });\n }\n\n /**\n * Runs the build process in debug mode for the specified entry points.\n * This method temporarily disables development and watch mode, initiates the build process, and spawns development processes\n * for the specified entry points. If any errors occur during the build, they are handled appropriately.\n *\n * @param entryPoints - An array of entry point file names for which the development processes will be spawned.\n * These entry points are matched against the build output files.\n *\n * @returns A `Promise<void>` that resolves when the build and process spawning have completed.\n *\n * @throws Handles any build-related errors using the `handleErrors` method.\n *\n * @remarks\n * - The `config.dev` and `config.watch` settings are temporarily disabled to prevent development mode or file watching during the build.\n * - The `build()` method is called to generate the necessary build outputs.\n * - The `spawnDev` method is then invoked to spawn processes for the matching entry points.\n * - If any errors occur during the build, they are caught and passed to the `handleErrors` method.\n *\n * @example\n * ```typescript\n * const entryPoints = ['index', 'main'];\n * await this.runDebug(entryPoints);\n * ```\n *\n * In this example, the `runDebug` method runs the build process and spawns development processes for `index` and `main`.\n *\n * @public\n */\n\n async runDebug(entryPoints: Array<string>): Promise<void> {\n return await this.execute(async () => {\n this.config.dev = false;\n this.config.watch = false;\n const result = <BuildResult> await this.build();\n this.spawnDev(<Metafile> result.metafile, entryPoints, true);\n });\n }\n\n /**\n * Serves the project and watches for changes.\n * This method starts the development server using the `ServerProvider`, builds the project using esbuild,\n * and watches for file changes to automatically rebuild as needed. It initializes the server and invokes\n * the build process, enabling continuous development mode.\n *\n * @returns A promise that resolves when the server is started and the build process is complete.\n *\n * @throws This method catches any errors thrown during the build process and handles them using the\n * `handleErrors` method.\n *\n * @example\n * ```typescript\n * const buildService = new BuildService(config);\n * buildService.serve().then(() => {\n * console.log('Server is running and watching for changes.');\n * }).catch((error) => {\n * console.error('Failed to start the server:', error);\n * });\n * ```\n *\n * In this example, the `serve` method starts the server and watches for changes. If an error occurs during\n * the build or server startup, it is handled and logged.\n */\n\n async serve(): Promise<void> {\n const server = new ServerProvider(this.config.serve, this.config.esbuild.outdir ?? '');\n\n return await this.execute(async () => {\n server.start();\n const result = await this.build();\n await (<BuildContext> result).watch();\n });\n }\n\n /**\n * Executes a provided callback function within a try-catch block.\n * This method ensures that any errors thrown during the execution of the callback\n * are properly handled. If the error is related to esbuild's `OnEndResult` and contains\n * an array of errors, it skips additional logging. Otherwise, it logs the error using\n * a custom `VMRuntimeError`.\n *\n * @param callback - A function that returns a `Promise<void>`, which is executed asynchronously.\n * This callback is wrapped in error handling logic.\n *\n * @returns A `Promise<void>` which resolves once the callback has been executed.\n * If an error is thrown, it is caught and handled.\n *\n * @throws In case of an error not related to esbuild, the method catches the error,\n * wraps it in a `VMRuntimeError`, and logs the error's stack trace to the console.\n *\n * @example\n * ```ts\n * await execute(async () => {\n * // Perform some asynchronous operation here\n * });\n * ```\n */\n\n private async execute(callback: () => Promise<void>): Promise<void> {\n try {\n await callback();\n } catch (error: unknown) {\n const esbuildError = <OnEndResult> error;\n if (!Array.isArray(esbuildError.errors)) {\n console.error(new VMRuntimeError(<Error> error).stack);\n }\n }\n }\n\n /**\n * Configures the development mode by ensuring that `config.dev` is set properly.\n */\n\n private configureDevelopmentMode(): void {\n if (this.config.dev !== false && (!Array.isArray(this.config.dev) || this.config.dev.length < 1)) {\n this.config.dev = [ 'index' ];\n }\n }\n\n /**\n * Sets up the plugin's provider and registers the plugin hooks.\n */\n\n private setupPlugins(): void {\n const rootDir = resolve(this.typeScriptProvider.options.baseUrl ?? '');\n const paths = this.generatePathAlias(rootDir);\n\n this.registerPluginHooks(paths, rootDir);\n }\n\n /**\n * Registers the plugin hooks for start, end, and load events.\n *\n * @param paths - The resolved path aliases.\n * @param rootDir - The root directory for resolving paths.\n */\n\n private registerPluginHooks(paths: Record<string, string>, rootDir: string): void {\n this.pluginsProvider.registerOnEnd(this.end.bind(this));\n this.pluginsProvider.registerOnStart(this.start.bind(this));\n\n this.pluginsProvider.registerOnLoad((content, loader, args) => {\n if (!args.path.endsWith('.ts')) return;\n\n if (!this.config.esbuild.bundle) {\n const sourceFile = dirname(resolve(args.path).replace(rootDir, '.'));\n content = resolveAliasPlugin(content.toString(), sourceFile, paths, this.config.esbuild.format === 'esm');\n }\n\n return {\n loader: 'ts',\n contents: parseIfDefConditionals(content.toString(), this.config.define)\n };\n });\n }\n\n /**\n * Generates a path alias object from the TypeScript provider's path options.\n * This method processes the `paths` property from the TypeScript provider's options,\n * which is expected to be an object where each key represents a path alias pattern,\n * and the corresponding value is an array of paths. The method removes any wildcard\n * characters (`*`) from both the keys and the first values of the arrays. It also\n * resolves the paths relative to the specified `rootDir`, returning a simplified\n * object that maps the cleaned keys to their respective paths.\n *\n * The resolved paths will be formatted to use a relative path notation.\n *\n * Example:\n * Given the following paths:\n * ```typescript\n * {\n * '@core/*': ['src/core/*'],\n * '@utils/*': ['src/utils/*']\n * }\n * ```\n * And assuming `rootDir` is set to the base directory of your project, the method\n * will return:\n * ```typescript\n * {\n * '@core/': './core/',\n * '@utils/': './utils/'\n * }\n * ```\n *\n * @param {string} rootDir - The root directory to resolve paths against.\n * @returns {Record<string, string>} An object mapping cleaned path aliases to their respective resolved paths.\n */\n\n private generatePathAlias(rootDir: string): Record<string, string> {\n const paths = this.typeScriptProvider.options.paths;\n const alias: Record<string, string> = {};\n\n for (const key in paths) {\n const valueArray = paths[key];\n if (valueArray.length > 0) {\n const newKey = key.replace(/\\*/g, '');\n alias[newKey] = resolve(valueArray[0].replace(/\\*/g, '')).replace(rootDir, '.');\n }\n }\n\n return alias;\n }\n\n /**\n * Handles errors during the build process.\n * This method processes and logs errors that occur during the esbuild process. It specifically filters out\n * errors related to TypeScript (`TypesError`) to prevent them from being logged, while logging all other errors\n * to the console. The error object is assumed to contain a list of messages, each with detailed information.\n *\n * @param esbuildError - The error object returned by esbuild, which is expected to contain an array of\n * error messages.\n *\n * @private\n *\n * @remarks\n * - TypeScript errors (denoted as `TypesError`) are skipped and not logged.\n * - Other errors are logged to the console with their text descriptions.\n *\n * @example\n * ```typescript\n * try {\n * await buildService.run();\n * } catch (esbuildError) {\n * buildService.handleErrors(esbuildError);\n * }\n * ```\n *\n * In this example, if an error occurs during the build process, the `handleErrors` method is used to\n * process and log the errors.\n */\n\n private handleErrors(esbuildError: OnEndResult): void {\n const errors = esbuildError.errors ?? [];\n for (const error of errors) {\n if (!error.detail) {\n console.error((new esBuildError(<Message> error)).stack);\n continue;\n }\n\n // ignore typescript eslint error\n if (error.detail.name === 'TypesError')\n continue;\n\n if (error.detail.name) {\n if (error.detail.name === 'VMRuntimeError') {\n console.error(error.detail.stack);\n continue;\n }\n\n if (error.detail instanceof Error) {\n console.error(new VMRuntimeError(error.detail).originalErrorStack);\n continue;\n }\n }\n\n return console.error(error.text);\n }\n }\n\n /**\n * Builds the project based on the configuration.\n * Depending on the configuration, this method either uses esbuild's `context` for watching or `build` for a one-time build.\n *\n * @returns A promise that resolves with the build context or result.\n *\n * @private\n */\n\n private async build(): Promise<BuildContext | SameShape<unknown, unknown> | BuildResult> {\n packageTypeComponent(this.config);\n const esbuild = this.config.esbuild;\n\n if (this.config.hooks) {\n this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd);\n this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad);\n this.pluginsProvider.registerOnStart(this.config.hooks.onStart);\n this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve);\n }\n\n if (!esbuild.define) {\n esbuild.define = {};\n }\n\n for (const key in this.config.define) {\n esbuild.define[key] = JSON.stringify(this.config.define[key]);\n }\n\n if (!this.config.esbuild.bundle) {\n await this.processEntryPoints();\n }\n\n esbuild.plugins = [ this.pluginsProvider.setup() ];\n if (this.config.watch || this.config.dev || this.config.serve.active) {\n return await context(esbuild);\n }\n\n return await build(esbuild);\n }\n\n /**\n * Manages development processes for specified entry points.*\n * This method spawns development processes for each file in the metafile that matches any of the specified entry points.\n * It enables features like source maps and optional debugging mode for each spawned process.\n *\n * @param meta - The metafile containing information about build outputs.\n * This typically includes a mapping of output files and their dependencies.\n * @param entryPoint - An array of entry point file names to match against the metafile outputs.\n * Only files that match these entry points will have development processes spawned.\n * @param debug - A boolean flag to enable debugging mode for spawned processes.\n * If `true`, the processes will start in debug mode with the `--inspect-brk` option. Defaults to `false`.\n *\n * @returns void\n *\n * @remarks\n * - Files that contain 'map' in their names (e.g., source map files) are ignored and no process is spawned for them.\n * - For each matching file in the metafile outputs, a new development process is spawned using the `spawn` function.\n * - The `activePossess` array tracks all spawned processes, allowing further management (e.g., termination).\n *\n * @example\n * ```typescript\n * const meta = {\n * outputs: {\n * 'dist/index.js': { \\/* ... *\\/ },\n * 'dist/index.js.map': { \\/* ... *\\/ }\n * }\n * };\n * const entryPoints = ['index'];\n *\n * this.spawnDev(meta, entryPoints, true); // Spawns processes in debug mode\n * ```\n *\n * @private\n */\n\n private spawnDev(meta: Metafile, entryPoint: Array<string>, debug: boolean = false) {\n if (!Array.isArray(entryPoint))\n return;\n\n for (const file in meta.outputs) {\n if (file.includes('map') || !entryPoint.some(key => file.includes(`/${ key }.`)))\n continue;\n\n this.activePossess.push(spawn(file, debug));\n }\n }\n\n /**\n * Starts the build process and type checking.\n * This method performs initial setup for the build and ensures that any child processes are terminated properly.\n *\n * @private\n */\n\n private async start(build: PluginBuild, state: BuildState) {\n try {\n state.startTime = Date.now();\n console.log(`${ prefix() } StartBuild ${ build.initialOptions.outdir }`);\n\n if (this.config.declaration)\n this.typeScriptProvider.generateDeclarations(this.config.esbuild.entryPoints, this.config.noTypeChecker, this.config.buildOnError);\n else if (!this.config.noTypeChecker)\n this.typeScriptProvider.typeCheck(this.config.buildOnError);\n } finally {\n while (this.activePossess.length > 0) {\n const element = this.activePossess.pop();\n if (element)\n element.kill('SIGTERM');\n }\n }\n }\n\n /**\n * Finalizes the build process and logs results.\n * This method handles the end of the build process, logs build results, and processes development files if applicable.\n *\n * @private\n */\n\n private async end(result: BuildResult, state: BuildState) {\n if (result.errors.length > 0) {\n return this.handleErrors(result);\n }\n\n const duration = Date.now() - <number> state.startTime;\n console.log(\n `\\n${ prefix() } ${ setColor(Colors.DeepOrange, `Build completed! in ${ duration } ms`) }`\n );\n console.log(`${ prefix() } ${ Object.keys(result.metafile!.outputs).length } Modules:`);\n Object.keys(result.metafile!.outputs).forEach((output) => {\n const size = result.metafile!.outputs[output].bytes;\n console.log(\n `${ prefix() } ${ setColor(Colors.CanaryYellow, output) }: ${ setColor(Colors.BurntOrange, size.toString()) } bytes`\n );\n });\n\n console.log('\\n');\n if (this.config.dev) {\n this.spawnDev(<Metafile> result.metafile, <Array<string>> this.config.dev);\n }\n }\n\n /**\n * Processes and updates entry points based on project dependencies.\n * This method analyzes the project's dependencies and adjusts entry points configuration as needed.\n *\n * @private\n */\n\n private async processEntryPoints(): Promise<void> {\n const esbuild = this.config.esbuild;\n const meta = await analyzeDependencies(esbuild.entryPoints, esbuild.platform);\n const rootDir = resolve(this.typeScriptProvider.options.baseUrl ?? '');\n\n // it pointer and change the esbuild.entryPoints if is object value from configuration !!\n let entryPoints = extractEntryPoints(esbuild.entryPoints);\n let entryPointsList = Object.values(entryPoints);\n\n if (Array.isArray(esbuild.entryPoints) && typeof esbuild.entryPoints[0] === 'string') {\n entryPoints = {};\n entryPointsList = [];\n }\n\n for (const file in meta.inputs) {\n if (entryPointsList.includes(file))\n continue;\n\n const resolveFile = resolve(file).replace(rootDir, '.');\n const fileName = resolveFile.substring(0, resolveFile.lastIndexOf('.'));\n entryPoints[fileName] = file;\n }\n\n esbuild.entryPoints = entryPoints;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\n\n/**\n * Imports\n */\n\nimport { spawn as process_spawn } from 'child_process';\n\n/**\n * Spawns a new Node.js process to execute the provided JavaScript file, with optional debugging support.\n *\n * This function creates a new Node.js process to run the specified JavaScript file with source map support enabled.\n * It optionally starts the process in debug mode, which allows WebStorm or other debuggers to attach to the process.\n * The output and error streams of the spawned process are captured and logged to the console.\n *\n * @param filePath - The path to the JavaScript file to execute.\n * @param debug - A boolean flag to enable debugging. If `true`, the process will be started with the `--inspect-brk` option,\n * which opens a debugger on `0.0.0.0:9229`, allowing external debuggers to attach.\n *\n * @returns A `ChildProcessWithoutNullStreams` object representing the spawned process.\n * This object allows interaction with the process, including capturing its output and error streams.\n *\n * @remarks\n * - The `--enable-source-maps` flag is used to enable source map support, which allows better debugging by mapping\n * errors and stack traces to the original source code.\n * - If `debug` is `true`, the `--inspect-brk=0.0.0.0:9229` flag is added, starting the process in debug mode and pausing\n * execution until a debugger is attached.\n * - The output (`stdout`) and error (`stderr`) streams of the spawned process are logged to the console.\n * - The function returns a `ChildProcessWithoutNullStreams` object that can be used to interact with the spawned process,\n * such as handling its termination or sending input.\n *\n * @throws {Error} Throws an error if the Node.js process fails to start or if there are issues with the provided file path.\n *\n * @example\n * ```typescript\n * import { spawn } from '@services/process.service';\n *\n * // Run without debugging\n * const process = spawn('./path/to/script.js', false);\n *\n * process.on('close', (code) => {\n * console.log(`Process exited with code ${code}`);\n * });\n *\n * // Run with debugging enabled\n * const debugProcess = spawn('./path/to/script.js', true);\n *\n * debugProcess.on('close', (code) => {\n * console.log(`Debug process exited with code ${code}`);\n * });\n * ```\n *\n * In these examples, the `spawn` function is used to execute a JavaScript file, once in normal mode and once with debugging enabled.\n * The process's exit code is logged when the process completes.\n *\n * @public\n * @category Services\n */\n\nexport function spawn(filePath: string, debug: boolean = false): ChildProcessWithoutNullStreams {\n const args = [ '--enable-source-maps', filePath ];\n if (debug)\n args.unshift('--inspect-brk=0.0.0.0:0');\n\n const processInstance = process_spawn('node', args);\n\n // Capture stdout\n processInstance.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n\n // Capture stderr\n processInstance.stderr.on('data', (data) => {\n console.error(data.toString());\n });\n\n return processInstance;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { SourceService } from '@remotex-labs/xmap';\nimport type { ErrorType } from '@errors/interfaces/stack.interface';\n\n/**\n * Imports\n */\n\nimport { formatStackTrace } from '@errors/stack.error';\n\n/**\n * A base class for custom errors with enhanced stack trace formatting and source code information.\n *\n * The `BaseError` class extends the native `Error` class, adding functionality to format the error stack\n * trace and include details from a source map service. This is useful for debugging errors in compiled\n * or transpiled code by providing clearer information about the source of the error.\n */\n\nexport abstract class BaseError extends Error {\n callStacks: Array<NodeJS.CallSite> = [];\n\n /**\n * Creates a new instance of `BaseError`.\n *\n * This constructor initializes a new `BaseError` instance by setting the error message and formatting\n * the stack trace using the provided source map information. It also ensures the stack trace is maintained\n * correctly by using `Error.captureStackTrace` (if available). The default source map service is used if\n * none is provided.\n *\n * @param message - A descriptive error message to be associated with the error.\n * @param sourceMap - (Optional) The `SourceService` instance used to format and resolve the stack trace.\n * If not provided, the default source map service (`defaultSourceService`) is used.\n */\n\n protected constructor(message: string, public readonly sourceMap?: SourceService) {\n super(message);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, BaseError);\n }\n\n // Assign the name of the error\n this.name = 'xBuildBaseError';\n }\n\n /**\n * Reformats the error stack trace using source map information.\n *\n * This function enhances the original error stack trace by attempting to map each entry\n * back to its original position in the source file using the provided source map service.\n * If the source map information is not available, it returns the original stack trace.\n *\n * @param error - The original error with stack trace of the error.\n * @returns The reformatted stack trace or the original stack trace if no mapping is available.\n */\n\n protected reformatStack(error: ErrorType): string {;\n if (!error.callStacks)\n return error.stack ?? '';\n\n return formatStackTrace(this, error.callStacks);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Message } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { BaseError } from '@errors/base.error';\n\n/**\n * Represents an error that occurs during the esbuild process.\n *\n * This class extends the base error class to provide specific error handling for esbuild-related issues.\n * It captures the error message and maintains the proper stack trace, allowing for easier debugging\n * and identification of errors that occur during the build process.\n *\n * @class esbuildError\n * @extends BaseError\n *\n * @param message - An object containing the error message. The `text` property is used to set the\n * error message for the instance.\n *\n * @remarks\n * - This class is designed to handle errors specifically related to the esbuild process.\n * - A placeholder for printing the source code of the error is included for future implementation.\n * - The name of the error is set to 'EsbuildError' for clarity in error handling.\n *\n * @example\n * ```typescript\n * throw new EsbuildError({ text: 'Failed to build module.' });\n * ```\n * In this example, an instance of `EsbuildError` is thrown with a specified error message, which can\n * be caught and handled appropriately.\n *\n * @public\n */\n\nexport class esBuildError extends BaseError {\n /**\n * Creates an instance of the EsbuildError class.\n *\n * This constructor initializes the error message using the provided `message` object, captures\n * the stack trace for better debugging, and sets the name of the error to 'EsbuildError'.\n *\n * @param message - An object containing the error message. The `text` property is used to initialize\n * the base error class with a descriptive message about the error encountered during the esbuild process.\n *\n * @remarks\n * - The constructor includes a placeholder for future implementation of printing the source code related\n * to the error.\n * - The stack trace is captured to maintain the context of the error's origin, allowing developers\n * to trace back to the point of failure in the code.\n *\n * @public\n */\n\n constructor(message: Message) {\n super(message.text);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, esBuildError);\n }\n\n // Assign the name of the error\n this.name = 'EsbuildError';\n\n if (!message.location)\n return;\n\n // const location = message.location;\n // this.stackArray = this.getFormattedStackEntries([{\n // at: '',\n // line: location.line,\n // column: location.column,\n // file: location.file\n // }], this.sourceMap);\n //\n // const highlightedCode = __ACTIVE_COLOR ? highlightCode(location.lineText) : location.lineText;\n // this.blockCode = formatErrorCode({\n // line: location.line,\n // name: null,\n // column: location.column + 1,\n // source: location.file,\n // endLine: location.line + 1,\n // startLine: location.line - 1,\n // sourceRoot: location.file,\n // code: highlightedCode\n // }, {\n // color: __ACTIVE_COLOR ? Colors.BrightPink : '',\n // reset: __ACTIVE_COLOR ? Colors.Reset : ''\n // });\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 * ```typescript\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 * ```typescript\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 * Todo \\r${ activeColor ? cleanScreen : '' }\n *\n * @public\n */\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", "/**\n * Import will remove at compile time\n */\n\nimport type { SourceService } from '@remotex-labs/xmap';\nimport type { ErrorType } from '@errors/interfaces/stack.interface';\n\n/**\n * Imports\n */\n\nimport { BaseError } from '@errors/base.error';\n\n/**\n * A custom error class to handle errors occurring within a virtual machine (VM) execution context.\n *\n * The `VMRuntimeError` class extends the native `Error` class and enhances the error with\n * source map information to map stack traces back to the original source. This is particularly\n * useful when debugging errors from code executed in a `vm` or `evalmachine` environment.\n *\n * @param message - The error message describing the error.\n * @param originalError - The original error object thrown from the VM execution.\n * @param sourceMap - The `SourceService` providing source map data to link the error to its original source.\n *\n * @example\n * ```typescript\n * try {\n * vm.run(someCode);\n * } catch (error) {\n * throw new VMRuntimeError(\"VM execution failed\", error, sourceMapService);\n * }\n * ```\n */\n\nexport class VMRuntimeError extends BaseError {\n /**\n * The original error thrown during the VM execution.\n */\n\n originalError: Error;\n\n /**\n * Original error stack\n */\n\n originalErrorStack: string | undefined;\n\n /**\n * Creates a new VMRuntimeError instance.\n *\n * This constructor initializes a new `VMRuntimeError` object, extending the native `Error` class with\n * additional information, including the original error and optional source map data. It also ensures that\n * the stack trace is correctly captured and reformatted using the source map (if provided) to enhance\n * debugging.\n *\n * @param originalError - The original error object that was thrown during the VM execution.\n * @param sourceMap - (Optional) The source map service used to map the error stack trace to its original\n * source code locations. If not provided, this will be `null`.\n *\n * @example\n * ```typescript\n * try {\n * vm.run(code);\n * } catch (error) {\n * throw new VMRuntimeError(error, sourceMapService);\n * }\n * ```\n */\n\n constructor(originalError: ErrorType, sourceMap?: SourceService) {\n // Pass the message to the base class Error\n super(originalError.message, sourceMap);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, VMRuntimeError);\n }\n\n // Store the original error\n this.originalError = originalError;\n this.originalErrorStack = originalError.stack;\n\n // Assign the name of the error\n this.name = 'VMRuntimeError';\n this.stack = this.reformatStack(originalError);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Stats } from 'fs';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { Serve } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport * as http from 'http';\nimport * as https from 'https';\nimport html from './html/server.html';\nimport { extname, join, resolve } from 'path';\nimport { prefix } from '@components/banner.component';\nimport { Colors, setColor } from '@components/colors.component';\nimport { existsSync, readdir, readFile, readFileSync, stat } from 'fs';\n\n/**\n * A mapping of file extensions to their corresponding icon and color.\n *\n * This record associates common file types with a Font Awesome icon class\n * and a color code for display purposes in a file listing UI. Each file type\n * is represented by an icon and a color that visually distinguishes it.\n *\n * Example:\n * - HTML files are represented by a code icon (`fa-file-code`) with a color of `#d1a65f`.\n * - Image files (e.g., PNG, JPG, GIF) share a common image icon (`fa-file-image`) with a color of `#53a8e4`.\n *\n * @constant\n * @type {Record<string, { icon: string, color: string }>}\n */\n\nconst fileIcons: Record<string, { icon: string, color: string }> = {\n html: { icon: 'fa-file-code', color: '#d1a65f' },\n css: { icon: 'fa-file-css', color: '#264de4' },\n js: { icon: 'fa-file-code', color: '#f7df1e' },\n json: { icon: 'fa-file-json', color: '#b41717' },\n png: { icon: 'fa-file-image', color: '#53a8e4' },\n jpg: { icon: 'fa-file-image', color: '#53a8e4' },\n jpeg: { icon: 'fa-file-image', color: '#53a8e4' },\n gif: { icon: 'fa-file-image', color: '#53a8e4' },\n txt: { icon: 'fa-file-alt', color: '#8e8e8e' },\n folder: { icon: 'fa-folder', color: '#ffb800' }\n};\n\n\n/**\n * Manages the HTTP or HTTPS server based on the provided configuration.\n *\n * The `ServerProvider` class initializes and starts either an HTTP or HTTPS server based on whether SSL certificates\n * are provided. It handles incoming requests, serves static files, and lists directory contents with appropriate\n * icons and colors.\n *\n * @class\n */\n\nexport class ServerProvider {\n /**\n * Root dir to serve\n */\n\n private readonly rootDir: string;\n\n /**\n * Indicates whether the server is configured to use HTTPS.\n */\n\n private readonly isHttps: boolean;\n\n /**\n * The server configuration object, including SSL certificate paths and other settings.\n */\n\n private readonly config: Required<Serve>;\n\n /**\n * Creates an instance of ServerProvider.\n *\n * @param config - The server configuration object, including port number, SSL certificate paths, and an optional request handler.\n * @param dir - The root directory from which to serve files.\n *\n * @example\n * ```typescript\n * import { ServerProvider } from './server-provider';\n *\n * const serverConfig = {\n * port: 8080,\n * keyfile: './path/to/keyfile',\n * certfile: './path/to/certfile',\n * onRequest: (req, res, next) => { /* custom request handling *\\/ }\n * };\n * const provider = new ServerProvider(serverConfig, './public');\n * provider.start();\n * ```\n *\n * This example shows how to create an instance of `ServerProvider` and start the server.\n */\n\n constructor(config: Serve, dir: string) {\n this.rootDir = resolve(dir);\n this.config = <Required<Serve>> config;\n this.isHttps = this.config.keyfile && this.config.certfile\n ? existsSync(this.config.keyfile) && existsSync(this.config.certfile)\n : false;\n }\n\n /**\n * Starts the server based on the configuration.\n * If SSL certificates are provided and valid, an HTTPS server is started. Otherwise, an HTTP server is started.\n *\n * @example\n * ```typescript\n * provider.start();\n * ```\n *\n * This example demonstrates how to start the server. It will either start an HTTP or HTTPS server based on the configuration.\n */\n\n start(): void {\n if (this.isHttps)\n return this.startHttpsServer();\n\n this.startHttpServer();\n }\n\n /**\n * Starts an HTTP server.\n * This method creates an HTTP server that listens on the configured port and handles incoming requests.\n *\n * @example\n * ```typescript\n * provider.startHttpServer();\n * ```\n *\n * This example shows how the `startHttpServer` method is used internally to start an HTTP server.\n */\n\n private startHttpServer(): void {\n const server = http.createServer((req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n server.listen(this.config.port, this.config.host, () => {\n console.log(`${ prefix() } HTTP/S server is running at http://${ this.config.host }:${ this.config.port }`);\n });\n }\n\n /**\n * Starts an HTTPS server.\n *\n * This method creates an HTTPS server with SSL/TLS certificates, listens on the configured port, and handles incoming requests.\n *\n * @example\n * ```typescript\n * provider.startHttpsServer();\n * ```\n *\n * This example shows how the `startHttpsServer` method is used internally to start an HTTPS server.\n */\n\n private startHttpsServer(): void {\n const options = {\n key: readFileSync(this.config.keyfile),\n cert: readFileSync(this.config.certfile)\n };\n\n const server = https.createServer(options, (req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n server.listen(this.config.port, this.config.host, () => {\n const server = setColor(Colors.CanaryYellow, `https://${ this.config.host }:${ this.config.port }`);\n console.log(\n `${ prefix() } HTTPS server is running at ${ server }`\n );\n });\n }\n\n /**\n * Handles incoming requests.\n *\n * This method checks if a custom request handler is provided in the configuration. If so, it uses the custom handler.\n * Otherwise, it delegates to the default request handler.\n *\n * @param req - The incoming request object.\n * @param res - The response object.\n * @param defaultHandler - The default handler function to be called if no custom handler is provided.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * // This method is used internally to handle requests\n * ```\n */\n\n private handleRequest(req: IncomingMessage, res: ServerResponse, defaultHandler: () => void): void {\n try {\n if (this.config.onRequest) {\n this.config.onRequest(req, res, defaultHandler);\n } else {\n defaultHandler();\n }\n } catch (error) {\n this.sendError(res, <Error> error);\n }\n }\n\n /**\n * Returns the MIME type for a given file extension.\n *\n * This method maps file extensions to their corresponding MIME types.\n *\n * @param ext - The file extension.\n * @returns The MIME type associated with the file extension.\n *\n * @example\n * ```typescript\n * const mimeType = provider.getContentType('html');\n * console.log(mimeType); // 'text/html'\n * ```\n */\n\n private getContentType(ext: string): string {\n const contentTypes: Record<string, string> = {\n html: 'text/html',\n css: 'text/css',\n js: 'application/javascript',\n ts: 'text/plain',\n map: 'application/json',\n json: 'application/json',\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n txt: 'text/plain'\n };\n\n return contentTypes[ext] || 'application/octet-stream';\n }\n\n /**\n * Handles the default response for requests, serving files or directories.\n *\n * This method serves the content of files or directories. If the request is for a directory, it lists the contents with\n * appropriate icons and colors.\n *\n * @param req - The incoming request object.\n * @param res - The response object.\n *\n * @returns A promise that resolves when the response is sent.\n *\n * @throws Throws an error if the file or directory cannot be accessed.\n *\n * @example\n * ```typescript\n * // This method is used internally to handle file and directory responses\n * ```\n */\n\n private async defaultResponse(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const requestPath = req.url === '/' ? '' : req.url?.replace(/^\\/+/, '') || '';\n const fullPath = join(this.rootDir, requestPath);\n\n if (!fullPath.startsWith(this.rootDir)) {\n res.statusCode = 403;\n res.end();\n\n return;\n }\n\n try {\n const stats = await this.promisifyStat(fullPath);\n\n if (stats.isDirectory()) {\n this.handleDirectory(fullPath, requestPath, res);\n } else if (stats.isFile()) {\n this.handleFile(fullPath, res);\n }\n } catch (error) {\n const msg = (<Error> error).message;\n if (!msg.includes('favicon')) {\n console.log(prefix(), msg);\n }\n\n this.sendNotFound(res);\n }\n }\n\n /**\n * promisifyStat the `fs.stat` method.\n *\n * Converts the `fs.stat` callback-based method to return a promise.\n *\n * @param path - The file or directory path.\n * @returns A promise that resolves with the file statistics.\n *\n * @example\n * ```typescript\n * const stats = await provider.promisifyStat('./path/to/file');\n * console.log(stats.isFile()); // true or false\n * ```\n */\n\n private promisifyStat(path: string): Promise<Stats> {\n return new Promise((resolve, reject) => {\n stat(path, (err, stats) => (err ? reject(err) : resolve(stats)));\n });\n }\n\n /**\n * Handles directory listings.\n *\n * Reads the contents of a directory and generates an HTML response with file icons and colors.\n *\n * @param fullPath - The full path to the directory.\n * @param requestPath - The request path for generating relative links.\n * @param res - The response object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * // This method is used internally to handle directory listings\n * ```\n */\n\n private handleDirectory(fullPath: string, requestPath: string, res: ServerResponse): void {\n readdir(fullPath, (err, files) => {\n if (err)\n return this.sendError(res, err);\n\n const fileList = files.map(file => {\n if (file.match(/[^A-Za-z0-9_\\/\\\\.-]/))\n return;\n\n const fullPath = join(requestPath, file);\n if (fullPath.match(/[^A-Za-z0-9_\\/\\\\.-]/))\n return;\n\n const ext = extname(file).slice(1) || 'folder';\n const { icon, color } = fileIcons[ext] || fileIcons.folder;\n\n return `<li><i class=\"fas ${ icon }\" style=\"color: ${ color };\"></i> <a href=\"/${ fullPath }\">${ file }</a></li>`;\n }).join('');\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(html.replace('${ fileList }', fileList));\n });\n }\n\n /**\n * Handles file responses.\n *\n * Reads and serves the content of a file.\n *\n * @param fullPath - The full path to the file.\n * @param res - The response object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * // This method is used internally to handle file responses\n * ```\n */\n\n private handleFile(fullPath: string, res: ServerResponse): void {\n const ext = extname(fullPath).slice(1) || 'txt';\n const contentType = this.getContentType(ext);\n\n readFile(fullPath, (err, data) => {\n if (err) {\n return this.sendError(res, err);\n }\n\n res.writeHead(200, { 'Content-Type': contentType });\n res.end(data);\n });\n }\n\n /**\n * Sends a 404 Not Found response.\n *\n * @param res - The response object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * provider.sendNotFound(response);\n * ```\n *\n * This example demonstrates how to send a 404 response using the `sendNotFound` method.\n */\n\n private sendNotFound(res: ServerResponse): void {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n\n /**\n * Sends an error response.\n *\n * @param res - The response object.\n * @param error - The error object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * provider.sendError(response, new Error('Some error'));\n * ```\n *\n * This example shows how to send an error response using the `sendError` method.\n */\n\n private sendError(res: ServerResponse, error: Error): void {\n console.error(`${ prefix() }`, error.toString());\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end('Internal Server Error');\n }\n}\n", "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Directory Listing</title>\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css\">\n <style>\n body {\n font-family: Arial, sans-serif;\n margin: 0;\n padding: 0;\n background-color: #f4f4f4;\n }\n h1 {\n color: #333;\n text-align: center;\n padding: 20px;\n }\n ul {\n list-style: none;\n padding: 0;\n margin: 0;\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n }\n li {\n background: #fff;\n border: 1px solid #ddd;\n border-radius: 4px;\n margin: 5px;\n padding: 10px;\n width: 200px;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n display: flex;\n align-items: center;\n }\n i {\n margin-right: 10px;\n font-size: 18px;\n color: #666;\n }\n a {\n text-decoration: none;\n color: #007bff;\n }\n a:hover {\n text-decoration: underline;\n }\n </style>\n </head>\n <body>\n <h1>Directory Listing</h1>\n <ul>${ fileList }</ul>\n </body>\n</html>\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n OnEndType,\n OnLoadType,\n BuildState,\n OnStartType,\n OnResolveType\n} from '@providers/interfaces/plugins.interfaces';\nimport type {\n Message,\n OnLoadArgs,\n BuildResult,\n OnEndResult,\n PluginBuild,\n OnLoadResult,\n OnResolveArgs,\n OnResolveResult\n} from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { promises } from 'fs';\nimport { resolve } from 'path';\n\n/**\n * Plugin provider for esbuild that registers hooks for lifecycle events such as onStart, onEnd, onResolve, and onLoad.\n * This class allows dynamic behavior by registering multiple hooks for different stages of the build process.\n */\n\nexport class PluginsProvider {\n /**\n * Holds the build state that hooks can modify.\n */\n\n private buildState: BuildState = {};\n\n /**\n * Holds the registered hooks for the `onEnd` lifecycle event.\n * This array contains functions that are called after the build process completes.\n */\n\n private onEndHooks: Array<OnEndType> = [];\n\n /**\n * Holds the registered hooks for the `onLoad` lifecycle event.\n * This array contains functions that are called when esbuild attempts to load a module.\n */\n\n private onLoadHooks: Array<OnLoadType> = [];\n\n /**\n * Holds the registered hooks for the `onStart` lifecycle event.\n * This array contains functions that are called before the build process starts.\n */\n\n private onStartHooks: Array<OnStartType> = [];\n\n /**\n * Holds the registered hooks for the `onResolve` lifecycle event.\n * This array contains functions that are called when esbuild attempts to resolve a module path.\n */\n\n private onResolveHooks: Array<OnResolveType> = [];\n\n /**\n * Registers a hook function for the `onStart` lifecycle event.\n * The hook will be called before the build process starts.\n *\n * @param fn - A function of type `OnStartType` that will be executed when the build process starts.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnStart(async (build) => {\n * console.log('Build started:', build);\n * });\n * ```\n */\n\n registerOnStart(fn: OnStartType | undefined): void {\n if (fn)\n this.onStartHooks.push(fn);\n }\n\n /**\n * Registers a hook function for the `onEnd` lifecycle event.\n * The hook will be called after the build process completes.\n *\n * @param fn - A function of type `OnEndType` that will be executed after the build completes.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnEnd(async (result) => {\n * console.log('Build finished:', result);\n * });\n * ```\n */\n\n registerOnEnd(fn: OnEndType | undefined): void {\n if (fn)\n this.onEndHooks.push(fn);\n }\n\n /**\n * Registers a hook function for the `onResolve` lifecycle event.\n * The hook will be called when esbuild attempts to resolve a module path.\n *\n * @param fn - A function of type `OnResolveType` that will be executed during module resolution.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnResolve(async (args) => {\n * if (args.path === 'my-module') {\n * return { path: './src/my-module.ts' };\n * }\n * return null;\n * });\n * ```\n */\n\n registerOnResolve(fn: OnResolveType | undefined): void {\n if (fn)\n this.onResolveHooks.push(fn);\n }\n\n /**\n * Registers a hook function for the `onLoad` lifecycle event.\n * The hook will be called when esbuild attempts to load a module.\n *\n * @param fn - A function of type `OnLoadType` that will be executed during module loading.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnLoad(async (contents, loader, args) => {\n * if (args.path.endsWith('.json')) {\n * return { contents: JSON.stringify({ key: 'value' }), loader: 'json' };\n * }\n * return null;\n * });\n * ```\n */\n\n registerOnLoad(fn: OnLoadType | undefined): void {\n if (fn)\n this.onLoadHooks.push(fn);\n }\n\n /**\n * Registers esbuild plugin hooks and sets up the middleware plugin.\n *\n * This function defines the setup for an esbuild plugin, enabling hooks for various lifecycle events:\n * onStart, onEnd, onResolve, and onLoad. It ensures that hooks registered by the user are called at\n * the appropriate stages of the build process.\n *\n * @returns An object with the plugin configuration that can be passed to esbuild's `plugins` array.\n * The configuration includes the plugin name and setup function.\n *\n * @example\n * ```typescript\n * // Example usage with esbuild:\n * const esbuild = require('esbuild');\n * const pluginProvider = new PluginsProvider();\n *\n * esbuild.build({\n * entryPoints: ['./src/index.ts'],\n * bundle: true,\n * plugins: [pluginProvider.setup()],\n * }).catch(() => process.exit(1));\n * ```\n */\n\n setup() {\n return {\n name: 'middleware-plugin',\n setup: (build: PluginBuild) => {\n build.initialOptions.metafile = true;\n build.onEnd(this.handleOnEnd.bind(this));\n build.onStart(this.handleOnStart.bind(this, build));\n build.onLoad({ filter: /.*/ }, this.handleOnLoad.bind(this));\n build.onResolve({ filter: /.*/ }, this.handleOnResolve.bind(this));\n }\n };\n }\n\n /**\n * Executes all registered onStart hooks.\n *\n * This function is called when the build process starts and invokes each hook registered via\n * `registerOnStart`. Hooks can perform actions such as initializing tasks, logging, or setting\n * up build conditions.\n *\n * @param build - The esbuild `PluginBuild` object that represents the current build process.\n *\n * @returns A promise that resolves when all hooks have been executed.\n *\n * @example\n * ```typescript\n * // Registering an onStart hook\n * pluginProvider.registerOnStart(async (build) => {\n * console.log('Build started:', build);\n * });\n * ```\n */\n\n private async handleOnStart(build: PluginBuild): Promise<OnEndResult> {\n this.buildState = {};\n const result: Required<OnEndResult> = {\n errors: [],\n warnings: []\n };\n\n for (const hook of this.onStartHooks) {\n const status = await hook(build, this.buildState);\n if (status) {\n if (status.errors?.length)\n result.errors.push(...status.errors);\n\n if (status.warnings?.length)\n result.warnings.push(...status.warnings);\n }\n }\n\n return result;\n }\n\n /**\n * Executes all registered onEnd hooks after the build finishes.\n *\n * This function is called after the build process completes and invokes each hook registered via\n * `registerOnEnd`. Hooks can be used to process the build results, such as performing analysis or cleanup.\n *\n * @param buildResult - The build buildResult object provided by esbuild, containing details about the build process.\n *\n * @returns A promise that resolves when all hooks have been executed.\n *\n * @example\n * ```typescript\n * // Registering an onEnd hook\n * pluginProvider.registerOnEnd(async (buildResult) => {\n * console.log('Build completed:', buildResult);\n * });\n * ```\n */\n\n private async handleOnEnd(buildResult: BuildResult): Promise<OnEndResult> {\n const result: Required<OnEndResult> = {\n errors: buildResult.errors ?? [],\n warnings: buildResult.warnings ?? []\n };\n\n for (const hook of this.onEndHooks) {\n // Update buildResult with the current errors and warnings from result\n buildResult.errors = <Message[]> result.errors;\n buildResult.warnings = <Message[]> result.warnings;\n\n const status = await hook(buildResult, this.buildState);\n\n // Merge errors and warnings from the hook status\n if (status) {\n if (status.errors?.length)\n result.errors.push(...status.errors);\n\n if (status.warnings?.length)\n result.warnings.push(...status.warnings);\n }\n }\n\n return result;\n }\n\n /**\n * Resolves module imports using registered onResolve hooks.\n *\n * This function is called whenever esbuild attempts to resolve a module path. It iterates over all registered\n * onResolve hooks and merges their results. If no hook resolves a path, `null` is returned.\n *\n * @param args - The esbuild `OnResolveArgs` object containing information about the module being resolved.\n *\n * @returns A promise that resolves to an `OnResolveResult` containing the resolved path, or `null` if no path is found.\n *\n * @example\n * ```typescript\n * // Registering an onResolve hook\n * pluginProvider.registerOnResolve(async (args) => {\n * if (args.path === 'my-module') {\n * return { path: './src/my-module.ts' };\n * }\n * return null;\n * });\n * ```\n */\n\n private async handleOnResolve(args: OnResolveArgs): Promise<OnResolveResult | null> {\n let result: OnResolveResult = {};\n for (const hook of this.onResolveHooks) {\n const hookResult = await hook(args, this.buildState);\n if (hookResult) {\n result = {\n ...result,\n ...hookResult,\n path: hookResult.path || result.path\n };\n }\n }\n\n return result.path ? result : null;\n }\n\n /**\n * Loads module contents using registered onLoad hooks.\n *\n * This function is called when esbuild attempts to load a module. It reads the module contents and then\n * processes it through all registered onLoad hooks. The hooks can modify the contents and loader type.\n *\n * @param args - The esbuild `OnLoadArgs` object containing information about the module being loaded.\n *\n * @returns A promise that resolves to an `OnLoadResult` containing the module contents and loader, or `null` if no contents are loaded.\n *\n * @example\n * ```typescript\n * // Registering an onLoad hook\n * pluginProvider.registerOnLoad(async (contents, loader, args) => {\n * if (args.path.endsWith('.json')) {\n * return { contents: JSON.stringify({ key: 'value' }), loader: 'json' };\n * }\n * return null;\n * });\n * ```\n */\n\n private async handleOnLoad(args: OnLoadArgs): Promise<OnLoadResult | null> {\n let result: OnLoadResult = { contents: undefined, loader: 'default' };\n const filePath = resolve(args.path);\n\n if (!result.contents) {\n result.contents = await promises.readFile(filePath, 'utf8');\n }\n\n for (const hook of this.onLoadHooks) {\n const hookResult = await hook(result.contents ?? '', result.loader, args, this.buildState);\n if (hookResult) {\n result = {\n ...result,\n ...hookResult,\n contents: hookResult.contents || result.contents,\n loader: hookResult.loader || result.loader\n };\n }\n }\n\n return result.contents ? result : null;\n }\n}\n", "/**\n * Parses and filters content based on conditional directives.\n *\n * This function processes the given code contents and removes sections that\n * are conditionally compiled based on the provided `defines` object.\n *\n * @param contents - The code contents to be processed.\n * @param defines - An object containing conditional\n * definitions. Keys are condition names, and values are their definitions.\n * @returns The processed code contents with conditional blocks removed\n * according to the `defines` object.\n */\n\nexport function parseIfDefConditionals(contents: string, defines: Record<string, unknown>): string {\n return contents.replace(/\\/\\/\\s?ifdef\\s?(\\w+)([\\s\\S]*?)\\/\\/\\s?endif/g, (match, condition, code) => {\n // Check if the condition is defined\n return defines[condition] ? code : '';\n });\n}\n", "/**\n * Imports\n */\n\nimport { relative } from 'path';\n\n/**\n * Resolves path aliases in the provided content based on the specified paths and root directory.\n *\n * This function takes a string of content and replaces occurrences of defined path alias keys\n * with their corresponding relative paths derived from the specified source file and root directory.\n * It ensures that the resulting paths are relative to the directory of the source file and formatted\n * correctly for use in a JavaScript/TypeScript environment.\n *\n * Example:\n * Given the following inputs:\n * ```typescript\n * const content = \"import { foo } from '@core/foo';\";\n * const sourceFile = \"/project/src/index.ts\";\n * const paths = {\n * '@core/': 'src/core',\n * '@utils/': 'src/utils'\n * };\n * const rootDir = \"/project\";\n * ```\n * The function will replace `@core/foo` with a relative path based on the source file's location,\n * potentially resulting in:\n * ```typescript\n * const content = \"import { foo } from './core/foo';\";\n * ```\n *\n * @param content - The content in which path aliases need to be resolved.\n * @param sourceFile - The path of the source file from which relative paths will be calculated.\n * @param paths - An object mapping path alias keys to their corresponding paths.\n * @param esm - A flag indicating whether ESM is enabled.\n * @returns The updated content with resolved path aliases.\n */\n\nexport function resolveAliasPlugin(content: string, sourceFile: string, paths: Record<string, string>, esm: boolean): string {\n const importExportRegex = /(?:import|export)\\s.*?\\sfrom\\s+['\"]([^'\"]+)['\"]/g;\n for (const key in paths) {\n let relativePath = relative(sourceFile, paths[key]).replace(/\\\\/g, '/');\n if (!relativePath.startsWith('..')) {\n relativePath = `./${ relativePath }`;\n }\n\n content = content.replaceAll(key, `${ relativePath }/`);\n if (esm) {\n content = content.replace(importExportRegex, (match, p1) =>\n (p1.startsWith('../') || p1.startsWith('./')) && !p1.endsWith('.js')\n ? match.replace(p1, `${p1}.js`)\n : match\n );\n }\n }\n\n return content;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions, Metafile } from 'esbuild';\nimport type { transpileFileInterface } from '@services/interfaces/transpiler.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { build } from 'esbuild';\nimport { xBuildError } from '@errors/xbuild.error';\nimport type { EntryPoints } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Default build options for esbuild bundler in RemoteX framework.\n *\n * These options are used to configure how esbuild processes and bundles the TypeScript\n * files for the RemoteX testing framework.\n *\n * @public\n * @category Configuration\n */\n\nexport const defaultBuildOptions: BuildOptions = {\n write: false,\n bundle: true,\n minify: false,\n format: 'cjs',\n target: 'esnext',\n platform: 'node',\n sourcemap: true,\n sourcesContent: true,\n preserveSymlinks: true\n};\n\n/**\n * Extracts the source map from the provided data string and returns the modified code and source map separately.\n *\n * This function searches for the inline source map in the data string using a regular expression, removes the\n * source map comment from the data string, and returns an object containing the code without the source map\n * comment and the extracted source map.\n *\n * @param dataString - The string containing the transpiled code with an inline source map.\n * @returns An object containing the modified code without the source map comment and the extracted source map.\n * @throws Error -Throws an error if the source map URL is not found in the data string.\n *\n * @public\n */\n\nexport function extractSourceMap(dataString: string): transpileFileInterface {\n const sourceMapRegex = /\\/\\/# sourceMappingURL=data:application\\/json;base64,([^'\"\\s]+)/;\n const match = dataString.match(sourceMapRegex);\n\n if (!match || !match[1]) {\n throw new xBuildError('Source map URL not found in the output.');\n }\n\n const sourceMap = match[1];\n const codeWithoutSourceMap = dataString.replace(sourceMapRegex, '');\n\n return { code: codeWithoutSourceMap, sourceMap };\n}\n\n/**\n * Transpiles a TypeScript file and extracts the source map.\n *\n * This function uses esbuild to transpile the specified TypeScript file based on provided build options,\n * and then extracts the source map from the transpiled code.\n *\n * @param filePath - The path to the TypeScript file to be transpiled.\n * @param buildOptions - Optional build options to override the default build options.\n * @returns A promise that resolves to an object containing the transpiled code and the extracted source map.\n * @throws Error - Throws an error if the build process fails or the source map extraction fails.\n *\n * @public\n * @category Services\n */\n\nexport async function transpileFile(filePath: string, buildOptions: BuildOptions = {}): Promise<transpileFileInterface> {\n const options: BuildOptions = {\n absWorkingDir: cwd(),\n ...defaultBuildOptions,\n ...buildOptions,\n entryPoints: [ filePath ]\n };\n\n const result = await build(options);\n const fileContent = result.outputFiles?.pop()?.text ?? '';\n\n // Retrieve the transpiled code from the build output.\n return extractSourceMap(fileContent);\n}\n\n/**\n * Analyzes the dependencies of a given entry point using esbuild.\n *\n * This function bundles the specified entry point without writing the output files to disk.\n * Instead, it generates a metafile that contains detailed information about the dependencies\n * and imports used in the bundled code. The metafile is returned as a result of the analysis.\n *\n * @param entryPoint - The path to the entry point file that should be analyzed.\n * @param platform - The platform for which the code is being analyzed.\n * 'browser' indicates that the code is intended for a browser environment,\n * 'node' indicates a Node.js environment, and 'neutral' is platform-agnostic.\n * @returns A promise that resolves to the metafile containing the analysis of dependencies.\n * @throws Error - Throws an error if the build process fails.\n *\n * @public\n * @category Services\n */\n\nexport async function analyzeDependencies(entryPoint: EntryPoints, platform: 'browser' | 'node' | 'neutral' = 'browser'): Promise<Metafile> {\n const result = await build({\n entryPoints: entryPoint,\n bundle: true, // Bundle to analyze imports\n write: false, // Prevent writing output files\n metafile: true, // Generate a metafile to analyze dependencies\n platform: platform,\n packages: 'external',\n logLevel: 'silent',\n outdir: 'dist'\n });\n\n return result.metafile;\n}\n", "/**\n * Imports\n */\n\nimport { BaseError } from '@errors/base.error';\n\n/**\n * Represents an error specific to the xBuild process.\n *\n * The `xBuildError` class extends the `BaseError` class to provide a custom error type for the xBuild system.\n * It includes additional functionality to maintain stack trace information and assigns a specific name to\n * the error, making it easier to identify and handle in different parts of the application.\n *\n * @augments BaseError\n */\n\nexport class xBuildError extends BaseError {\n /**\n * Original error stack\n */\n\n originalErrorStack: string | undefined;\n\n /**\n * Creates an instance of `xBuildError`.\n *\n * @param message - The error message that describes the error. This message is passed to the base class\n * `BaseError` constructor and is used to provide context about the nature of the error.\n * @param options - Optional configuration for the error. This can include additional properties or settings\n * that customize the error's behavior.\n */\n\n constructor(message: string, options?: ErrorOptions) {\n // Pass the message to the base class Error\n super(message);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, xBuildError);\n }\n\n // Apply additional options if provided\n if (options) {\n Object.assign(this, options);\n }\n\n // Assign the name of the error\n this.name = 'xBuildError';\n this.originalErrorStack = this.stack;\n this.stack = this.reformatStack(this);\n }\n}\n", "/**\n * Custom error class to represent type-related errors.\n *\n * This class extends the built-in `Error` class to provide more specific\n * error handling for issues related to types. It can be used to distinguish\n * errors that occur due to type mismatches or other type-related problems\n * in your application.\n *\n * @example\n * ```typescript\n * throw new TypesError('Invalid type encountered.');\n * ```\n *\n * @augments Error\n */\n\nexport class TypesError extends Error {\n /**\n * Creates an instance of `TypesError`.\n *\n * @param message - A human-readable message providing details about the error.\n * @param options - Optional configuration for the error, such as a `cause` (ECMAScript 2022+).\n * @param options.cause\n */\n\n constructor(message?: string, options?: { cause?: Error }) {\n super(message);\n this.name = 'TypesError';\n\n // Set the prototype explicitly to ensure instanceof checks work correctly\n Object.setPrototypeOf(this, TypesError.prototype);\n\n if (options?.cause) {\n // Optionally include the cause of the error, if provided\n this.cause = options.cause;\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { EntryPoints } from '@configuration/interfaces/configuration.interface';\nimport type {\n Node,\n Bundle,\n Diagnostic,\n SourceFile,\n StringLiteral,\n CompilerOptions,\n CustomTransformer,\n ImportDeclaration,\n ExportDeclaration,\n ParsedCommandLine,\n TransformationContext,\n CustomTransformerFactory\n} from 'typescript';\n\n/**\n * Imports\n */\n\nimport { TypesError } from '@errors/types.error';\nimport { prefix } from '@components/banner.component';\nimport { resolve, relative, dirname, parse } from 'path';\nimport { Colors, setColor } from '@components/colors.component';\nimport { extractEntryPoints } from '@components/entry-points.component';\nimport {\n sys,\n factory,\n createProgram,\n visitEachChild,\n isStringLiteral,\n resolveModuleName,\n DiagnosticCategory,\n isImportDeclaration,\n isExportDeclaration,\n getPreEmitDiagnostics,\n flattenDiagnosticMessageText\n} from 'typescript';\n\n/**\n * Provides TypeScript-related utilities such as type-checking, generating declaration files,\n * and transforming module specifiers into relative paths based on the output directory.\n *\n * The `TypescriptProvider` class enables users to type-check TypeScript projects, generate\n * declaration files, and transform import/export paths into relative paths that match the output directory.\n * It uses the TypeScript Compiler API to achieve these transformations.\n *\n * @class\n * @example\n * ```typescript\n * const tsProvider = new TypescriptProvider(parsedConfig, './dist');\n * tsProvider.typeCheck(entryPoints);\n * tsProvider.generateDeclarations(entryPoints);\n * ```\n */\n\nexport class TypeScriptProvider {\n\n /**\n * Compiler options for configuring TypeScript compilation.\n */\n\n readonly options: CompilerOptions;\n\n /**\n * Creates an instance of `TypescriptProvider` with the given TypeScript configuration and output directory.\n *\n * This constructor initializes a `TypescriptProvider` with the provided TypeScript configuration\n * and the directory where output files (such as declaration files) will be stored.\n * Additionally, it accepts a flag to control whether ANSI color formatting should be applied in output messages.\n *\n * @param tsConfig - The parsed TypeScript configuration object.\n * @param outDir - The directory where output files (such as declaration files) will be stored.\n * @param activeColor - A boolean flag indicating whether ANSI color formatting should be applied in output messages.\n * Default is `true`.\n *\n * @example\n * ```typescript\n * const tsProvider = new TypescriptProvider(parsedConfig, './dist');\n * ```\n *\n * @example\n * ```typescript\n * const tsProvider = new TypescriptProvider(parsedConfig, './dist', false);\n * // This instance will not apply ANSI color formatting in output messages\n * ```\n */\n\n constructor(public tsConfig: ParsedCommandLine, private outDir: string, private activeColor: boolean = true) {\n this.options = {\n ...this.tsConfig.options,\n outDir: this.outDir\n };\n }\n\n /**\n * Performs type-checking on the specified entry points without emitting any files.\n *\n * This method compiles the provided TypeScript files to check for type errors and other diagnostics without\n * generating any output files. It ensures that the code adheres to TypeScript's type constraints and reports\n * any issues found during the type-checking process.\n *\n * @param allowError - A boolean flag indicating whether to throw an error if diagnostics are present. If set to\n * `true`, errors are logged but not thrown, allowing the process to continue. Defaults to `false`, which throws\n * an error if diagnostics are encountered.\n *\n * @returns void\n *\n * @throws Throws an error if type-checking fails due to TypeScript diagnostics and `allowError` is `false`.\n * The error indicates that the type-checking process has encountered issues.\n *\n * @example\n * ```typescript\n * // Type-check files and handle any diagnostics\n * tsProvider.typeCheck(['src/index.ts', 'src/app.ts']);\n * ```\n */\n\n typeCheck(allowError: boolean = false): void {\n const program = createProgram(this.tsConfig.fileNames, {\n ...this.options,\n noEmit: true,\n skipLibCheck: true\n });\n\n this.handleDiagnostics(getPreEmitDiagnostics(program), allowError);\n }\n\n /**\n * Generates TypeScript declaration files (`.d.ts`) for the specified entry points.\n *\n * This method compiles the provided TypeScript files and emits only the declaration files, without generating\n * JavaScript code. It applies a custom transformer to modify module specifiers to relative paths based on the\n * output directory. This ensures that the generated declaration files are accurate and the module paths are\n * aligned with the project's build structure.\n *\n * @param entryPoints - An array of entry points or an object representing the entry files for which declarations\n * are generated. Entry points can be provided in the following formats:\n * - An array of strings representing file paths (`string[]`).\n * - An array of objects with `in` and `out` properties (`{ in: string, out: string }[]`).\n * - A record object with file paths as values (`Record<string, string>`).\n *\n * @param noTypeChecker - Skips TypeScript type checking.\n * @param allowError - A boolean flag indicating whether to throw an error if diagnostics are present. If set to\n * `true`, errors are logged but not thrown, allowing the process to continue. Defaults to `false`, which throws\n * an error if diagnostics are encountered.\n *\n * @returns void\n *\n * @example\n * ```typescript\n * // Generate declaration files for specific entry points\n * tsProvider.generateDeclarations(['src/index.ts', 'src/app.ts']);\n * ```\n */\n\n generateDeclarations(entryPoints: EntryPoints, noTypeChecker = false, allowError: boolean = false): void {\n const files = Object.values(extractEntryPoints(entryPoints));\n const program = createProgram(files, {\n ...this.options,\n rootDir: this.options.baseUrl,\n declaration: true,\n skipLibCheck: true,\n emitDeclarationOnly: true\n });\n\n // Collect diagnostics and check for errors\n const diagnostics = getPreEmitDiagnostics(program);\n if (!noTypeChecker && diagnostics.some(diagnostic => diagnostic.category === DiagnosticCategory.Error)) {\n return this.handleDiagnostics(diagnostics, allowError);\n }\n\n // Emit declarations if no type errors were found\n program.emit(undefined, undefined, undefined, true, {\n afterDeclarations: [ this.createTransformerFactory() ]\n });\n }\n\n /**\n * Checks if the provided node is an import or export declaration.\n *\n * @param node - A TypeScript AST node to check.\n *\n * @returns `true` if the node is either an `ImportDeclaration` or `ExportDeclaration`; otherwise, `false`.\n *\n * @example\n * ```typescript\n * const isDeclaration = tsProvider.isImportOrExportDeclaration(node);\n * console.log(isDeclaration); // true or false\n * ```\n */\n\n private isImportOrExportDeclaration(node: Node): boolean {\n return isImportDeclaration(node) || isExportDeclaration(node);\n }\n\n /**\n * Checks if the provided node has a string literal as its module specifier.\n *\n * @param node - A TypeScript AST node to check.\n *\n * @returns `true` if the node has a string literal module specifier; otherwise, `undefined`.\n *\n * @example\n * ```typescript\n * const hasModuleSpecifier = tsProvider.hasStringLiteralModuleSpecifier(importNode);\n * console.log(hasModuleSpecifier); // true or undefined\n * ```\n */\n\n private hasStringLiteralModuleSpecifier(node: Node): boolean | undefined {\n return (<ImportDeclaration> node).moduleSpecifier && isStringLiteral((<ImportDeclaration> node).moduleSpecifier);\n }\n\n /**\n * Resolves the module file name based on the module specifier and TypeScript compiler options.\n *\n * @param specifierText - The module specifier text (e.g., `'./module'`).\n * @param options - The TypeScript compiler options.\n *\n * @returns The resolved file path of the module or `undefined` if the module cannot be resolved.\n *\n * @example\n * ```typescript\n * const resolvedPath = tsProvider.resolveModuleFileName('./module', compilerOptions);\n * console.log(resolvedPath); // './dist/module.js'\n * ```\n */\n\n private resolveModuleFileName(specifierText: string, options: CompilerOptions): string | undefined {\n let path = undefined;\n const resolvedModule = resolveModuleName(specifierText, options.baseUrl!, options, sys);\n\n if (resolvedModule.resolvedModule && options.baseUrl) {\n if (resolvedModule.resolvedModule.resolvedFileName.includes('node_modules'))\n return path;\n\n path = resolve(resolvedModule.resolvedModule.resolvedFileName).replace(\n resolve(options.baseUrl), '.'\n );\n }\n\n return path;\n }\n\n /**\n * Computes the relative path from the source file to the resolved target file.\n *\n * @param sourceFile - The absolute path of the source file.\n * @param resolvedTargetFile - The absolute path of the resolved target file.\n *\n * @returns A relative path from the source file to the target file.\n *\n * @example\n * ```typescript\n * const relativePath = tsProvider.getRelativePathToOutDir('./src/index.ts', './dist/module.js');\n * console.log(relativePath); // './module.js'\n * ```\n */\n\n private getRelativePathToOutDir(sourceFile: string, resolvedTargetFile: string): string {\n sourceFile = resolve(sourceFile).replace(resolve(this.options.baseUrl ?? ''), '.');\n const relativePath = relative(dirname(sourceFile), resolvedTargetFile).replace(/\\\\/g, '/');\n const parsePath = parse(relativePath);\n\n if (!parsePath.dir.startsWith('..')) {\n parsePath.dir = `./${ parsePath.dir }`;\n }\n\n return `${ parsePath.dir }/${ parsePath.name }`;\n }\n\n /**\n * Updates the module specifier of an import or export declaration to a relative path based on the output directory.\n *\n * This method takes a TypeScript `ImportDeclaration` or `ExportDeclaration` node and updates its module\n * specifier to a relative path that matches the output directory. It uses the TypeScript compiler options\n * to resolve the full path of the module and converts it into a relative path from the source file.\n *\n * This is useful when transforming module specifiers to ensure the generated declaration files (`.d.ts`)\n * have correct paths when files are moved to the output directory.\n *\n * @param node - The TypeScript `ImportDeclaration` or `ExportDeclaration` node whose module specifier needs to be updated.\n * @param sourceFile - The absolute path of the source file containing the node.\n *\n * @returns The updated `ImportDeclaration` or `ExportDeclaration` node with the new relative module specifier.\n *\n * @example\n * ```typescript\n * const updatedNode = tsProvider.updateModuleSpecifier(importNode, './src/index.ts');\n * console.log(updatedNode.moduleSpecifier.text); // './module.js'\n * ```\n */\n\n private updateModuleSpecifier(node: Node, sourceFile: string): Node {\n const newModuleSpecifier = factory.createStringLiteral(sourceFile);\n\n if (isImportDeclaration(node)) {\n return factory.updateImportDeclaration(\n node,\n node.modifiers,\n node.importClause,\n newModuleSpecifier,\n undefined\n );\n } else if (isExportDeclaration(node)) {\n return factory.updateExportDeclaration(\n node,\n node.modifiers,\n node.isTypeOnly,\n node.exportClause,\n newModuleSpecifier,\n undefined\n );\n }\n\n return node;\n }\n\n /**\n * Creates a visitor function that transforms `ImportDeclaration` and `ExportDeclaration` nodes by updating\n * their module specifiers to relative paths based on the output directory.\n *\n * This method returns a visitor function, which is used to traverse and transform the nodes in a TypeScript\n * `SourceFile`. The visitor identifies `ImportDeclaration` and `ExportDeclaration` nodes with module specifiers\n * that are string literals. For these nodes, the module specifiers are resolved to their corresponding file paths\n * and updated to relative paths that align with the output directory.\n *\n * The visitor is designed to recursively visit all nodes in the `SourceFile`, transforming only the relevant\n * import and export declarations while leaving other nodes unchanged.\n *\n * @param sourceFile - The TypeScript `SourceFile` that will be traversed by the visitor.\n * @param context - The transformation context provided by the TypeScript compiler, used for visiting nodes.\n *\n * @returns A visitor function that processes the nodes in the source file, updating module specifiers as needed.\n *\n * @example\n * ```typescript\n * const visitor = tsProvider.createVisitor(sourceFile, context);\n * const transformedNode = visitor(importNode);\n * console.log(transformedNode); // ImportDeclaration with updated module specifier\n * ```\n */\n\n private createVisitor(sourceFile: SourceFile, context: TransformationContext): (node: Node) => Node {\n // Define the visitor function that will handle transformations\n const visitNode = (node: Node | ImportDeclaration | ExportDeclaration): Node => {\n // Example transformation: replace import/export module specifiers with relative paths\n if (this.isImportOrExportDeclaration(node) && this.hasStringLiteralModuleSpecifier(node)) {\n const specifierText = ((<ImportDeclaration> node).moduleSpecifier as StringLiteral).text;\n const resolvedTargetFile = this.resolveModuleFileName(specifierText, this.options);\n\n if (resolvedTargetFile) {\n const relativePath = this.getRelativePathToOutDir(sourceFile.fileName, resolvedTargetFile);\n\n return this.updateModuleSpecifier(node as Node & { moduleSpecifier: StringLiteral }, relativePath);\n }\n }\n\n // Recursively visit each child node\n return visitEachChild(node, visitNode, context);\n };\n\n // Return the visitor function\n return visitNode;\n }\n\n /**\n * Creates a custom transformer factory for TypeScript that processes `SourceFile` nodes.\n *\n * This method returns a custom transformer factory function which generates a transformer that can be used\n * during the TypeScript compilation process. The transformer specifically processes `SourceFile` nodes to\n * apply custom transformations and does not alter `Bundle` nodes.\n *\n * The factory function generates a transformer that performs the following:\n * - **Transforming `SourceFile` nodes**: Uses the `createVisitor` method to visit and transform all nodes in\n * a `SourceFile`. This allows custom modifications or analysis of TypeScript source files.\n * - **No transformation for `Bundle` nodes**: The `transformBundle` method returns the bundle unchanged, as\n * no specific transformation is needed for bundles in this implementation.\n *\n * This transformer factory is used primarily for customizing TypeScript file transformations, such as updating\n * module specifiers or other source-level adjustments during the compilation process.\n *\n * @returns A custom transformer factory function that produces a `CustomTransformer` object. This object\n * implements the `transformSourceFile` and `transformBundle` methods.\n *\n * @example\n * ```typescript\n * const transformerFactory = tsProvider.createTransformerFactory();\n * const emitResult = program.emit(undefined, undefined, undefined, true, {\n * after: [transformerFactory]\n * });\n * ```\n */\n\n private createTransformerFactory(): CustomTransformerFactory {\n return (context: TransformationContext): CustomTransformer => {\n return {\n // Transform the source file by visiting all nodes\n transformSourceFile: (sourceFile: SourceFile): SourceFile => {\n return visitEachChild(sourceFile, this.createVisitor(sourceFile, context), context);\n },\n\n // Required for transformers but usually not necessary for us to implement\n transformBundle: (bundle: Bundle): Bundle => {\n return bundle; // No transformation needed for bundles in this case\n }\n };\n };\n }\n\n /**\n * Handles and logs TypeScript diagnostics, providing detailed error messages with file and position information.\n *\n * This method processes an array of TypeScript diagnostics, printing formatted error messages to the console.\n * If a diagnostic is associated with a specific file and position, the error message includes the filename,\n * line, and character information. Colors are applied to highlight different parts of the message, such as\n * file paths, positions, error messages, and error codes.\n *\n * If the `allowError` flag is `false`, the method throws an error when diagnostics are present, indicating\n * that type checking has failed. If `allowError` is `true`, errors are logged but not thrown, allowing the process\n * to continue despite the diagnostics.\n *\n * @param diagnostics - An array of readonly `Diagnostic` objects returned by the TypeScript compiler.\n * These diagnostics contain information about errors or warnings that occurred during compilation.\n *\n * @param allowError - A boolean flag that determines whether the method should throw an error when diagnostics\n * are encountered. If set to `true`, the method logs diagnostics but does not throw an error. Defaults to `false`.\n *\n * @throws Will throw an error if diagnostics are present and `allowError` is set to `false`. The error\n * indicates that type checking has failed.\n *\n * @example\n * ```typescript\n * const diagnostics = program.getSemanticDiagnostics();\n * handleDiagnostics(diagnostics, false); // Throws an error if any diagnostics exist.\n * ```\n */\n\n private handleDiagnostics(diagnostics: readonly Diagnostic[], allowError: boolean = false): void {\n if (diagnostics.length === 0)\n return;\n\n diagnostics.forEach(diagnostic => {\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n const message = flattenDiagnosticMessageText(diagnostic.messageText, '\\n');\n\n const file = setColor(Colors.Cyan, diagnostic.file.fileName, this.activeColor);\n const position = setColor(Colors.LightYellow, `${ line + 1 }:${ character + 1 }`, this.activeColor);\n const errorMsg = setColor(Colors.Red, 'error', this.activeColor);\n const errorCode = setColor(Colors.Gray, `TS${ diagnostic.code }`, this.activeColor);\n\n console.error(`${ prefix() } ${ file }:${ position } - ${ errorMsg } ${ errorCode }:${ message }`);\n } else {\n console.error(flattenDiagnosticMessageText(diagnostic.messageText, '\\n'));\n }\n });\n\n console.log('\\n');\n if (!allowError) {\n throw new TypesError('Type checking failed due to errors.');\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { EntryPoints } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildError } from '@errors/xbuild.error';\n\n/**\n * Maps an array of file paths to an object where the keys are filenames (without extensions)\n * and the values are the corresponding file paths.\n *\n * Each key in the resulting object is derived from the filename by removing the file extension.\n * For example, given a file path `src/index.ts`, the key in the resulting object will be `src/index`.\n *\n * @param filePaths - An array of file paths to map. Each file path should be a string.\n * @returns An object where the keys are filenames (without extensions) and the values are the corresponding file paths.\n *\n * @example\n * ```typescript\n * const filePaths = ['src/index.ts', 'src/utils.ts'];\n * const result = mapFilePathsToNames(filePaths);\n * console.log(result);\n * // Output: {\n * // 'src/index': 'src/index.ts',\n * // 'src/utils': 'src/utils.ts'\n * // }\n * ```\n */\n\nexport function mapFilePathsToNames(filePaths: Array<string>): Record<string, string> {\n const result: Record<string, string> = {};\n\n filePaths.forEach(filePath => {\n // Extract the filename without extension\n const fileName = filePath.substring(0, filePath.lastIndexOf('.'));\n // Map the filename to the file path\n result[fileName] = filePath;\n });\n\n return result;\n}\n\n/**\n * Extracts and returns an object mapping output file paths to input file paths from the provided `EntryPoints` object.\n *\n * This function handles multiple formats of entry points, including:\n * - An array of strings representing file paths.\n * - An array of objects containing `in` and `out` properties, where `in` is the input file path and `out` is the output file path.\n * - A `Record<string, string>` where the keys represent input file paths and the values represent output file paths.\n *\n * Depending on the format, the function constructs an object with the output file paths as keys and the input file paths as values.\n * If the output path is not available, the filename (without extension) is used as the key.\n *\n * If a regular object with string keys and values (not in the supported formats) is provided, it will be returned as is.\n *\n * @param entryPoints - The entry points to extract from, which can be in different formats: an array of strings,\n * an array of objects with `in` and `out` properties, or a `Record<string, string>`.\n *\n * @returns An object mapping output file paths to input file paths, or filename (without extension) to file path.\n *\n * @throws Will throw an `Error` if the entry points format is unsupported.\n *\n * @example\n * ```typescript\n * const entryPoints = extractEntryPoints(['src/index.ts', 'src/utils.ts']);\n * console.log(entryPoints); // { 'index': 'src/index.ts', 'utils': 'src/utils.ts' }\n * ```\n *\n * @example\n * ```typescript\n * const entryPoints = extractEntryPoints([{ in: 'src/index.ts', out: 'dist/index.js' }]);\n * console.log(entryPoints); // { 'dist/index.js': 'src/index.ts' }\n * ```\n *\n * @example\n * ```typescript\n * const entryPoints = extractEntryPoints({ index: 'src/index.ts', index2: 'dist/index2.js' });\n * console.log(entryPoints); // { index: 'src/index.ts', index2: 'dist/index2.js' }\n * ```\n */\n\nexport function extractEntryPoints(entryPoints: EntryPoints): Record<string, string> {\n if (Array.isArray(entryPoints)) {\n let result: Record<string, string> = {};\n\n if (entryPoints.length > 0 && typeof entryPoints[0] === 'object') {\n (entryPoints as { in: string, out: string }[]).forEach(entry => {\n result[entry.out] = entry.in;\n });\n } else if (typeof entryPoints[0] === 'string') {\n result = mapFilePathsToNames(<Array<string>> entryPoints);\n }\n\n return result;\n } else if (entryPoints && typeof entryPoints === 'object') {\n return entryPoints;\n }\n\n throw new xBuildError('Unsupported entry points format');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Argv } from 'yargs';\nimport type { BuildOptions } from 'esbuild';\nimport type { ParsedCommandLine } from 'typescript';\nimport type { ArgvInterface } from '@services/interfaces/cli.interface';\nimport type {\n ConfigurationInterface,\n PartialDeepConfigurationsType\n} from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { dirname } from 'path';\nimport { existsSync, readFileSync } from 'fs';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { defaultConfiguration } from '@configuration/default.configuration';\nimport { parseConfigurationFile } from '@configuration/parse.configuration';\n\n/**\n * Default tsconfig if not supplied\n */\n\nconst defaultTsConfig = JSON.stringify({\n 'compilerOptions': {\n 'strict': true,\n 'target': 'ESNext',\n 'module': 'ESNext',\n 'outDir': 'dist',\n 'skipLibCheck': true,\n 'isolatedModules': false,\n 'esModuleInterop': false,\n 'moduleDetection': 'force',\n 'moduleResolution': 'node',\n 'resolveJsonModule': true,\n 'allowSyntheticDefaultImports': true,\n 'forceConsistentCasingInFileNames': true\n }\n});\n\n/**\n * Parses CLI arguments and sets the configuration for the application.\n *\n * @param cli - An instance of `Argv<ArgvInterface>` that contains CLI arguments and options.\n * @returns The final configuration object as a `ConfigurationInterface`.\n * @throws Error - Throws an error if critical configuration properties are missing or invalid.\n */\n\nfunction parseCliArgs(cli: Argv<ArgvInterface>): PartialDeepConfigurationsType {\n const args = <ArgvInterface> cli.argv;\n\n // Helper function to filter out undefined values\n const pickDefined = <T extends object>(obj: T): PartialDeepConfigurationsType => Object.fromEntries(\n Object.entries(obj).filter(([ , value ]) => value !== undefined)\n );\n\n const esbuildConfig = pickDefined({\n bundle: args.bundle,\n minify: args.minify,\n outdir: args.outdir,\n tsconfig: args.tsconfig,\n entryPoints: args.file ? [ args.file ] : undefined,\n target: args.node ? [ `node${ process.version.slice(1) }` ] : undefined,\n platform: args.node ? 'node' : undefined,\n format: args.format\n });\n\n return <PartialDeepConfigurationsType> {\n ...pickDefined({\n dev: args.dev,\n watch: args.watch,\n declaration: args.declaration,\n serve: args.serve ? { active: args.serve } : { undefined }\n }),\n ...{ esbuild: esbuildConfig }\n };\n}\n\n/**\n * Reads and parses the TypeScript configuration file.\n *\n * @param options - A `BuildOptions` object that may contain a custom `tsconfig` path.\n * @returns A `ParsedCommandLine` object representing the parsed TypeScript configuration.\n * @throws xBuildError - Throws an error if the configuration file contains syntax errors.\n */\n\nexport function tsConfiguration(options: BuildOptions): ParsedCommandLine {\n const tsConfigFile = options.tsconfig ?? '';\n const configFile = existsSync(tsConfigFile) ? readFileSync(tsConfigFile, 'utf8') : JSON.stringify(defaultTsConfig);\n\n const parsedConfig = ts.parseConfigFileTextToJson(tsConfigFile, configFile);\n if (parsedConfig.error) {\n throw new xBuildError(ts.formatDiagnosticsWithColorAndContext([ parsedConfig.error ], {\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getCanonicalFileName: fileName => fileName,\n getNewLine: () => ts.sys.newLine\n }));\n }\n\n const configParseResult = ts.parseJsonConfigFileContent(parsedConfig.config, ts.sys, dirname(tsConfigFile));\n if (configParseResult.errors.length > 0) {\n throw new xBuildError(ts.formatDiagnosticsWithColorAndContext(configParseResult.errors, {\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getCanonicalFileName: fileName => fileName,\n getNewLine: () => ts.sys.newLine\n }));\n }\n\n return configParseResult;\n}\n\n/**\n * Merges CLI arguments with a configuration file to produce a final configuration object.\n *\n * @param configFile - The path to the configuration file to read and merge with CLI arguments.\n * @param cli - An instance of `Argv<ArgvInterface>` containing CLI arguments and options.\n * @returns A promise that resolves to the final `ConfigurationInterface` object.\n * @throws Error - Throws an error if the `entryPoints` property in the final configuration is undefined.\n */\n\nexport async function configuration(configFile: string, cli: Argv<ArgvInterface>): Promise<Array<ConfigurationInterface>> {\n const cliConfig = parseCliArgs(cli);\n const userConfig = existsSync(configFile) ? await parseConfigurationFile(configFile) : {};\n\n // Check if userConfig is an array and handle accordingly\n const userConfigs: Array<ConfigurationInterface> = Array.isArray(userConfig) ? userConfig : [ userConfig ];\n const defaultUserConfig = userConfigs[0];\n\n return userConfigs.flatMap<ConfigurationInterface>((userConfigEntry) => {\n const mergedConfig: ConfigurationInterface = {\n ...defaultConfiguration,\n ...defaultUserConfig,\n ...userConfigEntry,\n ...cliConfig,\n esbuild: {\n ...defaultConfiguration.esbuild,\n ...defaultUserConfig?.esbuild,\n ...userConfigEntry?.esbuild,\n ...cliConfig.esbuild\n },\n serve: {\n ...defaultConfiguration.serve,\n ...defaultUserConfig.serve,\n ...userConfigEntry.serve,\n ...cliConfig.serve\n }\n };\n\n if (!mergedConfig.esbuild.entryPoints) {\n throw new xBuildError('entryPoints cannot be undefined.');\n }\n\n return mergedConfig;\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigurationInterface } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\n\n/**\n * The default configuration options for the build.\n *\n * @example\n * ```typescript\n * import { defaultConfiguration } from '@configuration/default-configuration';\n *\n * console.log(defaultConfiguration);\n * ```\n *\n * In this example, the `defaultConfiguration` is imported and logged to the console to view the default settings.\n *\n * @public\n * @category Configuration\n */\n\nexport const defaultConfiguration: ConfigurationInterface = {\n dev: false,\n watch: false,\n declaration: false,\n buildOnError: false,\n noTypeChecker: false,\n define: {},\n esbuild: {\n write: true,\n bundle: true,\n minify: true,\n format: 'cjs',\n outdir: 'dist',\n platform: 'browser',\n absWorkingDir: cwd(),\n loader: {\n '.js': 'ts'\n }\n },\n serve: {\n port: 3000,\n host: 'localhost',\n active: false\n }\n};\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ErrorType } from '@errors/interfaces/stack.interface';\nimport type { ConfigurationInterface, ModuleInterface } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { createRequire } from 'module';\nimport { SourceService } from '@remotex-labs/xmap';\nimport { sandboxExecute } from '@services/vm.service';\nimport { VMRuntimeError } from '@errors/vm-runtime.error';\nimport { transpileFile } from '@services/transpiler.service';\n\n/**\n * Recursively wraps all functions in an object, including nested objects.\n *\n * @param obj - The object whose functions need to be wrapped.\n * @param sourceMap - The source map service to attach to the error in case of a thrown error.\n * @returns The object with its functions wrapped.\n */\n\nfunction wrapAllFunctions<T extends object>(obj: T, sourceMap: SourceService): T {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key as keyof T];\n\n if (typeof value === 'function') {\n // Safely cast and wrap the function\n (obj as Record<string, unknown>)[key] = wrapFunctionWithSourceMap(value as (...args: unknown[]) => unknown, sourceMap);\n } else if (typeof value === 'object' && value !== null) {\n // Recursively wrap functions in nested objects\n wrapAllFunctions(value, sourceMap);\n }\n }\n }\n\n return obj;\n}\n\n/**\n * Wraps a function to catch errors and attach sourcemap information.\n *\n * @param fn - The function to be wrapped.\n * @param sourceMap - The source map service to attach to the error in case of a thrown error.\n * @returns The wrapped function that includes error handling with sourcemap information.\n */\n\nfunction wrapFunctionWithSourceMap<T extends (...args: unknown[]) => unknown>(\n fn: T,\n sourceMap: SourceService\n): T {\n return ((...args: Parameters<T>): ReturnType<T> => {\n try {\n return fn(...args) as ReturnType<T>;\n } catch (error) {\n throw new VMRuntimeError(<Error> error, sourceMap);\n }\n }) as T;\n}\n\n/**\n * Wraps functions within a `ConfigurationInterface` object to add sourcemap information to any errors thrown.\n *\n * @param config - The configuration object containing functions that need to be wrapped.\n * @param sourceMap - The source map service used to provide sourcemap information in case of errors.\n * @returns The modified `ConfigurationInterface` object with its functions wrapped.\n */\n\nfunction wrapConfigFunctionsWithSourcemap(\n config: ConfigurationInterface,\n sourceMap: SourceService\n): ConfigurationInterface {\n return wrapAllFunctions(config, sourceMap);\n}\n\n/**\n * Parses a configuration file and returns a wrapped `ConfigurationInterface` object.\n *\n * This function reads the specified configuration file, transpiles it to a CommonJS format, and then executes it\n * in a sandbox environment. The exported configuration object is wrapped so that any functions it contains will\n * have sourcemap information attached to errors thrown during their execution.\n *\n * The wrapping of functions helps in debugging by associating errors with their source maps.\n *\n * @param file - The path to the configuration file that needs to be parsed and transpiled.\n *\n * @returns A promise that resolves to the parsed and transpiled `ConfigurationInterface` object.\n * This object has its functions wrapped to attach sourcemap information to any errors thrown.\n *\n * @throws Will throw an error if the transpilation or execution of the configuration file fails.\n * The thrown error will have sourcemap information attached if available.\n *\n * @async\n *\n * @example\n * ```typescript\n * const config = await parseConfigurationFile('./config.jet.ts');\n * console.log(config);\n * ```\n */\n\nexport async function parseConfigurationFile(file: string): Promise<ConfigurationInterface> {\n const { code, sourceMap } = await transpileFile(file, {\n banner: { js: '(function(module, exports) {' },\n footer: { js: '})(module, module.exports);' }\n });\n\n const module: ModuleInterface = { exports: {} };\n const require = createRequire(import.meta.url);\n const source = new SourceService(JSON.parse(atob(sourceMap)));\n\n try {\n await sandboxExecute(code, {\n require,\n module\n });\n } catch (error: unknown) {\n throw new VMRuntimeError(<ErrorType> error, source);\n }\n\n return wrapConfigFunctionsWithSourcemap(<ConfigurationInterface> module.exports.default, source);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Context } from 'vm';\n\n/**\n * Imports\n */\n\nimport { Script, createContext } from 'vm';\n\n/**\n * Executes JavaScript code within a sandboxed environment using Node.js's `vm` module.\n *\n * @param code - The JavaScript code to be executed within the sandbox.\n * @param sandbox - An optional context object to be used as the global scope for the executed code.\n *\n * @returns The result of executing the provided code within the sandboxed environment.\n *\n * @remarks\n * The `sandboxExecute` function creates a new `Script` instance with the provided code and\n * runs it within a sandboxed context using the `createContext` function from the `vm` module.\n * This approach ensures that the executed code is isolated from the rest of the application,\n * mitigating potential security risks.\n *\n * The `sandbox` parameter allows you to provide a custom context or global object for the\n * sandboxed code. If not provided, an empty context is used. The function also supports\n * breaking execution on interrupt signals (e.g., Ctrl+C) with the `breakOnSigint` option.\n *\n * @throws {Error} Throws an error if the code cannot be compiled or executed within the context.\n *\n * @example\n * ```typescript\n * const result = sandboxExecute('return 2 + 2;', { myGlobal: 10 });\n * console.log(result); // Output: 4\n * ```\n *\n * In this example, the `sandboxExecute` function runs a simple JavaScript expression and returns\n * the result. The `sandbox` parameter is provided with an empty object in this case.\n *\n * @public\n * @category Services\n */\n\nexport function sandboxExecute(code: string, sandbox: Context = {}) {\n sandbox.console = console;\n const script = new Script(code);\n const context = createContext(sandbox);\n\n return script.runInContext(context, { breakOnSigint: true });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigurationInterface } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { join } from 'path';\nimport { mkdirSync, writeFileSync } from 'fs';\n\n/**\n * Generates a `package.json` file with the appropriate `type` field\n * based on the format specified in the configuration.\n *\n * - If the format is `esm`, the `type` will be set to `\"module\"`.\n * - If the format is `cjs`, the `type` will be set to `\"commonjs\"`.\n *\n * The function will ensure that the specified output directory exists, and if it doesn't,\n * it will create the necessary directories before writing the `package.json` file.\n *\n * @param config - The build configuration object containing\n * esbuild-related settings, such as the format (`format`).\n *\n * - `config.esbuild.format`: The module format, either `'esm'` or `'cjs'`, that determines the `type` field.\n *\n * @throws Will throw an error if there is a problem creating the directory or writing the file.\n *\n * Example usage:\n *\n * ```ts\n * const config = {\n * esbuild: {\n * format: 'esm'\n * }\n * };\n * packageTypeComponent(config);\n * // This will create 'dist/package.json' with the content: {\"type\": \"module\"}\n * ```\n */\n\nexport function packageTypeComponent(config: ConfigurationInterface): void {\n const outDir = config.moduleTypeOutDir ?? config.esbuild.outdir ?? 'dist';\n const type = config.esbuild.format === 'esm' ? 'module' : 'commonjs';\n\n mkdirSync(outDir, { recursive: true });\n writeFileSync(join(outDir, 'package.json'), `{\"type\": \"${ type }\"}`);\n}\n", "#!/usr/bin/env node\n\n/**\n * Exports\n */\n\nexport type * from '@configuration/interfaces/configuration.interface';\nexport type { BuildResult, OnLoadArgs, OnLoadResult, OnResolveArgs, OnResolveResult, PluginBuild } from 'esbuild';\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';\nimport type { ArgvInterface } from '@services/interfaces/cli.interface';\n\n/**\n * Imports\n */\n\nimport '@errors/stack.error';\nimport '@errors/uncaught.error';\nimport { argvParser } from '@services/cli.service';\nimport { BuildService } from '@services/build.service';\nimport { bannerComponent } from '@components/banner.component';\nimport { configuration } from '@providers/configuration.provider';\n\n/**\n * Clean cli\n */\n\nglobal.__ACTIVE_COLOR = true;\nconsole.log(bannerComponent());\n\n/**\n * Main run\n */\n\nasync function run() {\n const cli = argvParser(process.argv);\n const args = <ArgvInterface> cli.argv;\n const configs = await configuration(args.config, cli);\n const buildPromises = configs.map(async (config): Promise<void> => {\n const build = new BuildService(config);\n if (args.typeCheck)\n return build.typeScriptProvider.typeCheck(true);\n\n if (args.serve || config.serve.active)\n return await build.serve();\n\n if (Array.isArray(args.debug)) {\n if (args.debug.length < 1) {\n args.debug = [ 'index' ];\n }\n\n return await build.runDebug(args.debug);\n }\n\n await build.run();\n });\n\n // Wait for all build promises to resolve\n await Promise.all(buildPromises);\n}\n\n/**\n * Run entrypoint of xBuild\n */\n\nrun().catch((error: VMRuntimeError & xBuildError) => {\n console.error(error.stack);\n});\n"],
|
|
6
|
-
"mappings": ";AAYA,OAAS,OAAAA,OAAW,UACpB,OAAS,gBAAAC,OAAoB,KAC7B,OAAS,iBAAAC,OAAqB,MAC9B,OAAS,WAAAC,EAAS,QAAAC,GAAM,WAAAC,MAAe,OCiDhC,SAASC,EAASC,EAAeC,EAAaC,EAAuB,eAAwB,CAChG,OAAKA,EAGE,GAAGF,CAAK,GAAGC,CAAG,UAFVA,CAGf,CDpDA,OAAS,iBAAAE,GAAe,mBAAAC,GAAiB,iBAAAC,OAAqB,qBAM9D,IAAMC,EAAUC,GAAI,EACdC,EAAWC,EAAQC,GAAc,YAAY,GAAG,CAAC,EACjDC,GAAWF,EAAQD,CAA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U,MAAMC,GAAcF,EAAK,OAAQF,CAAG,GACtB,IAAI,MAAOK,GAA0B,CAC/D,IAAMC,EAAQ,IAAIC,EAAaF,CAAM,EACrC,GAAIH,EAAK,UACL,OAAOI,EAAM,mBAAmB,UAAU,EAAI,EAElD,GAAIJ,EAAK,OAASG,EAAO,MAAM,OAC3B,OAAO,MAAMC,EAAM,MAAM,EAE7B,GAAI,MAAM,QAAQJ,EAAK,KAAK,EACxB,OAAIA,EAAK,MAAM,OAAS,IACpBA,EAAK,MAAQ,CAAE,OAAQ,GAGpB,MAAMI,EAAM,SAASJ,EAAK,KAAK,EAG1C,MAAMI,EAAM,IAAI,CACpB,CAAC,EAGD,MAAM,QAAQ,IAAIH,CAAa,CACnC,CAMAJ,GAAI,EAAE,MAAOS,GAAwC,CACjD,QAAQ,MAAMA,EAAM,KAAK,CAC7B,CAAC",
|
|
7
|
-
"names": ["cwd", "readFileSync", "fileURLToPath", "dirname", "join", "resolve", "setColor", "color", "msg", "activeColor", "SourceService", "formatErrorCode", "highlightCode", "cliPath", "cwd", "distPath", "dirname", "fileURLToPath", "rootPath", "xBuildLazy", "cachedSourceService", "sourceMapData", "readFileSync", "join", "modifyFilePathWithSourceRoot", "source", "sourceRoot", "line", "formatErrorLine", "name", "file", "column", "frame", "asyncPrefix", "formattedName", "position", "setColor", "extractFrameDetails", "typeName", "functionName", "highlightPositionCode", "error", "highlightedCode", "formatStackEntry", "state", "isXBuildService", "dirPath", "posLine", "posColumn", "resolve", "formattedStackEntries", "stackEntries", "formatStackTrace", "stackTrace", "originalPrepareStackTrace", "error", "reason", "yargs", "hideBin", "argvParser", "argv", "cli", "helpText", "dirname", "resolve", "build", "context", "process_spawn", "spawn", "filePath", "debug", "args", "processInstance", "data", "BaseError", "_BaseError", "message", "sourceMap", "error", "formatStackTrace", "esBuildError", "_esBuildError", "BaseError", "message", "asciiLogo", "bannerComponent", "activeColor", "setColor", "asciiLogo", "prefix", "VMRuntimeError", "_VMRuntimeError", "BaseError", "originalError", "sourceMap", "http", "https", "server_default", "extname", "join", "resolve", "existsSync", "readdir", "readFile", "readFileSync", "stat", "fileIcons", "ServerProvider", "config", "dir", "resolve", "req", "res", "prefix", "options", "server", "setColor", "defaultHandler", "error", "ext", "requestPath", "fullPath", "join", "stats", "msg", "path", "reject", "err", "files", "fileList", "file", "extname", "icon", "color", "server_default", "contentType", "data", "promises", "resolve", "PluginsProvider", "fn", "build", "result", "hook", "status", "buildResult", "args", "hookResult", "filePath", "parseIfDefConditionals", "contents", "defines", "match", "condition", "code", "relative", "resolveAliasPlugin", "content", "sourceFile", "paths", "esm", "importExportRegex", "key", "relativePath", "match", "p1", "cwd", "build", "xBuildError", "_xBuildError", "BaseError", "message", "options", "defaultBuildOptions", "extractSourceMap", "dataString", "sourceMapRegex", "match", "xBuildError", "sourceMap", "transpileFile", "filePath", "buildOptions", "options", "cwd", "fileContent", "build", "analyzeDependencies", "entryPoint", "platform", "TypesError", "_TypesError", "message", "options", "resolve", "relative", "dirname", "parse", "
|
|
3
|
+
"sources": ["../src/errors/stack.error.ts", "../src/components/colors.component.ts", "../src/errors/uncaught.error.ts", "../src/services/cli.service.ts", "../src/services/build.service.ts", "../src/services/process.service.ts", "../src/errors/base.error.ts", "../src/errors/esbuild.error.ts", "../src/components/banner.component.ts", "../src/errors/vm-runtime.error.ts", "../src/providers/server.provider.ts", "../src/providers/html/server.html", "../src/providers/plugins.provider.ts", "../src/plugins/ifdef.plugin.ts", "../src/plugins/resolve-alias.plugin.ts", "../src/services/transpiler.service.ts", "../src/errors/xbuild.error.ts", "../src/errors/types.error.ts", "../src/providers/typescript.provider.ts", "../src/providers/configuration.provider.ts", "../src/configuration/default.configuration.ts", "../src/configuration/parse.configuration.ts", "../src/services/vm.service.ts", "../src/components/entry-points.component.ts", "../src/components/package-type.component.ts", "../src/index.ts"],
|
|
4
|
+
"sourceRoot": "https://github.com/remotex-lab/xBuild/tree/v1.3.3/",
|
|
5
|
+
"sourcesContent": ["/**\n * Import will remove at compile time\n */\n\nimport type { BaseError } from '@errors/base.error';\nimport type { PositionWithCodeInterface } from '@remotex-labs/xmap';\nimport type { ErrorType, FrameDetailsInterface, StackTraceStateInterface } from '@errors/interfaces/stack.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join, resolve } from 'path';\nimport { Colors, setColor } from '@components/colors.component';\nimport { SourceService, formatErrorCode, highlightCode } from '@remotex-labs/xmap';\n\n/**\n * Defines\n */\n\nconst cliPath = cwd();\nconst distPath = dirname(fileURLToPath(import.meta.url));\nconst rootPath = dirname(distPath);\nexport const xBuildLazy = (() => {\n let cachedSourceService: SourceService;\n\n return {\n get service() {\n if (!cachedSourceService) {\n // Lazy loading the sourceMap\n const sourceMapData = readFileSync(join(distPath, 'index.js.map'));\n cachedSourceService = new SourceService(sourceMapData.toString(), import.meta.url);\n }\n\n return cachedSourceService;\n }\n };\n})();\n\nif (!global.__ACTIVE_COLOR) {\n global.__ACTIVE_COLOR = true;\n}\n\n/**\n * Modifies the file path by applying the source root and appending the line number.\n *\n * @param source - The original full file path.\n * @param sourceRoot - The source root to be applied to the file path.\n * @param line - The line number point ot in the file.\n * @param rootPath - The project root directory to remove from the path.\n * @returns The modified file path with the source root applied and line number appended.\n */\n\nfunction modifyFilePathWithSourceRoot(source: string, sourceRoot: string, line: number, rootPath: string): string {\n return `${ source.replace(`${ rootPath }\\\\`, sourceRoot).replace(/\\\\/g, '/') }#L${ line }`;\n}\n\n/**\n * Formats a single error line for the stack trace.\n *\n * @param name - The name of the function.\n * @param file - The file name.\n * @param line - The line number.\n * @param column - The column number.\n * @param frame - The frame call stack\n * @returns The formatted error line as a string.\n */\n\nfunction formatErrorLine(name: string, file: string, line: number, column: number, frame: NodeJS.CallSite): string {\n if (frame.isPromiseAll())\n return `at async Promise.all (index: ${ frame.getPromiseIndex() })`;\n\n const asyncPrefix = frame.isAsync() ? 'async' : '';\n const formattedName = name ? `${ asyncPrefix } ${ name }` : asyncPrefix;\n const position = (line >= 0 && column >= 0) ? setColor(Colors.Gray, `[${ line }:${ column }]`) : '';\n\n return `at ${ formattedName } ${ setColor(Colors.DarkGray, file) } ${ position }`\n .replace(/\\s{2,}/g, ' ').trim();\n}\n\n/**\n * Extracts details such as function name, file name, line, and column from a stack frame.\n *\n * @param frame - The call site from the stack trace.\n * @returns An object containing function name, file name, line number, and column number.\n */\n\nfunction extractFrameDetails(frame: NodeJS.CallSite): FrameDetailsInterface {\n const line = frame.getLineNumber() || -1;\n const column = frame.getColumnNumber() || -1;\n const source = frame.getFileName() || '<anonymous>';\n const typeName = frame.getTypeName() || '';\n const functionName = frame.getFunctionName() || '';\n\n let name = frame.isNative() ? '<native>' : functionName;\n if (typeName)\n name = `${ typeName }.${ name }`;\n\n return { functionName: name, source, line, column };\n}\n\n/**\n * Highlights the code at a given position and formats it for display.\n *\n * @param position - The position containing the code to be highlighted. It must implement the `PositionWithCodeInterface`.\n * @param error - The error object that may be modified if a TypeError is detected. It should be of type `ErrorType`.\n * @returns The formatted highlighted code as a string, incorporating any modifications based on the error type.\n */\n\nfunction highlightPositionCode(position: PositionWithCodeInterface, error: ErrorType): string {\n const highlightedCode = __ACTIVE_COLOR ? highlightCode(position.code) : position.code;\n if (position.name && error.name == 'TypeError') {\n error.message = error.message.replace(/^\\S+/, position.name);\n }\n\n return formatErrorCode({ ...position, code: highlightedCode }, {\n color: __ACTIVE_COLOR ? Colors.BrightPink : '',\n reset: __ACTIVE_COLOR ? Colors.Reset : ''\n });\n}\n\n/**\n * Formats a single stack entry from the call stack.\n *\n * @param frame - The call site from the stack trace.\n * @param state - The current state containing error and formatting information.\n * @returns The formatted stack entry as a string.\n */\n\nfunction formatStackEntry(frame: NodeJS.CallSite, state: StackTraceStateInterface): string {\n const { functionName, source, line, column } = extractFrameDetails(frame);\n\n if (frame.isPromiseAll() || frame.isEval() || frame.isNative())\n return formatErrorLine(functionName, source, line, column, frame);\n\n let position: PositionWithCodeInterface | null = null;\n const isXBuildService = source === xBuildLazy.service.file;\n\n if (isXBuildService)\n position = xBuildLazy.service.getPositionWithCode(line, column);\n else if (state.error.sourceMap)\n position = state.error.sourceMap.getPositionWithCode(line, column);\n\n if (position) {\n const dirPath = isXBuildService ? distPath : cliPath;\n const { line: posLine, column: posColumn, name } = position;\n let source = resolve(dirPath, position.source);\n\n if (!state.blockCode)\n state.blockCode = highlightPositionCode(position, state.error);\n\n if (position.sourceRoot)\n source = modifyFilePathWithSourceRoot(\n resolve(dirPath, position.source),\n position.sourceRoot,\n position.line,\n isXBuildService ? rootPath : cliPath\n );\n\n return formatErrorLine(name || functionName, source, posLine, posColumn, frame);\n }\n\n if (source === 'evalmachine.<anonymous>')\n return '';\n\n return formatErrorLine(functionName, source, line, column, frame);\n}\n\n/**\n * Formats all stack entries into an array of strings for display.\n *\n * @param state - The current state containing error and formatting information.\n * @param stackEntries - The array of stack entries from the call stack.\n * @returns An array of formatted stack entry strings.\n */\n\nfunction formattedStackEntries(state: StackTraceStateInterface, stackEntries: Array<NodeJS.CallSite>): Array<string> {\n return stackEntries.map((frame) => formatStackEntry(frame, state)).filter(Boolean);\n}\n\n/**\n * Prepares the error stack trace for display.\n *\n * This function overrides the default stack trace preparation to provide a custom format,\n * including enhanced stack trace information and error details.\n *\n * @param error - The error object (Error or BaseError).\n * @param stackEntries - The array of stack entries from the call stack.\n * @returns The formatted stack trace as a string.\n */\n\nexport function formatStackTrace(error: ErrorType & BaseError, stackEntries: Array<NodeJS.CallSite>): string {\n const state: StackTraceStateInterface = {\n error: error,\n blockCode: null,\n formattedError: global.__ACTIVE_COLOR ? Colors.Reset : ''\n };\n\n const stackTrace = formattedStackEntries(state, stackEntries);\n state.formattedError += `\\n${ error.name }: \\n${ setColor(Colors.LightCoral, error.message) }\\n\\n`;\n\n if (state.blockCode)\n state.formattedError += `${ state.blockCode }\\n\\n`;\n\n if (stackTrace.length > 0)\n state.formattedError += `Enhanced Stack Trace:\\n${ stackTrace.join('\\n') }\\n`;\n\n return state.formattedError;\n}\n\n// Preserve the original Error.prepareStackTrace function\nconst originalPrepareStackTrace = Error.prepareStackTrace;\n\n/**\n * Custom Error.prepareStackTrace to capture CallSite objects in the error.\n *\n * @param error - The error object being processed.\n * @param stackEntries - An array of CallSite objects representing the stack trace.\n * @returns A string stack trace generated by the original prepareStackTrace function.\n */\n\nError.prepareStackTrace = (error: ErrorType, stackEntries: Array<NodeJS.CallSite>): string => {\n // Attach the stack entries (CallSite objects) to the error object\n error.callStacks = stackEntries;\n\n // Call the original prepareStackTrace to return the standard string representation of the stack\n return originalPrepareStackTrace ? originalPrepareStackTrace(error, stackEntries) : '';\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 * ```typescript\n * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);\n * ```\n *\n * @enum {string}\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 {string} A string with the specified color applied to the message,\n * followed by a reset sequence if `activeColor` is true.\n *\n * @example\n * ```typescript\n * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');\n * console.log(coloredMessage);\n * ```\n *\n * @example\n * ```typescript\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 * Handles uncaught exceptions in the Node.js process.\n *\n * This handler is triggered when an error is thrown that is not caught by any try-catch blocks.\n * It captures such exceptions and logs them to the console. If the exception is an instance of `Error`,\n * its string representation is logged. Otherwise, the raw error object is logged.\n *\n * This setup helps in debugging by ensuring that all uncaught exceptions are logged, providing visibility\n * into errors that might otherwise go unnoticed.\n *\n * @example\n * ```ts\n * process.on('uncaughtException', (error) => {\n * if (error instanceof Error) {\n * console.error(error.toString());\n * } else {\n * console.error(error);\n * }\n * });\n * ```\n *\n * @throws Will log uncaught exceptions to the console.\n * Custom handling logic should be added if additional error handling or logging is required.\n */\n\nprocess.on('uncaughtException', (error: Error) => {\n console.error(error.stack);\n});\n\n/**\n * Handles unhandled promise rejections in the Node.js process.\n *\n * This handler is triggered when a promise is rejected, and no rejection handler is attached to it.\n * It captures such rejections and logs them to the console. If the rejection reason is an instance of `Error`,\n * its string representation is logged. Otherwise, the raw rejection reason is logged.\n *\n * This setup helps in debugging by ensuring that all unhandled promise rejections are logged, providing visibility\n * into issues related to unhandled promises that might otherwise go unnoticed.\n *\n * @example\n * ```ts\n * process.on('unhandledRejection', (reason) => {\n * if (reason instanceof Error) {\n * console.error(reason.toString());\n * } else {\n * console.error(reason);\n * }\n * });\n * ```\n *\n * @throws Will log unhandled promise rejections to the console.\n * Custom handling logic should be added if additional handling or logging is required.\n */\n\nprocess.on('unhandledRejection', (reason: Error) => {\n console.error(reason.stack);\n});\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Argv } from 'yargs';\nimport type { ArgvInterface } from '@services/interfaces/cli.interface';\n\n/**\n * Imports\n */\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\n\n/**\n * Parses command-line arguments into an `ArgvInterface` object using `yargs`.\n *\n * This function configures `yargs` to handle various build-related options for a JavaScript and TypeScript toolchain.\n * It returns an object that adheres to the `ArgvInterface` structure based on the parsed arguments.\n *\n * @param argv - An array of command-line arguments (e.g., `process.argv`).\n * @returns An object representing the parsed command-line arguments.\n *\n * @see {@link ArgvInterface} for the structure of the returned object.\n *\n * @example\n * // Example usage:\n * const args = argvParser(process.argv);\n * console.log(args.file); // Output: the file to build\n * console.log(args.dev); // Output: true or false based on the --dev flag\n */\n\nexport function argvParser(argv: Array<string>): Argv<ArgvInterface> {\n const cli = yargs(hideBin(argv))\n .command('$0 [file]', 'A versatile JavaScript and TypeScript toolchain build system.', (yargs) => {\n yargs\n .positional('entryPoints', {\n describe: 'The file entryPoints to build',\n type: 'string'\n })\n .option('typeCheck', {\n describe: 'Perform type checking',\n alias: 'tc',\n type: 'boolean'\n })\n .option('node', {\n alias: 'n',\n describe: 'Build for node platform',\n type: 'boolean'\n })\n .option('dev', {\n alias: 'd',\n describe: 'Array entryPoints to run as development in Node.js',\n type: 'array'\n })\n .option('debug', {\n alias: 'db',\n describe: 'Array entryPoints to run in Node.js with debug state',\n type: 'array'\n })\n .option('serve', {\n alias: 's',\n describe: 'Serve the build folder over HTTP',\n type: 'boolean'\n })\n .option('outdir', {\n alias: 'o',\n describe: 'Output directory',\n type: 'string'\n })\n .option('declaration', {\n alias: 'de',\n describe: 'Add TypeScript declarations',\n type: 'boolean'\n })\n .option('watch', {\n alias: 'w',\n describe: 'Watch for file changes',\n type: 'boolean'\n })\n .option('config', {\n alias: 'c',\n describe: 'Build configuration file (js/ts)',\n type: 'string',\n default: 'xbuild.config.ts'\n })\n .option('tsconfig', {\n alias: 'tsc',\n describe: 'Set TypeScript configuration file to use',\n type: 'string',\n default: 'tsconfig.json'\n })\n .option('minify', {\n alias: 'm',\n describe: 'Minify the code',\n type: 'boolean'\n })\n .option('bundle', {\n alias: 'b',\n describe: 'Bundle the code',\n type: 'boolean'\n })\n .option('noTypeChecker', {\n alias: 'ntc',\n describe: 'Skip TypeScript type checking',\n type: 'boolean'\n })\n .option('buildOnError', {\n alias: 'boe',\n describe: 'Continue building even if there are TypeScript type errors',\n type: 'boolean'\n })\n .option('format', {\n alias: 'f',\n describe: 'Defines the format for the build output (\\'cjs\\' | \\'esm\\' | \\'iif\\').',\n type: 'string'\n })\n .option('version', {\n alias: 'v',\n describe: 'Show version number',\n type: 'boolean',\n default: false,\n conflicts: 'help'\n });\n })\n .help()\n .alias('help', 'h')\n .version(false) // Disable the default version behavior\n .middleware((argv) => {\n if (argv.version) {\n // todo fix the banner and color\n process.exit(0);\n }\n });\n\n // Custom help message with version info at the top\n cli.showHelp((helpText) => {\n if (process.argv.includes('--help') || process.argv.includes('-h')) {\n console.log(helpText + '\\n\\n');\n process.exit(0); // Ensure the process exits after showing help\n }\n });\n\n return <Argv<ArgvInterface>> cli;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { ConfigurationInterface } from '@configuration/interfaces/configuration.interface';\nimport type { BuildContext, BuildResult, Message, Metafile, OnEndResult, PluginBuild, SameShape } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { dirname, resolve } from 'path';\nimport { build, context } from 'esbuild';\nimport { spawn } from '@services/process.service';\nimport { esBuildError } from '@errors/esbuild.error';\nimport { prefix } from '@components/banner.component';\nimport { VMRuntimeError } from '@errors/vm-runtime.error';\nimport { ServerProvider } from '@providers/server.provider';\nimport { PluginsProvider } from '@providers/plugins.provider';\nimport { parseIfDefConditionals } from '@plugins/ifdef.plugin';\nimport { Colors, setColor } from '@components/colors.component';\nimport { resolveAliasPlugin } from '@plugins/resolve-alias.plugin';\nimport { analyzeDependencies } from '@services/transpiler.service';\nimport { TypeScriptProvider } from '@providers/typescript.provider';\nimport { tsConfiguration } from '@providers/configuration.provider';\nimport { extractEntryPoints } from '@components/entry-points.component';\nimport { packageTypeComponent } from '@components/package-type.component';\nimport type { BuildState } from '@providers/interfaces/plugins.interfaces';\n\n/**\n * Manages the build process for a TypeScript project using esbuild.\n *\n * The `BuildService` class orchestrates the build process, including TypeScript compilation, handling of build errors,\n * and lifecycle management of the build. It can operate in various modes, such as watching for file changes or running\n * in development mode. It also provides functionality for spawning development processes and processing entry points.\n *\n * @remarks\n * - The build process can be configured using the provided `ConfigurationInterface`.\n * - Errors related to TypeScript are handled separately and are not logged by default.\n * - The class supports various build modes, including watch mode and development mode, and handles different scenarios\n * based on the configuration.\n *\n * @public\n * @category Services\n */\n\nexport class BuildService {\n /**\n * Provides TypeScript-related functionality for the build process.\n */\n\n readonly typeScriptProvider: TypeScriptProvider;\n\n /**\n * Keeps track of active development processes spawned during the build.\n * This property holds an array of `ChildProcessWithoutNullStreams` instances that represent Node.js processes spawned\n * for running development tasks. These processes are used to handle development builds or runtime tasks and are managed\n * by the `BuildService` class to ensure they are properly started and stopped.\n *\n * @private\n * @type {Array<ChildProcessWithoutNullStreams>}\n *\n * @remarks\n * - The array is populated when development processes are spawned, such as when specific development files are\n * processed or when running in development mode.\n * - The processes are terminated gracefully at the end of the build to avoid leaving orphaned processes running.\n * - It is important to manage these processes correctly to avoid resource leaks and ensure proper cleanup.\n */\n\n private activePossess: Array<ChildProcessWithoutNullStreams> = [];\n\n /**\n * Plugin provider\n *\n * @private\n */\n\n private pluginsProvider: PluginsProvider;\n\n /**\n * Initializes the build service with the provided configuration.\n *\n * The constructor configures the TypeScript provider, suppresses esbuild logging,\n * sets up development modes, and registers the necessary plugins.\n *\n * Declaration files will be output based on the following order of precedence:\n * 1. If `declarationOutDir` is set in the configuration, it will be used.\n * 2. If `declarationOutDir` is not provided, it will use the `outDir` value from the tsconfig.\n * 3. If neither of the above is available, it falls back to using the `outdir` specified in the esbuild configuration.\n *\n * @param config - The configuration object for the build process, including esbuild and TypeScript settings.\n */\n\n constructor(private config: ConfigurationInterface) {\n const tsConfig = tsConfiguration(this.config.esbuild);\n\n this.config.esbuild.logLevel = 'silent';\n this.pluginsProvider = new PluginsProvider();\n this.typeScriptProvider = new TypeScriptProvider(\n tsConfig, this.config.declarationOutDir ?? tsConfig.options.outDir ?? this.config.esbuild.outdir!\n );\n\n this.configureDevelopmentMode();\n this.setupPlugins();\n }\n\n /**\n * Executes the build process.\n * This method performs the build and handles any errors that occur. If watching or development mode is enabled,\n * it starts watching for changes. It logs errors that are not related to TypeScript.\n *\n * @returns A promise that resolves when the build process is complete.\n *\n * @throws {Error} Throws an error if the build process encounters issues not related to TypeScript.\n *\n * @example\n * ```typescript\n * import { BuildService } from './build-service';\n *\n * const buildService = new BuildService(config);\n * buildService.run().then(() => {\n * console.log('Build process completed successfully.');\n * }).catch((error) => {\n * console.error('Build process failed:', error);\n * });\n * ```\n *\n * In this example, the `run` method is used to execute the build process. It handles both successful completion\n * and errors.\n */\n\n async run(): Promise<void> {\n return await this.execute(async () => {\n const result = await this.build();\n if (this.config.watch || this.config.dev) {\n await (<BuildContext> result).watch();\n }\n });\n }\n\n /**\n * Runs the build process in debug mode for the specified entry points.\n * This method temporarily disables development and watch mode, initiates the build process, and spawns development processes\n * for the specified entry points. If any errors occur during the build, they are handled appropriately.\n *\n * @param entryPoints - An array of entry point file names for which the development processes will be spawned.\n * These entry points are matched against the build output files.\n *\n * @returns A `Promise<void>` that resolves when the build and process spawning have completed.\n *\n * @throws Handles any build-related errors using the `handleErrors` method.\n *\n * @remarks\n * - The `config.dev` and `config.watch` settings are temporarily disabled to prevent development mode or file watching during the build.\n * - The `build()` method is called to generate the necessary build outputs.\n * - The `spawnDev` method is then invoked to spawn processes for the matching entry points.\n * - If any errors occur during the build, they are caught and passed to the `handleErrors` method.\n *\n * @example\n * ```typescript\n * const entryPoints = ['index', 'main'];\n * await this.runDebug(entryPoints);\n * ```\n *\n * In this example, the `runDebug` method runs the build process and spawns development processes for `index` and `main`.\n *\n * @public\n */\n\n async runDebug(entryPoints: Array<string>): Promise<void> {\n return await this.execute(async () => {\n this.config.dev = false;\n this.config.watch = false;\n const result = <BuildResult> await this.build();\n this.spawnDev(<Metafile> result.metafile, entryPoints, true);\n });\n }\n\n /**\n * Serves the project and watches for changes.\n * This method starts the development server using the `ServerProvider`, builds the project using esbuild,\n * and watches for file changes to automatically rebuild as needed. It initializes the server and invokes\n * the build process, enabling continuous development mode.\n *\n * @returns A promise that resolves when the server is started and the build process is complete.\n *\n * @throws This method catches any errors thrown during the build process and handles them using the\n * `handleErrors` method.\n *\n * @example\n * ```typescript\n * const buildService = new BuildService(config);\n * buildService.serve().then(() => {\n * console.log('Server is running and watching for changes.');\n * }).catch((error) => {\n * console.error('Failed to start the server:', error);\n * });\n * ```\n *\n * In this example, the `serve` method starts the server and watches for changes. If an error occurs during\n * the build or server startup, it is handled and logged.\n */\n\n async serve(): Promise<void> {\n const server = new ServerProvider(this.config.serve, this.config.esbuild.outdir ?? '');\n\n return await this.execute(async () => {\n server.start();\n const result = await this.build();\n await (<BuildContext> result).watch();\n });\n }\n\n /**\n * Executes a provided callback function within a try-catch block.\n * This method ensures that any errors thrown during the execution of the callback\n * are properly handled. If the error is related to esbuild's `OnEndResult` and contains\n * an array of errors, it skips additional logging. Otherwise, it logs the error using\n * a custom `VMRuntimeError`.\n *\n * @param callback - A function that returns a `Promise<void>`, which is executed asynchronously.\n * This callback is wrapped in error handling logic.\n *\n * @returns A `Promise<void>` which resolves once the callback has been executed.\n * If an error is thrown, it is caught and handled.\n *\n * @throws In case of an error not related to esbuild, the method catches the error,\n * wraps it in a `VMRuntimeError`, and logs the error's stack trace to the console.\n *\n * @example\n * ```ts\n * await execute(async () => {\n * // Perform some asynchronous operation here\n * });\n * ```\n */\n\n private async execute(callback: () => Promise<void>): Promise<void> {\n try {\n await callback();\n } catch (error: unknown) {\n const esbuildError = <OnEndResult> error;\n if (!Array.isArray(esbuildError.errors)) {\n console.error(new VMRuntimeError(<Error> error).stack);\n }\n }\n }\n\n /**\n * Configures the development mode by ensuring that `config.dev` is set properly.\n */\n\n private configureDevelopmentMode(): void {\n if (this.config.dev !== false && (!Array.isArray(this.config.dev) || this.config.dev.length < 1)) {\n this.config.dev = [ 'index' ];\n }\n }\n\n /**\n * Sets up the plugin's provider and registers the plugin hooks.\n */\n\n private setupPlugins(): void {\n const rootDir = resolve(this.typeScriptProvider.options.baseUrl ?? '');\n const paths = this.generatePathAlias(rootDir);\n\n this.registerPluginHooks(paths, rootDir);\n }\n\n /**\n * Registers the plugin hooks for start, end, and load events.\n *\n * @param paths - The resolved path aliases.\n * @param rootDir - The root directory for resolving paths.\n */\n\n private registerPluginHooks(paths: Record<string, string>, rootDir: string): void {\n this.pluginsProvider.registerOnEnd(this.end.bind(this));\n this.pluginsProvider.registerOnStart(this.start.bind(this));\n\n this.pluginsProvider.registerOnLoad((content, loader, args) => {\n if (!args.path.endsWith('.ts')) return;\n\n if (!this.config.esbuild.bundle) {\n const sourceFile = dirname(resolve(args.path).replace(rootDir, '.'));\n content = resolveAliasPlugin(content.toString(), sourceFile, paths, this.config.esbuild.format === 'esm');\n }\n\n return {\n loader: 'ts',\n contents: parseIfDefConditionals(content.toString(), this.config.define)\n };\n });\n }\n\n /**\n * Generates a path alias object from the TypeScript provider's path options.\n * This method processes the `paths` property from the TypeScript provider's options,\n * which is expected to be an object where each key represents a path alias pattern,\n * and the corresponding value is an array of paths. The method removes any wildcard\n * characters (`*`) from both the keys and the first values of the arrays. It also\n * resolves the paths relative to the specified `rootDir`, returning a simplified\n * object that maps the cleaned keys to their respective paths.\n *\n * The resolved paths will be formatted to use a relative path notation.\n *\n * Example:\n * Given the following paths:\n * ```typescript\n * {\n * '@core/*': ['src/core/*'],\n * '@utils/*': ['src/utils/*']\n * }\n * ```\n * And assuming `rootDir` is set to the base directory of your project, the method\n * will return:\n * ```typescript\n * {\n * '@core/': './core/',\n * '@utils/': './utils/'\n * }\n * ```\n *\n * @param {string} rootDir - The root directory to resolve paths against.\n * @returns {Record<string, string>} An object mapping cleaned path aliases to their respective resolved paths.\n */\n\n private generatePathAlias(rootDir: string): Record<string, string> {\n const paths = this.typeScriptProvider.options.paths;\n const alias: Record<string, string> = {};\n\n for (const key in paths) {\n const valueArray = paths[key];\n if (valueArray.length > 0) {\n const newKey = key.replace(/\\*/g, '');\n alias[newKey] = resolve(valueArray[0].replace(/\\*/g, '')).replace(rootDir, '.');\n }\n }\n\n return alias;\n }\n\n /**\n * Handles errors during the build process.\n * This method processes and logs errors that occur during the esbuild process. It specifically filters out\n * errors related to TypeScript (`TypesError`) to prevent them from being logged, while logging all other errors\n * to the console. The error object is assumed to contain a list of messages, each with detailed information.\n *\n * @param esbuildError - The error object returned by esbuild, which is expected to contain an array of\n * error messages.\n *\n * @private\n *\n * @remarks\n * - TypeScript errors (denoted as `TypesError`) are skipped and not logged.\n * - Other errors are logged to the console with their text descriptions.\n *\n * @example\n * ```typescript\n * try {\n * await buildService.run();\n * } catch (esbuildError) {\n * buildService.handleErrors(esbuildError);\n * }\n * ```\n *\n * In this example, if an error occurs during the build process, the `handleErrors` method is used to\n * process and log the errors.\n */\n\n private handleErrors(esbuildError: OnEndResult): void {\n const errors = esbuildError.errors ?? [];\n for (const error of errors) {\n if (!error.detail) {\n console.error((new esBuildError(<Message> error)).stack);\n continue;\n }\n\n // ignore typescript eslint error\n if (error.detail.name === 'TypesError')\n continue;\n\n if (error.detail.name) {\n if (error.detail.name === 'VMRuntimeError') {\n console.error(error.detail.stack);\n continue;\n }\n\n if (error.detail instanceof Error) {\n console.error(new VMRuntimeError(error.detail).originalErrorStack);\n continue;\n }\n }\n\n return console.error(error.text);\n }\n }\n\n /**\n * Builds the project based on the configuration.\n * Depending on the configuration, this method either uses esbuild's `context` for watching or `build` for a one-time build.\n *\n * @returns A promise that resolves with the build context or result.\n *\n * @private\n */\n\n private async build(): Promise<BuildContext | SameShape<unknown, unknown> | BuildResult> {\n packageTypeComponent(this.config);\n const esbuild = this.config.esbuild;\n\n if (this.config.hooks) {\n this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd);\n this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad);\n this.pluginsProvider.registerOnStart(this.config.hooks.onStart);\n this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve);\n }\n\n if (!esbuild.define) {\n esbuild.define = {};\n }\n\n for (const key in this.config.define) {\n esbuild.define[key] = JSON.stringify(this.config.define[key]);\n }\n\n if (!this.config.esbuild.bundle) {\n await this.processEntryPoints();\n }\n\n esbuild.plugins = [ this.pluginsProvider.setup() ];\n if (this.config.watch || this.config.dev || this.config.serve.active) {\n return await context(esbuild);\n }\n\n return await build(esbuild);\n }\n\n /**\n * Manages development processes for specified entry points.*\n * This method spawns development processes for each file in the metafile that matches any of the specified entry points.\n * It enables features like source maps and optional debugging mode for each spawned process.\n *\n * @param meta - The metafile containing information about build outputs.\n * This typically includes a mapping of output files and their dependencies.\n * @param entryPoint - An array of entry point file names to match against the metafile outputs.\n * Only files that match these entry points will have development processes spawned.\n * @param debug - A boolean flag to enable debugging mode for spawned processes.\n * If `true`, the processes will start in debug mode with the `--inspect-brk` option. Defaults to `false`.\n *\n * @returns void\n *\n * @remarks\n * - Files that contain 'map' in their names (e.g., source map files) are ignored and no process is spawned for them.\n * - For each matching file in the metafile outputs, a new development process is spawned using the `spawn` function.\n * - The `activePossess` array tracks all spawned processes, allowing further management (e.g., termination).\n *\n * @example\n * ```typescript\n * const meta = {\n * outputs: {\n * 'dist/index.js': { \\/* ... *\\/ },\n * 'dist/index.js.map': { \\/* ... *\\/ }\n * }\n * };\n * const entryPoints = ['index'];\n *\n * this.spawnDev(meta, entryPoints, true); // Spawns processes in debug mode\n * ```\n *\n * @private\n */\n\n private spawnDev(meta: Metafile, entryPoint: Array<string>, debug: boolean = false) {\n if (!Array.isArray(entryPoint))\n return;\n\n for (const file in meta.outputs) {\n if (file.includes('map') || !entryPoint.some(key => file.includes(`/${ key }.`)))\n continue;\n\n this.activePossess.push(spawn(file, debug));\n }\n }\n\n /**\n * Starts the build process and type checking.\n * This method performs initial setup for the build and ensures that any child processes are terminated properly.\n *\n * @private\n */\n\n private async start(build: PluginBuild, state: BuildState) {\n try {\n state.startTime = Date.now();\n console.log(`${ prefix() } StartBuild ${ build.initialOptions.outdir }`);\n\n if (this.config.declaration)\n this.typeScriptProvider.generateDeclarations(this.config.noTypeChecker, this.config.buildOnError);\n else if (!this.config.noTypeChecker)\n this.typeScriptProvider.typeCheck(this.config.buildOnError);\n } finally {\n while (this.activePossess.length > 0) {\n const element = this.activePossess.pop();\n if (element)\n element.kill('SIGTERM');\n }\n }\n }\n\n /**\n * Finalizes the build process and logs results.\n * This method handles the end of the build process, logs build results, and processes development files if applicable.\n *\n * @private\n */\n\n private async end(result: BuildResult, state: BuildState) {\n if (result.errors.length > 0) {\n return this.handleErrors(result);\n }\n\n const duration = Date.now() - <number> state.startTime;\n console.log(\n `\\n${ prefix() } ${ setColor(Colors.DeepOrange, `Build completed! in ${ duration } ms`) }`\n );\n console.log(`${ prefix() } ${ Object.keys(result.metafile!.outputs).length } Modules:`);\n Object.keys(result.metafile!.outputs).forEach((output) => {\n const size = result.metafile!.outputs[output].bytes;\n console.log(\n `${ prefix() } ${ setColor(Colors.CanaryYellow, output) }: ${ setColor(Colors.BurntOrange, size.toString()) } bytes`\n );\n });\n\n console.log('\\n');\n if (this.config.dev) {\n this.spawnDev(<Metafile> result.metafile, <Array<string>> this.config.dev);\n }\n }\n\n /**\n * Processes and updates entry points based on project dependencies.\n * This method analyzes the project's dependencies and adjusts entry points configuration as needed.\n *\n * @private\n */\n\n private async processEntryPoints(): Promise<void> {\n const esbuild = this.config.esbuild;\n const meta = await analyzeDependencies(esbuild.entryPoints, esbuild.platform);\n const rootDir = resolve(this.typeScriptProvider.options.baseUrl ?? '');\n\n // it pointer and change the esbuild.entryPoints if is object value from configuration !!\n let entryPoints = extractEntryPoints(esbuild.entryPoints);\n let entryPointsList = Object.values(entryPoints);\n\n if (Array.isArray(esbuild.entryPoints) && typeof esbuild.entryPoints[0] === 'string') {\n entryPoints = {};\n entryPointsList = [];\n }\n\n for (const file in meta.inputs) {\n if (entryPointsList.includes(file))\n continue;\n\n const resolveFile = resolve(file).replace(rootDir, '.');\n const fileName = resolveFile.substring(0, resolveFile.lastIndexOf('.'));\n entryPoints[fileName] = file;\n }\n\n esbuild.entryPoints = entryPoints;\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\n\n/**\n * Imports\n */\n\nimport { spawn as process_spawn } from 'child_process';\n\n/**\n * Spawns a new Node.js process to execute the provided JavaScript file, with optional debugging support.\n *\n * This function creates a new Node.js process to run the specified JavaScript file with source map support enabled.\n * It optionally starts the process in debug mode, which allows WebStorm or other debuggers to attach to the process.\n * The output and error streams of the spawned process are captured and logged to the console.\n *\n * @param filePath - The path to the JavaScript file to execute.\n * @param debug - A boolean flag to enable debugging. If `true`, the process will be started with the `--inspect-brk` option,\n * which opens a debugger on `0.0.0.0:9229`, allowing external debuggers to attach.\n *\n * @returns A `ChildProcessWithoutNullStreams` object representing the spawned process.\n * This object allows interaction with the process, including capturing its output and error streams.\n *\n * @remarks\n * - The `--enable-source-maps` flag is used to enable source map support, which allows better debugging by mapping\n * errors and stack traces to the original source code.\n * - If `debug` is `true`, the `--inspect-brk=0.0.0.0:9229` flag is added, starting the process in debug mode and pausing\n * execution until a debugger is attached.\n * - The output (`stdout`) and error (`stderr`) streams of the spawned process are logged to the console.\n * - The function returns a `ChildProcessWithoutNullStreams` object that can be used to interact with the spawned process,\n * such as handling its termination or sending input.\n *\n * @throws {Error} Throws an error if the Node.js process fails to start or if there are issues with the provided file path.\n *\n * @example\n * ```typescript\n * import { spawn } from '@services/process.service';\n *\n * // Run without debugging\n * const process = spawn('./path/to/script.js', false);\n *\n * process.on('close', (code) => {\n * console.log(`Process exited with code ${code}`);\n * });\n *\n * // Run with debugging enabled\n * const debugProcess = spawn('./path/to/script.js', true);\n *\n * debugProcess.on('close', (code) => {\n * console.log(`Debug process exited with code ${code}`);\n * });\n * ```\n *\n * In these examples, the `spawn` function is used to execute a JavaScript file, once in normal mode and once with debugging enabled.\n * The process's exit code is logged when the process completes.\n *\n * @public\n * @category Services\n */\n\nexport function spawn(filePath: string, debug: boolean = false): ChildProcessWithoutNullStreams {\n const args = [ '--enable-source-maps', filePath ];\n if (debug)\n args.unshift('--inspect-brk=0.0.0.0:0');\n\n const processInstance = process_spawn('node', args);\n\n // Capture stdout\n processInstance.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n\n // Capture stderr\n processInstance.stderr.on('data', (data) => {\n console.error(data.toString());\n });\n\n return processInstance;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { SourceService } from '@remotex-labs/xmap';\nimport type { ErrorType } from '@errors/interfaces/stack.interface';\n\n/**\n * Imports\n */\n\nimport { formatStackTrace } from '@errors/stack.error';\n\n/**\n * A base class for custom errors with enhanced stack trace formatting and source code information.\n *\n * The `BaseError` class extends the native `Error` class, adding functionality to format the error stack\n * trace and include details from a source map service. This is useful for debugging errors in compiled\n * or transpiled code by providing clearer information about the source of the error.\n */\n\nexport abstract class BaseError extends Error {\n callStacks: Array<NodeJS.CallSite> = [];\n\n /**\n * Creates a new instance of `BaseError`.\n *\n * This constructor initializes a new `BaseError` instance by setting the error message and formatting\n * the stack trace using the provided source map information. It also ensures the stack trace is maintained\n * correctly by using `Error.captureStackTrace` (if available). The default source map service is used if\n * none is provided.\n *\n * @param message - A descriptive error message to be associated with the error.\n * @param sourceMap - (Optional) The `SourceService` instance used to format and resolve the stack trace.\n * If not provided, the default source map service (`defaultSourceService`) is used.\n */\n\n protected constructor(message: string, public readonly sourceMap?: SourceService) {\n super(message);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, BaseError);\n }\n\n // Assign the name of the error\n this.name = 'xBuildBaseError';\n }\n\n /**\n * Reformats the error stack trace using source map information.\n *\n * This function enhances the original error stack trace by attempting to map each entry\n * back to its original position in the source file using the provided source map service.\n * If the source map information is not available, it returns the original stack trace.\n *\n * @param error - The original error with stack trace of the error.\n * @returns The reformatted stack trace or the original stack trace if no mapping is available.\n */\n\n protected reformatStack(error: ErrorType): string {;\n if (!error.callStacks)\n return error.stack ?? '';\n\n return formatStackTrace(this, error.callStacks);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Message } from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { BaseError } from '@errors/base.error';\n\n/**\n * Represents an error that occurs during the esbuild process.\n *\n * This class extends the base error class to provide specific error handling for esbuild-related issues.\n * It captures the error message and maintains the proper stack trace, allowing for easier debugging\n * and identification of errors that occur during the build process.\n *\n * @class esbuildError\n * @extends BaseError\n *\n * @param message - An object containing the error message. The `text` property is used to set the\n * error message for the instance.\n *\n * @remarks\n * - This class is designed to handle errors specifically related to the esbuild process.\n * - A placeholder for printing the source code of the error is included for future implementation.\n * - The name of the error is set to 'EsbuildError' for clarity in error handling.\n *\n * @example\n * ```typescript\n * throw new EsbuildError({ text: 'Failed to build module.' });\n * ```\n * In this example, an instance of `EsbuildError` is thrown with a specified error message, which can\n * be caught and handled appropriately.\n *\n * @public\n */\n\nexport class esBuildError extends BaseError {\n /**\n * Creates an instance of the EsbuildError class.\n *\n * This constructor initializes the error message using the provided `message` object, captures\n * the stack trace for better debugging, and sets the name of the error to 'EsbuildError'.\n *\n * @param message - An object containing the error message. The `text` property is used to initialize\n * the base error class with a descriptive message about the error encountered during the esbuild process.\n *\n * @remarks\n * - The constructor includes a placeholder for future implementation of printing the source code related\n * to the error.\n * - The stack trace is captured to maintain the context of the error's origin, allowing developers\n * to trace back to the point of failure in the code.\n *\n * @public\n */\n\n constructor(message: Message) {\n super(message.text);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, esBuildError);\n }\n\n // Assign the name of the error\n this.name = 'EsbuildError';\n\n if (!message.location)\n return;\n\n // const location = message.location;\n // this.stackArray = this.getFormattedStackEntries([{\n // at: '',\n // line: location.line,\n // column: location.column,\n // file: location.file\n // }], this.sourceMap);\n //\n // const highlightedCode = __ACTIVE_COLOR ? highlightCode(location.lineText) : location.lineText;\n // this.blockCode = formatErrorCode({\n // line: location.line,\n // name: null,\n // column: location.column + 1,\n // source: location.file,\n // endLine: location.line + 1,\n // startLine: location.line - 1,\n // sourceRoot: location.file,\n // code: highlightedCode\n // }, {\n // color: __ACTIVE_COLOR ? Colors.BrightPink : '',\n // reset: __ACTIVE_COLOR ? Colors.Reset : ''\n // });\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 * ```typescript\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 * ```typescript\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 * Todo \\r${ activeColor ? cleanScreen : '' }\n *\n * @public\n */\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", "/**\n * Import will remove at compile time\n */\n\nimport type { SourceService } from '@remotex-labs/xmap';\nimport type { ErrorType } from '@errors/interfaces/stack.interface';\n\n/**\n * Imports\n */\n\nimport { BaseError } from '@errors/base.error';\n\n/**\n * A custom error class to handle errors occurring within a virtual machine (VM) execution context.\n *\n * The `VMRuntimeError` class extends the native `Error` class and enhances the error with\n * source map information to map stack traces back to the original source. This is particularly\n * useful when debugging errors from code executed in a `vm` or `evalmachine` environment.\n *\n * @param message - The error message describing the error.\n * @param originalError - The original error object thrown from the VM execution.\n * @param sourceMap - The `SourceService` providing source map data to link the error to its original source.\n *\n * @example\n * ```typescript\n * try {\n * vm.run(someCode);\n * } catch (error) {\n * throw new VMRuntimeError(\"VM execution failed\", error, sourceMapService);\n * }\n * ```\n */\n\nexport class VMRuntimeError extends BaseError {\n /**\n * The original error thrown during the VM execution.\n */\n\n originalError: Error;\n\n /**\n * Original error stack\n */\n\n originalErrorStack: string | undefined;\n\n /**\n * Creates a new VMRuntimeError instance.\n *\n * This constructor initializes a new `VMRuntimeError` object, extending the native `Error` class with\n * additional information, including the original error and optional source map data. It also ensures that\n * the stack trace is correctly captured and reformatted using the source map (if provided) to enhance\n * debugging.\n *\n * @param originalError - The original error object that was thrown during the VM execution.\n * @param sourceMap - (Optional) The source map service used to map the error stack trace to its original\n * source code locations. If not provided, this will be `null`.\n *\n * @example\n * ```typescript\n * try {\n * vm.run(code);\n * } catch (error) {\n * throw new VMRuntimeError(error, sourceMapService);\n * }\n * ```\n */\n\n constructor(originalError: ErrorType, sourceMap?: SourceService) {\n // Pass the message to the base class Error\n super(originalError.message, sourceMap);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, VMRuntimeError);\n }\n\n // Store the original error\n this.originalError = originalError;\n this.originalErrorStack = originalError.stack;\n\n // Assign the name of the error\n this.name = 'VMRuntimeError';\n this.stack = this.reformatStack(originalError);\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Stats } from 'fs';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { Serve } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport * as http from 'http';\nimport * as https from 'https';\nimport html from './html/server.html';\nimport { extname, join, resolve } from 'path';\nimport { prefix } from '@components/banner.component';\nimport { Colors, setColor } from '@components/colors.component';\nimport { existsSync, readdir, readFile, readFileSync, stat } from 'fs';\n\n/**\n * A mapping of file extensions to their corresponding icon and color.\n *\n * This record associates common file types with a Font Awesome icon class\n * and a color code for display purposes in a file listing UI. Each file type\n * is represented by an icon and a color that visually distinguishes it.\n *\n * Example:\n * - HTML files are represented by a code icon (`fa-file-code`) with a color of `#d1a65f`.\n * - Image files (e.g., PNG, JPG, GIF) share a common image icon (`fa-file-image`) with a color of `#53a8e4`.\n *\n * @constant\n * @type {Record<string, { icon: string, color: string }>}\n */\n\nconst fileIcons: Record<string, { icon: string, color: string }> = {\n html: { icon: 'fa-file-code', color: '#d1a65f' },\n css: { icon: 'fa-file-css', color: '#264de4' },\n js: { icon: 'fa-file-code', color: '#f7df1e' },\n json: { icon: 'fa-file-json', color: '#b41717' },\n png: { icon: 'fa-file-image', color: '#53a8e4' },\n jpg: { icon: 'fa-file-image', color: '#53a8e4' },\n jpeg: { icon: 'fa-file-image', color: '#53a8e4' },\n gif: { icon: 'fa-file-image', color: '#53a8e4' },\n txt: { icon: 'fa-file-alt', color: '#8e8e8e' },\n folder: { icon: 'fa-folder', color: '#ffb800' }\n};\n\n\n/**\n * Manages the HTTP or HTTPS server based on the provided configuration.\n *\n * The `ServerProvider` class initializes and starts either an HTTP or HTTPS server based on whether SSL certificates\n * are provided. It handles incoming requests, serves static files, and lists directory contents with appropriate\n * icons and colors.\n *\n * @class\n */\n\nexport class ServerProvider {\n /**\n * Root dir to serve\n */\n\n private readonly rootDir: string;\n\n /**\n * Indicates whether the server is configured to use HTTPS.\n */\n\n private readonly isHttps: boolean;\n\n /**\n * The server configuration object, including SSL certificate paths and other settings.\n */\n\n private readonly config: Required<Serve>;\n\n /**\n * Creates an instance of ServerProvider.\n *\n * @param config - The server configuration object, including port number, SSL certificate paths, and an optional request handler.\n * @param dir - The root directory from which to serve files.\n *\n * @example\n * ```typescript\n * import { ServerProvider } from './server-provider';\n *\n * const serverConfig = {\n * port: 8080,\n * keyfile: './path/to/keyfile',\n * certfile: './path/to/certfile',\n * onRequest: (req, res, next) => { /* custom request handling *\\/ }\n * };\n * const provider = new ServerProvider(serverConfig, './public');\n * provider.start();\n * ```\n *\n * This example shows how to create an instance of `ServerProvider` and start the server.\n */\n\n constructor(config: Serve, dir: string) {\n this.rootDir = resolve(dir);\n this.config = <Required<Serve>> config;\n this.isHttps = this.config.keyfile && this.config.certfile\n ? existsSync(this.config.keyfile) && existsSync(this.config.certfile)\n : false;\n }\n\n /**\n * Starts the server based on the configuration.\n * If SSL certificates are provided and valid, an HTTPS server is started. Otherwise, an HTTP server is started.\n *\n * @example\n * ```typescript\n * provider.start();\n * ```\n *\n * This example demonstrates how to start the server. It will either start an HTTP or HTTPS server based on the configuration.\n */\n\n start(): void {\n if (this.isHttps)\n return this.startHttpsServer();\n\n this.startHttpServer();\n }\n\n /**\n * Starts an HTTP server.\n * This method creates an HTTP server that listens on the configured port and handles incoming requests.\n *\n * @example\n * ```typescript\n * provider.startHttpServer();\n * ```\n *\n * This example shows how the `startHttpServer` method is used internally to start an HTTP server.\n */\n\n private startHttpServer(): void {\n const server = http.createServer((req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n server.listen(this.config.port, this.config.host, () => {\n console.log(`${ prefix() } HTTP/S server is running at http://${ this.config.host }:${ this.config.port }`);\n });\n }\n\n /**\n * Starts an HTTPS server.\n *\n * This method creates an HTTPS server with SSL/TLS certificates, listens on the configured port, and handles incoming requests.\n *\n * @example\n * ```typescript\n * provider.startHttpsServer();\n * ```\n *\n * This example shows how the `startHttpsServer` method is used internally to start an HTTPS server.\n */\n\n private startHttpsServer(): void {\n const options = {\n key: readFileSync(this.config.keyfile),\n cert: readFileSync(this.config.certfile)\n };\n\n const server = https.createServer(options, (req, res) => {\n this.handleRequest(req, res, () => this.defaultResponse(req, res));\n });\n\n server.listen(this.config.port, this.config.host, () => {\n const server = setColor(Colors.CanaryYellow, `https://${ this.config.host }:${ this.config.port }`);\n console.log(\n `${ prefix() } HTTPS server is running at ${ server }`\n );\n });\n }\n\n /**\n * Handles incoming requests.\n *\n * This method checks if a custom request handler is provided in the configuration. If so, it uses the custom handler.\n * Otherwise, it delegates to the default request handler.\n *\n * @param req - The incoming request object.\n * @param res - The response object.\n * @param defaultHandler - The default handler function to be called if no custom handler is provided.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * // This method is used internally to handle requests\n * ```\n */\n\n private handleRequest(req: IncomingMessage, res: ServerResponse, defaultHandler: () => void): void {\n try {\n if (this.config.onRequest) {\n this.config.onRequest(req, res, defaultHandler);\n } else {\n defaultHandler();\n }\n } catch (error) {\n this.sendError(res, <Error> error);\n }\n }\n\n /**\n * Returns the MIME type for a given file extension.\n *\n * This method maps file extensions to their corresponding MIME types.\n *\n * @param ext - The file extension.\n * @returns The MIME type associated with the file extension.\n *\n * @example\n * ```typescript\n * const mimeType = provider.getContentType('html');\n * console.log(mimeType); // 'text/html'\n * ```\n */\n\n private getContentType(ext: string): string {\n const contentTypes: Record<string, string> = {\n html: 'text/html',\n css: 'text/css',\n js: 'application/javascript',\n ts: 'text/plain',\n map: 'application/json',\n json: 'application/json',\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n txt: 'text/plain'\n };\n\n return contentTypes[ext] || 'application/octet-stream';\n }\n\n /**\n * Handles the default response for requests, serving files or directories.\n *\n * This method serves the content of files or directories. If the request is for a directory, it lists the contents with\n * appropriate icons and colors.\n *\n * @param req - The incoming request object.\n * @param res - The response object.\n *\n * @returns A promise that resolves when the response is sent.\n *\n * @throws Throws an error if the file or directory cannot be accessed.\n *\n * @example\n * ```typescript\n * // This method is used internally to handle file and directory responses\n * ```\n */\n\n private async defaultResponse(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const requestPath = req.url === '/' ? '' : req.url?.replace(/^\\/+/, '') || '';\n const fullPath = join(this.rootDir, requestPath);\n\n if (!fullPath.startsWith(this.rootDir)) {\n res.statusCode = 403;\n res.end();\n\n return;\n }\n\n try {\n const stats = await this.promisifyStat(fullPath);\n\n if (stats.isDirectory()) {\n this.handleDirectory(fullPath, requestPath, res);\n } else if (stats.isFile()) {\n this.handleFile(fullPath, res);\n }\n } catch (error) {\n const msg = (<Error> error).message;\n if (!msg.includes('favicon')) {\n console.log(prefix(), msg);\n }\n\n this.sendNotFound(res);\n }\n }\n\n /**\n * promisifyStat the `fs.stat` method.\n *\n * Converts the `fs.stat` callback-based method to return a promise.\n *\n * @param path - The file or directory path.\n * @returns A promise that resolves with the file statistics.\n *\n * @example\n * ```typescript\n * const stats = await provider.promisifyStat('./path/to/file');\n * console.log(stats.isFile()); // true or false\n * ```\n */\n\n private promisifyStat(path: string): Promise<Stats> {\n return new Promise((resolve, reject) => {\n stat(path, (err, stats) => (err ? reject(err) : resolve(stats)));\n });\n }\n\n /**\n * Handles directory listings.\n *\n * Reads the contents of a directory and generates an HTML response with file icons and colors.\n *\n * @param fullPath - The full path to the directory.\n * @param requestPath - The request path for generating relative links.\n * @param res - The response object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * // This method is used internally to handle directory listings\n * ```\n */\n\n private handleDirectory(fullPath: string, requestPath: string, res: ServerResponse): void {\n readdir(fullPath, (err, files) => {\n if (err)\n return this.sendError(res, err);\n\n const fileList = files.map(file => {\n if (file.match(/[^A-Za-z0-9_\\/\\\\.-]/))\n return;\n\n const fullPath = join(requestPath, file);\n if (fullPath.match(/[^A-Za-z0-9_\\/\\\\.-]/))\n return;\n\n const ext = extname(file).slice(1) || 'folder';\n const { icon, color } = fileIcons[ext] || fileIcons.folder;\n\n return `<li><i class=\"fas ${ icon }\" style=\"color: ${ color };\"></i> <a href=\"/${ fullPath }\">${ file }</a></li>`;\n }).join('');\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(html.replace('${ fileList }', fileList));\n });\n }\n\n /**\n * Handles file responses.\n *\n * Reads and serves the content of a file.\n *\n * @param fullPath - The full path to the file.\n * @param res - The response object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * // This method is used internally to handle file responses\n * ```\n */\n\n private handleFile(fullPath: string, res: ServerResponse): void {\n const ext = extname(fullPath).slice(1) || 'txt';\n const contentType = this.getContentType(ext);\n\n readFile(fullPath, (err, data) => {\n if (err) {\n return this.sendError(res, err);\n }\n\n res.writeHead(200, { 'Content-Type': contentType });\n res.end(data);\n });\n }\n\n /**\n * Sends a 404 Not Found response.\n *\n * @param res - The response object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * provider.sendNotFound(response);\n * ```\n *\n * This example demonstrates how to send a 404 response using the `sendNotFound` method.\n */\n\n private sendNotFound(res: ServerResponse): void {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n\n /**\n * Sends an error response.\n *\n * @param res - The response object.\n * @param error - The error object.\n *\n * @returns {void}\n *\n * @example\n * ```typescript\n * provider.sendError(response, new Error('Some error'));\n * ```\n *\n * This example shows how to send an error response using the `sendError` method.\n */\n\n private sendError(res: ServerResponse, error: Error): void {\n console.error(`${ prefix() }`, error.toString());\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end('Internal Server Error');\n }\n}\n", "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Directory Listing</title>\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css\">\n <style>\n body {\n font-family: Arial, sans-serif;\n margin: 0;\n padding: 0;\n background-color: #f4f4f4;\n }\n h1 {\n color: #333;\n text-align: center;\n padding: 20px;\n }\n ul {\n list-style: none;\n padding: 0;\n margin: 0;\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n }\n li {\n background: #fff;\n border: 1px solid #ddd;\n border-radius: 4px;\n margin: 5px;\n padding: 10px;\n width: 200px;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n display: flex;\n align-items: center;\n }\n i {\n margin-right: 10px;\n font-size: 18px;\n color: #666;\n }\n a {\n text-decoration: none;\n color: #007bff;\n }\n a:hover {\n text-decoration: underline;\n }\n </style>\n </head>\n <body>\n <h1>Directory Listing</h1>\n <ul>${ fileList }</ul>\n </body>\n</html>\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n OnEndType,\n OnLoadType,\n BuildState,\n OnStartType,\n OnResolveType\n} from '@providers/interfaces/plugins.interfaces';\nimport type {\n Message,\n OnLoadArgs,\n BuildResult,\n OnEndResult,\n PluginBuild,\n OnLoadResult,\n OnResolveArgs,\n OnResolveResult\n} from 'esbuild';\n\n/**\n * Imports\n */\n\nimport { promises } from 'fs';\nimport { resolve } from 'path';\n\n/**\n * Plugin provider for esbuild that registers hooks for lifecycle events such as onStart, onEnd, onResolve, and onLoad.\n * This class allows dynamic behavior by registering multiple hooks for different stages of the build process.\n */\n\nexport class PluginsProvider {\n /**\n * Holds the build state that hooks can modify.\n */\n\n private buildState: BuildState = {};\n\n /**\n * Holds the registered hooks for the `onEnd` lifecycle event.\n * This array contains functions that are called after the build process completes.\n */\n\n private onEndHooks: Array<OnEndType> = [];\n\n /**\n * Holds the registered hooks for the `onLoad` lifecycle event.\n * This array contains functions that are called when esbuild attempts to load a module.\n */\n\n private onLoadHooks: Array<OnLoadType> = [];\n\n /**\n * Holds the registered hooks for the `onStart` lifecycle event.\n * This array contains functions that are called before the build process starts.\n */\n\n private onStartHooks: Array<OnStartType> = [];\n\n /**\n * Holds the registered hooks for the `onResolve` lifecycle event.\n * This array contains functions that are called when esbuild attempts to resolve a module path.\n */\n\n private onResolveHooks: Array<OnResolveType> = [];\n\n /**\n * Registers a hook function for the `onStart` lifecycle event.\n * The hook will be called before the build process starts.\n *\n * @param fn - A function of type `OnStartType` that will be executed when the build process starts.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnStart(async (build) => {\n * console.log('Build started:', build);\n * });\n * ```\n */\n\n registerOnStart(fn: OnStartType | undefined): void {\n if (fn)\n this.onStartHooks.push(fn);\n }\n\n /**\n * Registers a hook function for the `onEnd` lifecycle event.\n * The hook will be called after the build process completes.\n *\n * @param fn - A function of type `OnEndType` that will be executed after the build completes.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnEnd(async (result) => {\n * console.log('Build finished:', result);\n * });\n * ```\n */\n\n registerOnEnd(fn: OnEndType | undefined): void {\n if (fn)\n this.onEndHooks.push(fn);\n }\n\n /**\n * Registers a hook function for the `onResolve` lifecycle event.\n * The hook will be called when esbuild attempts to resolve a module path.\n *\n * @param fn - A function of type `OnResolveType` that will be executed during module resolution.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnResolve(async (args) => {\n * if (args.path === 'my-module') {\n * return { path: './src/my-module.ts' };\n * }\n * return null;\n * });\n * ```\n */\n\n registerOnResolve(fn: OnResolveType | undefined): void {\n if (fn)\n this.onResolveHooks.push(fn);\n }\n\n /**\n * Registers a hook function for the `onLoad` lifecycle event.\n * The hook will be called when esbuild attempts to load a module.\n *\n * @param fn - A function of type `OnLoadType` that will be executed during module loading.\n *\n * @example\n * ```typescript\n * pluginProvider.registerOnLoad(async (contents, loader, args) => {\n * if (args.path.endsWith('.json')) {\n * return { contents: JSON.stringify({ key: 'value' }), loader: 'json' };\n * }\n * return null;\n * });\n * ```\n */\n\n registerOnLoad(fn: OnLoadType | undefined): void {\n if (fn)\n this.onLoadHooks.push(fn);\n }\n\n /**\n * Registers esbuild plugin hooks and sets up the middleware plugin.\n *\n * This function defines the setup for an esbuild plugin, enabling hooks for various lifecycle events:\n * onStart, onEnd, onResolve, and onLoad. It ensures that hooks registered by the user are called at\n * the appropriate stages of the build process.\n *\n * @returns An object with the plugin configuration that can be passed to esbuild's `plugins` array.\n * The configuration includes the plugin name and setup function.\n *\n * @example\n * ```typescript\n * // Example usage with esbuild:\n * const esbuild = require('esbuild');\n * const pluginProvider = new PluginsProvider();\n *\n * esbuild.build({\n * entryPoints: ['./src/index.ts'],\n * bundle: true,\n * plugins: [pluginProvider.setup()],\n * }).catch(() => process.exit(1));\n * ```\n */\n\n setup() {\n return {\n name: 'middleware-plugin',\n setup: (build: PluginBuild) => {\n build.initialOptions.metafile = true;\n build.onEnd(this.handleOnEnd.bind(this));\n build.onStart(this.handleOnStart.bind(this, build));\n build.onLoad({ filter: /.*/ }, this.handleOnLoad.bind(this));\n build.onResolve({ filter: /.*/ }, this.handleOnResolve.bind(this));\n }\n };\n }\n\n /**\n * Executes all registered onStart hooks.\n *\n * This function is called when the build process starts and invokes each hook registered via\n * `registerOnStart`. Hooks can perform actions such as initializing tasks, logging, or setting\n * up build conditions.\n *\n * @param build - The esbuild `PluginBuild` object that represents the current build process.\n *\n * @returns A promise that resolves when all hooks have been executed.\n *\n * @example\n * ```typescript\n * // Registering an onStart hook\n * pluginProvider.registerOnStart(async (build) => {\n * console.log('Build started:', build);\n * });\n * ```\n */\n\n private async handleOnStart(build: PluginBuild): Promise<OnEndResult> {\n this.buildState = {};\n const result: Required<OnEndResult> = {\n errors: [],\n warnings: []\n };\n\n for (const hook of this.onStartHooks) {\n const status = await hook(build, this.buildState);\n if (status) {\n if (status.errors?.length)\n result.errors.push(...status.errors);\n\n if (status.warnings?.length)\n result.warnings.push(...status.warnings);\n }\n }\n\n return result;\n }\n\n /**\n * Executes all registered onEnd hooks after the build finishes.\n *\n * This function is called after the build process completes and invokes each hook registered via\n * `registerOnEnd`. Hooks can be used to process the build results, such as performing analysis or cleanup.\n *\n * @param buildResult - The build buildResult object provided by esbuild, containing details about the build process.\n *\n * @returns A promise that resolves when all hooks have been executed.\n *\n * @example\n * ```typescript\n * // Registering an onEnd hook\n * pluginProvider.registerOnEnd(async (buildResult) => {\n * console.log('Build completed:', buildResult);\n * });\n * ```\n */\n\n private async handleOnEnd(buildResult: BuildResult): Promise<OnEndResult> {\n const result: Required<OnEndResult> = {\n errors: buildResult.errors ?? [],\n warnings: buildResult.warnings ?? []\n };\n\n for (const hook of this.onEndHooks) {\n // Update buildResult with the current errors and warnings from result\n buildResult.errors = <Message[]> result.errors;\n buildResult.warnings = <Message[]> result.warnings;\n\n const status = await hook(buildResult, this.buildState);\n\n // Merge errors and warnings from the hook status\n if (status) {\n if (status.errors?.length)\n result.errors.push(...status.errors);\n\n if (status.warnings?.length)\n result.warnings.push(...status.warnings);\n }\n }\n\n return result;\n }\n\n /**\n * Resolves module imports using registered onResolve hooks.\n *\n * This function is called whenever esbuild attempts to resolve a module path. It iterates over all registered\n * onResolve hooks and merges their results. If no hook resolves a path, `null` is returned.\n *\n * @param args - The esbuild `OnResolveArgs` object containing information about the module being resolved.\n *\n * @returns A promise that resolves to an `OnResolveResult` containing the resolved path, or `null` if no path is found.\n *\n * @example\n * ```typescript\n * // Registering an onResolve hook\n * pluginProvider.registerOnResolve(async (args) => {\n * if (args.path === 'my-module') {\n * return { path: './src/my-module.ts' };\n * }\n * return null;\n * });\n * ```\n */\n\n private async handleOnResolve(args: OnResolveArgs): Promise<OnResolveResult | null> {\n let result: OnResolveResult = {};\n for (const hook of this.onResolveHooks) {\n const hookResult = await hook(args, this.buildState);\n if (hookResult) {\n result = {\n ...result,\n ...hookResult,\n path: hookResult.path || result.path\n };\n }\n }\n\n return result.path ? result : null;\n }\n\n /**\n * Loads module contents using registered onLoad hooks.\n *\n * This function is called when esbuild attempts to load a module. It reads the module contents and then\n * processes it through all registered onLoad hooks. The hooks can modify the contents and loader type.\n *\n * @param args - The esbuild `OnLoadArgs` object containing information about the module being loaded.\n *\n * @returns A promise that resolves to an `OnLoadResult` containing the module contents and loader, or `null` if no contents are loaded.\n *\n * @example\n * ```typescript\n * // Registering an onLoad hook\n * pluginProvider.registerOnLoad(async (contents, loader, args) => {\n * if (args.path.endsWith('.json')) {\n * return { contents: JSON.stringify({ key: 'value' }), loader: 'json' };\n * }\n * return null;\n * });\n * ```\n */\n\n private async handleOnLoad(args: OnLoadArgs): Promise<OnLoadResult | null> {\n let result: OnLoadResult = { contents: undefined, loader: 'default' };\n const filePath = resolve(args.path);\n\n if (!result.contents) {\n result.contents = await promises.readFile(filePath, 'utf8');\n }\n\n for (const hook of this.onLoadHooks) {\n const hookResult = await hook(result.contents ?? '', result.loader, args, this.buildState);\n if (hookResult) {\n result = {\n ...result,\n ...hookResult,\n contents: hookResult.contents || result.contents,\n loader: hookResult.loader || result.loader\n };\n }\n }\n\n return result.contents ? result : null;\n }\n}\n", "/**\n * Parses and filters content based on conditional directives.\n *\n * This function processes the given code contents and removes sections that\n * are conditionally compiled based on the provided `defines` object.\n *\n * @param contents - The code contents to be processed.\n * @param defines - An object containing conditional\n * definitions. Keys are condition names, and values are their definitions.\n * @returns The processed code contents with conditional blocks removed\n * according to the `defines` object.\n */\n\nexport function parseIfDefConditionals(contents: string, defines: Record<string, unknown>): string {\n return contents.replace(/\\/\\/\\s?ifdef\\s?(\\w+)([\\s\\S]*?)\\/\\/\\s?endif/g, (match, condition, code) => {\n // Check if the condition is defined\n return defines[condition] ? code : '';\n });\n}\n", "/**\n * Imports\n */\n\nimport { relative } from 'path';\n\n/**\n * Resolves path aliases in the provided content based on the specified paths and root directory.\n *\n * This function takes a string of content and replaces occurrences of defined path alias keys\n * with their corresponding relative paths derived from the specified source file and root directory.\n * It ensures that the resulting paths are relative to the directory of the source file and formatted\n * correctly for use in a JavaScript/TypeScript environment.\n *\n * Example:\n * Given the following inputs:\n * ```typescript\n * const content = \"import { foo } from '@core/foo';\";\n * const sourceFile = \"/project/src/index.ts\";\n * const paths = {\n * '@core/': 'src/core',\n * '@utils/': 'src/utils'\n * };\n * const rootDir = \"/project\";\n * ```\n * The function will replace `@core/foo` with a relative path based on the source file's location,\n * potentially resulting in:\n * ```typescript\n * const content = \"import { foo } from './core/foo';\";\n * ```\n *\n * @param content - The content in which path aliases need to be resolved.\n * @param sourceFile - The path of the source file from which relative paths will be calculated.\n * @param paths - An object mapping path alias keys to their corresponding paths.\n * @param esm - A flag indicating whether ESM is enabled.\n * @returns The updated content with resolved path aliases.\n */\n\nexport function resolveAliasPlugin(content: string, sourceFile: string, paths: Record<string, string>, esm: boolean): string {\n const importExportRegex = /(?:import|export)\\s.*?\\sfrom\\s+['\"]([^'\"]+)['\"]/g;\n for (const key in paths) {\n let relativePath = relative(sourceFile, paths[key]).replace(/\\\\/g, '/');\n if (!relativePath.startsWith('..')) {\n relativePath = `./${ relativePath }`;\n }\n\n content = content.replaceAll(key, `${ relativePath }/`);\n if (esm) {\n content = content.replace(importExportRegex, (match, p1) =>\n (p1.startsWith('../') || p1.startsWith('./')) && !p1.endsWith('.js')\n ? match.replace(p1, `${p1}.js`)\n : match\n );\n }\n }\n\n return content;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { BuildOptions, Metafile } from 'esbuild';\nimport type { transpileFileInterface } from '@services/interfaces/transpiler.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\nimport { build } from 'esbuild';\nimport { xBuildError } from '@errors/xbuild.error';\nimport type { EntryPoints } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Default build options for esbuild bundler in RemoteX framework.\n *\n * These options are used to configure how esbuild processes and bundles the TypeScript\n * files for the RemoteX testing framework.\n *\n * @public\n * @category Configuration\n */\n\nexport const defaultBuildOptions: BuildOptions = {\n write: false,\n bundle: true,\n minify: false,\n format: 'cjs',\n target: 'esnext',\n platform: 'node',\n sourcemap: true,\n sourcesContent: true,\n preserveSymlinks: true\n};\n\n/**\n * Extracts the source map from the provided data string and returns the modified code and source map separately.\n *\n * This function searches for the inline source map in the data string using a regular expression, removes the\n * source map comment from the data string, and returns an object containing the code without the source map\n * comment and the extracted source map.\n *\n * @param dataString - The string containing the transpiled code with an inline source map.\n * @returns An object containing the modified code without the source map comment and the extracted source map.\n * @throws Error -Throws an error if the source map URL is not found in the data string.\n *\n * @public\n */\n\nexport function extractSourceMap(dataString: string): transpileFileInterface {\n const sourceMapRegex = /\\/\\/# sourceMappingURL=data:application\\/json;base64,([^'\"\\s]+)/;\n const match = dataString.match(sourceMapRegex);\n\n if (!match || !match[1]) {\n throw new xBuildError('Source map URL not found in the output.');\n }\n\n const sourceMap = match[1];\n const codeWithoutSourceMap = dataString.replace(sourceMapRegex, '');\n\n return { code: codeWithoutSourceMap, sourceMap };\n}\n\n/**\n * Transpiles a TypeScript file and extracts the source map.\n *\n * This function uses esbuild to transpile the specified TypeScript file based on provided build options,\n * and then extracts the source map from the transpiled code.\n *\n * @param filePath - The path to the TypeScript file to be transpiled.\n * @param buildOptions - Optional build options to override the default build options.\n * @returns A promise that resolves to an object containing the transpiled code and the extracted source map.\n * @throws Error - Throws an error if the build process fails or the source map extraction fails.\n *\n * @public\n * @category Services\n */\n\nexport async function transpileFile(filePath: string, buildOptions: BuildOptions = {}): Promise<transpileFileInterface> {\n const options: BuildOptions = {\n absWorkingDir: cwd(),\n ...defaultBuildOptions,\n ...buildOptions,\n entryPoints: [ filePath ]\n };\n\n const result = await build(options);\n const fileContent = result.outputFiles?.pop()?.text ?? '';\n\n // Retrieve the transpiled code from the build output.\n return extractSourceMap(fileContent);\n}\n\n/**\n * Analyzes the dependencies of a given entry point using esbuild.\n *\n * This function bundles the specified entry point without writing the output files to disk.\n * Instead, it generates a metafile that contains detailed information about the dependencies\n * and imports used in the bundled code. The metafile is returned as a result of the analysis.\n *\n * @param entryPoint - The path to the entry point file that should be analyzed.\n * @param platform - The platform for which the code is being analyzed.\n * 'browser' indicates that the code is intended for a browser environment,\n * 'node' indicates a Node.js environment, and 'neutral' is platform-agnostic.\n * @returns A promise that resolves to the metafile containing the analysis of dependencies.\n * @throws Error - Throws an error if the build process fails.\n *\n * @public\n * @category Services\n */\n\nexport async function analyzeDependencies(entryPoint: EntryPoints, platform: 'browser' | 'node' | 'neutral' = 'browser'): Promise<Metafile> {\n const result = await build({\n entryPoints: entryPoint,\n bundle: true, // Bundle to analyze imports\n write: false, // Prevent writing output files\n metafile: true, // Generate a metafile to analyze dependencies\n platform: platform,\n packages: 'external',\n logLevel: 'silent',\n outdir: 'dist'\n });\n\n return result.metafile;\n}\n", "/**\n * Imports\n */\n\nimport { BaseError } from '@errors/base.error';\n\n/**\n * Represents an error specific to the xBuild process.\n *\n * The `xBuildError` class extends the `BaseError` class to provide a custom error type for the xBuild system.\n * It includes additional functionality to maintain stack trace information and assigns a specific name to\n * the error, making it easier to identify and handle in different parts of the application.\n *\n * @augments BaseError\n */\n\nexport class xBuildError extends BaseError {\n /**\n * Original error stack\n */\n\n originalErrorStack: string | undefined;\n\n /**\n * Creates an instance of `xBuildError`.\n *\n * @param message - The error message that describes the error. This message is passed to the base class\n * `BaseError` constructor and is used to provide context about the nature of the error.\n * @param options - Optional configuration for the error. This can include additional properties or settings\n * that customize the error's behavior.\n */\n\n constructor(message: string, options?: ErrorOptions) {\n // Pass the message to the base class Error\n super(message);\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, xBuildError);\n }\n\n // Apply additional options if provided\n if (options) {\n Object.assign(this, options);\n }\n\n // Assign the name of the error\n this.name = 'xBuildError';\n this.originalErrorStack = this.stack;\n this.stack = this.reformatStack(this);\n }\n}\n", "/**\n * Custom error class to represent type-related errors.\n *\n * This class extends the built-in `Error` class to provide more specific\n * error handling for issues related to types. It can be used to distinguish\n * errors that occur due to type mismatches or other type-related problems\n * in your application.\n *\n * @example\n * ```typescript\n * throw new TypesError('Invalid type encountered.');\n * ```\n *\n * @augments Error\n */\n\nexport class TypesError extends Error {\n /**\n * Creates an instance of `TypesError`.\n *\n * @param message - A human-readable message providing details about the error.\n * @param options - Optional configuration for the error, such as a `cause` (ECMAScript 2022+).\n * @param options.cause\n */\n\n constructor(message?: string, options?: { cause?: Error }) {\n super(message);\n this.name = 'TypesError';\n\n // Set the prototype explicitly to ensure instanceof checks work correctly\n Object.setPrototypeOf(this, TypesError.prototype);\n\n if (options?.cause) {\n // Optionally include the cause of the error, if provided\n this.cause = options.cause;\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type {\n Node,\n Bundle,\n Diagnostic,\n SourceFile,\n StringLiteral,\n CompilerOptions,\n CustomTransformer,\n ImportDeclaration,\n ExportDeclaration,\n ParsedCommandLine,\n TransformationContext,\n CustomTransformerFactory\n} from 'typescript';\n\n/**\n * Imports\n */\n\nimport { TypesError } from '@errors/types.error';\nimport { prefix } from '@components/banner.component';\nimport { resolve, relative, dirname, parse } from 'path';\nimport { Colors, setColor } from '@components/colors.component';\nimport {\n sys,\n factory,\n createProgram,\n visitEachChild,\n isStringLiteral,\n resolveModuleName,\n DiagnosticCategory,\n isImportDeclaration,\n isExportDeclaration,\n getPreEmitDiagnostics,\n flattenDiagnosticMessageText\n} from 'typescript';\n\n/**\n * Provides TypeScript-related utilities such as type-checking, generating declaration files,\n * and transforming module specifiers into relative paths based on the output directory.\n *\n * The `TypescriptProvider` class enables users to type-check TypeScript projects, generate\n * declaration files, and transform import/export paths into relative paths that match the output directory.\n * It uses the TypeScript Compiler API to achieve these transformations.\n *\n * @class\n * @example\n * ```typescript\n * const tsProvider = new TypescriptProvider(parsedConfig, './dist');\n * tsProvider.typeCheck(entryPoints);\n * tsProvider.generateDeclarations(entryPoints);\n * ```\n */\n\nexport class TypeScriptProvider {\n\n /**\n * Compiler options for configuring TypeScript compilation.\n */\n\n readonly options: CompilerOptions;\n\n /**\n * Creates an instance of `TypescriptProvider` with the given TypeScript configuration and output directory.\n *\n * This constructor initializes a `TypescriptProvider` with the provided TypeScript configuration\n * and the directory where output files (such as declaration files) will be stored.\n * Additionally, it accepts a flag to control whether ANSI color formatting should be applied in output messages.\n *\n * @param tsConfig - The parsed TypeScript configuration object.\n * @param outDir - The directory where output files (such as declaration files) will be stored.\n * @param activeColor - A boolean flag indicating whether ANSI color formatting should be applied in output messages.\n * Default is `true`.\n *\n * @example\n * ```typescript\n * const tsProvider = new TypescriptProvider(parsedConfig, './dist');\n * ```\n *\n * @example\n * ```typescript\n * const tsProvider = new TypescriptProvider(parsedConfig, './dist', false);\n * // This instance will not apply ANSI color formatting in output messages\n * ```\n */\n\n constructor(public tsConfig: ParsedCommandLine, private outDir: string, private activeColor: boolean = true) {\n this.options = {\n ...this.tsConfig.options,\n outDir: this.outDir\n };\n }\n\n /**\n * Performs type-checking on the specified entry points without emitting any files.\n *\n * This method compiles the provided TypeScript files to check for type errors and other diagnostics without\n * generating any output files. It ensures that the code adheres to TypeScript's type constraints and reports\n * any issues found during the type-checking process.\n *\n * @param allowError - A boolean flag indicating whether to throw an error if diagnostics are present. If set to\n * `true`, errors are logged but not thrown, allowing the process to continue. Defaults to `false`, which throws\n * an error if diagnostics are encountered.\n *\n * @returns void\n *\n * @throws Throws an error if type-checking fails due to TypeScript diagnostics and `allowError` is `false`.\n * The error indicates that the type-checking process has encountered issues.\n *\n * @example\n * ```typescript\n * // Type-check files and handle any diagnostics\n * tsProvider.typeCheck(['src/index.ts', 'src/app.ts']);\n * ```\n */\n\n typeCheck(allowError: boolean = false): void {\n const program = createProgram(this.tsConfig.fileNames, {\n ...this.options,\n noEmit: true,\n skipLibCheck: true\n });\n\n this.handleDiagnostics(getPreEmitDiagnostics(program), allowError);\n }\n\n /**\n * Generates TypeScript declaration files (`.d.ts`) for the specified entry points.\n *\n * This method compiles the provided TypeScript files and emits only the declaration files, without generating\n * JavaScript code. It applies a custom transformer to modify module specifiers to relative paths based on the\n * output directory. This ensures that the generated declaration files are accurate and the module paths are\n * aligned with the project's build structure.\n *\n * @param noTypeChecker - Skips TypeScript type checking.\n * @param allowError - A boolean flag indicating whether to throw an error if diagnostics are present. If set to\n * `true`, errors are logged but not thrown, allowing the process to continue. Defaults to `false`, which throws\n * an error if diagnostics are encountered.\n *\n * @returns void\n *\n * @example\n * ```typescript\n * // Generate declaration files for specific entry points\n * tsProvider.generateDeclarations(['src/index.ts', 'src/app.ts']);\n * ```\n */\n\n generateDeclarations(noTypeChecker = false, allowError: boolean = false): void {\n const program = createProgram(this.tsConfig.fileNames, {\n ...this.options,\n rootDir: this.options.baseUrl,\n declaration: true,\n skipLibCheck: true,\n emitDeclarationOnly: true\n });\n\n // Collect diagnostics and check for errors\n const diagnostics = getPreEmitDiagnostics(program);\n if (!noTypeChecker && diagnostics.some(diagnostic => diagnostic.category === DiagnosticCategory.Error)) {\n this.handleDiagnostics(diagnostics, allowError);\n }\n\n // Emit declarations if no type errors were found\n program.emit(undefined, undefined, undefined, true, {\n afterDeclarations: [ this.createTransformerFactory() ]\n });\n }\n\n /**\n * Checks if the provided node is an import or export declaration.\n *\n * @param node - A TypeScript AST node to check.\n *\n * @returns `true` if the node is either an `ImportDeclaration` or `ExportDeclaration`; otherwise, `false`.\n *\n * @example\n * ```typescript\n * const isDeclaration = tsProvider.isImportOrExportDeclaration(node);\n * console.log(isDeclaration); // true or false\n * ```\n */\n\n private isImportOrExportDeclaration(node: Node): boolean {\n return isImportDeclaration(node) || isExportDeclaration(node);\n }\n\n /**\n * Checks if the provided node has a string literal as its module specifier.\n *\n * @param node - A TypeScript AST node to check.\n *\n * @returns `true` if the node has a string literal module specifier; otherwise, `undefined`.\n *\n * @example\n * ```typescript\n * const hasModuleSpecifier = tsProvider.hasStringLiteralModuleSpecifier(importNode);\n * console.log(hasModuleSpecifier); // true or undefined\n * ```\n */\n\n private hasStringLiteralModuleSpecifier(node: Node): boolean | undefined {\n return (<ImportDeclaration> node).moduleSpecifier && isStringLiteral((<ImportDeclaration> node).moduleSpecifier);\n }\n\n /**\n * Resolves the module file name based on the module specifier and TypeScript compiler options.\n *\n * @param specifierText - The module specifier text (e.g., `'./module'`).\n * @param options - The TypeScript compiler options.\n *\n * @returns The resolved file path of the module or `undefined` if the module cannot be resolved.\n *\n * @example\n * ```typescript\n * const resolvedPath = tsProvider.resolveModuleFileName('./module', compilerOptions);\n * console.log(resolvedPath); // './dist/module.js'\n * ```\n */\n\n private resolveModuleFileName(specifierText: string, options: CompilerOptions): string | undefined {\n let path = undefined;\n const resolvedModule = resolveModuleName(specifierText, options.baseUrl!, options, sys);\n\n if (resolvedModule.resolvedModule && options.baseUrl) {\n if (resolvedModule.resolvedModule.resolvedFileName.includes('node_modules'))\n return path;\n\n path = resolve(resolvedModule.resolvedModule.resolvedFileName).replace(\n resolve(options.baseUrl), '.'\n );\n }\n\n return path;\n }\n\n /**\n * Computes the relative path from the source file to the resolved target file.\n *\n * @param sourceFile - The absolute path of the source file.\n * @param resolvedTargetFile - The absolute path of the resolved target file.\n *\n * @returns A relative path from the source file to the target file.\n *\n * @example\n * ```typescript\n * const relativePath = tsProvider.getRelativePathToOutDir('./src/index.ts', './dist/module.js');\n * console.log(relativePath); // './module.js'\n * ```\n */\n\n private getRelativePathToOutDir(sourceFile: string, resolvedTargetFile: string): string {\n sourceFile = resolve(sourceFile).replace(resolve(this.options.baseUrl ?? ''), '.');\n const relativePath = relative(dirname(sourceFile), resolvedTargetFile).replace(/\\\\/g, '/');\n const parsePath = parse(relativePath);\n\n if (!parsePath.dir.startsWith('..')) {\n parsePath.dir = `./${ parsePath.dir }`;\n }\n\n return `${ parsePath.dir }/${ parsePath.name }`;\n }\n\n /**\n * Updates the module specifier of an import or export declaration to a relative path based on the output directory.\n *\n * This method takes a TypeScript `ImportDeclaration` or `ExportDeclaration` node and updates its module\n * specifier to a relative path that matches the output directory. It uses the TypeScript compiler options\n * to resolve the full path of the module and converts it into a relative path from the source file.\n *\n * This is useful when transforming module specifiers to ensure the generated declaration files (`.d.ts`)\n * have correct paths when files are moved to the output directory.\n *\n * @param node - The TypeScript `ImportDeclaration` or `ExportDeclaration` node whose module specifier needs to be updated.\n * @param sourceFile - The absolute path of the source file containing the node.\n *\n * @returns The updated `ImportDeclaration` or `ExportDeclaration` node with the new relative module specifier.\n *\n * @example\n * ```typescript\n * const updatedNode = tsProvider.updateModuleSpecifier(importNode, './src/index.ts');\n * console.log(updatedNode.moduleSpecifier.text); // './module.js'\n * ```\n */\n\n private updateModuleSpecifier(node: Node, sourceFile: string): Node {\n const newModuleSpecifier = factory.createStringLiteral(sourceFile);\n\n if (isImportDeclaration(node)) {\n return factory.updateImportDeclaration(\n node,\n node.modifiers,\n node.importClause,\n newModuleSpecifier,\n undefined\n );\n } else if (isExportDeclaration(node)) {\n return factory.updateExportDeclaration(\n node,\n node.modifiers,\n node.isTypeOnly,\n node.exportClause,\n newModuleSpecifier,\n undefined\n );\n }\n\n return node;\n }\n\n /**\n * Creates a visitor function that transforms `ImportDeclaration` and `ExportDeclaration` nodes by updating\n * their module specifiers to relative paths based on the output directory.\n *\n * This method returns a visitor function, which is used to traverse and transform the nodes in a TypeScript\n * `SourceFile`. The visitor identifies `ImportDeclaration` and `ExportDeclaration` nodes with module specifiers\n * that are string literals. For these nodes, the module specifiers are resolved to their corresponding file paths\n * and updated to relative paths that align with the output directory.\n *\n * The visitor is designed to recursively visit all nodes in the `SourceFile`, transforming only the relevant\n * import and export declarations while leaving other nodes unchanged.\n *\n * @param sourceFile - The TypeScript `SourceFile` that will be traversed by the visitor.\n * @param context - The transformation context provided by the TypeScript compiler, used for visiting nodes.\n *\n * @returns A visitor function that processes the nodes in the source file, updating module specifiers as needed.\n *\n * @example\n * ```typescript\n * const visitor = tsProvider.createVisitor(sourceFile, context);\n * const transformedNode = visitor(importNode);\n * console.log(transformedNode); // ImportDeclaration with updated module specifier\n * ```\n */\n\n private createVisitor(sourceFile: SourceFile, context: TransformationContext): (node: Node) => Node {\n // Define the visitor function that will handle transformations\n const visitNode = (node: Node | ImportDeclaration | ExportDeclaration): Node => {\n // Example transformation: replace import/export module specifiers with relative paths\n if (this.isImportOrExportDeclaration(node) && this.hasStringLiteralModuleSpecifier(node)) {\n const specifierText = ((<ImportDeclaration> node).moduleSpecifier as StringLiteral).text;\n const resolvedTargetFile = this.resolveModuleFileName(specifierText, this.options);\n\n if (resolvedTargetFile) {\n const relativePath = this.getRelativePathToOutDir(sourceFile.fileName, resolvedTargetFile);\n\n return this.updateModuleSpecifier(node as Node & { moduleSpecifier: StringLiteral }, relativePath);\n }\n }\n\n // Recursively visit each child node\n return visitEachChild(node, visitNode, context);\n };\n\n // Return the visitor function\n return visitNode;\n }\n\n /**\n * Creates a custom transformer factory for TypeScript that processes `SourceFile` nodes.\n *\n * This method returns a custom transformer factory function which generates a transformer that can be used\n * during the TypeScript compilation process. The transformer specifically processes `SourceFile` nodes to\n * apply custom transformations and does not alter `Bundle` nodes.\n *\n * The factory function generates a transformer that performs the following:\n * - **Transforming `SourceFile` nodes**: Uses the `createVisitor` method to visit and transform all nodes in\n * a `SourceFile`. This allows custom modifications or analysis of TypeScript source files.\n * - **No transformation for `Bundle` nodes**: The `transformBundle` method returns the bundle unchanged, as\n * no specific transformation is needed for bundles in this implementation.\n *\n * This transformer factory is used primarily for customizing TypeScript file transformations, such as updating\n * module specifiers or other source-level adjustments during the compilation process.\n *\n * @returns A custom transformer factory function that produces a `CustomTransformer` object. This object\n * implements the `transformSourceFile` and `transformBundle` methods.\n *\n * @example\n * ```typescript\n * const transformerFactory = tsProvider.createTransformerFactory();\n * const emitResult = program.emit(undefined, undefined, undefined, true, {\n * after: [transformerFactory]\n * });\n * ```\n */\n\n private createTransformerFactory(): CustomTransformerFactory {\n return (context: TransformationContext): CustomTransformer => {\n return {\n // Transform the source file by visiting all nodes\n transformSourceFile: (sourceFile: SourceFile): SourceFile => {\n return visitEachChild(sourceFile, this.createVisitor(sourceFile, context), context);\n },\n\n // Required for transformers but usually not necessary for us to implement\n transformBundle: (bundle: Bundle): Bundle => {\n return bundle; // No transformation needed for bundles in this case\n }\n };\n };\n }\n\n /**\n * Handles and logs TypeScript diagnostics, providing detailed error messages with file and position information.\n *\n * This method processes an array of TypeScript diagnostics, printing formatted error messages to the console.\n * If a diagnostic is associated with a specific file and position, the error message includes the filename,\n * line, and character information. Colors are applied to highlight different parts of the message, such as\n * file paths, positions, error messages, and error codes.\n *\n * If the `allowError` flag is `false`, the method throws an error when diagnostics are present, indicating\n * that type checking has failed. If `allowError` is `true`, errors are logged but not thrown, allowing the process\n * to continue despite the diagnostics.\n *\n * @param diagnostics - An array of readonly `Diagnostic` objects returned by the TypeScript compiler.\n * These diagnostics contain information about errors or warnings that occurred during compilation.\n *\n * @param allowError - A boolean flag that determines whether the method should throw an error when diagnostics\n * are encountered. If set to `true`, the method logs diagnostics but does not throw an error. Defaults to `false`.\n *\n * @throws Will throw an error if diagnostics are present and `allowError` is set to `false`. The error\n * indicates that type checking has failed.\n *\n * @example\n * ```typescript\n * const diagnostics = program.getSemanticDiagnostics();\n * handleDiagnostics(diagnostics, false); // Throws an error if any diagnostics exist.\n * ```\n */\n\n private handleDiagnostics(diagnostics: readonly Diagnostic[], allowError: boolean = false): void {\n if (diagnostics.length === 0)\n return;\n\n diagnostics.forEach(diagnostic => {\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n const message = flattenDiagnosticMessageText(diagnostic.messageText, '\\n');\n\n const file = setColor(Colors.Cyan, diagnostic.file.fileName, this.activeColor);\n const position = setColor(Colors.LightYellow, `${ line + 1 }:${ character + 1 }`, this.activeColor);\n const errorMsg = setColor(Colors.Red, 'error', this.activeColor);\n const errorCode = setColor(Colors.Gray, `TS${ diagnostic.code }`, this.activeColor);\n\n console.error(`${ prefix() } ${ file }:${ position } - ${ errorMsg } ${ errorCode }:${ message }`);\n } else {\n console.error(flattenDiagnosticMessageText(diagnostic.messageText, '\\n'));\n }\n });\n\n console.log('\\n');\n if (!allowError) {\n throw new TypesError('Type checking failed due to errors.');\n }\n }\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Argv } from 'yargs';\nimport type { BuildOptions } from 'esbuild';\nimport type { ParsedCommandLine } from 'typescript';\nimport type { ArgvInterface } from '@services/interfaces/cli.interface';\nimport type {\n ConfigurationInterface,\n PartialDeepConfigurationsType\n} from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport ts from 'typescript';\nimport { dirname } from 'path';\nimport { existsSync, readFileSync } from 'fs';\nimport { xBuildError } from '@errors/xbuild.error';\nimport { defaultConfiguration } from '@configuration/default.configuration';\nimport { parseConfigurationFile } from '@configuration/parse.configuration';\n\n/**\n * Default tsconfig if not supplied\n */\n\nconst defaultTsConfig = JSON.stringify({\n 'compilerOptions': {\n 'strict': true,\n 'target': 'ESNext',\n 'module': 'ESNext',\n 'outDir': 'dist',\n 'skipLibCheck': true,\n 'isolatedModules': false,\n 'esModuleInterop': false,\n 'moduleDetection': 'force',\n 'moduleResolution': 'node',\n 'resolveJsonModule': true,\n 'allowSyntheticDefaultImports': true,\n 'forceConsistentCasingInFileNames': true\n }\n});\n\n/**\n * Parses CLI arguments and sets the configuration for the application.\n *\n * @param cli - An instance of `Argv<ArgvInterface>` that contains CLI arguments and options.\n * @returns The final configuration object as a `ConfigurationInterface`.\n * @throws Error - Throws an error if critical configuration properties are missing or invalid.\n */\n\nfunction parseCliArgs(cli: Argv<ArgvInterface>): PartialDeepConfigurationsType {\n const args = <ArgvInterface> cli.argv;\n\n // Helper function to filter out undefined values\n const pickDefined = <T extends object>(obj: T): PartialDeepConfigurationsType => Object.fromEntries(\n Object.entries(obj).filter(([ , value ]) => value !== undefined)\n );\n\n const esbuildConfig = pickDefined({\n bundle: args.bundle,\n minify: args.minify,\n outdir: args.outdir,\n tsconfig: args.tsconfig,\n entryPoints: args.file ? [ args.file ] : undefined,\n target: args.node ? [ `node${ process.version.slice(1) }` ] : undefined,\n platform: args.node ? 'node' : undefined,\n format: args.format\n });\n\n return <PartialDeepConfigurationsType> {\n ...pickDefined({\n dev: args.dev,\n watch: args.watch,\n declaration: args.declaration,\n serve: args.serve ? { active: args.serve } : { undefined }\n }),\n ...{ esbuild: esbuildConfig }\n };\n}\n\n/**\n * Reads and parses the TypeScript configuration file.\n *\n * @param options - A `BuildOptions` object that may contain a custom `tsconfig` path.\n * @returns A `ParsedCommandLine` object representing the parsed TypeScript configuration.\n * @throws xBuildError - Throws an error if the configuration file contains syntax errors.\n */\n\nexport function tsConfiguration(options: BuildOptions): ParsedCommandLine {\n const tsConfigFile = options.tsconfig ?? '';\n const configFile = existsSync(tsConfigFile) ? readFileSync(tsConfigFile, 'utf8') : JSON.stringify(defaultTsConfig);\n\n const parsedConfig = ts.parseConfigFileTextToJson(tsConfigFile, configFile);\n if (parsedConfig.error) {\n throw new xBuildError(ts.formatDiagnosticsWithColorAndContext([ parsedConfig.error ], {\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getCanonicalFileName: fileName => fileName,\n getNewLine: () => ts.sys.newLine\n }));\n }\n\n const configParseResult = ts.parseJsonConfigFileContent(parsedConfig.config, ts.sys, dirname(tsConfigFile));\n if (configParseResult.errors.length > 0) {\n throw new xBuildError(ts.formatDiagnosticsWithColorAndContext(configParseResult.errors, {\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getCanonicalFileName: fileName => fileName,\n getNewLine: () => ts.sys.newLine\n }));\n }\n\n return configParseResult;\n}\n\n/**\n * Merges CLI arguments with a configuration file to produce a final configuration object.\n *\n * @param configFile - The path to the configuration file to read and merge with CLI arguments.\n * @param cli - An instance of `Argv<ArgvInterface>` containing CLI arguments and options.\n * @returns A promise that resolves to the final `ConfigurationInterface` object.\n * @throws Error - Throws an error if the `entryPoints` property in the final configuration is undefined.\n */\n\nexport async function configuration(configFile: string, cli: Argv<ArgvInterface>): Promise<Array<ConfigurationInterface>> {\n const cliConfig = parseCliArgs(cli);\n const userConfig = existsSync(configFile) ? await parseConfigurationFile(configFile) : {};\n\n // Check if userConfig is an array and handle accordingly\n const userConfigs: Array<ConfigurationInterface> = Array.isArray(userConfig) ? userConfig : [ userConfig ];\n const defaultUserConfig = userConfigs[0];\n\n return userConfigs.flatMap<ConfigurationInterface>((userConfigEntry) => {\n const mergedConfig: ConfigurationInterface = {\n ...defaultConfiguration,\n ...defaultUserConfig,\n ...userConfigEntry,\n ...cliConfig,\n esbuild: {\n ...defaultConfiguration.esbuild,\n ...defaultUserConfig?.esbuild,\n ...userConfigEntry?.esbuild,\n ...cliConfig.esbuild\n },\n serve: {\n ...defaultConfiguration.serve,\n ...defaultUserConfig.serve,\n ...userConfigEntry.serve,\n ...cliConfig.serve\n }\n };\n\n if (!mergedConfig.esbuild.entryPoints) {\n throw new xBuildError('entryPoints cannot be undefined.');\n }\n\n return mergedConfig;\n });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigurationInterface } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { cwd } from 'process';\n\n/**\n * The default configuration options for the build.\n *\n * @example\n * ```typescript\n * import { defaultConfiguration } from '@configuration/default-configuration';\n *\n * console.log(defaultConfiguration);\n * ```\n *\n * In this example, the `defaultConfiguration` is imported and logged to the console to view the default settings.\n *\n * @public\n * @category Configuration\n */\n\nexport const defaultConfiguration: ConfigurationInterface = {\n dev: false,\n watch: false,\n declaration: false,\n buildOnError: false,\n noTypeChecker: false,\n define: {},\n esbuild: {\n write: true,\n bundle: true,\n minify: true,\n format: 'cjs',\n outdir: 'dist',\n platform: 'browser',\n absWorkingDir: cwd(),\n loader: {\n '.js': 'ts'\n }\n },\n serve: {\n port: 3000,\n host: 'localhost',\n active: false\n }\n};\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ErrorType } from '@errors/interfaces/stack.interface';\nimport type { ConfigurationInterface, ModuleInterface } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { createRequire } from 'module';\nimport { SourceService } from '@remotex-labs/xmap';\nimport { sandboxExecute } from '@services/vm.service';\nimport { VMRuntimeError } from '@errors/vm-runtime.error';\nimport { transpileFile } from '@services/transpiler.service';\n\n/**\n * Recursively wraps all functions in an object, including nested objects.\n *\n * @param obj - The object whose functions need to be wrapped.\n * @param sourceMap - The source map service to attach to the error in case of a thrown error.\n * @returns The object with its functions wrapped.\n */\n\nfunction wrapAllFunctions<T extends object>(obj: T, sourceMap: SourceService): T {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key as keyof T];\n\n if (typeof value === 'function') {\n // Safely cast and wrap the function\n (obj as Record<string, unknown>)[key] = wrapFunctionWithSourceMap(value as (...args: unknown[]) => unknown, sourceMap);\n } else if (typeof value === 'object' && value !== null) {\n // Recursively wrap functions in nested objects\n wrapAllFunctions(value, sourceMap);\n }\n }\n }\n\n return obj;\n}\n\n/**\n * Wraps a function to catch errors and attach sourcemap information.\n *\n * @param fn - The function to be wrapped.\n * @param sourceMap - The source map service to attach to the error in case of a thrown error.\n * @returns The wrapped function that includes error handling with sourcemap information.\n */\n\nfunction wrapFunctionWithSourceMap<T extends (...args: unknown[]) => unknown>(\n fn: T,\n sourceMap: SourceService\n): T {\n return ((...args: Parameters<T>): ReturnType<T> => {\n try {\n return fn(...args) as ReturnType<T>;\n } catch (error) {\n throw new VMRuntimeError(<Error> error, sourceMap);\n }\n }) as T;\n}\n\n/**\n * Wraps functions within a `ConfigurationInterface` object to add sourcemap information to any errors thrown.\n *\n * @param config - The configuration object containing functions that need to be wrapped.\n * @param sourceMap - The source map service used to provide sourcemap information in case of errors.\n * @returns The modified `ConfigurationInterface` object with its functions wrapped.\n */\n\nfunction wrapConfigFunctionsWithSourcemap(\n config: ConfigurationInterface,\n sourceMap: SourceService\n): ConfigurationInterface {\n return wrapAllFunctions(config, sourceMap);\n}\n\n/**\n * Parses a configuration file and returns a wrapped `ConfigurationInterface` object.\n *\n * This function reads the specified configuration file, transpiles it to a CommonJS format, and then executes it\n * in a sandbox environment. The exported configuration object is wrapped so that any functions it contains will\n * have sourcemap information attached to errors thrown during their execution.\n *\n * The wrapping of functions helps in debugging by associating errors with their source maps.\n *\n * @param file - The path to the configuration file that needs to be parsed and transpiled.\n *\n * @returns A promise that resolves to the parsed and transpiled `ConfigurationInterface` object.\n * This object has its functions wrapped to attach sourcemap information to any errors thrown.\n *\n * @throws Will throw an error if the transpilation or execution of the configuration file fails.\n * The thrown error will have sourcemap information attached if available.\n *\n * @async\n *\n * @example\n * ```typescript\n * const config = await parseConfigurationFile('./config.jet.ts');\n * console.log(config);\n * ```\n */\n\nexport async function parseConfigurationFile(file: string): Promise<ConfigurationInterface> {\n const { code, sourceMap } = await transpileFile(file, {\n banner: { js: '(function(module, exports) {' },\n footer: { js: '})(module, module.exports);' }\n });\n\n const module: ModuleInterface = { exports: {} };\n const require = createRequire(import.meta.url);\n const source = new SourceService(JSON.parse(atob(sourceMap)));\n\n try {\n await sandboxExecute(code, {\n require,\n module\n });\n } catch (error: unknown) {\n throw new VMRuntimeError(<ErrorType> error, source);\n }\n\n return wrapConfigFunctionsWithSourcemap(<ConfigurationInterface> module.exports.default, source);\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { Context } from 'vm';\n\n/**\n * Imports\n */\n\nimport { Script, createContext } from 'vm';\n\n/**\n * Executes JavaScript code within a sandboxed environment using Node.js's `vm` module.\n *\n * @param code - The JavaScript code to be executed within the sandbox.\n * @param sandbox - An optional context object to be used as the global scope for the executed code.\n *\n * @returns The result of executing the provided code within the sandboxed environment.\n *\n * @remarks\n * The `sandboxExecute` function creates a new `Script` instance with the provided code and\n * runs it within a sandboxed context using the `createContext` function from the `vm` module.\n * This approach ensures that the executed code is isolated from the rest of the application,\n * mitigating potential security risks.\n *\n * The `sandbox` parameter allows you to provide a custom context or global object for the\n * sandboxed code. If not provided, an empty context is used. The function also supports\n * breaking execution on interrupt signals (e.g., Ctrl+C) with the `breakOnSigint` option.\n *\n * @throws {Error} Throws an error if the code cannot be compiled or executed within the context.\n *\n * @example\n * ```typescript\n * const result = sandboxExecute('return 2 + 2;', { myGlobal: 10 });\n * console.log(result); // Output: 4\n * ```\n *\n * In this example, the `sandboxExecute` function runs a simple JavaScript expression and returns\n * the result. The `sandbox` parameter is provided with an empty object in this case.\n *\n * @public\n * @category Services\n */\n\nexport function sandboxExecute(code: string, sandbox: Context = {}) {\n sandbox.console = console;\n const script = new Script(code);\n const context = createContext(sandbox);\n\n return script.runInContext(context, { breakOnSigint: true });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { EntryPoints } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { xBuildError } from '@errors/xbuild.error';\n\n/**\n * Maps an array of file paths to an object where the keys are filenames (without extensions)\n * and the values are the corresponding file paths.\n *\n * Each key in the resulting object is derived from the filename by removing the file extension.\n * For example, given a file path `src/index.ts`, the key in the resulting object will be `src/index`.\n *\n * @param filePaths - An array of file paths to map. Each file path should be a string.\n * @returns An object where the keys are filenames (without extensions) and the values are the corresponding file paths.\n *\n * @example\n * ```typescript\n * const filePaths = ['src/index.ts', 'src/utils.ts'];\n * const result = mapFilePathsToNames(filePaths);\n * console.log(result);\n * // Output: {\n * // 'src/index': 'src/index.ts',\n * // 'src/utils': 'src/utils.ts'\n * // }\n * ```\n */\n\nexport function mapFilePathsToNames(filePaths: Array<string>): Record<string, string> {\n const result: Record<string, string> = {};\n\n filePaths.forEach(filePath => {\n // Extract the filename without extension\n const fileName = filePath.substring(0, filePath.lastIndexOf('.'));\n // Map the filename to the file path\n result[fileName] = filePath;\n });\n\n return result;\n}\n\n/**\n * Extracts and returns an object mapping output file paths to input file paths from the provided `EntryPoints` object.\n *\n * This function handles multiple formats of entry points, including:\n * - An array of strings representing file paths.\n * - An array of objects containing `in` and `out` properties, where `in` is the input file path and `out` is the output file path.\n * - A `Record<string, string>` where the keys represent input file paths and the values represent output file paths.\n *\n * Depending on the format, the function constructs an object with the output file paths as keys and the input file paths as values.\n * If the output path is not available, the filename (without extension) is used as the key.\n *\n * If a regular object with string keys and values (not in the supported formats) is provided, it will be returned as is.\n *\n * @param entryPoints - The entry points to extract from, which can be in different formats: an array of strings,\n * an array of objects with `in` and `out` properties, or a `Record<string, string>`.\n *\n * @returns An object mapping output file paths to input file paths, or filename (without extension) to file path.\n *\n * @throws Will throw an `Error` if the entry points format is unsupported.\n *\n * @example\n * ```typescript\n * const entryPoints = extractEntryPoints(['src/index.ts', 'src/utils.ts']);\n * console.log(entryPoints); // { 'index': 'src/index.ts', 'utils': 'src/utils.ts' }\n * ```\n *\n * @example\n * ```typescript\n * const entryPoints = extractEntryPoints([{ in: 'src/index.ts', out: 'dist/index.js' }]);\n * console.log(entryPoints); // { 'dist/index.js': 'src/index.ts' }\n * ```\n *\n * @example\n * ```typescript\n * const entryPoints = extractEntryPoints({ index: 'src/index.ts', index2: 'dist/index2.js' });\n * console.log(entryPoints); // { index: 'src/index.ts', index2: 'dist/index2.js' }\n * ```\n */\n\nexport function extractEntryPoints(entryPoints: EntryPoints): Record<string, string> {\n if (Array.isArray(entryPoints)) {\n let result: Record<string, string> = {};\n\n if (entryPoints.length > 0 && typeof entryPoints[0] === 'object') {\n (entryPoints as { in: string, out: string }[]).forEach(entry => {\n result[entry.out] = entry.in;\n });\n } else if (typeof entryPoints[0] === 'string') {\n result = mapFilePathsToNames(<Array<string>> entryPoints);\n }\n\n return result;\n } else if (entryPoints && typeof entryPoints === 'object') {\n return entryPoints;\n }\n\n throw new xBuildError('Unsupported entry points format');\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigurationInterface } from '@configuration/interfaces/configuration.interface';\n\n/**\n * Imports\n */\n\nimport { join } from 'path';\nimport { mkdirSync, writeFileSync } from 'fs';\n\n/**\n * Generates a `package.json` file with the appropriate `type` field\n * based on the format specified in the configuration.\n *\n * - If the format is `esm`, the `type` will be set to `\"module\"`.\n * - If the format is `cjs`, the `type` will be set to `\"commonjs\"`.\n *\n * The function will ensure that the specified output directory exists, and if it doesn't,\n * it will create the necessary directories before writing the `package.json` file.\n *\n * @param config - The build configuration object containing\n * esbuild-related settings, such as the format (`format`).\n *\n * - `config.esbuild.format`: The module format, either `'esm'` or `'cjs'`, that determines the `type` field.\n *\n * @throws Will throw an error if there is a problem creating the directory or writing the file.\n *\n * Example usage:\n *\n * ```ts\n * const config = {\n * esbuild: {\n * format: 'esm'\n * }\n * };\n * packageTypeComponent(config);\n * // This will create 'dist/package.json' with the content: {\"type\": \"module\"}\n * ```\n */\n\nexport function packageTypeComponent(config: ConfigurationInterface): void {\n const outDir = config.moduleTypeOutDir ?? config.esbuild.outdir ?? 'dist';\n const type = config.esbuild.format === 'esm' ? 'module' : 'commonjs';\n\n mkdirSync(outDir, { recursive: true });\n writeFileSync(join(outDir, 'package.json'), `{\"type\": \"${ type }\"}`);\n}\n", "#!/usr/bin/env node\n\n/**\n * Exports\n */\n\nexport type * from '@configuration/interfaces/configuration.interface';\nexport type { BuildResult, OnLoadArgs, OnLoadResult, OnResolveArgs, OnResolveResult, PluginBuild } from 'esbuild';\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';\nimport type { ArgvInterface } from '@services/interfaces/cli.interface';\n\n/**\n * Imports\n */\n\nimport '@errors/stack.error';\nimport '@errors/uncaught.error';\nimport { argvParser } from '@services/cli.service';\nimport { BuildService } from '@services/build.service';\nimport { bannerComponent } from '@components/banner.component';\nimport { configuration } from '@providers/configuration.provider';\n\n/**\n * Clean cli\n */\n\nglobal.__ACTIVE_COLOR = true;\nconsole.log(bannerComponent());\n\n/**\n * Main run\n */\n\nasync function run() {\n const cli = argvParser(process.argv);\n const args = <ArgvInterface> cli.argv;\n const configs = await configuration(args.config, cli);\n const buildPromises = configs.map(async (config): Promise<void> => {\n const build = new BuildService(config);\n if (args.typeCheck)\n return build.typeScriptProvider.typeCheck(true);\n\n if (args.serve || config.serve.active)\n return await build.serve();\n\n if (Array.isArray(args.debug)) {\n if (args.debug.length < 1) {\n args.debug = [ 'index' ];\n }\n\n return await build.runDebug(args.debug);\n }\n\n await build.run();\n });\n\n // Wait for all build promises to resolve\n await Promise.all(buildPromises);\n}\n\n/**\n * Run entrypoint of xBuild\n */\n\nrun().catch((error: VMRuntimeError & xBuildError) => {\n console.error(error.stack);\n});\n"],
|
|
6
|
+
"mappings": ";AAYA,OAAS,OAAAA,OAAW,UACpB,OAAS,gBAAAC,OAAoB,KAC7B,OAAS,iBAAAC,OAAqB,MAC9B,OAAS,WAAAC,EAAS,QAAAC,GAAM,WAAAC,MAAe,OCiDhC,SAASC,EAASC,EAAeC,EAAaC,EAAuB,eAAwB,CAChG,OAAKA,EAGE,GAAGF,CAAK,GAAGC,CAAG,UAFVA,CAGf,CDpDA,OAAS,iBAAAE,GAAe,mBAAAC,GAAiB,iBAAAC,OAAqB,qBAM9D,IAAMC,EAAUC,GAAI,EACdC,EAAWC,EAAQC,GAAc,YAAY,GAAG,CAAC,EACjDC,GAAWF,EAAQD,CAAQ,EACpBI,GAAc,IAAM,CAC7B,IAAIC,EAEJ,MAAO,CACH,IAAI,SAAU,CACV,GAAI,CAACA,EAAqB,CAEtB,IAAMC,EAAgBC,GAAaC,GAAKR,EAAU,cAAc,CAAC,EACjEK,EAAsB,IAAIV,GAAcW,EAAc,SAAS,EAAG,YAAY,GAAG,CACrF,CAEA,OAAOD,CACX,CACJ,CACJ,GAAG,EAE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,GAGpB,MAAMI,EAAM,SAASJ,EAAK,KAAK,EAG1C,MAAMI,EAAM,IAAI,CACpB,CAAC,EAGD,MAAM,QAAQ,IAAIH,CAAa,CACnC,CAMAJ,GAAI,EAAE,MAAOS,GAAwC,CACjD,QAAQ,MAAMA,EAAM,KAAK,CAC7B,CAAC",
|
|
7
|
+
"names": ["cwd", "readFileSync", "fileURLToPath", "dirname", "join", "resolve", "setColor", "color", "msg", "activeColor", "SourceService", "formatErrorCode", "highlightCode", "cliPath", "cwd", "distPath", "dirname", "fileURLToPath", "rootPath", "xBuildLazy", "cachedSourceService", "sourceMapData", "readFileSync", "join", "modifyFilePathWithSourceRoot", "source", "sourceRoot", "line", "formatErrorLine", "name", "file", "column", "frame", "asyncPrefix", "formattedName", "position", "setColor", "extractFrameDetails", "typeName", "functionName", "highlightPositionCode", "error", "highlightedCode", "formatStackEntry", "state", "isXBuildService", "dirPath", "posLine", "posColumn", "resolve", "formattedStackEntries", "stackEntries", "formatStackTrace", "stackTrace", "originalPrepareStackTrace", "error", "reason", "yargs", "hideBin", "argvParser", "argv", "cli", "helpText", "dirname", "resolve", "build", "context", "process_spawn", "spawn", "filePath", "debug", "args", "processInstance", "data", "BaseError", "_BaseError", "message", "sourceMap", "error", "formatStackTrace", "esBuildError", "_esBuildError", "BaseError", "message", "asciiLogo", "bannerComponent", "activeColor", "setColor", "asciiLogo", "prefix", "VMRuntimeError", "_VMRuntimeError", "BaseError", "originalError", "sourceMap", "http", "https", "server_default", "extname", "join", "resolve", "existsSync", "readdir", "readFile", "readFileSync", "stat", "fileIcons", "ServerProvider", "config", "dir", "resolve", "req", "res", "prefix", "options", "server", "setColor", "defaultHandler", "error", "ext", "requestPath", "fullPath", "join", "stats", "msg", "path", "reject", "err", "files", "fileList", "file", "extname", "icon", "color", "server_default", "contentType", "data", "promises", "resolve", "PluginsProvider", "fn", "build", "result", "hook", "status", "buildResult", "args", "hookResult", "filePath", "parseIfDefConditionals", "contents", "defines", "match", "condition", "code", "relative", "resolveAliasPlugin", "content", "sourceFile", "paths", "esm", "importExportRegex", "key", "relativePath", "match", "p1", "cwd", "build", "xBuildError", "_xBuildError", "BaseError", "message", "options", "defaultBuildOptions", "extractSourceMap", "dataString", "sourceMapRegex", "match", "xBuildError", "sourceMap", "transpileFile", "filePath", "buildOptions", "options", "cwd", "fileContent", "build", "analyzeDependencies", "entryPoint", "platform", "TypesError", "_TypesError", "message", "options", "resolve", "relative", "dirname", "parse", "sys", "factory", "createProgram", "visitEachChild", "isStringLiteral", "resolveModuleName", "DiagnosticCategory", "isImportDeclaration", "isExportDeclaration", "getPreEmitDiagnostics", "flattenDiagnosticMessageText", "TypeScriptProvider", "tsConfig", "outDir", "activeColor", "allowError", "program", "noTypeChecker", "diagnostics", "diagnostic", "node", "specifierText", "options", "path", "resolvedModule", "resolve", "sourceFile", "resolvedTargetFile", "relativePath", "relative", "dirname", "parsePath", "parse", "newModuleSpecifier", "context", "visitNode", "bundle", "line", "character", "message", "file", "setColor", "position", "errorMsg", "errorCode", "prefix", "TypesError", "ts", "dirname", "existsSync", "readFileSync", "cwd", "defaultConfiguration", "createRequire", "SourceService", "Script", "createContext", "sandboxExecute", "code", "sandbox", "script", "context", "wrapAllFunctions", "obj", "sourceMap", "key", "value", "wrapFunctionWithSourceMap", "fn", "args", "error", "VMRuntimeError", "wrapConfigFunctionsWithSourcemap", "config", "parseConfigurationFile", "file", "code", "transpileFile", "module", "require", "createRequire", "source", "SourceService", "sandboxExecute", "defaultTsConfig", "parseCliArgs", "cli", "args", "pickDefined", "obj", "value", "esbuildConfig", "tsConfiguration", "options", "tsConfigFile", "configFile", "existsSync", "readFileSync", "parsedConfig", "ts", "xBuildError", "fileName", "configParseResult", "dirname", "configuration", "cliConfig", "userConfig", "parseConfigurationFile", "userConfigs", "defaultUserConfig", "userConfigEntry", "mergedConfig", "defaultConfiguration", "mapFilePathsToNames", "filePaths", "result", "filePath", "fileName", "extractEntryPoints", "entryPoints", "entry", "xBuildError", "join", "mkdirSync", "writeFileSync", "packageTypeComponent", "config", "outDir", "type", "BuildService", "config", "tsConfig", "tsConfiguration", "PluginsProvider", "TypeScriptProvider", "result", "entryPoints", "server", "ServerProvider", "callback", "error", "esbuildError", "VMRuntimeError", "rootDir", "resolve", "paths", "content", "loader", "args", "sourceFile", "dirname", "resolveAliasPlugin", "parseIfDefConditionals", "alias", "key", "valueArray", "newKey", "errors", "esBuildError", "packageTypeComponent", "esbuild", "context", "build", "meta", "entryPoint", "debug", "file", "spawn", "state", "prefix", "element", "duration", "setColor", "output", "size", "analyzeDependencies", "extractEntryPoints", "entryPointsList", "resolveFile", "fileName", "bannerComponent", "run", "cli", "argvParser", "args", "buildPromises", "configuration", "config", "build", "BuildService", "error"]
|
|
8
8
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Import will remove at compile time
|
|
3
3
|
*/
|
|
4
|
-
import type { EntryPoints } from "../configuration/interfaces/configuration.interface";
|
|
5
4
|
import type { CompilerOptions, ParsedCommandLine } from 'typescript';
|
|
6
5
|
/**
|
|
7
6
|
* Provides TypeScript-related utilities such as type-checking, generating declaration files,
|
|
@@ -82,12 +81,6 @@ export declare class TypeScriptProvider {
|
|
|
82
81
|
* output directory. This ensures that the generated declaration files are accurate and the module paths are
|
|
83
82
|
* aligned with the project's build structure.
|
|
84
83
|
*
|
|
85
|
-
* @param entryPoints - An array of entry points or an object representing the entry files for which declarations
|
|
86
|
-
* are generated. Entry points can be provided in the following formats:
|
|
87
|
-
* - An array of strings representing file paths (`string[]`).
|
|
88
|
-
* - An array of objects with `in` and `out` properties (`{ in: string, out: string }[]`).
|
|
89
|
-
* - A record object with file paths as values (`Record<string, string>`).
|
|
90
|
-
*
|
|
91
84
|
* @param noTypeChecker - Skips TypeScript type checking.
|
|
92
85
|
* @param allowError - A boolean flag indicating whether to throw an error if diagnostics are present. If set to
|
|
93
86
|
* `true`, errors are logged but not thrown, allowing the process to continue. Defaults to `false`, which throws
|
|
@@ -101,7 +94,7 @@ export declare class TypeScriptProvider {
|
|
|
101
94
|
* tsProvider.generateDeclarations(['src/index.ts', 'src/app.ts']);
|
|
102
95
|
* ```
|
|
103
96
|
*/
|
|
104
|
-
generateDeclarations(
|
|
97
|
+
generateDeclarations(noTypeChecker?: boolean, allowError?: boolean): void;
|
|
105
98
|
/**
|
|
106
99
|
* Checks if the provided node is an import or export declaration.
|
|
107
100
|
*
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"author": "Garefild",
|
|
7
|
-
"version": "1.3.
|
|
7
|
+
"version": "1.3.3",
|
|
8
8
|
"license": "Mozilla Public License Version 2.0",
|
|
9
9
|
"description": "A versatile JavaScript and TypeScript toolchain build system",
|
|
10
10
|
"homepage": "https://github.com/remotex-lab/xBuild",
|