@remotex-labs/xbuild
Version:
A versatile JavaScript and TypeScript toolchain build system
103 lines (95 loc) • 34.9 kB
JavaScript
import{cwd as Pe}from"process";import{readFileSync as Te}from"fs";import{fileURLToPath as Oe}from"url";import{dirname as q,join as Re,resolve as U}from"path";import{SourceService as ke}from"@remotex-labs/xmap";function p(n,e,t=__ACTIVE_COLOR){return t?`${n}${e}\x1B[0m`:e}import{formatErrorCode as Ae}from"@remotex-labs/xmap/formatter.component";import{highlightCode as De}from"@remotex-labs/xmap/highlighter.component";var G=Pe(),N=q(Oe(import.meta.url)),Fe=q(N),z=(()=>{let n;return{get service(){if(!n){let e=Te(Re(N,"index.js.map"));n=new ke(e.toString(),import.meta.url)}return n}}})();global.__ACTIVE_COLOR||(global.__ACTIVE_COLOR=!0);function Le(n,e,t,r){return`${n.replace(`${r}\\`,e).replace(/\\/g,"/")}#L${t}`}function M(n,e,t,r,i){if(i.isPromiseAll())return`at async Promise.all (index: ${i.getPromiseIndex()})`;let o=i.isAsync()?"async":"",s=n?`${o} ${n}`:o,a=t>=0&&r>=0?p("\x1B[38;5;243m",`[${t}:${r}]`):"";return`at ${s} ${p("\x1B[38;5;238m",e)} ${a}`.replace(/\s{2,}/g," ").trim()}function Be(n){let e=n.getLineNumber()||-1,t=n.getColumnNumber()||-1,r=n.getFileName()||"<anonymous>",i=n.getTypeName()||"",o=n.getFunctionName()||"",s=n.isNative()?"<native>":o;return i&&(s=`${i}.${s}`),{functionName:s,source:r,line:e,column:t}}function Ie(n,e){let t=__ACTIVE_COLOR?De(n.code):n.code;return n.name&&e.name=="TypeError"&&(e.message=e.message.replace(/^\S+/,n.name)),Ae({...n,code:t},{color:__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:__ACTIVE_COLOR?"\x1B[0m":""})}function _e(n,e){let{functionName:t,source:r,line:i,column:o}=Be(n);if(n.isPromiseAll()||n.isEval()||n.isNative())return M(t,r,i,o,n);let s=null,a=r===z.service.file;if(a?s=z.service.getPositionWithCode(i,o):e.error.sourceMap&&(s=e.error.sourceMap.getPositionWithCode(i,o)),s){let c=a?N:G,{line:l,column:g,name:m}=s,b=U(c,s.source);return e.blockCode||(e.blockCode=Ie(s,e.error)),s.sourceRoot&&(b=Le(U(c,s.source),s.sourceRoot,s.line,a?Fe:G)),M(m||t,b,l,g,n)}return r==="evalmachine.<anonymous>"?"":M(t,r,i,o,n)}function $e(n,e){return e.map(t=>_e(t,n)).filter(Boolean)}function Y(n,e){let t={error:n,blockCode:null,formattedError:global.__ACTIVE_COLOR?"\x1B[0m":""},r=$e(t,e);return t.formattedError+=`
${n.name}:
${p("\x1B[38;5;203m",n.message)}
`,t.blockCode&&(t.formattedError+=`${t.blockCode}
`),r.length>0&&(t.formattedError+=`Enhanced Stack Trace:
${r.join(`
`)}
`),t.formattedError}var J=Error.prepareStackTrace;Error.prepareStackTrace=(n,e)=>(n.callStacks=e,J?J(n,e):"");process.on("uncaughtException",n=>{console.error(n.stack),process.exit(1)});process.on("unhandledRejection",n=>{console.error(n.stack),process.exit(1)});import{existsSync as $t}from"fs";import Me from"yargs";import{hideBin as Ne}from"yargs/helpers";function K(n){let e=Me(Ne(n)).command("$0 [file]","A versatile JavaScript and TypeScript toolchain build system.",t=>{t.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(t=>{t.version&&process.exit(0)});return e.showHelp(t=>{(process.argv.includes("--help")||process.argv.includes("-h"))&&(console.log(t+`
`),process.exit(0))}),e}import*as ye from"node:process";import{dirname as dt,resolve as w}from"path";import{build as gt,context as mt}from"esbuild";var T=class n extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,n.prototype),t?.cause&&(this.cause=t.cause)}};import{spawn as je}from"child_process";function X(n,e=!1){let t=["--enable-source-maps",n];e&&t.unshift("--inspect-brk=0.0.0.0:0");let r=je("node",t);return r.stdout.on("data",i=>{console.log(i.toString())}),r.stderr.on("data",i=>{console.error(i.toString())}),r}import f from"typescript";import{promises as Ue}from"fs";import{cwd as We}from"process";import{build as Z}from"esbuild";var h=class n extends Error{constructor(t,r){super(t);this.sourceMap=r;Error.captureStackTrace&&Error.captureStackTrace(this,n),this.name="xBuildBaseError"}callStacks=[];reformatStack(t){return t.callStacks?Y(this,t.callStacks):t.stack??""}};var y=class n extends h{originalErrorStack;constructor(e,t){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,n),t&&Object.assign(this,t),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var He={write:!1,bundle:!0,minify:!0,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function Ve(n){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,t=n.match(e);if(!t||!t[1])throw new y("Source map URL not found in the output.");let r=t[1];return{code:n.replace(e,""),sourceMap:r}}async function Q(n,e={}){let t={absWorkingDir:We(),...He,...e,entryPoints:[n]},i=(await Z(t)).outputFiles?.pop()?.text??"";return Ve(i)}async function O(n,e="browser"){return await Z({outdir:"tmp",write:!1,bundle:!0,metafile:!0,platform:e,packages:"external",logLevel:"silent",entryPoints:n,loader:{".html":"text"}})}function Ge(n,e){let t=f.createSourceFile("temp.ts",n,f.ScriptTarget.Latest,!0),r=i=>{if(f.isFunctionDeclaration(i)&&i.name&&i.name.text.startsWith("$$")){e.removeFunctions.add(i.name.text);return}if(f.isVariableStatement(i)&&i.declarationList.declarations.length>0){i.declarationList.declarations.forEach(o=>{f.isIdentifier(o.name)&&o.name.text.startsWith("$$")&&o.initializer&&(f.isArrowFunction(o.initializer)||f.isFunctionExpression(o.initializer))&&e.removeFunctions.add(o.name.text)});return}if(f.isIdentifier(i)&&f.isExpression(i)&&i.escapedText&&i.escapedText.startsWith("$$")){e.removeFunctions.add(i.escapedText);return}f.forEachChild(i,r)};r(t)}async function ze(n,e,t){let r=Object.keys(n.inputs);for(let i of r){let o=await Ue.readFile(i,"utf8"),s=/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,a;for(;(a=s.exec(o))!==null;){let[,c,l]=a;e.define[c]||Ge(l,t)}}}function Je(n,e){let t=[];function r(o){if(f.isCallExpression(o)){let s=o.expression.getText(),a=s.endsWith("!")?s.slice(0,-1):s;a.startsWith("$$")&&e.removeFunctions.has(a)&&t.push({start:o.getStart(),end:o.getEnd(),replacement:"undefined"});let c=o.expression;if(f.isPropertyAccessExpression(c)){let l=c.name;f.isIdentifier(l)&&l.text.startsWith("$$")&&t.push({start:o.getStart(),end:o.getEnd(),replacement:"undefined"})}}f.forEachChild(o,r)}r(n),t.sort((o,s)=>s.start-o.start);let i=n.getFullText();for(let{start:o,end:s,replacement:a}of t)i=i.substring(0,o)+a+i.substring(s);return i}async function ee(n,e,t,r,i){if(!t.path.endsWith(".ts")&&!t.path.endsWith(".js"))return{loader:e,contents:n};if(!r.macros){let a={removeFunctions:new Set},c=await O([t.path]);await ze(c.metafile,i,a),r.macros=a}let o=n.toString(),s=f.createSourceFile(t.path,o,f.ScriptTarget.Latest,!0);return{loader:e??"ts",contents:Je(s,r.macros)}}import{join as qe}from"path";import{cwd as Ye}from"process";import{existsSync as Ke,readFileSync as Xe}from"fs";import{formatErrorCode as Ze}from"@remotex-labs/xmap/formatter.component";import{highlightCode as Qe}from"@remotex-labs/xmap/highlighter.component";var R=class n extends h{originalErrorStack;constructor(e){super(e.text),this.name="esBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,n),e.location?this.stack=this.generateFormattedError(e):(this.originalErrorStack=this.stack,this.stack=this.reformatStack(this))}generateFormattedError(e){let{text:t,location:r,notes:i}=e,o=this.applyColor("\x1B[0m",`
${this.name}: ${this.applyColor("\x1B[38;5;243m",r?.file??"")}
`);if(o+=this.applyColor("\x1B[38;5;203m",`${t}
`),i.forEach(s=>{o+=this.applyColor("\x1B[38;5;243m",`${s.text}
`)}),r){let s=this.readCode(r.file);s&&(o+=`${this.formatCodeSnippet(s,r)}
`)}return o}readCode(e){try{return Ke(e)?Xe(qe(Ye(),e),"utf-8").split(`
`):null}catch{return null}}formatCodeSnippet(e,t){let{line:r=1,column:i=0,file:o}=t,s=Math.max(r-3,0),a=Math.min(r+3,e.length),c=Qe(e.slice(s,a).join(`
`));return Ze({line:r,name:null,code:c,source:o,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,t){return global.__ACTIVE_COLOR?p(e,t):t}};function d(){return p("\x1B[38;5;203m","[xBuild]")}var v=class n extends h{originalError;originalErrorStack;constructor(e,t){super(e.message,t),Error.captureStackTrace&&Error.captureStackTrace(this,n),this.originalError=e,this.originalErrorStack=e.stack,this.name="VMRuntimeError",this.stack=this.reformatStack(e)}};import*as ae from"http";import*as ce from"https";var te=`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Directory Listing</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
h1 {
color: #333;
text-align: center;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
li {
background: #fff;
border: 1px solid #ddd;
border-radius: 4px;
margin: 5px;
padding: 10px;
width: 200px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
}
i {
margin-right: 10px;
font-size: 18px;
color: #666;
}
a {
text-decoration: none;
color: #007bff;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Directory Listing</h1>
<ul>\${ fileList }</ul>
</body>
</html>
`;import{extname as re,join as ie,resolve as tt}from"path";import{existsSync as oe,readdir as rt,readFile as it,readFileSync as ne,stat as ot}from"fs";var se={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"}},k=class{rootDir;isHttps;config;constructor(e,t){this.rootDir=tt(t),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?oe(this.config.keyfile)&&oe(this.config.certfile):!1}start(){if(this.config.onStart&&this.config.onStart(),this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){ae.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}).listen(this.config.port,this.config.host,()=>{console.log(`${d()} HTTP/S server is running at http://${this.config.host}:${this.config.port}`)})}startHttpsServer(){let e={key:ne(this.config.keyfile),cert:ne(this.config.certfile)};ce.createServer(e,(r,i)=>{this.handleRequest(r,i,()=>this.defaultResponse(r,i))}).listen(this.config.port,this.config.host,()=>{let r=p("\x1B[38;5;227m",`https://${this.config.host}:${this.config.port}`);console.log(`${d()} HTTPS server is running at ${r}`)})}handleRequest(e,t,r){try{this.config.onRequest?this.config.onRequest(e,t,r):r()}catch(i){this.sendError(t,i)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",ts:"text/plain",map:"application/json",json:"application/json",png:"image/png",jpg:"image/jpeg",gif:"image/gif",txt:"text/plain"}[e]||"application/octet-stream"}async defaultResponse(e,t){let r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",i=ie(this.rootDir,r);if(!i.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await this.promisifyStat(i);o.isDirectory()?this.handleDirectory(i,r,t):o.isFile()&&this.handleFile(i,t)}catch(o){let s=o.message;s.includes("favicon")||console.log(d(),s),this.sendNotFound(t)}}promisifyStat(e){return new Promise((t,r)=>{ot(e,(i,o)=>i?r(i):t(o))})}handleDirectory(e,t,r){rt(e,(i,o)=>{if(i)return this.sendError(r,i);let s=o.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let c=ie(t,a);if(c.match(/[^A-Za-z0-9_\/\\.-]/))return;let l=re(a).slice(1)||"folder",{icon:g,color:m}=se[l]||se.folder;return`<li><i class="fas ${g}" style="color: ${m};"></i> <a href="/${c}">${a}</a></li>`}).join("");r.writeHead(200,{"Content-Type":"text/html"}),r.end(te.replace("${ fileList }",s))})}handleFile(e,t){let r=re(e).slice(1)||"txt",i=this.getContentType(r);it(e,(o,s)=>{if(o)return this.sendError(t,o);t.writeHead(200,{"Content-Type":i}),t.end(s)})}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(`${d()}`,t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{promises as nt}from"fs";import{resolve as st}from"path";var A=class{buildState={};onEndHooks=[];onSuccess=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnSuccess(e){e&&this.onSuccess.push(e)}registerOnResolve(e){e&&this.onResolveHooks.push(e)}registerOnLoad(e){e&&this.onLoadHooks.push(e)}setup(){return{name:"middleware-plugin",setup:e=>{e.initialOptions.metafile=!0,e.onEnd(this.handleOnEnd.bind(this)),e.onStart(this.handleOnStart.bind(this,e)),e.onLoad({filter:/.*/},this.handleOnLoad.bind(this)),e.onResolve({filter:/.*/},this.handleOnResolve.bind(this))}}}async handleOnStart(e){this.buildState={};let t={errors:[],warnings:[]};for(let r of this.onStartHooks){let i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}return t}async handleOnEnd(e){let t={errors:e.errors??[],warnings:e.warnings??[]};for(let r of this.onEndHooks){e.errors=t.errors,e.warnings=t.warnings;let i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}if(t.errors.length<1)for(let r of this.onSuccess)await r(e,this.buildState);return t}async handleOnResolve(e){let t={};for(let r of this.onResolveHooks){let i=await r(e,this.buildState);i&&(t={...t,...i,path:i.path||t.path})}return t.path?t:null}async handleOnLoad(e){let t={contents:void 0,loader:"default"},r=st(e.path);t.contents||(t.contents=await nt.readFile(r,"utf8"));for(let i of this.onLoadHooks){let o=await i(t.contents??"",t.loader,e,this.buildState);o&&(t={...t,...o,contents:o.contents||t.contents,loader:o.loader||t.loader})}return t.contents?t:null}};function le(n,e){return n.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(t,r,i)=>e[r]?i:`
`.repeat((i.match(/\n/g)||[]).length))}import u from"typescript";import{mkdirSync as pe,writeFileSync as de}from"fs";import{dirname as L,relative as H,resolve as ge,join as at}from"path";import{xterm as C}from"@remotex-labs/xansi/xterm.component";import{sys as j}from"typescript";var ue={getNewLine:()=>j.newLine,getCurrentDirectory:j.getCurrentDirectory,getCanonicalFileName:n=>j.useCaseSensitiveFileNames?n:n.toLowerCase()},W=`
/**
* This file was automatically generated by xBuild.
* DO NOT EDIT MANUALLY.
*/
`;import S from"typescript";import{resolve as fe}from"path";var D=class{constructor(e){this.options=e}fileVersions=new Map;touchFiles(e){let t=fe(e),r=this.fileVersions.get(t)??0;this.fileVersions.set(t,r+1)}fileExists(e){return S.sys.fileExists(e)}readFile(e,t){return S.sys.readFile(e,t)}readDirectory(e,t,r,i,o){return S.sys.readDirectory(e,t,r,i,o)}getDirectories(e){return S.sys.getDirectories(e)}directoryExists(e){return S.sys.directoryExists(e)}getCurrentDirectory(){return S.sys.getCurrentDirectory()}getScriptFileNames(){return Array.from(this.fileVersions.keys())}getCompilationSettings(){return this.options}getDefaultLibFileName(e){return S.getDefaultLibFilePath(e)}getScriptVersion(e){return this.fileVersions.get(fe(e))?.toString()??"0"}getScriptSnapshot(e){if(!this.fileExists(e))return;let t=this.readFile(e);return t!=null?S.ScriptSnapshot.fromString(t):void 0}};import x from"typescript";var F=class{constructor(e,t){this.config=e;this.languageService=t}emitBundledDeclarations(e){let t=[];for(let r of e){let i=this.generateBundledDeclaration(r);i&&t.push(i)}return t}generateBundledDeclaration(e){let t=this.languageService.getProgram();if(!t)return;let r=t.getTypeChecker(),i=t.getSourceFile(e);if(!i)throw new Error(`Entry point not found: ${e}
Please verify that:
1. The file exists at the specified path
2. The file is included in the "include" section of your tsconfig.json
3. The file path is correctly specified in your bundle configuration`);let o=new Set,s=new Set;this.collectFilesRecursive(i,t,o),this.collectExportsFromSourceFile(i,r,s);let{bundledContent:a,externalImports:c}=this.processDeclaredFiles(o,s);return this.createFinalBundleContent(c,a)}resolveModule(e,t,r){return x.resolveModuleName(e,t,r.getCompilerOptions(),x.sys).resolvedModule?.resolvedFileName}collectFilesRecursive(e,t,r){if(!r.has(e.fileName)){r.add(e.fileName);for(let i of e.statements)if((x.isImportDeclaration(i)||x.isExportDeclaration(i))&&i.moduleSpecifier&&x.isStringLiteral(i.moduleSpecifier)){let o=i.moduleSpecifier.text,s=this.resolveModule(o,e.fileName,t);if(s&&!s.includes("node_modules")){let a=t.getSourceFile(s);a&&this.collectFilesRecursive(a,t,r)}}}}collectExportsRecursive(e,t,r){for(let i of t.getExportsOfModule(e)){let o=i.getName();r.add(o);let s=i.getDeclarations()?.[0];s&&x.isModuleDeclaration(s)&&this.collectExportsRecursive(i,t,r)}}processDeclaredFiles(e,t){let r=new Set,i=[];for(let o of e){let s=this.processDeclarationFile(o,t,r);s&&i.push(s)}return{bundledContent:i,externalImports:r}}collectExportsFromSourceFile(e,t,r){let i=t.getSymbolAtLocation(e);i&&this.collectExportsRecursive(i,t,r)}processDeclarationFile(e,t,r){let i=this.languageService.getEmitOutput(e,!0);if(i.emitSkipped)return;let o=i.outputFiles.find(c=>c.name.endsWith(".d.ts"));if(!o)return;let s=o.text.split(`
`),a=[];for(let c of s)if(c=c.trimEnd(),!!c){if(this.isImportOrExportWithFrom(c)){let l=this.extractModulePath(c);if(l)if(this.isExternalModule(l,e)){r.add(c);continue}else continue}c.startsWith("export ")&&(c=this.processExportLine(c,t)),c&&a.push(c)}return a.join(`
`)}isImportOrExportWithFrom(e){return e.startsWith("import ")||e.startsWith("export ")&&(e.includes(" from ")||e.startsWith("export *"))}extractModulePath(e){return e.match(/from\s+["'](.+)["']/)?.[1]}isExternalModule(e,t){if(e.startsWith(".")||e.startsWith("/"))return!1;let r=x.resolveModuleName(e,t,this.config.options,x.sys);return r.resolvedModule?r.resolvedModule.resolvedFileName.includes("node_modules"):!0}processExportLine(e,t){let r=e.match(/export\s+(?:declare\s+)?(?:class|interface|function|const|let|var|type|enum)\s+(\w+)/);if(r){let i=r[1];if(!t.has(i))return e.replace("export ","")}return e}createFinalBundleContent(e,t){let r=Array.from(e).join(`
`),i=t.join(`
`);return r?`${W}${r}
${i}`:`${W}${i}`}};var B=class{root;config;languageService;languageServiceHost;declarationBundlerService;constructor(e,t,r="dist"){this.root=L(e),this.config=this.parseConfig(e,t,r),this.languageServiceHost=new D(this.config.options),this.languageService=this.createLanguageService(),this.declarationBundlerService=new F(this.config,this.languageService),this.initializeDiagnostics(),this.updateFiles(this.config.fileNames)}updateFiles(e){let t=Array.isArray(e)?e:[e];for(let r of t)this.languageServiceHost.touchFiles(r)}check(){let e=[],t=this.languageService.getProgram()?.getSourceFiles()??[];for(let r of t){let i=r.fileName;!i.includes("/node_modules/")&&!i.endsWith(".d.ts")&&e.push(...this.getDiagnostics(i))}return e}emitDeclarations(){let e=this.languageService.getProgram();if(e)for(let t of e.getSourceFiles()){let r=t.fileName;if(r.includes("/node_modules/")||r.endsWith(".d.ts"))continue;let i=this.getEmitOutput(r);if(!i.emitSkipped){let o=i.outputFile;if(o&&o.name.endsWith(".d.ts")){let s=L(o.name);pe(s,{recursive:!0}),de(o.name,o.text)}}}}emitBundleDeclarations(e){if(!this.languageService.getProgram())return;let r=Object.keys(e),i=Object.values(e),o=this.declarationBundlerService.emitBundledDeclarations(i);r.forEach((s,a)=>{let c=o[a],l=s.endsWith(".d.ts")?s:`${s}.d.ts`,g=at(this.config.options.outDir,l),m=L(g);pe(m,{recursive:!0}),de(g,c)})}formatDiagnostics(e){return e.length?e.map(t=>{if(t.file&&t.start!==void 0){let{line:r,character:i}=t.file.getLineAndCharacterOfPosition(t.start),o=u.flattenDiagnosticMessageText(t.messageText,`
`),s=H(this.root,t.file.fileName);return[C.deepOrange("[TS]"),`${C.hex("#5fd7ff")(s)}:${C.lightYellow(`${r+1}:${i+1}`)}`,"-",`${C.lightCoral("error")} ${C.gray(`TS${t.code}`)}:`,o].join(" ")}return u.flattenDiagnosticMessageText(t.messageText,`
`)}):[]}getEmitOutput(e){let t=this.languageService.getEmitOutput(e,!0),r=t.outputFiles.find(l=>l.name.endsWith(".d.ts"));if(t.emitSkipped||!r)return{emitSkipped:!0,outputFile:void 0};let i=u.createSourceFile(r.name,r.text,u.ScriptTarget.Latest,!0),o=u.transform(i,[l=>this.createVisitor(r.name,l)]),s=u.createPrinter(),a=o.transformed[0],c=s.printFile(a);return o.dispose(),{emitSkipped:!1,outputFile:{name:r.name,text:c,writeByteOrderMark:!1}}}resolveModuleFileName(e){let t=this.config.options;if(!t.rootDir)return;let r=u.resolveModuleName(e,t.rootDir,t,u.sys).resolvedModule;if(!(!r||r.resolvedFileName.includes("node_modules")))return H(ge(t.rootDir),r.resolvedFileName)}getRelativePathToOutDir(e,t){let r=L(e),i=ge(this.config.options.outDir,t),o=H(r,i).replace(/\\/g,"/");return o=o.replace(/\.[jt]s$/,""),o.startsWith(".")||(o="./"+o),o}createVisitor(e,t){return r=>{let i=o=>{if((u.isImportDeclaration(o)||u.isExportDeclaration(o))&&o.moduleSpecifier&&u.isStringLiteral(o.moduleSpecifier)){let s=o.moduleSpecifier.text,a=this.resolveModuleFileName(s);if(a){let c=this.getRelativePathToOutDir(e,a),l=u.factory.createStringLiteral(c);return u.isImportDeclaration(o)?u.factory.updateImportDeclaration(o,o.modifiers,o.importClause,l,void 0):u.factory.updateExportDeclaration(o,o.modifiers,o.isTypeOnly??!1,o.exportClause,l,void 0)}}return u.visitEachChild(o,i,t)};return u.visitNode(r,i)}}parseConfig(e,t,r){let i=u.getParsedCommandLineOfConfigFile(e,{stripInternal:!0,skipLibCheck:!0},{...u.sys,onUnRecoverableConfigFileDiagnostic:o=>{throw new Error(u.formatDiagnostic(o,ue))}});if(!i)throw new Error(`Unable to parse TypeScript configuration: ${e}`);return i.options={...i.options,baseUrl:i.options.baseUrl||this.root,rootDir:i.options.rootDir||this.root,outDir:t||i.options.outDir||r},i}createLanguageService(){return u.createLanguageService(this.languageServiceHost,u.createDocumentRegistry())}initializeDiagnostics(){}getDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e),...this.languageService.getSyntacticDiagnostics(e)]}};import{relative as ct}from"path";function me(n,e,t,r){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let o in t){let s=ct(e,t[o]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),n=n.replaceAll(o,`${s}/`),r&&(n=n.replace(i,(a,c)=>(c.startsWith("../")||c.startsWith("./"))&&!c.endsWith(".js")?a.replace(c,`${c}.js`):a))}return n}function lt(n){let e={};return n.forEach(t=>{let r=t.substring(0,t.lastIndexOf("."));e[r]=t}),e}function V(n){if(Array.isArray(n)){let e={};return n.length>0&&typeof n[0]=="object"?n.forEach(t=>{e[t.out]=t.in}):typeof n[0]=="string"&&(e=lt(n)),e}else if(n&&typeof n=="object")return n;throw new y("Unsupported entry points format")}import{join as ut}from"path";import{mkdirSync as ft,writeFileSync as pt}from"fs";function he(n){let e=n.moduleTypeOutDir??n.esbuild.outdir??"dist",t=n.esbuild.format==="esm"?"module":"commonjs";ft(e,{recursive:!0}),pt(ut(e,"package.json"),`{"type": "${t}"}`)}var E=class{constructor(e){this.config=e;this.config.esbuild.logLevel="silent",this.pluginsProvider=new A,this.typescriptModule=new B(this.config.esbuild.tsconfig??"tsconfig.json",this.config.declarationOutDir,this.config.esbuild.outdir),this.entryPoints=V(this.config.esbuild.entryPoints),this.typescriptModule.updateFiles(Object.values(this.entryPoints)),this.configureDevelopmentMode(),this.setupPlugins()}typescriptModule;activePossess=[];pluginsProvider;entryPoints;async run(){return await this.execute(async()=>{let e=await this.build();return(this.config.watch||this.config.dev)&&await e.watch(),e})}async runDebug(e){return await this.execute(async()=>{this.config.dev=!1,this.config.watch=!1;let t=await this.build();this.spawnDev(t.metafile,e,!0)})}async serve(){let e=new k(this.config.serve,this.config.esbuild.outdir??"");return await this.execute(async()=>{e.start(),await(await this.build()).watch()})}async execute(e){try{return await e()}catch(t){let r=t;Array.isArray(r.errors)&&(!this.config.watch||!this.config.dev||!this.config.serve.active)?this.handleErrors(r):console.error(new v(t).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=w(this.typescriptModule.config.options.baseUrl??""),t=this.generatePathAlias(e);this.registerPluginHooks(t,e),this.pluginsProvider.registerOnLoad(async(r,i,o,s)=>await ee(r,i,o,s,this.config))}registerPluginHooks(e,t){this.pluginsProvider.registerOnLoad((r,i,o)=>{this.typescriptModule.updateFiles(o.path)}),this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((r,i,o)=>{if(o.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let s=dt(w(o.path).replace(t,"."));r=me(r.toString(),s,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:le(r.toString(),this.config.define)}}})}generatePathAlias(e){let t=this.typescriptModule.config.options.paths,r={};for(let i in t){let o=t[i];if(o.length>0){let s=i.replace(/\*/g,"");r[s]=w(o[0].replace(/\*/g,"")).replace(e,".")}}return r}handleErrors(e){let t=e.errors??[];for(let r of t){if(!r.detail){console.error(new R(r).stack);continue}if(r.detail.name!=="TypesError"){if(r.detail.name){if(r.detail.name==="VMRuntimeError"){console.error(r.detail.stack);continue}if(r.detail instanceof Error){console.error(new v(r.detail).stack);continue}}return console.error(r.text)}}}injects(e,t,r){if(!t)return;e[r]||(e[r]={});let i=e[r];for(let o in t)if(t.hasOwnProperty(o)){let s=t[o];if(typeof s=="function"){console.log(`${d()} trigger ${r} function`),i[o]=s();continue}i[o]=s}}async build(){he(this.config);let e=this.config.esbuild;this.config.hooks&&(this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd),this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad),this.pluginsProvider.registerOnEnd(this.config.hooks.onSuccess),this.pluginsProvider.registerOnStart(this.config.hooks.onStart),this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve)),e.define||(e.define={});for(let t in this.config.define)e.define[t]=JSON.stringify(this.config.define[t]);return this.config.esbuild.bundle||await this.processEntryPoints(),e.plugins=[this.pluginsProvider.setup()],this.injects(this.config.esbuild,this.config.banner,"banner"),this.injects(this.config.esbuild,this.config.footer,"footer"),this.config.watch||this.config.dev||this.config.serve.active?await mt(e):await gt(e)}spawnDev(e,t,r=!1){if(Array.isArray(t))for(let i in e.outputs)i.includes("map")||!t.some(o=>i.includes(`/${o}.`))||this.activePossess.push(X(i,r))}async start(e,t){try{if(t.startTime=Date.now(),console.log(`${d()} StartBuild ${e.initialOptions.outdir}`),!this.config.noTypeChecker){let r=this.typescriptModule.check();if(r.length>0&&(console.log(this.typescriptModule.formatDiagnostics(r).join(`
`)+`
`),!this.config.buildOnError))throw new T("Type checking failed due to errors.")}this.config.bundleDeclaration?this.typescriptModule.emitBundleDeclarations(this.entryPoints):this.config.declaration&&this.typescriptModule.emitDeclarations()}finally{for(;this.activePossess.length>0;){let r=this.activePossess.pop();r&&r.kill("SIGTERM")}}}async end(e,t){if(e.errors.length>0){this.handleErrors(e),!this.config.serve.active&&!this.config.dev&&!this.config.watch&&ye.exit(1);return}let r=Date.now()-t.startTime;console.log(`
${d()} ${p("\x1B[38;5;166m",`Build completed! in ${r} ms`)}`),console.log(`${d()} ${Object.keys(e.metafile.outputs).length} Modules:`),Object.keys(e.metafile.outputs).forEach(i=>{let o=e.metafile.outputs[i].bytes;console.log(`${d()} ${p("\x1B[38;5;227m",i)}: ${p("\x1B[38;5;208m",o.toString())} bytes`)}),console.log(`
`),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,t=await O(e.entryPoints,e.platform),r=w(this.typescriptModule.config.options.baseUrl??""),i=V(e.entryPoints),o=Object.values(i);Array.isArray(e.entryPoints)&&typeof e.entryPoints[0]=="string"&&(i={},o=[]);for(let s in t.metafile.inputs){if(o.includes(s))continue;let a=w(s).replace(r,"."),c=a.substring(0,a.lastIndexOf("."));i[c]=s}e.entryPoints=i}};import{createRequire as vt}from"module";import{SourceService as St}from"@remotex-labs/xmap";import{Script as ht,createContext as yt}from"vm";function ve(n,e={}){e.RegExp=RegExp,e.console=console;let t=new ht(n),r=yt(e);return t.runInContext(r,{breakOnSigint:!0})}function Se(n,e){for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let r=n[t];typeof r=="function"?n[t]=xt(r,e):typeof r=="object"&&r!==null&&Se(r,e)}return n}function xt(n,e){return(...t)=>{try{return n(...t)}catch(r){throw new v(r,e)}}}function bt(n,e){return Se(n,e)}async function I(n){let{code:e,sourceMap:t}=await Q(n,{banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),r={exports:{}},i=vt(import.meta.url),o=new St(JSON.parse(atob(t)));try{await ve(e,{URL,module:r,require:i,process})}catch(s){throw new v(s,o)}return bt(r.exports.default,o)}import{cwd as Bt}from"process";import{existsSync as It}from"fs";import{join as Et,relative as Ct}from"path";import{existsSync as wt,readdirSync as Pt}from"fs";var Tt=/\?/g,Ot=/\{([^}]+)\}/g,Rt=/(?:\/|^)\*{2}(?:\/|$)/g,kt=/\*/g,At=/\\\[([^\]]+)\\\]/g,Dt=/[.+$|[\]\\]/g;function Ft(n){let e=r=>r.replace(Dt,"\\$&"),t=r=>r.replace(At,(i,o)=>`[${o}]`).replace(Rt,".*").replace(kt,(i,o,s)=>{let a=s.slice(Math.max(0,o-2),o);return a[0]==="\\"?a[1]==="."?".*":"[^\\/]*":a[1]==="."?"*":"[^\\/]*"}).replace(Tt,".").replace(Ot,(i,o)=>`(${o.split(",").join("|")})`);return new RegExp(`^${t(e(n))}$`)}function Ee(n){let e=/[*?[\]{}!@+()|\]]/.test(n),t=/{[^}]+}/.test(n),r=/@\([^)]+\)/.test(n);return e||t||r}function xe(n,e){return e.some(t=>t.test(n))}function be(n){return n.map(e=>e instanceof RegExp?e:Ft(e.replace(/\\/g,"/").replace(/^!/,"")))}function Ce(n,e,t){if(!wt(n))return[];let r=e.filter(l=>!l.startsWith("!")),i=[...t,...e.filter(l=>l.startsWith("!"))],o=be(r),s=be(i),a=[],c=l=>{for(let g of Pt(l,{withFileTypes:!0})){let m=Et(l,g.name),b=Ct(n,m).replace(/\\/g,"/");xe(b,s)||(g.isDirectory()?c(m):xe(b,o)&&a.push(b))}};return c(n),a}import{cwd as Lt}from"process";var _={dev:!1,watch:!1,declaration:!1,buildOnError:!1,noTypeChecker:!1,bundleDeclaration:!1,define:{},esbuild:{write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:Lt(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};function _t(n){let e=n.argv,t=i=>Object.fromEntries(Object.entries(i).filter(([,o])=>o!==void 0)),r=t({bundle:e.bundle,minify:e.minify,outdir:e.outdir,tsconfig:e.tsconfig,entryPoints:e.file?[e.file]:void 0,target:e.node?[`node${process.version.slice(1)}`]:void 0,platform:e.node?"node":void 0,format:e.format});return{...t({dev:e.dev,watch:e.watch,declaration:e.declaration,serve:e.serve?{active:e.serve}:{undefined:void 0}}),esbuild:r}}async function $(n,e={}){let t=Array.isArray(n)?n:[n],r=t[0];return t.flatMap(i=>{let o={..._,...r,...i,...e,esbuild:{..._.esbuild,...r?.esbuild,...i?.esbuild,...e.esbuild},serve:{..._.serve,...r.serve,...i.serve,...e.serve}};if(!o.esbuild.entryPoints)throw new y("entryPoints cannot be undefined.");let s=o.esbuild.entryPoints;return Array.isArray(s)&&s.every(a=>typeof a=="string")&&s.some(a=>Ee(a))&&(o.esbuild.entryPoints=Ce(Bt(),s,["node_modules/**","dist/**","bundle/**","**/*.d.ts"])),o})}async function we(n,e){let t=_t(e),r=It(n)?await I(n):{};return $(r,t)}global.__ACTIVE_COLOR=!0;async function Yi(n){let e=K(n),t=e.argv,i=(await we(t.config,e)).map(async o=>{let s=new E(o);if(t.serve||o.serve.active)return await s.serve();if(Array.isArray(t.debug))return t.debug.length<1&&(t.debug=["index"]),await s.runDebug(t.debug);await s.run()});await Promise.all(i)}async function Ki(n){let e=$t(n)?await I(n):{},r=(await $(e)).map(async i=>await new E(i).run());return await Promise.all(r)}async function Xi(n){let t=(await $(n)).map(async r=>await new E(r).run());return await Promise.all(t)}export{Xi as build,Yi as buildWithArgv,Ki as buildWithConfigPath};
//# sourceMappingURL=index.js.map