@remotex-labs/xbuild 1.3.2 → 1.3.4
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/errors/esbuild.error.d.ts +31 -31
- package/dist/index.js +24 -15
- package/dist/index.js.map +5 -5
- package/dist/providers/typescript.provider.d.ts +1 -8
- package/package.json +3 -3
|
@@ -2,9 +2,6 @@
|
|
|
2
2
|
* Import will remove at compile time
|
|
3
3
|
*/
|
|
4
4
|
import type { Message } from 'esbuild';
|
|
5
|
-
/**
|
|
6
|
-
* Imports
|
|
7
|
-
*/
|
|
8
5
|
import { BaseError } from ".//base.error";
|
|
9
6
|
/**
|
|
10
7
|
* Represents an error that occurs during the esbuild process.
|
|
@@ -13,43 +10,46 @@ import { BaseError } from ".//base.error";
|
|
|
13
10
|
* It captures the error message and maintains the proper stack trace, allowing for easier debugging
|
|
14
11
|
* and identification of errors that occur during the build process.
|
|
15
12
|
*
|
|
16
|
-
* @class
|
|
13
|
+
* @class esBuildError
|
|
17
14
|
* @extends BaseError
|
|
18
|
-
*
|
|
19
|
-
* @param message - An object containing the error message. The `text` property is used to set the
|
|
20
|
-
* error message for the instance.
|
|
21
|
-
*
|
|
22
|
-
* @remarks
|
|
23
|
-
* - This class is designed to handle errors specifically related to the esbuild process.
|
|
24
|
-
* - A placeholder for printing the source code of the error is included for future implementation.
|
|
25
|
-
* - The name of the error is set to 'EsbuildError' for clarity in error handling.
|
|
26
|
-
*
|
|
27
|
-
* @example
|
|
28
|
-
* ```typescript
|
|
29
|
-
* throw new EsbuildError({ text: 'Failed to build module.' });
|
|
30
|
-
* ```
|
|
31
|
-
* In this example, an instance of `EsbuildError` is thrown with a specified error message, which can
|
|
32
|
-
* be caught and handled appropriately.
|
|
33
|
-
*
|
|
34
|
-
* @public
|
|
35
15
|
*/
|
|
36
16
|
export declare class esBuildError extends BaseError {
|
|
17
|
+
originalErrorStack?: string;
|
|
37
18
|
/**
|
|
38
19
|
* Creates an instance of the EsbuildError class.
|
|
39
20
|
*
|
|
40
|
-
* This constructor initializes the error message using the provided `message` object, captures
|
|
41
|
-
* the stack trace for better debugging, and sets the name of the error to 'EsbuildError'.
|
|
42
|
-
*
|
|
43
21
|
* @param message - An object containing the error message. The `text` property is used to initialize
|
|
44
22
|
* the base error class with a descriptive message about the error encountered during the esbuild process.
|
|
23
|
+
*/
|
|
24
|
+
constructor(message: Message);
|
|
25
|
+
/**
|
|
26
|
+
* Generates a formatted error message with highlighted code.
|
|
45
27
|
*
|
|
46
|
-
* @
|
|
47
|
-
*
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
28
|
+
* @param message - An esbuild Message object containing error information.
|
|
29
|
+
* @returns A formatted string of the error message.
|
|
30
|
+
*/
|
|
31
|
+
private generateFormattedError;
|
|
32
|
+
/**
|
|
33
|
+
* Reads code from a file if it exists.
|
|
51
34
|
*
|
|
52
|
-
* @
|
|
35
|
+
* @param path - The file path to read from.
|
|
36
|
+
* @returns Array of lines if file exists, otherwise null.
|
|
53
37
|
*/
|
|
54
|
-
|
|
38
|
+
private readCode;
|
|
39
|
+
/**
|
|
40
|
+
* Formats a code snippet with highlighted errors.
|
|
41
|
+
*
|
|
42
|
+
* @param code - Array of code lines.
|
|
43
|
+
* @param location - The error location within the file.
|
|
44
|
+
* @returns A formatted and highlighted code snippet string.
|
|
45
|
+
*/
|
|
46
|
+
private formatCodeSnippet;
|
|
47
|
+
/**
|
|
48
|
+
* Applies color to a given text if colors are enabled.
|
|
49
|
+
*
|
|
50
|
+
* @param color - The color code.
|
|
51
|
+
* @param text - The text to colorize.
|
|
52
|
+
* @returns The colorized text if colors are active, otherwise plain text.
|
|
53
|
+
*/
|
|
54
|
+
private applyColor;
|
|
55
55
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,26 +1,35 @@
|
|
|
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 L}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 Ce}from"@remotex-labs/xmap";var _=me(),R=$(he(import.meta.url)),be=$(R),B=(()=>{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 Ee(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 we(o,e){let r=__ACTIVE_COLOR?Ce(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}=Ee(o);if(o.isPromiseAll()||o.isEval()||o.isNative())return O(r,t,i,n,o);let s=null,a=t===B.service.file;if(a?s=B.service.getPositionWithCode(i,n):e.error.sourceMap&&(s=e.error.sourceMap.getPositionWithCode(i,n)),s){let l=a?R:_,{line:g,column:h,name:P}=s,D=L(l,s.source);return e.blockCode||(e.blockCode=we(s,e.error)),s.sourceRoot&&(D=xe(L(l,s.source),s.sourceRoot,s.line,a?be:_)),O(P||r,D,g,h,o)}return t==="evalmachine.<anonymous>"?"":O(r,t,i,n,o)}function Te(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=Te(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 I=Error.prepareStackTrace;Error.prepareStackTrace=(o,e)=>(o.callStacks=e,I?I(o,e):"");process.on("uncaughtException",o=>{console.error(o.stack)});process.on("unhandledRejection",o=>{console.error(o.stack)});import Pe from"yargs";import{hideBin as Oe}from"yargs/helpers";function M(o){let e=Pe(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 hr,resolve as v}from"path";import{build as yr,context as vr}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}import{join as Ae}from"path";import{cwd as De}from"process";import{existsSync as Le,readFileSync as _e}from"fs";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??""}};import{formatErrorCode as Be,highlightCode as Ie}from"@remotex-labs/xmap";var S=class o extends d{originalErrorStack;constructor(e){super(e.text),this.name="esBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,o),e.location&&(this.stack=this.generateFormattedError(e))}generateFormattedError(e){let{text:r,location:t,notes:i}=e,n=this.applyColor("\x1B[0m",`
|
|
14
|
+
${this.name}: ${this.applyColor("\x1B[38;5;243m",t?.file??"")}
|
|
15
|
+
`);if(n+=this.applyColor("\x1B[38;5;203m",`${r}
|
|
16
|
+
|
|
17
|
+
`),i.forEach(s=>{n+=this.applyColor("\x1B[38;5;243m",`${s.text}
|
|
18
|
+
|
|
19
|
+
`)}),t){let s=this.readCode(t.file);s&&(n+=`${this.formatCodeSnippet(s,t)}
|
|
20
|
+
`)}return n}readCode(e){try{return Le(e)?_e(Ae(De(),e),"utf-8").split(`
|
|
21
|
+
`):null}catch{return null}}formatCodeSnippet(e,r){let{line:t=1,column:i=0,file:n}=r,s=Math.max(t-3,0),a=Math.min(t+3,e.length),l=Ie(e.slice(s,a).join(`
|
|
22
|
+
`));return Be({line:t,name:null,code:l,source:n,endLine:a,startLine:s,column:i+1,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1},{color:global.__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:global.__ACTIVE_COLOR?"\x1B[0m":""})}applyColor(e,r){return global.__ACTIVE_COLOR?c(e,r):r}};var $e=`
|
|
14
23
|
______ _ _ _
|
|
15
24
|
| ___ \\ (_) | | |
|
|
16
25
|
__ _| |_/ /_ _ _| | __| |
|
|
17
26
|
\\ \\/ / ___ \\ | | | | |/ _\` |
|
|
18
27
|
> <| |_/ / |_| | | | (_| |
|
|
19
28
|
/_/\\_\\____/ \\__,_|_|_|\\__,_|
|
|
20
|
-
`;function
|
|
21
|
-
\r${c("\x1B[38;5;208m",
|
|
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,
|
|
29
|
+
`;function j(o=!0){return`
|
|
30
|
+
\r${c("\x1B[38;5;208m",$e,o)}
|
|
31
|
+
\rVersion: ${c("\x1B[38;5;197m","1.3.4",o)}
|
|
32
|
+
\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 q from"http";import*as z from"https";var H=`<!DOCTYPE html>
|
|
24
33
|
<html>
|
|
25
34
|
<head>
|
|
26
35
|
<meta charset="UTF-8">
|
|
@@ -77,10 +86,10 @@ __ _| |_/ /_ _ _| | __| |
|
|
|
77
86
|
<ul>\${ fileList }</ul>
|
|
78
87
|
</body>
|
|
79
88
|
</html>
|
|
80
|
-
`;import{extname as
|
|
81
|
-
`),a=c("\x1B[38;5;81m",
|
|
89
|
+
`;import{extname as W,join as V,resolve as Me}from"path";import{existsSync as J,readdir as Fe,readFile as je,readFileSync as U,stat as He}from"fs";var G={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"}},C=class{rootDir;isHttps;config;constructor(e,r){this.rootDir=Me(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(){q.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)=>{He(e,(i,n)=>i?t(i):r(n))})}handleDirectory(e,r,t){Fe(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:P}=G[g]||G.folder;return`<li><i class="fas ${h}" style="color: ${P};"></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);je(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 We}from"fs";import{resolve as Ve}from"path";var b=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=Ve(e.path);r.contents||(r.contents=await We.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 Je}from"path";function Z(o,e,r,t){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in r){let s=Je(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 Ue}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 Ge={write:!1,bundle:!0,minify:!1,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function qe(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:Ue(),...Ge,...e,entryPoints:[o]},i=(await K(r)).outputFiles?.pop()?.text??"";return qe(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 E,relative as ze,dirname as Ye,parse as Ze}from"path";import{sys as Ke,factory as A,createProgram as ee,visitEachChild as re,isStringLiteral as Xe,resolveModuleName as Qe,DiagnosticCategory as er,isImportDeclaration as te,isExportDeclaration as oe,getPreEmitDiagnostics as ie,flattenDiagnosticMessageText as ne}from"typescript";var w=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===er.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&&Xe(e.moduleSpecifier)}resolveModuleFileName(e,r){let t,i=Qe(e,r.baseUrl,r,Ke);if(i.resolvedModule&&r.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return t;t=E(i.resolvedModule.resolvedFileName).replace(E(r.baseUrl),".")}return t}getRelativePathToOutDir(e,r){e=E(e).replace(E(this.options.baseUrl??""),".");let t=ze(Ye(e),r).replace(/\\/g,"/"),i=Ze(t);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,r){let t=A.createStringLiteral(r);return te(e)?A.updateImportDeclaration(e,e.modifiers,e.importClause,t,void 0):oe(e)?A.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,`
|
|
90
|
+
`),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
91
|
`))}),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,
|
|
92
|
+
`),!r))throw new x("Type checking failed due to errors.")}};import u from"typescript";import{dirname as cr}from"path";import{existsSync as le,readFileSync as lr}from"fs";import{cwd as rr}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:rr(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as ir}from"module";import{SourceService as nr}from"@remotex-labs/xmap";import{Script as tr,createContext as or}from"vm";function se(o,e={}){e.console=console;let r=new tr(o),t=or(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]=sr(t,e):typeof t=="object"&&t!==null&&ae(t,e)}return o}function sr(o,e){return(...r)=>{try{return o(...r)}catch(t){throw new m(t,e)}}}function ar(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=ir(import.meta.url),n=new nr(JSON.parse(atob(r)));try{await se(e,{require:i,module:t})}catch(s){throw new m(s,n)}return ar(t.exports.default,n)}var fr=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 pr(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)?lr(e,"utf8"):JSON.stringify(fr),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,cr(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=pr(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 ur(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=ur(o)),e}else if(o&&typeof o=="object")return o;throw new p("Unsupported entry points format")}import{join as dr}from"path";import{mkdirSync as mr,writeFileSync as gr}from"fs";function de(o){let e=o.moduleTypeOutDir??o.esbuild.outdir??"dist",r=o.esbuild.format==="esm"?"module":"commonjs";mr(e,{recursive:!0}),gr(dr(e,"package.json"),`{"type": "${r}"}`)}var T=class{constructor(e){this.config=e;let r=fe(this.config.esbuild);this.config.esbuild.logLevel="silent",this.pluginsProvider=new b,this.typeScriptProvider=new w(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 C(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=v(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=hr(v(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]=v(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 vr(e):await yr(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(`
|
|
93
|
+
${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(`
|
|
94
|
+
`),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=v(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=v(s).replace(t,"."),l=a.substring(0,a.lastIndexOf("."));i[l]=s}e.entryPoints=i}};global.__ACTIVE_COLOR=!0;console.log(j());async function Sr(){let o=M(process.argv),e=o.argv,t=(await pe(e.config,o)).map(async i=>{let n=new T(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)}Sr().catch(o=>{console.error(o.stack)});
|
|
86
95
|
//# sourceMappingURL=index.js.map
|