UNPKG

@remotex-labs/xbuild

Version:

A versatile JavaScript and TypeScript toolchain build system

34 lines (32 loc) 61.1 kB
var Et=Object.create;var me=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var Be=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),J=r=>{throw TypeError(r)};var Ft=(r,e,t)=>e in r?me(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ne=(r,e)=>me(r,"name",{value:e,configurable:!0});var T=r=>[,,,Et(r?.[Be("metadata")]??null)],$e=["class","method","getter","setter","accessor","field","value","get","set"],X=r=>r!==void 0&&typeof r!="function"?J("Function expected"):r,Ot=(r,e,t,i,n)=>({kind:$e[r],name:e,metadata:i,addInitializer:o=>t._?J("Already initialized"):n.push(X(o||null))}),kt=(r,e)=>Ft(e,Be("metadata"),r[3]),F=(r,e,t,i)=>{for(var n=0,o=r[e>>1],s=o&&o.length;n<s;n++)e&1?o[n].call(t):i=o[n].call(t,i);return i},O=(r,e,t,i,n,o)=>{var s,a,c,l,f,p=e&7,u=!!(e&8),m=!!(e&16),C=p>3?r.length+1:p?u?1:2:0,R=$e[p+5],M=p>3&&(r[C-1]=[]),ue=r[C]||(r[C]=[]),y=p&&(!m&&!u&&(n=n.prototype),p<5&&(p>3||!m)&&Tt(p<4?n:{get[t](){return De(this,o)},set[t](S){return je(this,o,S)}},t));p?m&&p<4&&Ne(o,(p>2?"set ":p>1?"get ":"")+t):Ne(n,t);for(var G=i.length-1;G>=0;G--)l=Ot(p,t,c={},r[3],ue),p&&(l.static=u,l.private=m,f=l.access={has:m?S=>Pt(n,S):S=>t in S},p^3&&(f.get=m?S=>(p^1?De:At)(S,n,p^4?o:y.get):S=>S[t]),p>2&&(f.set=m?(S,de)=>je(S,n,de,p^4?o:y.set):(S,de)=>S[t]=de)),a=(0,i[G])(p?p<4?m?o:y[R]:p>4?void 0:{get:y.get,set:y.set}:n,l),c._=1,p^4||a===void 0?X(a)&&(p>4?M.unshift(a):p?m?o=a:y[R]=a:n=a):typeof a!="object"||a===null?J("Object expected"):(X(s=a.get)&&(y.get=s),X(s=a.set)&&(y.set=s),X(s=a.init)&&M.unshift(s));return p||kt(r,n),y&&me(n,t,y),m?p^4?o:y:n};var ge=(r,e,t)=>e.has(r)||J("Cannot "+t),Pt=(r,e)=>Object(e)!==e?J('Cannot use the "in" operator on this value'):r.has(e),De=(r,e,t)=>(ge(r,e,"read from private field"),t?t.call(r):e.get(r));var je=(r,e,t,i)=>(ge(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),At=(r,e,t)=>(ge(r,e,"access private method"),t);var he=new Map,Le=new Map;function Mt(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Rt(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Nt(r){return typeof r=="object"&&r!==null&&"useValue"in r}function k(r){return function(e){Le.set(e,r||{})}}function ve(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Mt(i))t.push(d(i.useClass,...ve(i.providers)));else if(Rt(i))t.push(i.useFactory(...ve(i.providers)));else if(Nt(i))t.push(i.useValue);else if(typeof i=="function")t.push(d(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function d(r,...e){if(he.has(r))return he.get(r);let t=Le.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=ve(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&he.set(r,n),n}function He(r){return e=>new N(t=>e.subscribe({next:i=>{try{let n=r(i);t.next?.(n)}catch(n){t.error?.(n)}},error:i=>t.error?.(i),complete:()=>t.complete?.()}))}function Ve(r=(e,t)=>e===t){return e=>new N(t=>{let i=!1,n;return e.subscribe({next:o=>{try{if(!i){n=o,i=!0,t.next?.(o);return}r(n,o)||(n=o,t.next?.(o))}catch(s){t.error?.(s)}},error:o=>t.error?.(o),complete:()=>t.complete?.()})})}var N=class{constructor(e){this.handler=e}handler;subscribe(e,t,i){let n=this.createSafeObserver(e,t,i),o;try{o=this.handler(n)}catch(s){return n.error?.(s),()=>{}}return()=>{try{o?.()}catch(s){n.error?.(s)}}}pipe(...e){return e.length===0?this:e.reduce((t,i)=>i(t),this)}createSafeObserver(e,t,i){return typeof e=="function"?{next:e,error:t,complete:i}:e||{}}};var Y=class extends N{isCompleted=!1;observers=new Set;constructor(){super(e=>{if(this.isCompleted){e.complete?.();return}return this.observers.add(e),()=>this.observers.delete(e)})}next(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.next?.(e)}catch(n){t.push(n);try{i.error?.(n)}catch{}}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in next()`)}error(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.error?.(e)}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in error()`)}complete(){if(this.isCompleted)return;let e=[];for(let t of[...this.observers])try{t.complete?.()}catch(i){e.push(i)}if(this.observers.clear(),this.isCompleted=!0,e.length>0)throw new AggregateError(e,`${e.length} observer(s) failed in complete()`)}};var Q=class extends Y{lastValue;constructor(e){super(),this.lastValue=typeof e=="function"?e():e}get value(){return this.lastValue}subscribe(e,t,i){if(this.isCompleted)return()=>{};let n=this.createSafeObserver(e,t,i),o=super.subscribe(n);return n.next?.(this.lastValue),o}next(e){this.isCompleted||(this.lastValue=e,super.next(e))}};function Z(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function D(r,...e){if(!e.length)return r;let t=e.shift();if(Z(r)&&Z(t)){for(let i in t){let n=t[i],o=r[i];Array.isArray(n)&&Array.isArray(o)?Object.assign(r,{[i]:[...o,...n]}):Z(n)?Object.assign(r,{[i]:D(Z(o)?o:{},n)}):Object.assign(r,{[i]:n})}return D(r,...e)}return r}function ee(r,e,t=!0){return r===e||Object.is(r,e)?!0:r===null||e===null?!1:r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.source===e.source&&r.flags===e.flags:URL&&r instanceof URL&&e instanceof URL?r.href===e.href:typeof r=="object"&&typeof e=="object"?jt(r,e,t):!1}function Dt(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function jt(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>ee(o,e[s],t));let i=Object.keys(r),n=Object.keys(e);if(t&&i.length!==n.length)return!1;for(let o of i)if(!Dt(e,o)||!ee(r[o],e[o],t))return!1;return!0}var _e=Object.freeze({verbose:!1,common:Object.freeze({types:!0,declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd()})})});var ze,ye;ze=[k({scope:"singleton"})];var x=class{constructor(e=_e){this.initialConfig=e;this.config$=new Q(D({},e))}initialConfig;config$;getValue(e){return e?e(this.config$.value):this.config$.value}subscribe(e){return this.config$.subscribe(e)}select(e){return this.config$.pipe(He(e),Ve((t,i)=>ee(t,i)))}patch(e){let t=D({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(D({},this.initialConfig,e))}};ye=T(null),x=O(ye,0,"ConfigurationService",ze,x),F(ye,1,x);import{cwd as Bt}from"process";import{readdirSync as $t}from"fs";import{matchesGlob as xe}from"path";import{join as Lt}from"@remotex-labs/xmap";function Ht(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function te(r,e){for(let t of e)if(t.endsWith(r)||xe(r,t))return!0;return!1}function Vt(r,e){let t=r+"/**";for(let i of e)if(xe(r,i)||xe(t,i))return!0;return!1}function Ui(r,e,t){return te(r,e)?!te(r,t):!1}function Ue(r,e){let{include:t,exclude:i}=Ht(e),n=Object.create(null),s=Bt().length+1,a=r.length+1,c=i.length>0;function l(f){let p;try{p=$t(f,{withFileTypes:!0})}catch{return}let u=p.length;for(let m=0;m<u;m++){let C=p[m],R=Lt(f,C.name),M=R.slice(a);if(C.isDirectory()){(!c||!Vt(M,i))&&l(R);continue}if(!(c&&te(M,i))&&te(M,t)){let ue=R.slice(s),y=M.lastIndexOf("."),G=y>0?M.slice(0,y):M;n[G]=ue}}}return l(r),n}var j=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};import{resolveError as Jt}from"@remotex-labs/xmap";import{xterm as Ce}from"@remotex-labs/xansi/xterm.component";import _t from"typescript";import{resolve as zt}from"@remotex-labs/xmap";import{closeSync as Ut,fstatSync as Kt,openSync as qt,readFileSync as Wt}from"fs";var Ke,be;Ke=[k({scope:"singleton"})];var v=class{resolvedPathCache=new Map;snapshotsByPath=new Map;clear(){this.snapshotsByPath.clear(),this.resolvedPathCache.clear()}getSnapshot(e){return this.snapshotsByPath.get(this.resolve(e))}getOrTouchFile(e){return this.snapshotsByPath.get(this.resolve(e))??this.touchFile(e)}getTrackedFilePaths(){return[...this.snapshotsByPath.keys()]}touchFile(e){let t=this.resolve(e),i=this.snapshotsByPath.get(t)??this.createEntry(t);try{this.syncEntry(t,i)}catch{(i.contentSnapshot!==void 0||i.version>0)&&(i.version++,i.mtimeMs=0,i.contentSnapshot=void 0)}return{...i}}resolve(e){let t=this.resolvedPathCache.get(e);if(t)return t;let i=zt(e);return this.resolvedPathCache.set(e,i),i}createEntry(e){let t={version:0,mtimeMs:0,contentSnapshot:void 0};return this.snapshotsByPath.set(e,t),t}syncEntry(e,t){let i=qt(e,"r");try{let{mtimeMs:n}=Kt(i);if(n===t.mtimeMs)return;let o=Wt(i,"utf-8");t.version++,t.mtimeMs=n,t.contentSnapshot=o?_t.ScriptSnapshot.fromString(o):void 0}finally{Ut(i)}}};be=T(null),v=O(be,0,"FilesModel",Ke,v),F(be,1,v);import{readFileSync as Gt}from"fs";import{SourceService as Xt}from"@remotex-labs/xmap";import{resolve as Se,toPosix as qe}from"@remotex-labs/xmap";var We,we;We=[k({scope:"singleton"})];var b=class{filePath;distPath;rootPath;sourceMaps=new Map;constructor(){this.filePath=import.meta.filename,this.setSourceFile(this.filePath),this.rootPath=this.getRootDir(),this.distPath=this.getDistDir()}isFrameworkFile(e){let{source:t,sourceRoot:i}=e,n=t?.toLowerCase();return!!(t&&n.includes("xbuild")&&!n.includes("xbuild.config")||i&&i.includes("xBuild"))}getSourceMap(e){if(e=Se(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=Se(t);try{return this.initializeSourceMap(e,i)}catch(n){throw new Error(`Failed to initialize SourceService: ${i} ${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=Se(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=Gt(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t} ${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return qe(process.cwd())}getDistDir(){return qe(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Xt(e,t);this.sourceMaps.set(t,i)}};we=T(null),b=O(we,0,"FrameworkService",We,b),F(we,1,b);import{parseErrorStack as Ge}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as Yt}from"@remotex-labs/xmap/formatter.component";import{highlightCode as Qt}from"@remotex-labs/xmap/highlighter.component";function Zt(r=""){let t=d(b).getSourceMap(r);if(t)return t;let i=d(v).getOrTouchFile(r),n=i?.contentSnapshot?.text;if(!i||!n)return null;let o=n.split(` `);return{getPositionWithCode:(s,a,c,l)=>{let f=l?.linesBefore??3,p=l?.linesAfter??3,u=Math.max(s-f,0),m=Math.min(s+p,o.length);return{line:s,column:a+1,code:o.slice(u,m).join(` `),source:r,name:null,startLine:u,endLine:m,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function er(r){return r instanceof Error?Ge(r):r.detail instanceof Error?Ge(r.detail):r.location?{name:"esBuildMessage",message:r.text??"",rawStack:"",stack:[{source:`@${r.location.file}`,line:r.location.line,column:r.location.column,fileName:r.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:r.text??"",rawStack:""}}function _(r,e){let t=d(b),i=d(x).getValue(s=>s.verbose)??!1,n=er(r),o=Jt(n,{...e,withNativeFrames:i||(e?.withFrameworkFrames??!1),getSource(s){return Zt(s)}});return o.stack.filter(s=>{if(!(e?.withFrameworkFrames??!1)&&t.isFrameworkFile(s))return!1;!o.formatCode&&s.code&&(o.formatCode=Yt({code:Qt(s.code),line:s.line??0,column:s.column??0,startLine:s.stratLine??0},{color:Ce.brightPink}))}),o}function z(r,e,t,i=[]){let n=[` ${e}: ${Ce.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(` `+Ce.gray(o.text));return r.formatCode&&n.push(` ${r.formatCode}`),r.stack.length&&n.push(` Enhanced Stack Trace: ${r.stack.map(o=>o.format).join(` `)} `),n.join("")}var I=class extends Error{errorMetadata;formattedStack;constructor(e,t="xBuildBaseError"){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=t,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}get metadata(){return this.errorMetadata}[Symbol.for("nodejs.util.inspect.custom")](){return this.formattedStack||this.stack}reformatStack(e,t){this.errorMetadata=_(e,t),this.formattedStack=z(this.errorMetadata,e.name,e.message)}};var w=class extends I{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};var B=class extends I{id;constructor(e,t){super(e.text??"","esBuildError"),this.id=e.id??"",e.detail instanceof Error?(this.stack=e.detail.stack,this.message=e.detail.message,this.reformatStack(e.detail,t)):(this.errorMetadata=_(e,{withFrameworkFrames:!0}),this.stack=z(this.errorMetadata,this.name,this.message,e.notes))}};function tr(r){if(r instanceof I)return r;if(r.detail instanceof I||r.detail instanceof j)return r.detail;if(r.detail instanceof Error)return new B(r,{withFrameworkFrames:!0});if(r.location)return new B(r);if(r.text)return new w(r.text)}function re(r=[],e){for(let t of r){let i=tr(t);i&&e.push(i)}}function Ie(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return re(r.errors,e.errors),re(r.warnings,e.warnings),e}function U(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Qe from"http";import*as Ze from"https";import{extname as Je}from"path";import{readFileSync as Ye}from"fs";var Xe=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{resolve as nr,join as ie}from"@remotex-labs/xmap";import{xterm as ir}from"@remotex-labs/xansi/xterm.component";function H(){return ir.lightCoral("[xBuild]")}import{readdir as or,stat as sr,readFile as ar}from"fs/promises";import{xterm as ne}from"@remotex-labs/xansi/xterm.component";var Ee=class{constructor(e,t){this.config=e;this.rootDir=nr(t),this.config.port||=0,this.config.host||="localhost"}config;server;rootDir;framework=d(b);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(H(),ne.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(H(),ne.dim("Server stopped.")),this.server=void 0}async restart(){console.log(H(),ne.burntOrange("Restarting server...")),await this.stop(),await this.start()}setActualPort(){if(this.config.port===0){let e=this.server.address();e&&typeof e=="object"&&e.port&&(this.config.port=e.port)}}startHttpServer(){return new Promise(e=>{this.server=Qe.createServer((t,i)=>{this.handleRequest(t,i,()=>this.defaultResponse(t,i))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`http://${this.config.host}:${this.config.port}`}),e()})})}startHttpsServer(){return new Promise(e=>{let t={key:Ye(this.config.key??ie(this.framework.distPath,"..","certs","server.key")),cert:Ye(this.config.cert??ie(this.framework.distPath,"..","certs","server.crt"))};this.server=Ze.createServer(t,(i,n)=>{this.handleRequest(i,n,()=>this.defaultResponse(i,n))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`}),e()})})}handleRequest(e,t,i){try{this.config.verbose&&console.log(`${H()} Request ${ne.lightCoral(e.url?.toString()??"")}`),this.config.onRequest?this.config.onRequest(e,t,i):i()}catch(n){this.sendError(t,n)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",cjs:"application/javascript",mjs:"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 i=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",n=ie(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await sr(n);o.isDirectory()?await this.handleDirectory(n,i,t):o.isFile()&&await this.handleFile(n,t)}catch(o){let s=o.message;s.includes("favicon")||console.log(H(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await or(e)).map(l=>{let f=ie(t,l),p=Je(l).slice(1)||"folder";return p==="folder"?` <a href="/${f}" class="folder-row"> <div class="icon"><i class="fa-solid fa-folder"></i></div> <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div> </a> `:` <a href="/${f}" class="file-row"> <div class="icon"><i class="fa-solid fa-file-code"></i></div> <div class="meta"><div class="name">${l}</div><div class="sub">${p}</div></div> </a> `}).join("");o?o=`<div class="list">${o}</div>`:o='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(l=>(s+=`${l}/`,`<li><a href="${s}">${l}</a></li>`)).join(""),c=Xe.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=Je(e).slice(1)||"txt",n=this.getContentType(i),o=await ar(e);t.writeHead(200,{"Content-Type":n}),t.end(o)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(H(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as et}from"path";import{stat as cr,watch as lr}from"fs/promises";import{normalize as pr,join as fr}from"@remotex-labs/xmap";var Te=class{excludes;include;debounceTimer=null;framework=d(b);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=lr(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=pr(n);if(o.endsWith("~")||!this.include.some(a=>et(o,a))||this.excludes.some(a=>et(o,a)))continue;let s=fr(this.framework.rootPath,o);try{if(!(await cr(s)).isFile())continue}catch{}t.add(o),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};import Br from"typescript";import{build as $r}from"esbuild";import{writeFile as pt,mkdir as Lr,readFile as Hr}from"fs/promises";import g from"typescript";import ur from"typescript";import{dirname as tt,relative as dr,toPosix as mr}from"@remotex-labs/xmap";var gr=/^#!.*(\r?\n)?/,hr=/export {};\n?/g,vr=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,yr=/^export\s+(?:default\s+)?/gm,xr=/(?<=[:;,{}\[\]()\w"'`])[ \t]*\/\*\*[^\r\n]*?\*\/[ \t]*$/gm;function br(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(gr,""):r}function Sr(r){return r.includes("export {}")?r.replace(hr,""):r}function wr(r){return r=r.replace(xr,""),r.replace(vr,"$1")}function rt(r){return r.replace(yr,"")}function Cr(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function oe(r){return Cr(r)&&(r=br(r),r=Sr(r),r=wr(r)),r}function Fe(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||tt(r),s=i||tt(r),c=dr(s,r).replace(/\.tsx?$/,".d.ts"),l=ur.sys.resolvePath(`${o}/${c}`);return mr(l)}var it,Oe;it=[k({scope:"singleton"})];var V=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=d(v);constructor(){this.printer=g.createPrinter({newLine:g.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!g.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return g.canHaveModifiers(e)?g.getModifiers(e)?.some(i=>i.kind===g.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return g.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,g.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[],o=[];for(let l of e.statements){if(g.isImportDeclaration(l)){this.handleImport(l,t,i,n);continue}if(g.isExportDeclaration(l)){this.handleExport(l,t);continue}this.hasExportModifier(l)&&this.extractExportName(l,t),o.push(l)}let s=g.factory.createNodeArray(o),a=this.printer.printList(g.ListFormat.MultiLine,s,e),c=rt(oe(a));for(let[l,f]of n)c=c.replace(new RegExp(`\\b${f}\\b`,"g"),l);for(let l of i)c=c.replace(new RegExp(`\\b${l}\\.`,"g"),"");return c}handleImport(e,t,i,n){let{importClause:o,moduleSpecifier:s}=e;if(!o||!s)return;let a=this.resolveModule(s,t.fileName);if(!a)return;let{fileName:c,isExternal:l}=a;if(!l){t.internalDeps.add(c);let{namedBindings:p}=o;if(!p)return;if(g.isNamespaceImport(p))i.push(p.name.text);else if(g.isNamedImports(p))for(let u of p.elements)u.propertyName&&n.push([u.propertyName.text,u.name.text]);return}if(!o){t.externalImports.namespace[c]="";return}o.name&&(t.externalImports.default[c]=o.name.text);let{namedBindings:f}=o;f&&(g.isNamespaceImport(f)?t.externalImports.namespace[f.name.text]=c:g.isNamedImports(f)&&this.addNamedElements(t.externalImports.named[c]??=[],f.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(g.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}g.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(g.isVariableStatement(e)){for(let i of e.declarationList.declarations)g.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(g.isEnumDeclaration(e)||g.isClassDeclaration(e)||g.isFunctionDeclaration(e)||g.isInterfaceDeclaration(e)||g.isTypeAliasDeclaration(e))&&e.name&&g.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};Oe=T(null),V=O(Oe,0,"GraphModel",it,V),F(Oe,1,V);import $ from"typescript";import{matchesGlob as Nr}from"path";import{relative as Dr}from"@remotex-labs/xmap";import{mkdir as Ir,writeFile as Er}from"fs/promises";import{join as Tr,dirname as Fr}from"@remotex-labs/xmap";var nt=`/** * This file was automatically generated by xBuild. * DO NOT EDIT MANUALLY. */ `;var se=class{constructor(e,t){this.languageService=e;this.languageHostService=t}languageService;languageHostService;graphModel=d(V);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let n=this.languageHostService.getCompilationSettings();t&&(n={...n,outDir:t}),await Promise.all(Object.entries(e).map(async([o,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=Tr(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Ir(Fr(i),{recursive:!0}),await Er(i,o,"utf-8")}async getBundleContent(e,t){let i=new Set,n=new Set([e]),o=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let f=t.getSourceFile(l);if(!f)continue;let p=this.graphModel.scan(f,this.languageService,this.languageHostService);if(o.add(p),a.has(l)){n.add(p);for(let u of p.internalExports.star)a.add(u)}for(let u of p.internalDeps)i.has(u)||s.push(u);c+=p.content}return c+=e.content,this.parseContent(c,o,n)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[n,o]of Object.entries(i.externalImports.default)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});let s=t.get(n);s.default||(s.default=o)}for(let[n,o]of Object.entries(i.externalImports.named)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});for(let s of o)t.get(n).named.add(s)}for(let[n,o]of Object.entries(i.externalImports.namespace))t.has(o)||t.set(o,{named:new Set,namespace:new Map}),t.get(o).namespace.set(n,o)}return t}generateImportStatements(e){let t=[];for(let[i,{default:n,named:o,namespace:s}]of e){let a=[];if(n&&a.push(n),o.size>0&&a.push(`{ ${Array.from(o).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let n=[...i.internalExports.exports],o=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(o.push(...c.declarations),o.push(`const ${s} = { ${c.exports.join(", ")} };`),n.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);n.push(...a.exports),o.push(...a.declarations)}return{exports:n,declarations:o}}collectBundleExports(e){let t=[],i=[],n=[];for(let o of e){t.push(...o.internalExports.exports);for(let[s,a]of Object.entries(o.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of o.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(o.externalExports.namespace))n.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(o.externalExports.exports))n.push(`export { ${a.join(`, `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[nt],o=this.collectExternalImports(t),s=this.generateImportStatements(o);n.push(...s),s.length>0&&n.push("");let{exports:a,declarations:c,externalExports:l}=this.collectBundleExports(i);if(c.length>0&&(n.push(...c),n.push("")),n.push(e),a.length>0){let f=Array.from(new Set(a)).sort();n.push(`export { ${f.join(`, `)} };`)}return l.length>0&&n.push(...l),n.join(` `)}};import{dirname as Or}from"@remotex-labs/xmap";import{mkdir as kr,writeFile as Pr}from"fs/promises";import{xterm as Ar}from"@remotex-labs/xansi/xterm.component";var ae=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}languageService;languageHostService;static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Ar.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=Fe(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=Fe(e.fileName,t);n=oe(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await kr(Or(o),{recursive:!0}),await Pr(o,n,"utf8")}};import K from"typescript";import{relative as Mr,dirname as Rr}from"@remotex-labs/xmap";var q=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=K.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}compilerOptions;static sys=K.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=d(v);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=K.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static reload(){let e=d(v);e.getTrackedFilePaths().map(t=>{e.touchFile(t)})}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return K.getDefaultLibFilePath(e)}getScriptVersion(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.version.toString():"0"}hasScriptSnapshot(e){return this.trackFiles.has(this.filesCache.resolve(e))}getScriptSnapshot(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.contentSnapshot:this.touchFile(e).contentSnapshot}resolveModuleName(e,t){return K.resolveModuleName(e,t,this.compilerOptions,K.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),c=Mr(Rr(t),a);return n.replace(o,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var ot,ke;ot=[k({providers:[{useValue:"tsconfig.json"}]})];var P=class P{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new ae(n,i),this.bundlerService=new se(n,i)}configPath;config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=P.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=P.serviceCache.get(e);t&&(t.refCount--,P.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){if(!e||e.fileName.includes("node_modules"))return!1;if(this.config.raw?.exclude){for(let t of this.config.raw.exclude)if(Nr(Dr(this.config.options.rootDir,e.fileName),t))return!1}return!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=P.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new q(e.options),i=$.createLanguageService(t,$.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return P.serviceCache.set(this.configPath,n),n}parseConfig(){let e=$.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...$.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:$.ScriptTarget.ESNext,module:$.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:$.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:$.flattenDiagnosticMessageText(e.messageText,` `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};ke=T(null),P=O(ke,0,"TypescriptService",ot,P),F(ke,1,P);var W=P;import{cwd as Pe}from"process";import{build as st}from"esbuild";var jr={write:!1,bundle:!0,minify:!0,outdir:`${Pe()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function at(r,e,t={}){return await st({absWorkingDir:Pe(),...jr,...t,stdin:{loader:"ts",contents:r,resolveDir:Pe(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ct(r,e={}){try{return await st({...e,outdir:"tmp",write:!1,bundle:!0,outfile:void 0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(U(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw re(t.errors,i.errors),i}throw t}}import{relative as Vr,resolve as _r,join as ft,dirname as zr}from"@remotex-labs/xmap";function lt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Ue(r,e)),t}else{if(e&&typeof e=="object")return e;if(e===void 0)return}throw new w("Unsupported entry points format")}var ce=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new w(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new W(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}name;lifecycle;buildConfig;argv;dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=d(x);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(!this.active)return;this.applyInjections();let e=Object.assign({},this.buildConfig.esbuild);if(this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile}),this.config.define&&e.define)for(let[t,i]of Object.entries(this.config.define))typeof i=="function"&&(e.define[t]=JSON.stringify(i()));try{let t=await $r(e);return await this.packageTypeComponent(),t}catch(t){if(U(t)){if(t.errors.filter(n=>n.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?D({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;if(typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError){let n=new j("Type checking failed",t);e.warnings?.push({detail:n,location:void 0})}else{let n=[],o=[],s=new j("Type checking failed",n),a=new j("Type checking failed",o);for(let c of t)(c.category===Br.DiagnosticCategory.Error?n:o).push(c);n.length&&e.errors?.push({detail:s,location:void 0}),o.length&&e.warnings?.push({detail:a,location:void 0})}return e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(typeof e.buildResult.metafile?.outputs=="object"){let s=Object.keys(e.buildResult.metafile?.outputs);for(let a of s){if(!a.endsWith(".map"))continue;let c=zr(a),l=await Hr(a,"utf8"),f=JSON.parse(l);f.sources=f.sources.map(p=>p.startsWith("http")?p:ft(c,p)),await pt(a,JSON.stringify(f),"utf8")}}if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Lr(e,{recursive:!0}),await pt(ft(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new w(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints&&!e.esbuild.stdin)throw new w("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).flatMap(([n,o])=>typeof o=="function"?[]:[[n,JSON.stringify(o)]])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=lt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.outdir&&i.esbuild.outfile&&(this.buildConfig.esbuild.outdir=void 0),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new W(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,t={...e,plugins:void 0},{metafile:i}=await ct(e.entryPoints,t),n={};for(let o of Object.keys(i.inputs)){let s=Vr(this.typescriptModule.config.options.rootDir,_r(o)),a=this.stripExtension(s);n[a]=o}return n}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Ur}from"fs/promises";import{resolve as Kr}from"@remotex-labs/xmap";var le=class{constructor(e,t){this.variantName=e;this.argv=t}variantName;argv;filesModel=d(v);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,options:e.initialOptions,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(this.executeStartHooks.bind(this,t,e)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(this.executeEndHooks.bind(this,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},this.executeResolveHooks.bind(this,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},this.executeLoadHooks.bind(this,t))}}}pushError(e,t,i,n=this.variantName){e.push({id:t,detail:i,location:null,pluginName:n})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],n=[],o={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(o);c?.errors&&i.push(...c.errors),c?.warnings&&n.push(...c.warnings)}catch(c){this.pushError(i,"startHook",c,s)}return{errors:i,warnings:n}}async executeEndHooks(e,t){let{errors:i,warnings:n}=t,o=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:o,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&n.push(...l.warnings)}catch(l){this.pushError(i,"endHook",l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,"endHook",l,a)}}async executeResolveHooks(e,t){let i={errors:[]},n={args:t,...e};for(let[o,s]of this.resolveHooks.entries())try{let a=await s(n);if(!a)continue;i={...i,...a}}catch(a){this.pushError(i.errors,"endResolve",a,o)}return i}async executeLoadHooks(e,t){let i=[],n=[],o="default",s=Kr(t.path),a=this.filesModel.getOrTouchFile(s),c;try{c=a?.contentSnapshot?a.contentSnapshot.text:await Ur(s,"utf8")}catch{return e.options.logOverride?.["lifecycle-file-ignored"]!=="silent"&&n.push({id:"",text:`${t.path} ignored`,pluginName:"lifecycle"}),{warnings:n,errors:i,loader:o}}for(let[l,f]of this.loadHooks.entries())try{let p=await f({contents:c,loader:o,args:t,...e});if(!p)continue;p.contents!==void 0&&(c=p.contents),p.loader&&(o=p.loader),p.errors&&i.push(...p.errors),p.warnings&&n.push(...p.warnings)}catch(p){this.pushError(i,"loadHook",p,l)}return{contents:c,loader:o,errors:i,warnings:n}}};import h from"typescript";import{createSourceFile as li}from"typescript";import{highlightCode as xt}from"@remotex-labs/xmap/highlighter.component";import A from"typescript";var qr="$$ifdef";function Wr(r,e,t,i=!1){let n=i?"export function ":"function ";return A.isArrowFunction(e)||A.isFunctionExpression(e)?Gr(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Gr(r,e,t,i){let o=e.modifiers?.some(l=>l.kind===A.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Xr(e,t);return`${o}${i}${r}(${s})${a} ${c}`}function Xr(r,e){let t=r.body.getText(e);return A.isArrowFunction(r)&&!A.isBlock(r.body)?`{ return ${t}; }`:t}function Jr(r,e,t="",i="();"){return A.isArrowFunction(r)||A.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===A.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function ut(r,e,t){let i=r in t&&!!t[r];return e===qr===i}function dt(r,e,t,i){let[n,o]=e.arguments;if(!A.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!ut(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Wr(c,o,i.sourceFile,t)}function pe(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!A.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!ut(a,c,e.defines))return"";let l="",f=t?.name.getText(e.sourceFile);return f&&(l=i?`export const ${f} = `:`const ${f} = `),Jr(s,e.sourceFile,l,n)}import E from"typescript";import{createRequire as Zr}from"module";var fe=class extends I{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=_(e,{lineOffset:t}),this.stack=z(this.errorMetadata,this.name,this.message)}};i