@remotex-labs/xbuild 2.1.1 → 2.1.2

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/bash.js CHANGED
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- var Sr=Object.create;var qe=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var xt=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),ue=r=>{throw TypeError(r)};var Cr=(r,e,t)=>e in r?qe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ht=(r,e)=>qe(r,"name",{value:e,configurable:!0});var k=r=>[,,,Sr(r?.[xt("metadata")]??null)],bt=["class","method","getter","setter","accessor","field","value","get","set"],fe=r=>r!==void 0&&typeof r!="function"?ue("Function expected"):r,Er=(r,e,t,i,o)=>({kind:bt[r],name:e,metadata:i,addInitializer:n=>t._?ue("Already initialized"):o.push(fe(n||null))}),Ir=(r,e)=>Cr(e,xt("metadata"),r[3]),F=(r,e,t,i)=>{for(var o=0,n=r[e>>1],s=n&&n.length;o<s;o++)e&1?n[o].call(t):i=n[o].call(t,i);return i},P=(r,e,t,i,o,n)=>{var s,a,l,c,f,p=e&7,h=!!(e&8),m=!!(e&16),W=p>3?r.length+1:p?h?1:2:0,te=bt[p+5],L=p>3&&(r[W-1]=[]),We=r[W]||(r[W]=[]),w=p&&(!m&&!h&&(o=o.prototype),p<5&&(p>3||!m)&&wr(p<4?o:{get[t](){return vt(this,n)},set[t](I){return yt(this,n,I)}},t));p?m&&p<4&&ht(n,(p>2?"set ":p>1?"get ":"")+t):ht(o,t);for(var pe=i.length-1;pe>=0;pe--)c=Er(p,t,l={},r[3],We),p&&(c.static=h,c.private=m,f=c.access={has:m?I=>Tr(o,I):I=>t in I},p^3&&(f.get=m?I=>(p^1?vt:Or)(I,o,p^4?n:w.get):I=>I[t]),p>2&&(f.set=m?(I,Ge)=>yt(I,o,Ge,p^4?n:w.set):(I,Ge)=>I[t]=Ge)),a=(0,i[pe])(p?p<4?m?n:w[te]:p>4?void 0:{get:w.get,set:w.set}:o,c),l._=1,p^4||a===void 0?fe(a)&&(p>4?L.unshift(a):p?m?n=a:w[te]=a:o=a):typeof a!="object"||a===null?ue("Object expected"):(fe(s=a.get)&&(w.get=s),fe(s=a.set)&&(w.set=s),fe(s=a.init)&&L.unshift(s));return p||Ir(r,o),w&&qe(o,t,w),m?p^4?n:w:o};var Ke=(r,e,t)=>e.has(r)||ue("Cannot "+t),Tr=(r,e)=>Object(e)!==e?ue('Cannot use the "in" operator on this value'):r.has(e),vt=(r,e,t)=>(Ke(r,e,"read from private field"),t?t.call(r):e.get(r));var yt=(r,e,t,i)=>(Ke(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),Or=(r,e,t)=>(Ke(r,e,"access private method"),t);import{rmSync as So}from"fs";import{cwd as wo}from"process";import ke from"node:process";var Xe=new Map,St=new Map;function kr(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Fr(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Pr(r){return typeof r=="object"&&r!==null&&"useValue"in r}function A(r){return function(e){St.set(e,r||{})}}function Ye(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(kr(i))t.push(u(i.useClass,...Ye(i.providers)));else if(Fr(i))t.push(i.useFactory(...Ye(i.providers)));else if(Pr(i))t.push(i.useValue);else if(typeof i=="function")t.push(u(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function u(r,...e){if(Xe.has(r))return Xe.get(r);let t=St.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Ye(t.providers,e),o=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Xe.set(r,o),o}import{xterm as he}from"@remotex-labs/xansi/xterm.component";import $r from"typescript";import{readFileSync as Mr,statSync as Br}from"fs";import*as de from"path";import*as re from"path/posix";var Ar=/\\/g,Rr=/\/+/g;function R(r){if(!r)return"";let e=String(r);return e=e.replace(Ar,"/"),e=e.replace(Rr,"/"),e}function wt(r){return re.normalize(R(r))}function v(...r){return re.join(...r.map(R))}function C(...r){return R(de.resolve(...r))}function $(r){return R(de.dirname(r))}function T(r,e){return re.relative(R(r),R(e))||"."}var Ct,Je;Ct=[A({scope:"singleton"})];var y=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);i||(i={version:0,mtimeMs:0,contentSnapshot:void 0},this.snapshotsByPath.set(t,i));try{let n=Br(t).mtimeMs;if(n===i.mtimeMs)return{...i};let s=Mr(t,"utf-8"),a=s?$r.ScriptSnapshot.fromString(s):void 0;i.version++,i.mtimeMs=n,i.contentSnapshot=a}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=C(e);return this.resolvedPathCache.set(e,i),i}};Je=k(null),y=P(Je,0,"FilesModel",Ct,y),F(Je,1,y);import{readFileSync as Nr}from"fs";import{SourceService as Dr}from"@remotex-labs/xmap";var Et,Qe;Et=[A({scope:"singleton"})];var S=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,o=t?.toLowerCase();return!!(t&&o.includes("xbuild")&&!o.includes("xbuild.config")||i&&i.includes("xBuild"))}getSourceMap(e){if(e=C(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=C(t);try{return this.initializeSourceMap(e,i)}catch(o){throw new Error(`Failed to initialize SourceService: ${i}
3
- ${o instanceof Error?o.message:String(o)}`)}}setSourceFile(e){if(!e)return;let t=C(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let o=Nr(i,"utf-8");return this.initializeSourceMap(o,t)}catch(o){throw new Error(`Failed to initialize SourceService: ${t}
4
- ${o instanceof Error?o.message:String(o)}`)}}getRootDir(){return R(process.cwd())}getDistDir(){return R(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Dr(e,t);this.sourceMaps.set(t,i)}};Qe=k(null),S=P(Qe,0,"FrameworkService",Et,S),F(Qe,1,S);import{parseErrorStack as Ft}from"@remotex-labs/xmap/parser.component";function It(r){return e=>new G(t=>e.subscribe({next:i=>{try{let o=r(i);t.next?.(o)}catch(o){t.error?.(o)}},error:i=>t.error?.(i),complete:()=>t.complete?.()}))}function Tt(r=(e,t)=>e===t){return e=>new G(t=>{let i=!1,o;return e.subscribe({next:n=>{try{if(!i){o=n,i=!0,t.next?.(n);return}r(o,n)||(o=n,t.next?.(n))}catch(s){t.error?.(s)}},error:n=>t.error?.(n),complete:()=>t.complete?.()})})}var G=class{constructor(e){this.handler=e}subscribe(e,t,i){let o=this.createSafeObserver(e,t,i),n;try{n=this.handler(o)}catch(s){return o.error?.(s),()=>{}}return()=>{try{n?.()}catch(s){o.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 me=class extends G{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(o){t.push(o);try{i.error?.(o)}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(o){t.push(o)}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 ge=class extends me{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 o=this.createSafeObserver(e,t,i),n=super.subscribe(o);return o.next?.(this.lastValue),n}next(e){this.isCompleted||(this.lastValue=e,super.next(e))}};function Te(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function q(r,...e){if(!e.length)return r;let t=e.shift();if(Te(r)&&Te(t)){for(let i in t){let o=t[i],n=r[i];Array.isArray(o)&&Array.isArray(n)?Object.assign(r,{[i]:[...n,...o]}):Te(o)?Object.assign(r,{[i]:q(Te(n)?n:{},o)}):Object.assign(r,{[i]:o})}return q(r,...e)}return r}function Oe(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"?Lr(r,e,t):!1}function jr(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function Lr(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((n,s)=>Oe(n,e[s],t));let i=Object.keys(r),o=Object.keys(e);if(t&&i.length!==o.length)return!1;for(let n of i)if(!jr(e,n)||!Oe(r[n],e[n],t))return!1;return!0}var Hr="tsconfig.json",Ot=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",tsconfig:Hr,absWorkingDir:process.cwd()})})});var kt,Ze;kt=[A({scope:"singleton"})];var b=class{constructor(e=Ot){this.initialConfig=e;this.config$=new ge(q({},e))}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(It(e),Tt((t,i)=>Oe(t,i)))}patch(e){let t=q({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(q({},this.initialConfig,e))}};Ze=k(null),b=P(Ze,0,"ConfigurationService",kt,b),F(Ze,1,b);import{highlightCode as _r}from"@remotex-labs/xmap/highlighter.component";import{Bias as Vr}from"@remotex-labs/xmap";import{formatErrorCode as Ur}from"@remotex-labs/xmap/formatter.component";var zr=/\s{2,}/g,Wr=/^https?:\/\//,Gr=/^file:\/\//;function qr(r){return r instanceof Error?Ft(r):r.detail instanceof Error?Ft(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 Kr(r){let e=r.fileName??"",t=this.framework.getSourceMap(e);if(t)return t;let i=this.files.getOrTouchFile(e),o=i?.contentSnapshot?.text;if(!i||!o)return null;let n=o.split(`
5
- `);return{getPositionWithCode:(s,a,l,c)=>{let f=c?.linesBefore??3,p=c?.linesAfter??3,h=Math.max(s-f,0),m=Math.min(s+p,n.length);return{line:s,column:a+1,code:n.slice(h,m).join(`
6
- `),source:e,name:null,startLine:h,endLine:m,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function Xr(r){return Ur({...r,code:_r(r.code)},{color:he.brightPink})}function et(r){let e=r.fileName;if(e?.includes(this.framework.rootPath)&&(e=T(this.framework.rootPath,e)),!e)return r.source??"";let t=r.line&&r.column?he.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${he.darkGray(e)} ${t}`.replace(zr," ").trim()}function Yr(r,e){let{source:t,sourceRoot:i,line:o}=e;if(!t)return r.fileName?r.fileName.replace(Gr,""):"";let n=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(n>0)return`${t.substring(n)}#L${o}`;if(Wr.test(t))return`${t}#L${o}`;if(i){let s=T($(this.framework.distPath),v(this.framework.distPath,t));return`${i}${s}#L${o}`}return`${t}#L${o}`}function Jr(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=Xr(e)),et.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:Yr.call(this,r,e)})}function Qr(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=Kr.call(this,r);if(!t)return et.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,Vr.LOWER_BOUND,e);return i?!this.withFrameworkFrames&&this.framework.isFrameworkFile(i)?"":(this.lineOffset&&(i.line+=this.lineOffset,i.startLine+=this.lineOffset,i.endLine+=this.lineOffset),this.line=i.line,this.column=i.column,Jr.call(this,r,i)):et.call(this,r)}function H(r,e,t=0){let i=u(b).getValue(a=>a.verbose)??!1,o={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(y),framework:u(S),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:qr(r).stack.map(a=>Qr.call(o,a,e)).filter(Boolean),code:o.code,line:o.line??0,column:o.column??0,source:o.source,formatCode:o.formatCode}}function _(r,e,t,i=[]){let o=[`
7
- ${e}: ${he.lightCoral(t)}`];for(let n of i??[])n.text&&o.push(`
8
- `+he.gray(n.text));return r.formatCode&&o.push(`
2
+ var Ir=Object.create;var Ke=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var Ct=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),me=r=>{throw TypeError(r)};var Tr=(r,e,t)=>e in r?Ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var xt=(r,e)=>Ke(r,"name",{value:e,configurable:!0});var O=r=>[,,,Ir(r?.[Ct("metadata")]??null)],wt=["class","method","getter","setter","accessor","field","value","get","set"],de=r=>r!==void 0&&typeof r!="function"?me("Function expected"):r,Fr=(r,e,t,i,n)=>({kind:wt[r],name:e,metadata:i,addInitializer:o=>t._?me("Already initialized"):n.push(de(o||null))}),Or=(r,e)=>Tr(e,Ct("metadata"),r[3]),k=(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},P=(r,e,t,i,n,o)=>{var s,a,c,l,p,f=e&7,m=!!(e&8),g=!!(e&16),B=f>3?r.length+1:f?m?1:2:0,W=wt[f+5],H=f>3&&(r[B-1]=[]),Ge=r[B]||(r[B]=[]),C=f&&(!g&&!m&&(n=n.prototype),f<5&&(f>3||!g)&&Er(f<4?n:{get[t](){return bt(this,o)},set[t](E){return St(this,o,E)}},t));f?g&&f<4&&xt(o,(f>2?"set ":f>1?"get ":"")+t):xt(n,t);for(var ue=i.length-1;ue>=0;ue--)l=Fr(f,t,c={},r[3],Ge),f&&(l.static=m,l.private=g,p=l.access={has:g?E=>kr(n,E):E=>t in E},f^3&&(p.get=g?E=>(f^1?bt:Pr)(E,n,f^4?o:C.get):E=>E[t]),f>2&&(p.set=g?(E,qe)=>St(E,n,qe,f^4?o:C.set):(E,qe)=>E[t]=qe)),a=(0,i[ue])(f?f<4?g?o:C[W]:f>4?void 0:{get:C.get,set:C.set}:n,l),c._=1,f^4||a===void 0?de(a)&&(f>4?H.unshift(a):f?g?o=a:C[W]=a:n=a):typeof a!="object"||a===null?me("Object expected"):(de(s=a.get)&&(C.get=s),de(s=a.set)&&(C.set=s),de(s=a.init)&&H.unshift(s));return f||Or(r,n),C&&Ke(n,t,C),g?f^4?o:C:n};var Xe=(r,e,t)=>e.has(r)||me("Cannot "+t),kr=(r,e)=>Object(e)!==e?me('Cannot use the "in" operator on this value'):r.has(e),bt=(r,e,t)=>(Xe(r,e,"read from private field"),t?t.call(r):e.get(r));var St=(r,e,t,i)=>(Xe(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),Pr=(r,e,t)=>(Xe(r,e,"access private method"),t);import{rmSync as En}from"fs";import{cwd as Tn}from"process";import ke from"node:process";var Ye=new Map,It=new Map;function Ar(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Rr(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function $r(r){return typeof r=="object"&&r!==null&&"useValue"in r}function A(r){return function(e){It.set(e,r||{})}}function Je(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Ar(i))t.push(u(i.useClass,...Je(i.providers)));else if(Rr(i))t.push(i.useFactory(...Je(i.providers)));else if($r(i))t.push(i.useValue);else if(typeof i=="function")t.push(u(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function u(r,...e){if(Ye.has(r))return Ye.get(r);let t=It.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Je(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Ye.set(r,n),n}import{xterm as ye}from"@remotex-labs/xansi/xterm.component";import Nr from"typescript";import{readFileSync as Dr,statSync as jr}from"fs";import*as ge from"path";import*as ie from"path/posix";var Mr=/\\/g,Br=/\/+/g;function R(r){if(!r)return"";let e=String(r);return e=e.replace(Mr,"/"),e=e.replace(Br,"/"),e}function Et(r){return ie.normalize(R(r))}function x(...r){return ie.join(...r.map(R))}function w(...r){return R(ge.resolve(...r))}function $(r){return R(ge.dirname(r))}function T(r,e){return ie.relative(R(r),R(e))||"."}var Tt,Qe;Tt=[A({scope:"singleton"})];var b=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);i||(i={version:0,mtimeMs:0,contentSnapshot:void 0},this.snapshotsByPath.set(t,i));try{let o=jr(t).mtimeMs;if(o===i.mtimeMs)return{...i};let s=Dr(t,"utf-8"),a=s?Nr.ScriptSnapshot.fromString(s):void 0;i.version++,i.mtimeMs=o,i.contentSnapshot=a}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=w(e);return this.resolvedPathCache.set(e,i),i}};Qe=O(null),b=P(Qe,0,"FilesModel",Tt,b),k(Qe,1,b);import{readFileSync as Lr}from"fs";import{SourceService as Hr}from"@remotex-labs/xmap";var Ft,Ze;Ft=[A({scope:"singleton"})];var S=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=w(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=w(t);try{return this.initializeSourceMap(e,i)}catch(n){throw new Error(`Failed to initialize SourceService: ${i}
3
+ ${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=w(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=Lr(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t}
4
+ ${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return R(process.cwd())}getDistDir(){return R(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Hr(e,t);this.sourceMaps.set(t,i)}};Ze=O(null),S=P(Ze,0,"FrameworkService",Ft,S),k(Ze,1,S);import{parseErrorStack as Rt}from"@remotex-labs/xmap/parser.component";function Ot(r){return e=>new G(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 kt(r=(e,t)=>e===t){return e=>new G(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 G=class{constructor(e){this.handler=e}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 he=class extends G{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 ve=class extends he{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 Fe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function q(r,...e){if(!e.length)return r;let t=e.shift();if(Fe(r)&&Fe(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]}):Fe(n)?Object.assign(r,{[i]:q(Fe(o)?o:{},n)}):Object.assign(r,{[i]:n})}return q(r,...e)}return r}function Oe(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"?Vr(r,e,t):!1}function _r(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function Vr(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>Oe(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(!_r(e,o)||!Oe(r[o],e[o],t))return!1;return!0}var Ur="tsconfig.json",Pt=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",tsconfig:Ur,absWorkingDir:process.cwd()})})});var At,et;At=[A({scope:"singleton"})];var y=class{constructor(e=Pt){this.initialConfig=e;this.config$=new ve(q({},e))}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(Ot(e),kt((t,i)=>Oe(t,i)))}patch(e){let t=q({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(q({},this.initialConfig,e))}};et=O(null),y=P(et,0,"ConfigurationService",At,y),k(et,1,y);import{highlightCode as zr}from"@remotex-labs/xmap/highlighter.component";import{Bias as Wr}from"@remotex-labs/xmap";import{formatErrorCode as Gr}from"@remotex-labs/xmap/formatter.component";var qr=/\s{2,}/g,Kr=/^https?:\/\//,Xr=/^file:\/\//;function Yr(r){return r instanceof Error?Rt(r):r.detail instanceof Error?Rt(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 Jr(r){let e=r.fileName??"",t=this.framework.getSourceMap(e);if(t)return t;let i=this.files.getOrTouchFile(e),n=i?.contentSnapshot?.text;if(!i||!n)return null;let o=n.split(`
5
+ `);return{getPositionWithCode:(s,a,c,l)=>{let p=l?.linesBefore??3,f=l?.linesAfter??3,m=Math.max(s-p,0),g=Math.min(s+f,o.length);return{line:s,column:a+1,code:o.slice(m,g).join(`
6
+ `),source:e,name:null,startLine:m,endLine:g,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function Qr(r){return Gr({...r,code:zr(r.code)},{color:ye.brightPink})}function tt(r){let e=r.fileName;if(e?.includes(this.framework.rootPath)&&(e=T(this.framework.rootPath,e)),!e)return r.source??"";let t=r.line&&r.column?ye.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${ye.darkGray(e)} ${t}`.replace(qr," ").trim()}function Zr(r,e){let{source:t,sourceRoot:i,line:n}=e;if(!t)return r.fileName?r.fileName.replace(Xr,""):"";let o=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(o>0)return`${t.substring(o)}#L${n}`;if(Kr.test(t))return`${t}#L${n}`;if(i){let s=T($(this.framework.distPath),x(this.framework.distPath,t));return`${i}${s}#L${n}`}return`${t}#L${n}`}function ei(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=Qr(e)),tt.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:Zr.call(this,r,e)})}function ti(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=Jr.call(this,r);if(!t)return tt.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,Wr.LOWER_BOUND,e);return i?!this.withFrameworkFrames&&this.framework.isFrameworkFile(i)?"":(this.lineOffset&&(i.line+=this.lineOffset,i.startLine+=this.lineOffset,i.endLine+=this.lineOffset),this.line=i.line,this.column=i.column,ei.call(this,r,i)):tt.call(this,r)}function _(r,e,t=0){let i=u(y).getValue(a=>a.verbose)??!1,n={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(b),framework:u(S),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:Yr(r).stack.map(a=>ti.call(n,a,e)).filter(Boolean),code:n.code,line:n.line??0,column:n.column??0,source:n.source,formatCode:n.formatCode}}function V(r,e,t,i=[]){let n=[`
7
+ ${e}: ${ye.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(`
8
+ `+ye.gray(o.text));return r.formatCode&&n.push(`
9
9
 
10
- ${r.formatCode}`),r.stacks.length&&o.push(`
10
+ ${r.formatCode}`),r.stacks.length&&n.push(`
11
11
 
12
12
  Enhanced Stack Trace:
13
13
  ${r.stacks.join(`
14
14
  `)}
15
- `),o.join("")}var g=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=H(e,t),this.formattedStack=_(this.errorMetadata,e.name,e.message)}};function Pt(r){if(r instanceof AggregateError){console.error("AggregateError:",r.message);for(let e of r.errors)if(e instanceof Error&&!(e instanceof g)){let t=H(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(_(t,e.name,e.message))}else console.error(e);return}if(r instanceof Error&&!(r instanceof g)){let e=H(r,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(_(e,r.name,r.message))}else console.error(r)}ke.on("uncaughtException",r=>{Pt(r),ke.exit(2)});ke.on("unhandledRejection",r=>{Pt(r),ke.exit(2)});import rt from"yargs";import{hideBin as ri}from"yargs/helpers";import{xterm as tt}from"@remotex-labs/xansi/xterm.component";var Zr=`
15
+ `),n.join("")}var v=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=V(this.errorMetadata,e.name,e.message)}};function $t(r){if(r instanceof AggregateError){console.error("AggregateError:",r.message);for(let e of r.errors)if(e instanceof Error&&!(e instanceof v)){let t=_(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(V(t,e.name,e.message))}else console.error(e);return}if(r instanceof Error&&!(r instanceof v)){let e=_(r,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(V(e,r.name,r.message))}else console.error(r)}ke.on("uncaughtException",r=>{$t(r),ke.exit(2)});ke.on("unhandledRejection",r=>{$t(r),ke.exit(2)});import it from"yargs";import{hideBin as oi}from"yargs/helpers";import{xterm as rt}from"@remotex-labs/xansi/xterm.component";var ri=`
16
16
  ______ _ _ _
17
17
  | ___ \\ (_) | | |
18
18
  __ _| |_/ /_ _ _| | __| |
19
19
  \\ \\/ / ___ \\ | | | | |/ _\` |
20
20
  > <| |_/ / |_| | | | (_| |
21
21
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
22
- `;function Fe(){return`
23
- \r${tt.burntOrange(Zr)}
24
- \rVersion: ${tt.brightPink("2.1.1")}
25
- \r`}function O(){return tt.lightCoral("[xBuild]")}var ei="tsconfig.json",ti="config.xbuild.ts",Pe={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ti},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string",default:ei},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},At=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Rt,it;Rt=[A({scope:"singleton"})];var Q=class{parseConfigFile(e){return rt(e).help(!1).version(!1).options({config:Pe.config}).parseSync()}parseUserArgv(e,t){return t?rt(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=rt(ri(e)).locale("en"),o=i.showHelp;return i.showHelp=function(n){return console.log(Fe()),this.group(Object.keys(Pe),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),o.call(this,n)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",n=>n.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Pe).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),At.forEach(([n,s])=>{i.example(n,s)}),i.parseSync()}};it=k(null),Q=P(it,0,"ArgvModule",Rt,Q),F(it,1,Q);import dt from"readline";import{exec as eo}from"child_process";import{cwd as ii}from"process";import{readdirSync as oi}from"fs";import{matchesGlob as ot}from"path";function ni(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 $t(r,e){for(let t of e)if(ot(r,t))return!0;return!1}function si(r,e){let t=r+"/**";for(let i of e)if(ot(r,i)||ot(t,i))return!0;return!1}function Ae(r,e){let{include:t,exclude:i}=ni(e),o=Object.create(null),s=ii().length+1,a=r.length+1,l=i.length>0;function c(f){let p;try{p=oi(f,{withFileTypes:!0})}catch{return}let h=p.length;for(let m=0;m<h;m++){let W=p[m],te=v(f,W.name),L=te.slice(a);if(W.isDirectory()){(!l||!si(L,i))&&c(te);continue}if(!(l&&$t(L,i))&&$t(L,t)){let We=te.slice(s),w=L.lastIndexOf("."),pe=w>0?L.slice(0,w):L;o[pe]=We}}}return c(r),o}var V=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var Re=class extends g{constructor(e){super(e.text,"esBuildError"),this.errorMetadata=H(e,{withFrameworkFrames:!0}),this.stack=_(this.errorMetadata,this.name,this.message,e.notes)}};var U=class r extends g{constructor(t,i){if(t instanceof g)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(o=>new r(o,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
22
+ `;function Pe(){return`
23
+ \r${rt.burntOrange(ri)}
24
+ \rVersion: ${rt.brightPink("2.1.2")}
25
+ \r`}function F(){return rt.lightCoral("[xBuild]")}var ii="tsconfig.json",ni="config.xbuild.ts",Ae={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ni},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string",default:ii},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},Mt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Bt,nt;Bt=[A({scope:"singleton"})];var Q=class{parseConfigFile(e){return it(e).help(!1).version(!1).options({config:Ae.config}).parseSync()}parseUserArgv(e,t){return t?it(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=it(oi(e)).locale("en"),n=i.showHelp;return i.showHelp=function(o){return console.log(Pe()),this.group(Object.keys(Ae),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",o=>o.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Ae).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),Mt.forEach(([o,s])=>{i.example(o,s)}),i.parseSync()}};nt=O(null),Q=P(nt,0,"ArgvModule",Bt,Q),k(nt,1,Q);import gt from"readline";import{exec as on}from"child_process";import{cwd as si}from"process";import{readdirSync as ai}from"fs";import{matchesGlob as ot}from"path";function ci(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 Nt(r,e){for(let t of e)if(ot(r,t))return!0;return!1}function li(r,e){let t=r+"/**";for(let i of e)if(ot(r,i)||ot(t,i))return!0;return!1}function Re(r,e){let{include:t,exclude:i}=ci(e),n=Object.create(null),s=si().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=ai(p,{withFileTypes:!0})}catch{return}let m=f.length;for(let g=0;g<m;g++){let B=f[g],W=x(p,B.name),H=W.slice(a);if(B.isDirectory()){(!c||!li(H,i))&&l(W);continue}if(!(c&&Nt(H,i))&&Nt(H,t)){let Ge=W.slice(s),C=H.lastIndexOf("."),ue=C>0?H.slice(0,C):H;n[ue]=Ge}}}return l(r),n}var U=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var Z=class extends v{constructor(e){super(e.text??"","esBuildError"),this.errorMetadata=_(e,{withFrameworkFrames:!0}),this.stack=V(this.errorMetadata,this.name,this.message,e.notes)}};var z=class r extends v{constructor(t,i){if(t instanceof v)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
26
26
  ${t}
27
- `}return this.formattedStack||this.stack}};function ai(r){return r instanceof g?r:r.detail instanceof g||r.detail instanceof V?r.detail:r.detail&&("errors"in r.detail||r.detail instanceof AggregateError)?new U(r.detail,{withFrameworkFrames:!0}):r.detail instanceof Error?new U(r.detail,{withFrameworkFrames:!0}):r.location?new Re(r):new U(new Error(r.text))}function ve(r=[],e){for(let t of r)e.push(ai(t))}function ye(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return ve(r.errors,e.errors),ve(r.warnings,e.warnings),e}function Z(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Dt from"http";import*as jt from"https";import{extname as Bt}from"path";import{readFileSync as Nt}from"fs";var Mt=`<!doctype html>
27
+ `}return this.formattedStack||this.stack}};function fi(r){return r instanceof v?r:r.detail instanceof v||r.detail instanceof U?r.detail:r.detail&&("errors"in r.detail||r.detail instanceof AggregateError)?new z(r.detail,{withFrameworkFrames:!0}):r.detail instanceof Error?new z(r.detail,{withFrameworkFrames:!0}):r.location?new Z(r):new z(new Error(r.text))}function xe(r=[],e){for(let t of r)e.push(fi(t))}function be(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return xe(r.errors,e.errors),xe(r.warnings,e.warnings),e}function ee(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Ht from"http";import*as _t from"https";import{extname as jt}from"path";import{readFileSync as Lt}from"fs";var Dt=`<!doctype html>
28
28
  <html lang="en">
29
29
  <head>
30
30
  <meta charset="utf-8"/>
@@ -342,50 +342,56 @@ ${t}
342
342
  });
343
343
  </script>
344
344
  </html>
345
- `;import{readdir as li,stat as pi,readFile as fi}from"fs/promises";import{xterm as $e}from"@remotex-labs/xansi/xterm.component";var xe=class{constructor(e,t){this.config=e;this.rootDir=C(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(S);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(O(),$e.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(O(),$e.dim("Server stopped.")),this.server=void 0}async restart(){console.log(O(),$e.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=Dt.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:Nt(this.config.key??v(this.framework.distPath,"..","certs","server.key")),cert:Nt(this.config.cert??v(this.framework.distPath,"..","certs","server.crt"))};this.server=jt.createServer(t,(i,o)=>{this.handleRequest(i,o,()=>this.defaultResponse(i,o))}),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(`${O()} Request ${$e.lightCoral(e.url?.toString()??"")}`),this.config.onRequest?this.config.onRequest(e,t,i):i()}catch(o){this.sendError(t,o)}}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(/^\/+/,"")||"",o=v(this.rootDir,i);if(!o.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await pi(o);n.isDirectory()?await this.handleDirectory(o,i,t):n.isFile()&&await this.handleFile(o,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(O(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let n=(await li(e)).map(c=>{let f=v(t,c),p=Bt(c).slice(1)||"folder";return p==="folder"?`
346
- <a href="/${f}" class="folder-row">
345
+ `;import{readdir as ui,stat as di,readFile as mi}from"fs/promises";import{xterm as $e}from"@remotex-labs/xansi/xterm.component";var Se=class{constructor(e,t){this.config=e;this.rootDir=w(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(S);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(F(),$e.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(F(),$e.dim("Server stopped.")),this.server=void 0}async restart(){console.log(F(),$e.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=Ht.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:Lt(this.config.key??x(this.framework.distPath,"..","certs","server.key")),cert:Lt(this.config.cert??x(this.framework.distPath,"..","certs","server.crt"))};this.server=_t.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(`${F()} Request ${$e.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=x(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await di(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(F(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await ui(e)).map(l=>{let p=x(t,l),f=jt(l).slice(1)||"folder";return f==="folder"?`
346
+ <a href="/${p}" class="folder-row">
347
347
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
348
- <div class="meta"><div class="name">${c}</div><div class="sub">Folder</div></div>
348
+ <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
349
349
  </a>
350
350
  `:`
351
- <a href="/${f}" class="file-row">
351
+ <a href="/${p}" class="file-row">
352
352
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
353
- <div class="meta"><div class="name">${c}</div><div class="sub">${p}</div></div>
353
+ <div class="meta"><div class="name">${l}</div><div class="sub">${f}</div></div>
354
354
  </a>
355
- `}).join("");n?n=`<div class="list">${n}</div>`:n='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(c=>(s+=`${c}/`,`<li><a href="${s}">${c}</a></li>`)).join(""),l=Mt.replace("${ fileList }",n).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(l)}async handleFile(e,t){let i=Bt(e).slice(1)||"txt",o=this.getContentType(i),n=await fi(e);t.writeHead(200,{"Content-Type":o}),t.end(n)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(O(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as Lt}from"path";import{stat as ui,watch as di}from"fs/promises";var be=class{excludes;include;debounceTimer=null;framework=u(S);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=di(this.framework.rootPath,{recursive:!0});for await(let{filename:o}of i){if(!o)continue;let n=wt(o);if(n.endsWith("~")||!this.include.some(a=>Lt(n,a))||this.excludes.some(a=>Lt(n,a)))continue;let s=v(this.framework.rootPath,n);try{if(!(await ui(s)).isFile())continue}catch{}t.add(n),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)}};var B=class extends g{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as Fi}from"esbuild";import{writeFile as Pi,mkdir as Ai}from"fs/promises";import d from"typescript";import mi from"typescript";var gi=/^#!.*(\r?\n)?/,hi=/export {};\n?/g,vi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,yi=/^export\s+(?:default\s+)?/gm,xi=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function bi(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(gi,""):r}function Si(r){return r.includes("export {}")?r.replace(hi,""):r}function wi(r){return r=r.replace(xi,""),r.replace(vi,"$1")}function Ht(r){return r.replace(yi,"")}function Ci(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function Me(r){return Ci(r)&&(r=bi(r),r=Si(r),r=wi(r)),r}function nt(r,e){let{outDir:t,rootDir:i,declarationDir:o}=e,n=o||t||$(r),s=i||$(r),l=T(s,r).replace(/\.tsx?$/,".d.ts"),c=mi.sys.resolvePath(`${n}/${l}`);return R(c)}var _t,st;_t=[A({scope:"singleton"})];var ee=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(y);constructor(){this.printer=d.createPrinter({newLine:d.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let o=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),n=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===n)return s;let a=this.initDeclaration(e.fileName,n),l=this.emitDeclaration.call(o,e);return a.content=this.stripImportsExports.call(o,l,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(!d.isStringLiteral(e))return null;let i=e.text,o=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!o||o.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:o,isExternal:!1}}addNamedElements(e,t){for(let i of t){let o=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(o)}}hasExportModifier(e){return d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.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 d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],o=[];for(let l of e.statements){if(d.isImportDeclaration(l)){this.handleImport(l,t,i);continue}if(d.isExportDeclaration(l)){this.handleExport(l,t);continue}this.hasExportModifier(l)&&this.extractExportName(l,t),o.push(l)}let n=d.factory.createNodeArray(o),s=this.printer.printList(d.ListFormat.MultiLine,n,e),a=Ht(Me(s));for(let l of i)if(l.includes(" as ")){let[c,f]=l.split(" as ");a=a.replace(new RegExp(`\\b${f}\\b`,"g"),c)}else a=a.replace(new RegExp(`\\b${l}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:o,moduleSpecifier:n}=e;if(!o||!n)return;let s=this.resolveModule(n,t.fileName);if(!s)return;let{fileName:a,isExternal:l}=s;if(!l){t.internalDeps.add(a);let{namedBindings:f}=o;if(!f)return;d.isNamespaceImport(f)?i.push(f.name.text):d.isNamedImports(f)&&this.addNamedElements(i,f.elements);return}if(!o){t.externalImports.namespace[a]="";return}o.name&&(t.externalImports.default[a]=o.name.text);let{namedBindings:c}=o;c&&(d.isNamespaceImport(c)?t.externalImports.namespace[c.name.text]=a:d.isNamedImports(c)&&this.addNamedElements(t.externalImports.named[a]??=[],c.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:o}=e;if(!i)return;let n=this.resolveModule(i,t.fileName);if(!n)return;let{fileName:s,isExternal:a}=n;if(a||t.internalDeps.add(s),!o){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(d.isNamespaceExport(o)){a?t.externalExports.namespace[o.name.text]=s:t.internalExports.namespace[o.name.text]=s;return}d.isNamedExports(o)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],o.elements):this.addNamedElements(t.internalExports.exports,o.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};st=k(null),ee=P(st,0,"GraphModel",_t,ee),F(st,1,ee);import K from"typescript";import{mkdir as Ei,writeFile as Ii}from"fs/promises";var Vt=`/**
355
+ `}).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=Dt.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=jt(e).slice(1)||"txt",n=this.getContentType(i),o=await mi(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(F(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as Vt}from"path";import{stat as gi,watch as hi}from"fs/promises";var Ce=class{excludes;include;debounceTimer=null;framework=u(S);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=hi(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Et(n);if(o.endsWith("~")||!this.include.some(a=>Vt(o,a))||this.excludes.some(a=>Vt(o,a)))continue;let s=x(this.framework.rootPath,o);try{if(!(await gi(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)}};var N=class extends v{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as Ri}from"esbuild";import{writeFile as $i,mkdir as Mi}from"fs/promises";import d from"typescript";import vi from"typescript";var yi=/^#!.*(\r?\n)?/,xi=/export {};\n?/g,bi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,Si=/^export\s+(?:default\s+)?/gm,Ci=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function wi(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(yi,""):r}function Ii(r){return r.includes("export {}")?r.replace(xi,""):r}function Ei(r){return r=r.replace(Ci,""),r.replace(bi,"$1")}function Ut(r){return r.replace(Si,"")}function Ti(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function Me(r){return Ti(r)&&(r=wi(r),r=Ii(r),r=Ei(r)),r}function st(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||$(r),s=i||$(r),c=T(s,r).replace(/\.tsx?$/,".d.ts"),l=vi.sys.resolvePath(`${o}/${c}`);return R(l)}var zt,at;zt=[A({scope:"singleton"})];var te=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(b);constructor(){this.printer=d.createPrinter({newLine:d.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(!d.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 d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.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 d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(d.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(d.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=d.factory.createNodeArray(n),s=this.printer.printList(d.ListFormat.MultiLine,o,e),a=Ut(Me(s));for(let c of i)if(c.includes(" as ")){let[l,p]=c.split(" as ");a=a.replace(new RegExp(`\\b${p}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:n,moduleSpecifier:o}=e;if(!n||!o)return;let s=this.resolveModule(o,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:p}=n;if(!p)return;d.isNamespaceImport(p)?i.push(p.name.text):d.isNamedImports(p)&&this.addNamedElements(i,p.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:l}=n;l&&(d.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:d.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.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(d.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}d.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};at=O(null),te=P(at,0,"GraphModel",zt,te),k(at,1,te);import K from"typescript";import{mkdir as Fi,writeFile as Oi}from"fs/promises";var Wt=`/**
356
356
  * This file was automatically generated by xBuild.
357
357
  * DO NOT EDIT MANUALLY.
358
358
  */
359
- `;var Be=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(ee);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let o=this.languageHostService.getCompilationSettings();t&&(o={...o,outDir:t}),await Promise.all(Object.entries(e).map(async([n,s])=>{let a=i.getSourceFile(s);if(!a)return;let l=v(o.outDir,`${n}.d.ts`);await this.bundleCollectDeclarations(a,i,l)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let o=this.graphModel.scan(e,this.languageService,this.languageHostService),n=await this.getBundleContent(o,t);await Ei($(i),{recursive:!0}),await Ii(i,n,"utf-8")}async getBundleContent(e,t){let i=new Set,o=new Set([e]),n=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),l="";for(;s.length>0;){let c=s.pop();if(i.has(c))continue;i.add(c);let f=t.getSourceFile(c);if(!f)continue;let p=this.graphModel.scan(f,this.languageService,this.languageHostService);if(n.add(p),a.has(c)){o.add(p);for(let h of p.internalExports.star)a.add(h)}for(let h of p.internalDeps)i.has(h)||s.push(h);l+=p.content}return l+=e.content,this.parseContent(l,n,o)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[o,n]of Object.entries(i.externalImports.default)){t.has(o)||t.set(o,{named:new Set,namespace:new Map});let s=t.get(o);s.default||(s.default=n)}for(let[o,n]of Object.entries(i.externalImports.named)){t.has(o)||t.set(o,{named:new Set,namespace:new Map});for(let s of n)t.get(o).named.add(s)}for(let[o,n]of Object.entries(i.externalImports.namespace))t.has(n)||t.set(n,{named:new Set,namespace:new Map}),t.get(n).namespace.set(o,n)}return t}generateImportStatements(e){let t=[];for(let[i,{default:o,named:n,namespace:s}]of e){let a=[];if(o&&a.push(o),n.size>0&&a.push(`{ ${Array.from(n).sort().join(", ")} }`),s.size>0)for(let[l]of s)t.push(`import * as ${l} 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 o=[...i.internalExports.exports],n=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let l=this.collectNamespaceExports(a,t);l.exports.length>0&&(n.push(...l.declarations),n.push(`const ${s} = { ${l.exports.join(", ")} };`),o.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);o.push(...a.exports),n.push(...a.declarations)}return{exports:o,declarations:n}}collectBundleExports(e){let t=[],i=[],o=[];for(let n of e){t.push(...n.internalExports.exports);for(let[s,a]of Object.entries(n.internalExports.namespace)){let l=this.collectNamespaceExports(a);l.exports.length>0&&(i.push(...l.declarations),i.push(`const ${s} = { ${l.exports.join(", ")} };`),t.push(s))}for(let s of n.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(n.externalExports.namespace))o.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(n.externalExports.exports))o.push(`export { ${a.join(`,
360
- `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:o}}parseContent(e,t,i){let o=[Vt],n=this.collectExternalImports(t),s=this.generateImportStatements(n);o.push(...s),s.length>0&&o.push("");let{exports:a,declarations:l,externalExports:c}=this.collectBundleExports(i);if(l.length>0&&(o.push(...l),o.push("")),o.push(e),a.length>0){let f=Array.from(new Set(a)).sort();o.push(`export {
361
- ${f.join(`,
359
+ `;var Be=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(te);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=x(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Fi($(i),{recursive:!0}),await Oi(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 p=t.getSourceFile(l);if(!p)continue;let f=this.graphModel.scan(p,this.languageService,this.languageHostService);if(o.add(f),a.has(l)){n.add(f);for(let m of f.internalExports.star)a.add(m)}for(let m of f.internalDeps)i.has(m)||s.push(m);c+=f.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(`,
360
+ `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[Wt],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 p=Array.from(new Set(a)).sort();n.push(`export {
361
+ ${p.join(`,
362
362
  `)}
363
- };`)}return c.length>0&&o.push(...c),o.join(`
364
- `)}};import{mkdir as Ti,writeFile as Oi}from"fs/promises";import{xterm as ki}from"@remotex-labs/xansi/xterm.component";var Ne=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${ki.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let o=[],n=t.getSourceFiles();for(let s=0;s<n.length;s++){let a=n[s];this.shouldEmitFile(a,t,i)&&o.push(a)}o.length!==0&&await Promise.all(o.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let o=nt(e.fileName,i),n=r.emittedVersions.get(o),s=this.languageHostService.getScriptVersion(e.fileName);return!n||n!==s?(r.emittedVersions.set(o,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let o=i.outputFiles[0].text,n=nt(e.fileName,t);o=Me(o),o=this.languageHostService.resolveAliases(o,e.fileName,".d.ts"),await Ti($(n),{recursive:!0}),await Oi(n,o,"utf8")}};import ie from"typescript";var De=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ie.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=ie.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(y);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ie.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}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,o,n){return r.sys.readDirectory(e,t,i,o,n)}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 ie.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 ie.resolveModuleName(e,t,this.compilerOptions,ie.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let o=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,o),o}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(o,n)=>{let s=this.resolveModuleFileName(n,t);if(!s)return o;let a=s.replace(/\.tsx?$/,i),l=T(t,a);return o.replace(n,l.startsWith(".")?l:"./"+l)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(o=>o.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var Ut,at;Ut=[A({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:o}=this.acquireLanguageService();this.config=t,this.languageService=o,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new Ne(o,i),this.bundlerService=new Be(o,i)}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(o=>t.getSourceFile(o)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(o=>this.shouldCheckFile(o)).flatMap(o=>this.collectDiagnostics(o)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=N.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=N.serviceCache.get(e);t&&(t.refCount--,N.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!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=N.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new De(e.options),i=K.createLanguageService(t,K.createDocumentRegistry()),o={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,o),o}parseConfig(){let e=K.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...K.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:K.ScriptTarget.ESNext,module:K.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:K.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:K.flattenDiagnosticMessageText(e.messageText,`
365
- `)};if(e.file&&e.start!==void 0){let{line:i,character:o}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=o+1,t.code=e.code}return t}};at=k(null),N=P(at,0,"TypescriptService",Ut,N),F(at,1,N);var oe=N;import{cwd as je}from"process";import{build as ct}from"esbuild";var zt={write:!1,bundle:!0,minify:!0,outdir:`${je()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Wt(r,e={}){try{return await ct({absWorkingDir:je(),...zt,...e,metafile:!0,entryPoints:r})}catch(t){if(Z(t)){let i=new AggregateError([],"Failed to build entryPoints");throw ve(t.errors,i.errors),i}throw t}}async function Gt(r,e,t={}){return await ct({absWorkingDir:je(),...zt,...t,stdin:{loader:"ts",contents:r,resolveDir:je(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function qt(r,e={}){try{return await ct({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(Z(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw ve(t.errors,i.errors),i}throw t}}function Kt(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=Ae(r,e)),t}else if(e&&typeof e=="object")return e;throw new B("Unsupported entry points format")}var Le=class{constructor(e,t,i,o={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=o;if(!this.buildConfig?.esbuild)throw new B(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new oe(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),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(n=>({variantConfig:n.variants?.[this.name],commonConfig:n.common})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);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){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Fi(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(Z(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?q({},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;let i=new V("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,o=typeof i=="object"?i.bundle!==!1:!0,n=typeof i=="object"?i.outDir:void 0;try{o?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,n):await this.typescriptModule.emit(n)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:o,onEnd:n,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),o&&this.lifecycle.onLoad(o),n&&this.lifecycle.onEnd(n),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Ai(e,{recursive:!0}),await Pi(v(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new B(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new B("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([o,n])=>[o,JSON.stringify(n)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=Kt(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.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new oe(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await qt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let o of Object.keys(t.inputs)){let n=T(this.typescriptModule.config.options.rootDir,C(o)),s=this.stripExtension(n);i[s]=o}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[o,n]of Object.entries(t))i[e][o]=typeof n=="function"?n(this.name,this.argv):n}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Ri}from"fs/promises";var He=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(y);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,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let o of this.startHooks.values()){let n=await o({build:e,...t});n&&(n.errors&&i.errors.push(...n.errors),n.warnings&&i.warnings.push(...n.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},o=Date.now()-t.stage.startTime.getTime();for(let n of this.endHooks.values()){let s=await n({buildResult:e,duration:o,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let n of this.successHooks.values())await n({buildResult:e,duration:o,...t});return i}async executeResolveHooks(e,t){let i;for(let o of this.resolveHooks.values()){let n=await o({args:e,...t});n&&(i?i={...i,...n}:i=n)}return i??null}async executeLoadHooks(e,t){let i,o="default",n={errors:[],warnings:[]},s=C(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await Ri(s,"utf8");for(let l of this.loadHooks.values()){let c=await l({contents:i,loader:o,args:e,...t});c&&(c.contents!==void 0&&(i=c.contents),c.loader&&(o=c.loader),c.errors&&n.errors.push(...c.errors),c.warnings&&n.warnings.push(...c.warnings))}return{contents:i,loader:o,...n}}};import x from"typescript";import X from"typescript";var $i="$$ifdef";function Mi(r,e,t,i=!1){let o=i?"export function ":"function ";return X.isArrowFunction(e)||X.isFunctionExpression(e)?Bi(r,e,t,o):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Bi(r,e,t,i){let o=e.parameters.map(a=>a.getText(t)).join(", "),n=e.type?`: ${e.type.getText(t)}`:"",s=Ni(e,t);return`${i}${r}(${o})${n} ${s}`}function Ni(r,e){let t=r.body.getText(e);return X.isArrowFunction(r)&&!X.isBlock(r.body)?`{ return ${t}; }`:t}function Di(r,e){return X.isArrowFunction(r)||X.isFunctionExpression(r)?`(${r.getText(e)})()`:`(() => { return ${r.getText(e)}; })()`}function Xt(r,e,t){let i=r in t&&!!t[r];return e===$i===i}function Yt(r,e,t,i){let[o,n]=e.arguments;if(!X.isStringLiteral(o))return!1;let s=e.expression.text,a=o.text;if(!Xt(a,s,i.defines))return"";let l=r.name.getText(i.sourceFile);return Mi(l,n,i.sourceFile,t)}function Jt(r,e,t){let[i,o]=r;if(!X.isStringLiteral(i))return!1;let n=i.text;return Xt(n,e,t.defines)?Di(o,t.sourceFile):""}import M from"typescript";import{createRequire as Hi}from"module";var _e=class extends g{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=H(e,{},t),this.stack=_(this.errorMetadata,this.name,this.message)}};import{Script as ji,createContext as Li}from"vm";async function Qt(r,e={},t={}){let i=new ji(r,t),o=Li(e);return await i.runInContext(o,{breakOnSigint:!0,displayErrors:!1})}async function Zt(r,e,t){let[i,o]=(await Gt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let n={exports:{}},s=Hi(e.sourceFile.fileName),a=await Qt(o.text,_i(e.sourceFile.fileName,n,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(n){Vi(n,e,i.text,t)}return"undefined"}function _i(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:$(r),__filename:r}}function Vi(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let o=i.getStart(e.sourceFile),{line:n}=e.sourceFile.getLineAndCharacterOfPosition(o);u(S).setSource(t,e.sourceFile.fileName);let s=new _e(r,n);e.errors.push({text:s.message,detail:s})}function Ui(r,e){let t=null,i=o=>{if(!t){if(M.isFunctionDeclaration(o)&&o.name?.text===r){t=o;return}M.isVariableStatement(o)&&(t=zi(o,r),t)||M.forEachChild(o,i)}};return i(e),t}function zi(r,e){for(let t of r.declarationList.declarations)if(M.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(M.isArrowFunction(t.initializer)||M.isFunctionExpression(t.initializer)))return t.initializer;return null}function er(r){return`module.exports = (${r})();`}function Wi(r){return r&M.NodeFlags.Const?"const":r&M.NodeFlags.Let?"let":"var"}function tr(r,e){return r?M.isIdentifier(r)?Gi(r,e):M.isArrowFunction(r)||M.isFunctionExpression(r)?{node:r,data:er(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Gi(r,e){let t=Ui(r.text,e.sourceFile);return t?{node:t,data:er(t.getText(e.sourceFile))}:(qi(r.text,e,r),{data:"",node:r})}function qi(r,e,t){let i=t.getStart(e.sourceFile),{line:o,character:n}=e.sourceFile.getLineAndCharacterOfPosition(i),s=T(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:o+1,column:n,file:e.sourceFile.fileName,lineText:"asd"}})}async function rr(r,e,t,i,o){let n=t.arguments[0],s=tr(n,o);if(!s)return!1;let a=await Zt(s.data,o,s.node),l=Wi(e.declarationList.flags),c=i?"export ":"",f=r.name.getText(o.sourceFile);return`${c}${l} ${f} = ${a};`}async function lt(r,e){let t=r[0],i=tr(t,e);return i?Zt(i.data,e,i.node):!1}var Ki=/\.(ts|js)$/,z=["$$ifdef","$$ifndef","$$inline"];async function Xi(r,e,t){for(let i of r.declarationList.declarations){let o=i.initializer;if(!o||!x.isCallExpression(o)||!x.isIdentifier(o.expression))continue;let n=o.expression.text;if(!z.includes(n))continue;let s=n==z[2]?1:2;if(!z.includes(n))continue;if(o.arguments.length<s||o.arguments.length>s)throw new Error(`Invalid macro call: ${n} with ${o.arguments.length} arguments`);let a=r.modifiers?.some(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1,l=!1;n===z[2]?l=await rr(i,r,o,a,t):l=Yt(i,o,a,t),l!==!1&&e.add({replacement:l,end:r.getEnd(),start:r.getStart(t.sourceFile)})}}async function Yi(r,e,t){let i=r.expression;if(!x.isIdentifier(i.expression))return;let o=i.expression.text,n=o==z[2]?1:2;if(!z.includes(o))return;if(i.arguments.length<n||i.arguments.length>n)throw new Error(`Invalid macro call: ${o} with ${i.arguments.length} arguments`);let s=!1;o==z[2]?s=await lt(i.arguments,t):s=Jt(i.arguments,o,t),s!==!1&&e.add({replacement:s,end:r.getEnd(),start:r.getStart(t.sourceFile)})}async function Ji(r){let e=new Set,t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let o=[r.sourceFile];for(;o.length>0;){let s=o.pop(),a=s?.kind;if(!a)continue;if(t.size>0){if(a===x.SyntaxKind.CallExpression){let c=s;x.isIdentifier(c.expression)&&t.has(c.expression.text)&&e.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===x.SyntaxKind.Identifier){let c=s;if(t.has(c.text)){let f=s.parent??s;if(f&&!x.isImportSpecifier(f)&&!x.isExportSpecifier(f)){let p=f?.getText(r.sourceFile);(!x.isCallExpression(f)||f.expression!==s)&&(!p||z.every(h=>!p.includes(h)))&&e.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}if(i){if(a===x.SyntaxKind.VariableStatement)await Xi(s,e,r);else if(a===x.SyntaxKind.ExpressionStatement){let c=s;x.isCallExpression(c.expression)&&await Yi(c,e,r)}else if(a===x.SyntaxKind.CallExpression){let c=s;if(x.isIdentifier(c.expression)&&c.expression.text===z[2]){let f=s.parent;if(!f||!x.isVariableDeclaration(f)&&!x.isExpressionStatement(f)){let p=await lt(c.arguments,r);p!==!1&&e.add({replacement:p,end:s.getEnd(),start:s.getStart(r.sourceFile)})}}}}let l=s.getChildren(r.sourceFile);for(let c=l.length-1;c>=0;c--)o.push(l[c])}if(e.size===0)return r.contents;let n=Array.from(e);n.sort((s,a)=>a.start-s.start);for(let{start:s,end:a,replacement:l}of n)r.contents=r.contents.slice(0,s)+l+r.contents.slice(a);return r.contents}async function ir(r,e){let{args:t,loader:i,stage:o,contents:n}=e;if(t.path.includes("node_modules")||n.length<1||!Ki.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let l=n.toString(),c={stage:o,errors:[],contents:l,warnings:[],defines:r.config.define??{},sourceFile:a};return a&&(l=await Ji(c)),r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var or="$$",nr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*['"]([^'"]+)['"]/g;function Qi(r,e,t,i){let o=1;for(let n=0;n<i;n++)r[n]===`
366
- `&&o++;return{file:t,line:o,column:r.indexOf(e,i)-i}}function Zi(r,e){let t=r.lastIndexOf(`
367
- `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],o=r[t+1];return i==="/"&&(o==="/"||o==="*")||i==="*"}async function sr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],o=u(y),n=r.config.define??{},s=Object.values(r.dependencies??{});if(!s)return Promise.resolve({warnings:i});for(let a of s){let c=o.getOrTouchFile(a)?.contentSnapshot?.text;if(c){nr.lastIndex=0;for(let f of c.matchAll(nr)){if(Zi(c,f.index))continue;t.filesWithMacros.add(o.resolve(a));let[,p,h,m]=f;if(!p)continue;let W=m in n&&!!n[m];h==="ifndef"===W&&t.disabledMacroNames.add(p),p.startsWith(or)||i.push({text:`Macro function '${p}' not start with '${or}' prefix to avoid conflicts`,location:Qi(c,p,a,f.index)})}}}return{warnings:i}}var Se=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(b);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},o=Object.entries(this.variants).map(async([n,s])=>{if(!(e&&!e.includes(n)))try{let a=await s.build();a&&(i[n]=ye(a))}catch(a){if(Z(a)||a instanceof AggregateError){let l=ye({errors:a.errors});t.push(...l.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(o),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await sr(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let o of t.errors)i.push({detail:o,text:o.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(n=>!(n in e))]}parseVariants(){if(!this.config.variants)throw new B("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new He(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Le(e,t,this.config.variants[e],this.argv),t.onLoad(ir.bind({},this.variants[e]),"build-service")}}};function ar(r){u(b).reload(r)}function cr(r){u(b).patch(r)}import{platform as to,exit as ro,stdin as Ve,stdout as ft}from"process";import{xterm as Ue}from"@remotex-labs/xansi/xterm.component";var pt={SIGINT:"",SIGQUIT:""},E={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},lr={win32:"start",darwin:"open",linux:"xdg-open"};function io(r=!1){let e=["\u{1F680} Shortcuts"],t=Ue.dim(" press "),i=(o,n)=>{e.push(`${t}${Ue.bold(o)}${Ue.dim(n)}`)};return r&&(i(E.SHOW_URL," to show server url"),i(E.OPEN_BROWSER," to open in browser")),i(E.VERBOSE," to enable / disable verbose mode"),i(E.RELOAD," to reload"),i(E.CLEAR," to clear console"),i(E.QUIT,` to quit
363
+ };`)}return l.length>0&&n.push(...l),n.join(`
364
+ `)}};import{mkdir as ki,writeFile as Pi}from"fs/promises";import{xterm as Ai}from"@remotex-labs/xansi/xterm.component";var Ne=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Ai.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=st(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=st(e.fileName,t);n=Me(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await ki($(o),{recursive:!0}),await Pi(o,n,"utf8")}};import ne from"typescript";var De=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ne.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=ne.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(b);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ne.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}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 ne.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 ne.resolveModuleName(e,t,this.compilerOptions,ne.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=T(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 Gt,ct;Gt=[A({providers:[{useValue:"tsconfig.json"}]})];var D=class D{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 Ne(n,i),this.bundlerService=new Be(n,i)}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=D.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=D.serviceCache.get(e);t&&(t.refCount--,D.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!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=D.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new De(e.options),i=K.createLanguageService(t,K.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return D.serviceCache.set(this.configPath,n),n}parseConfig(){let e=K.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...K.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:K.ScriptTarget.ESNext,module:K.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:K.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:K.flattenDiagnosticMessageText(e.messageText,`
365
+ `)};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}};ct=O(null),D=P(ct,0,"TypescriptService",Gt,D),k(ct,1,D);var oe=D;import{cwd as je}from"process";import{build as lt}from"esbuild";var qt={write:!1,bundle:!0,minify:!0,outdir:`${je()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Kt(r,e={}){try{return await lt({absWorkingDir:je(),...qt,...e,metafile:!0,entryPoints:r})}catch(t){if(ee(t)){let i=new AggregateError([],"Failed to build entryPoints");throw xe(t.errors,i.errors),i}throw t}}async function Xt(r,e,t={}){return await lt({absWorkingDir:je(),...qt,...t,stdin:{loader:"ts",contents:r,resolveDir:je(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Yt(r,e={}){try{return await lt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(ee(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw xe(t.errors,i.errors),i}throw t}}function Jt(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=Re(r,e)),t}else if(e&&typeof e=="object")return e;throw new N("Unsupported entry points format")}var Le=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new N(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new oe(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),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})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(y);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){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ri(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(ee(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?q({},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;let i=new U("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};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 Mi(e,{recursive:!0}),await $i(x(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new N(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new N("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=Jt(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.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new oe(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await Yt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=T(this.typescriptModule.config.options.rootDir,w(n)),s=this.stripExtension(o);i[s]=n}return i}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 Bi}from"fs/promises";var He=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(b);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,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=w(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await Bi(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import h from"typescript";import{highlightCode as or}from"@remotex-labs/xmap/highlighter.component";import X from"typescript";var Ni="$$ifdef";function Di(r,e,t,i=!1){let n=i?"export function ":"function ";return X.isArrowFunction(e)||X.isFunctionExpression(e)?ji(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function ji(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Li(e,t);return`${i}${r}(${n})${o} ${s}`}function Li(r,e){let t=r.body.getText(e);return X.isArrowFunction(r)&&!X.isBlock(r.body)?`{ return ${t}; }`:t}function Hi(r,e,t="",i="();"){return X.isArrowFunction(r)||X.isFunctionExpression(r)?`${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Qt(r,e,t){let i=r in t&&!!t[r];return e===Ni===i}function Zt(r,e,t,i){let[n,o]=e.arguments;if(!X.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!Qt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Di(c,o,i.sourceFile,t)}function _e(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!X.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!Qt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),Hi(s,e.sourceFile,l,n)}import M from"typescript";import{createRequire as Ui}from"module";var Ve=class extends v{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=_(e,{},t),this.stack=V(this.errorMetadata,this.name,this.message)}};import{Script as _i,createContext as Vi}from"vm";async function er(r,e={},t={}){let i=new _i(r,t),n=Vi(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function tr(r,e,t){let[i,n]=(await Xt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=Ui(e.sourceFile.fileName),a=await er(n.text,zi(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){Wi(o,e,i.text,t)}return"undefined"}function zi(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:$(r),__filename:r}}function Wi(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(S).setSource(t,e.sourceFile.fileName);let s=new Ve(r,o);e.errors.push({text:s.message,detail:s})}function Gi(r,e){let t=null,i=n=>{if(!t){if(M.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}M.isVariableStatement(n)&&(t=qi(n,r),t)||M.forEachChild(n,i)}};return i(e),t}function qi(r,e){for(let t of r.declarationList.declarations)if(M.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(M.isArrowFunction(t.initializer)||M.isFunctionExpression(t.initializer)))return t.initializer;return null}function rr(r){return`module.exports = (${r})();`}function Ki(r){return r&M.NodeFlags.Const?"const":r&M.NodeFlags.Let?"let":"var"}function ir(r,e){return r?M.isIdentifier(r)?Xi(r,e):M.isArrowFunction(r)||M.isFunctionExpression(r)?{node:r,data:rr(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xi(r,e){let t=Gi(r.text,e.sourceFile);return t?{node:t,data:rr(t.getText(e.sourceFile))}:(Yi(r.text,e,r),{data:"",node:r})}function Yi(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=T(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function nr(r,e,t,i,n){let o=t.arguments[0],s=ir(o,n);if(!s)return!1;let a=await tr(s.data,n,s.node),c=Ki(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(n.sourceFile);return`${l}${c} ${p} = ${a};`}async function ft(r,e){let t=r[0],i=ir(t,e);return i?tr(i.data,e,i.node):!1}var Ji=/\.(ts|js)$/,re=["$$ifdef","$$ifndef","$$inline"];function pt(r,e){return re.some(t=>r.getText(e).includes(t))}function sr(r){return r===re[2]?1:2}async function Qi(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,o=`(${a.arguments.map(f=>f.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(s.arguments.length!==sr(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new Z({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:p+1,column:f}})}let l=r.modifiers?.some(p=>p.kind===h.SyntaxKind.ExportKeyword)??!1;c===re[2]?i=await nr(n,r,s,l,t):o?i=_e(s,t,n,l,o):i=Zt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return!!i}async function Zi(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!re.includes(n))return!1;if(i.arguments.length!==sr(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new Z({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==re[2]?o=await ft(i.arguments,t):o=_e(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),!!o}async function en(r,e,t){if(!h.isCallExpression(r)||!pt(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===re[2]){let s=await ft(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=_e(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function tn(r){let e=r.stage.defineMetadata.disabledMacroNames,t=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!t&&e.size===0)return r.contents;let i=[r.sourceFile],n=new Set;for(;i.length>0;){let s=i.pop(),a=s?.kind;if(!s||!a||t&&(a===h.SyntaxKind.VariableStatement&&await Qi(s,n,r)||a===h.SyntaxKind.ExpressionStatement&&pt(s,r.sourceFile)&&await Zi(s,n,r)||a===h.SyntaxKind.CallExpression&&pt(s,r.sourceFile)&&await en(s,n,r)))continue;if(e.size>0){if(a===h.SyntaxKind.CallExpression){let l=s;h.isIdentifier(l.expression)&&e.has(l.expression.text)&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===h.SyntaxKind.Identifier){let l=s;if(e.has(l.text)){let p=s.parent??s;if(p&&!h.isImportSpecifier(p)&&!h.isExportSpecifier(p)){let f=p?.getText(r.sourceFile);(!h.isCallExpression(p)||p.expression!==s)&&(!f||re.every(m=>!f.includes(m)))&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}let c=s.getChildren(r.sourceFile);for(let l=c.length-1;l>=0;l--)i.push(c[l])}if(n.size===0)return r.contents;let o=Array.from(n);o.sort((s,a)=>a.start-s.start),r.stage.replacementInfo=[];for(let{start:s,end:a,replacement:c}of o)r.stage.replacementInfo.push({source:or(r.contents.slice(s,a)),replacement:or(c)}),r.contents=r.contents.slice(0,s)+c+r.contents.slice(a);return r.contents}async function ar(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Ji.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:a},l=await tn(c);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var cr="$$",lr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function rn(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
366
+ `&&n++;let o=r.lastIndexOf(`
367
+ `,i-1)+1;return{file:t,line:n,column:r.indexOf(e,o)-o}}function nn(r,e){let t=r.lastIndexOf(`
368
+ `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function fr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(b),o=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);lr.lastIndex=0;for(let p of c.matchAll(lr)){let f=p.index;if(nn(c,f))continue;let[,m,g,B]=p;if(t.filesWithMacros.add(l),!m)continue;let W=!!o[B];g==="ifndef"===W&&t.disabledMacroNames.add(m),m.startsWith(cr)||i.push({text:`Macro function '${m}' not start with '${cr}' prefix to avoid conflicts`,location:rn(c,m,a,f)})}}return{warnings:i}}var we=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(y);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=be(a))}catch(a){if(ee(a)||a instanceof AggregateError){let c=be({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await fr(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new N("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new He(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Le(e,t,this.config.variants[e],this.argv),t.onLoad(ar.bind({},this.variants[e]),"build-service")}}};function pr(r){u(y).reload(r)}function ur(r){u(y).patch(r)}import{platform as sn,exit as an,stdin as Ue,stdout as dt}from"process";import{xterm as ze}from"@remotex-labs/xansi/xterm.component";var ut={SIGINT:"",SIGQUIT:""},I={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},dr={win32:"start",darwin:"open",linux:"xdg-open"};function cn(r=!1){let e=["\u{1F680} Shortcuts"],t=ze.dim(" press "),i=(n,o)=>{e.push(`${t}${ze.bold(n)}${ze.dim(o)}`)};return r&&(i(I.SHOW_URL," to show server url"),i(I.OPEN_BROWSER," to open in browser")),i(I.VERBOSE," to enable / disable verbose mode"),i(I.RELOAD," to reload"),i(I.CLEAR," to clear console"),i(I.QUIT,` to quit
368
369
  `),e.join(`
369
- `)}function ut(){let r=Math.max(0,ft.rows-2);r>0&&console.log(`
370
- `.repeat(r)),dt.cursorTo(ft,0,0),dt.clearScreenDown(ft)}function oo(r){let e=lr[to]??"xdg-open";eo(`${e} ${r}`)}function no(r,e,t,i,o){if(e?.name)switch((e.sequence===E.QUIT||r===pt.SIGINT||r===pt.SIGQUIT)&&(console.log(`
371
- \u{1F44B} Exiting...`),ro(1)),e.name){case E.CLEAR:ut();break;case E.VERBOSE:let n=u(b).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${n?"DISABLED":"ENABLED"}`),cr({verbose:!n});break;case E.RELOAD:ut(),t();break;case E.HELP:ut(),console.log(i);break;case E.SHOW_URL:o&&console.log(`${O()} ${Ue.canaryYellow(o)}`);break;case E.OPEN_BROWSER:o&&oo(o);break}}function pr(r,e){if(!Ve.isTTY)return;let t=io(!!e);console.log(t),Ve.setRawMode(!0),dt.emitKeypressEvents(Ve),Ve.on("keypress",(i,o)=>{no(i,o,r,t,e)})}import{existsSync as so}from"fs";import{runInThisContext as ao}from"vm";import{createRequire as co}from"module";var lo={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function mt(r){if(!r||!so(r))return{};u(y).touchFile(r);let[e,t]=(await Wt([r],{...lo,outdir:"tmp"})).outputFiles;u(S).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=co(C(r)),await ao(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}import{xterm as Y}from"@remotex-labs/xansi/xterm.component";var fr=Y.hex("#80a36b"),we=Y.hex("#dcdfe4"),ne=Y.hex("#5798cd"),D=Y.hex("#e5c07b"),Ce=Y.hex("#56b6c2"),J=Y.hex("#e06c75"),se=Y.hex("#c678dd"),ae=Y.hex("#a5a7ab");import{xterm as mr}from"@remotex-labs/xansi/xterm.component";var j=" ",gt=1024,ur=gt*1024,gr="\u2014",le="\u2192",ce="\xD7",po="\u2022";function Ie(r,e=ne.dim(le)){return`${O()} ${e} ${ne(r)}`}function fo(r){return r<gt?`${r} B`:r<ur?`${(r/gt).toFixed(2)} KB`:`${(r/ur).toFixed(2)} MB`}function hr(r){let e=r.file?T(process.cwd(),r.file):"(unknown)",t=D(String((r.line??0)+1)),i=D(String((r.column??0)+1));return`${Ce(e)}:${t}:${i}`}function uo(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
370
+ `)}function mt(){let r=Math.max(0,dt.rows-2);r>0&&console.log(`
371
+ `.repeat(r)),gt.cursorTo(dt,0,0),gt.clearScreenDown(dt)}function ln(r){let e=dr[sn]??"xdg-open";on(`${e} ${r}`)}function fn(r,e,t,i,n){if(e?.name)switch((e.sequence===I.QUIT||r===ut.SIGINT||r===ut.SIGQUIT)&&(console.log(`
372
+ \u{1F44B} Exiting...`),an(1)),e.name){case I.CLEAR:mt();break;case I.VERBOSE:let o=u(y).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${o?"DISABLED":"ENABLED"}`),ur({verbose:!o});break;case I.RELOAD:mt(),t();break;case I.HELP:mt(),console.log(i);break;case I.SHOW_URL:n&&console.log(`${F()} ${ze.canaryYellow(n)}`);break;case I.OPEN_BROWSER:n&&ln(n);break}}function mr(r,e){if(!Ue.isTTY)return;let t=cn(!!e);console.log(t),Ue.setRawMode(!0),gt.emitKeypressEvents(Ue),Ue.on("keypress",(i,n)=>{fn(i,n,r,t,e)})}import{existsSync as pn}from"fs";import{runInThisContext as un}from"vm";import{createRequire as dn}from"module";var mn={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function ht(r){if(!r||!pn(r))return{};u(b).touchFile(r);let[e,t]=(await Kt([r],{...mn,outdir:"tmp"})).outputFiles;u(S).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=dn(w(r)),await un(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}import{xterm as Y}from"@remotex-labs/xansi/xterm.component";var gr=Y.hex("#80a36b"),Ie=Y.hex("#dcdfe4"),se=Y.hex("#5798cd"),j=Y.hex("#e5c07b"),Ee=Y.hex("#56b6c2"),J=Y.hex("#e06c75"),ae=Y.hex("#c678dd"),ce=Y.hex("#a5a7ab");import{xterm as vt}from"@remotex-labs/xansi/xterm.component";var L=" ",yt=1024,hr=yt*1024,yr="\u2014",pe="\u2192",le="\xD7",gn="\u2022";function fe(r,e=se.dim(pe)){return`${F()} ${e} ${se(r)}`}function hn(r){return r<yt?`${r} B`:r<hr?`${(r/yt).toFixed(2)} KB`:`${(r/hr).toFixed(2)} MB`}function xr(r){let e=r.file?T(process.cwd(),r.file):"(unknown)",t=j(String((r.line??0)+1)),i=j(String((r.column??0)+1));return`${Ee(e)}:${t}:${i}`}function vn(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
372
373
  `),i=e.metadata.stacks.join(`
373
- `);r.push("");for(let o of t)r.push(`${j}${o}`);r.push(""),r.push(`${j}Enhanced Stack Trace:`),r.push(` ${i}`)}function mo(r){if(!r.metadata?.formatCode)return;let e=r.metadata.formatCode.split(`
374
- `).map(i=>`${j}${i}`).join(`
374
+ `);r.push("");for(let n of t)r.push(`${L}${n}`);r.push(""),r.push(`${L}Enhanced Stack Trace:`),r.push(` ${i}`)}function yn(r){if(!r.metadata?.formatCode)return;let e=r.metadata.formatCode.split(`
375
+ `).map(i=>`${L}${i}`).join(`
375
376
  `),t=r.metadata.stacks.join(`
376
377
  `);console.log(`
377
378
  ${e}
378
379
 
379
- ${j}Enhanced Stack Trace:
380
- ${t}`)}function go(r,e,t){let i=hr(r),o=t(`TS${r.code}`),n=ae(r.message);return`${j}${e} ${i} ${we(le)} ${o} ${we(gr)} ${n}`}function vr(r,e,t=J){let i=hr(r),o=t(`TS${r.code}`),n=ae(r.message);console.log(`${j}${e} ${i}`,we(le),`${o} ${we(gr)} ${n}`)}function ho(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`
381
- ${j}${D(t)} ${D("TypesError")}: ${ae(e.message||"Type checking warning")}`),1;for(let o of e.diagnostics)r.push(go(o,D(t),mr.deepOrange));return i}function vo(r,e,t,i){r.push(`
382
- ${j}${i(t)} ${e}`),e instanceof g&&uo(r,e)}function yo(r,e,t,i){return e instanceof V?ho(r,e,t):(vo(r,e,t,i),1)}function dr(r,e){if(r.length===0)return;let t=e==="Errors",i=t?ce:po,o=t?J:D,n=0,s=[""];for(let a of r)n+=yo(s,a,i,o);s.push(""),s[0]=`
383
- ${o(e)} (${n})`,console.log(s.join(`
384
- `))}function xo(r){let e=Object.entries(r.outputs),t=e.length,i=[];i.push(`
385
- ${fr("Outputs")} (${t})`);for(let[o,n]of e){let s=D.dim(fo(n.bytes));i.push(`${j}${ne(le)} ${Ce(o)}: ${s}`)}i.push(""),console.log(i.join(`
386
- `))}function Ee(r){if(r instanceof AggregateError)for(let e of r.errors)Ee(e);else if(r instanceof V)for(let e of r.diagnostics)vr(e,J(ce));else r instanceof g?(console.log(`
387
- ${j}${J(ce)} ${r}`),mo(r)):r instanceof Error?Ee(new U(r)):Ee(new U(new Error(String(r))))}function bo(r,e){let t=e.length>0,i=t?D(r):se(r),o=t?J(ce):ne.dim(le),n=Ie("completed",o);if(console.log(`${n} ${i}`),t){console.log("");for(let s of e)vr(s,J(ce));console.log("")}}function yr(r){for(let[e,t]of Object.entries(r))bo(e,t)}function xr({variantName:r}){console.log(`${Ie("build")} ${se(r)}`)}function br({variantName:r,duration:e,buildResult:t}){let{errors:i,warnings:o,metafile:n}=ye(t),s=!!n,a=s?se(r):D(r),l=s?ne.dim(le):J(ce),c=Ie("completed",l),f=mr.dim(`in ${e} ms`);console.log(`${c} ${a} ${f}`),dr(i,"Errors"),dr(o,"Warnings"),s&&xo(n)}var Co=["!node_modules/**","!dist/**","!bundle/**","!**/*.d.ts"],Eo=["dist","dist/**",".git/**",".idea/**","node_modules/**"];function Io(r,e){if(!e.entryPoints)return;let t=[...e.entryPoints,...Co];e.outdir&&t.push(`!${e.outdir}/**`,`!${e.outdir}`),r.common?.esbuild?.outdir&&t.push(`!${r.common.esbuild.outdir}/**`,`!${r.common.esbuild.outdir}`),r.variants={argv:{esbuild:{entryPoints:Ae(wo(),t)}}}}function To(r,e){e.verbose!==void 0&&(r.verbose=e.verbose);let t=Object.values(r.variants??{});for(let i of t)e.types!==void 0&&(i.types=e.types),e.outdir!==void 0&&(i.esbuild.outdir=e.outdir),e.bundle!==void 0&&(i.esbuild.minify=e.bundle),e.minify!==void 0&&(i.esbuild.minify=e.minify),e.tsconfig!==void 0&&(i.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(i.esbuild.platform=e.platform),e.declaration!==void 0&&(i.declaration=e.declaration),e.failOnError!==void 0&&(i.types={failOnError:e.failOnError})}function Oo(r){let e=[...Eo];r.common?.esbuild?.outdir&&e.push(r.common.esbuild.outdir,`${r.common.esbuild.outdir}/**`);let t=Object.values(r.variants??{});for(let i of t)i.esbuild.outdir&&e.push(i.esbuild.outdir,`${i.esbuild.outdir}/**`);return e}async function ko(r,e){if(!((e.serve??!1)!==!1||r.serve?.start))return;let i,o=r.serve?.dir||e.serve||"dist",n={...r.serve,onStart({host:a,port:l,url:c}){i=c,console.log(`${Ie("serve")} ${se(o)} ${Ce(c)}
388
- `),r.serve?.onStart?.({host:a,port:l,url:c})}};return await new xe(n,o).start(),i}async function ze(r,e){try{let t=v(process.cwd(),"dist");if(So(t,{recursive:!0,force:!0}),e.typeCheck){let i=await r.typeChack();yr(i)}else await r.build(e.build)}catch(t){Ee(t)}}async function Fo(r,e,t,i){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let n=Oo(e),s=new be(n);pr(async()=>{await ze(r,t)},i),await ze(r,t),await s.start(async a=>{if(r.touchFiles(a),a.includes(t.config)){let l=await mt(t.config);r.reload(l)}console.log(`
389
- ${O()} ${ae("Rebuilding")}: files (${a.length})
390
- `),await ze(r,t)})}async function Po(){console.log(Fe());let r=u(Q),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await mt(e.config),i=r.enhancedParse(process.argv,t.userArgv),o=r.parseUserArgv(process.argv,t.userArgv);Io(t,i),To(t,i),ar(t);let n=new Se(o);n.onEnd=br,n.onStart=xr;let s=await ko(t,i);await Fo(n,t,i,s),await ze(n,i)}Po();
380
+ ${L}Enhanced Stack Trace:
381
+ ${t}`)}function xn(r,e,t){let i=xr(r),n=t(`TS${r.code}`),o=ce(r.message);return`${L}${e} ${i} ${Ie(pe)} ${n} ${Ie(yr)} ${o}`}function br(r,e,t=J){let i=xr(r),n=t(`TS${r.code}`),o=ce(r.message);console.log(`${L}${e} ${i}`,Ie(pe),`${n} ${Ie(yr)} ${o}`)}function bn(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`
382
+ ${L}${j(t)} ${j("TypesError")}: ${ce(e.message||"Type checking warning")}`),1;for(let n of e.diagnostics)r.push(xn(n,j(t),vt.deepOrange));return i}function Sn(r,e,t,i){r.push(`
383
+ ${L}${i(t)} ${e}`),e instanceof v&&vn(r,e)}function Cn(r,e,t,i){return e instanceof U?bn(r,e,t):(Sn(r,e,t,i),1)}function vr(r,e){if(r.length===0)return;let t=e==="Errors",i=t?le:gn,n=t?J:j,o=0,s=[""];for(let a of r)o+=Cn(s,a,i,n);s.push(""),s[0]=`
384
+ ${n(e)} (${o})
385
+ `,console.log(s.join(`
386
+ `))}function wn(r){let e=Object.entries(r.outputs),t=e.length,i=[];i.push(`
387
+ ${gr("Outputs")} (${t})`);for(let[n,o]of e){let s=j.dim(hn(o.bytes));i.push(`${L}${se(pe)} ${Ee(n)}: ${s}`)}i.push(""),console.log(i.join(`
388
+ `))}function Te(r){if(r instanceof AggregateError)for(let e of r.errors)Te(e);else if(r instanceof U)for(let e of r.diagnostics)br(e,J(le));else r instanceof v?(console.log(`
389
+ ${L}${J(le)} ${r}`),yn(r)):r instanceof Error?Te(new z(r)):Te(new z(new Error(String(r))))}function In(r,e){let t=e.length>0,i=t?j(r):ae(r),n=t?J(le):se.dim(pe),o=fe("completed",n);if(console.log(`${o} ${i}`),t){console.log("");for(let s of e)br(s,J(le));console.log("")}}function Sr(r){for(let[e,t]of Object.entries(r))In(e,t)}function Cr({variantName:r}){console.log(`${fe("build")} ${ae(r)}`)}function wr({variantName:r,duration:e,buildResult:t,stage:i}){let{errors:n,warnings:o,metafile:s}=be(t),a=!!s,c=a?ae(r):j(r),l=a?se.dim(pe):J(le),p=fe("completed",l),f=vt.dim(`in ${e} ms`);console.log(`${p} ${c} ${f}`),vr(n,"Errors"),vr(o,"Warnings"),u(y).getValue().verbose&&i?.replacementInfo&&Array.isArray(i.replacementInfo)&&i.replacementInfo.forEach(({source:g,replacement:B})=>{console.log(fe("Macro replacement:")+`
390
+ `),console.log(`${vt.dim(g)}
391
+
392
+ ${B}
393
+ `)}),a&&wn(s)}var Fn=["!node_modules/**","!dist/**","!bundle/**","!**/*.d.ts"],On=["dist","dist/**",".git/**",".idea/**","node_modules/**"];function kn(r,e){if(!e.entryPoints)return;let t=[...e.entryPoints,...Fn];e.outdir&&t.push(`!${e.outdir}/**`,`!${e.outdir}`),r.common?.esbuild?.outdir&&t.push(`!${r.common.esbuild.outdir}/**`,`!${r.common.esbuild.outdir}`),r.variants={argv:{esbuild:{entryPoints:Re(Tn(),t)}}}}function Pn(r,e){e.verbose!==void 0&&(r.verbose=e.verbose);let t=Object.values(r.variants??{});for(let i of t)e.types!==void 0&&(i.types=e.types),e.outdir!==void 0&&(i.esbuild.outdir=e.outdir),e.bundle!==void 0&&(i.esbuild.minify=e.bundle),e.minify!==void 0&&(i.esbuild.minify=e.minify),e.tsconfig!==void 0&&(i.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(i.esbuild.platform=e.platform),e.declaration!==void 0&&(i.declaration=e.declaration),e.failOnError!==void 0&&(i.types={failOnError:e.failOnError})}function An(r){let e=[...On];r.common?.esbuild?.outdir&&e.push(r.common.esbuild.outdir,`${r.common.esbuild.outdir}/**`);let t=Object.values(r.variants??{});for(let i of t)i.esbuild.outdir&&e.push(i.esbuild.outdir,`${i.esbuild.outdir}/**`);return e}async function Rn(r,e){if(!((e.serve??!1)!==!1||r.serve?.start))return;let i,n=r.serve?.dir||e.serve||"dist",o={...r.serve,onStart({host:a,port:c,url:l}){i=l,console.log(`${fe("serve")} ${ae(n)} ${Ee(l)}
394
+ `),r.serve?.onStart?.({host:a,port:c,url:l})}};return await new Se(o,n).start(),i}async function We(r,e){try{let t=x(process.cwd(),"dist");if(En(t,{recursive:!0,force:!0}),e.typeCheck){let i=await r.typeChack();Sr(i)}else await r.build(e.build)}catch(t){Te(t)}}async function $n(r,e,t,i){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let o=An(e),s=new Ce(o);mr(async()=>{await We(r,t)},i),await We(r,t),await s.start(async a=>{if(r.touchFiles(a),a.includes(t.config)){let c=await ht(t.config);r.reload(c)}console.log(`
395
+ ${F()} ${ce("Rebuilding")}: files (${a.length})
396
+ `),await We(r,t)})}async function Mn(){console.log(Pe());let r=u(Q),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await ht(e.config),i=r.enhancedParse(process.argv,t.userArgv),n=r.parseUserArgv(process.argv,t.userArgv);kn(t,i),Pn(t,i),pr(t);let o=new we(n);o.onEnd=wr,o.onStart=Cr;let s=await Rn(t,i);await $n(o,t,i,s),await We(o,i)}Mn();
391
397
  //# sourceMappingURL=bash.js.map