@remotex-labs/xbuild 3.0.1 → 3.0.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,7 +1,7 @@
1
- var rt=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var or=(i,e,t)=>e in i?rt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var b=(i,e,t,r)=>{for(var n=r>1?void 0:r?nr(e,t):e,o=i.length-1,s;o>=0;o--)(s=i[o])&&(n=(r?s(e,t,n):s(n))||n);return r&&n&&rt(e,t,n),n};var ce=(i,e,t)=>or(i,typeof e!="symbol"?e+"":e,t);import{rmSync as mn}from"fs";import le from"node:process";import{inject as Re}from"@remotex-labs/xinject";import{readFileSync as sr,statSync as ar}from"fs";import{resolve as cr}from"@remotex-labs/xmap";import{Injectable as lr}from"@remotex-labs/xinject";var h=class{resolved=new Map;cache=new Map;clear(){this.cache.clear(),this.resolved.clear()}getSnapshot(e){return this.cache.get(this.resolve(e))}touch(e,t){let r=this.resolve(e);return this.cache.get(r)??this.sync(r,this.stat(r),t)}refresh(e,t,r){let n=this.resolve(e);return this.sync(n,t??this.stat(n),r)}refreshAll(e){let t=e??this.cache.keys();for(let r of t)this.refresh(r)}resolve(e){let t=this.resolved.get(e);return t===void 0&&this.resolved.set(e,t=cr(e)),t}sync(e,t,r="utf-8"){let n=this.cache.get(e);return t?.isFile()?n?.mtimeMs===t.mtimeMs?n:this.store(e,{mtimeMs:t.mtimeMs,version:(n?.version??0)+1,snapshot:this.snapshot(sr(e,r))}):n&&!n.snapshot?n:this.store(e,{mtimeMs:0,snapshot:void 0,version:(n?.version??0)+1})}changeRange(e,t){let r=e.length,n=t.length,o=Math.min(r,n),s=0;for(;s<o&&e.charCodeAt(s)===t.charCodeAt(s);)s++;let a=0;for(;a<o-s&&e.charCodeAt(r-1-a)===t.charCodeAt(n-1-a);)a++;return{span:{start:s,length:r-s-a},newLength:n-s-a}}snapshot(e){return{text:e,getText:(t,r)=>e.slice(t,r),getLength:()=>e.length,getChangeRange:t=>this.changeRange(t.getText(0,t.getLength()),e)}}store(e,t){return this.cache.set(e,t),t}stat(e){return ar(e,{throwIfNoEntry:!1})}};h=b([lr({scope:"singleton"})],h);import{resolveError as hr}from"@remotex-labs/xmap";import{xterm as De}from"@remotex-labs/xansi/xterm.component";import{cwd as fr}from"process";import{readFileSync as pr}from"fs";import{inject as ur,Injectable as dr}from"@remotex-labs/xinject";import{normalize as Le,SourceService as mr}from"@remotex-labs/xmap";var it=/xbuild(?!\.config)/i,gr=/"mappings"\s*:\s*""/,u=class{frameworkFile;frameworkRoot;projectRoot;sourceMaps=new Map;constructor(){this.projectRoot=Le(fr()),this.frameworkFile=Le(import.meta.filename),this.frameworkRoot=Le(import.meta.dirname),this.loadSourceMap(this.frameworkFile)}static resolve(e){return(u.files??=ur(h)).resolve(e)}isFrameworkFile(e){return it.test(e.source??"")||it.test(e.sourceRoot??"")}getSourceMap(e){return this.sourceMaps.get(u.resolve(e))}addSourceMap(e,t,r=!1){let n=u.resolve(e);!r&&this.sourceMaps.has(n)||this.register(n,t)}loadSourceMap(e){if(!e)return;let t=u.resolve(e);if(this.sourceMaps.has(t))return;let r;try{r=pr(`${t}.map`,"utf-8")}catch(n){throw u.failure(t,n)}this.register(t,r)}static failure(e,t){return new Error(`Failed to load source map for: ${e}
2
- ${t instanceof Error?t.message:String(t)}`)}register(e,t){if(!gr.test(t))try{this.sourceMaps.set(e,new mr(t,e))}catch(r){throw u.failure(e,r)}}};ce(u,"files"),u=b([dr({scope:"singleton"})],u);import{parseErrorStack as nt}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as yr}from"@remotex-labs/xmap/formatter.component";import{highlightCode as vr}from"@remotex-labs/xmap/highlighter.component";function br(i=""){let t=Re(u).getSourceMap(i);if(t)return t;let r=Re(h).touch(i),n=r.snapshot?.text;if(!r||!n)return null;let o=n.split(`
1
+ var rt=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var or=(i,e,t)=>e in i?rt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var b=(i,e,t,r)=>{for(var n=r>1?void 0:r?nr(e,t):e,o=i.length-1,s;o>=0;o--)(s=i[o])&&(n=(r?s(e,t,n):s(n))||n);return r&&n&&rt(e,t,n),n};var ce=(i,e,t)=>or(i,typeof e!="symbol"?e+"":e,t);import{rmSync as gn}from"fs";import le from"node:process";import{inject as Le}from"@remotex-labs/xinject";import{readFileSync as sr,statSync as ar}from"fs";import{resolve as cr}from"@remotex-labs/xmap";import{Injectable as lr}from"@remotex-labs/xinject";var h=class{resolved=new Map;cache=new Map;clear(){this.cache.clear(),this.resolved.clear()}getSnapshot(e){return this.cache.get(this.resolve(e))}touch(e,t){let r=this.resolve(e);return this.cache.get(r)??this.sync(r,this.stat(r),t)}refresh(e,t,r){let n=this.resolve(e);return this.sync(n,t??this.stat(n),r)}refreshAll(e){let t=e??this.cache.keys();for(let r of t)this.refresh(r)}resolve(e){let t=this.resolved.get(e);return t===void 0&&this.resolved.set(e,t=cr(e)),t}sync(e,t,r="utf-8"){let n=this.cache.get(e);return t?.isFile()?n?.mtimeMs===t.mtimeMs?n:this.store(e,{mtimeMs:t.mtimeMs,version:(n?.version??0)+1,snapshot:this.snapshot(sr(e,r))}):n&&!n.snapshot?n:this.store(e,{mtimeMs:0,snapshot:void 0,version:(n?.version??0)+1})}changeRange(e,t){let r=e.length,n=t.length,o=Math.min(r,n),s=0;for(;s<o&&e.charCodeAt(s)===t.charCodeAt(s);)s++;let a=0;for(;a<o-s&&e.charCodeAt(r-1-a)===t.charCodeAt(n-1-a);)a++;return{span:{start:s,length:r-s-a},newLength:n-s-a}}snapshot(e){return{text:e,getText:(t,r)=>e.slice(t,r),getLength:()=>e.length,getChangeRange:t=>this.changeRange(t.getText(0,t.getLength()),e)}}store(e,t){return this.cache.set(e,t),t}stat(e){return ar(e,{throwIfNoEntry:!1})}};h=b([lr({scope:"singleton"})],h);import{resolveError as hr}from"@remotex-labs/xmap";import{xterm as De}from"@remotex-labs/xansi/xterm.component";import{cwd as fr}from"process";import{readFileSync as pr}from"fs";import{inject as ur,Injectable as dr}from"@remotex-labs/xinject";import{normalize as Re,SourceService as mr}from"@remotex-labs/xmap";var it=/xbuild(?!\.config)/i,gr=/"mappings"\s*:\s*""/,u=class{frameworkFile;frameworkRoot;projectRoot;sourceMaps=new Map;constructor(){this.projectRoot=Re(fr()),this.frameworkFile=Re(import.meta.filename),this.frameworkRoot=Re(import.meta.dirname),this.loadSourceMap(this.frameworkFile)}static resolve(e){return(u.files??=ur(h)).resolve(e)}isFrameworkFile(e){return it.test(e.source??"")||it.test(e.sourceRoot??"")}getSourceMap(e){return this.sourceMaps.get(u.resolve(e))}addSourceMap(e,t,r=!1){let n=u.resolve(e);!r&&this.sourceMaps.has(n)||this.register(n,t)}loadSourceMap(e){if(!e)return;let t=u.resolve(e);if(this.sourceMaps.has(t))return;let r;try{r=pr(`${t}.map`,"utf-8")}catch(n){throw u.failure(t,n)}this.register(t,r)}static failure(e,t){return new Error(`Failed to load source map for: ${e}
2
+ ${t instanceof Error?t.message:String(t)}`)}register(e,t){if(!gr.test(t))try{this.sourceMaps.set(e,new mr(t,e))}catch(r){throw u.failure(e,r)}}};ce(u,"files"),u=b([dr({scope:"singleton"})],u);import{parseErrorStack as nt}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as yr}from"@remotex-labs/xmap/formatter.component";import{highlightCode as vr}from"@remotex-labs/xmap/highlighter.component";function br(i=""){let t=Le(u).getSourceMap(i);if(t)return t;let r=Le(h).touch(i),n=r.snapshot?.text;if(!r||!n)return null;let o=n.split(`
3
3
  `);return{getPositionWithCode:(s,a,c,l)=>{let f=l?.linesAfter??3,p=l?.linesBefore??3,S=Math.max(s-p,1),d=Math.min(s+f,o.length);return{line:s,name:null,code:o.slice(S-1,d).join(`
4
- `),source:i,column:a,endLine:d,startLine:S,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function xr(i){return i instanceof Error?nt(i):i.detail instanceof Error?nt(i.detail):i.location?{name:"esBuildMessage",message:i.text??"",rawStack:"",stack:[{source:`@${i.location.file}`,line:i.location.line,column:i.location.column||1,fileName:i.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:i.text??"",rawStack:""}}function B(i,e,t=!1){let r=Re(u),n=xr(i),o=hr(n,{...e,withNativeFrames:t||(e?.withFrameworkFrames??!1),getSource(s){return br(s)}});return o.stack.filter(s=>{if(!(e?.withFrameworkFrames??!1)&&r.isFrameworkFile(s))return!1;!o.formatCode&&s.code&&(o.formatCode=yr({code:vr(s.code),line:s.line??1,column:s.column??1,startLine:s.stratLine??1},{color:De.brightPink}))}),o}function Q(i,e,t,r=[]){let n=[`
4
+ `),source:i,column:a,endLine:d,startLine:S,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function xr(i){return i instanceof Error?nt(i):i.detail instanceof Error?nt(i.detail):i.location?{name:"esBuildMessage",message:i.text??"",rawStack:"",stack:[{source:`@${i.location.file}`,line:i.location.line,column:i.location.column||1,fileName:i.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:i.text??"",rawStack:""}}function B(i,e,t=!1){let r=Le(u),n=xr(i),o=hr(n,{...e,withNativeFrames:t||(e?.withFrameworkFrames??!1),getSource(s){return br(s)}});return o.stack.filter(s=>{if(!(e?.withFrameworkFrames??!1)&&r.isFrameworkFile(s))return!1;!o.formatCode&&s.code&&(o.formatCode=yr({code:vr(s.code),line:s.line??1,column:s.column??1,startLine:s.stratLine??1},{color:De.brightPink}))}),o}function Q(i,e,t,r=[]){let n=[`
5
5
  ${e}: ${De.lightCoral(t)}`];for(let o of r??[])o.text&&n.push(`
6
6
  `+De.gray(o.text));return i.formatCode&&n.push(`
7
7
 
@@ -10,7 +10,7 @@ ${i.formatCode}`),i.stack.length&&n.push(`
10
10
  Enhanced Stack Trace:
11
11
  ${i.stack.map(o=>o.format).join(`
12
12
  `)}
13
- `),n.join("")}var F=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=B(e,t),this.formattedStack=Q(this.errorMetadata,e.name,e.message)}};function ot(i){if(i instanceof AggregateError){console.error("AggregateError:",i.message);for(let e of i.errors)if(e instanceof Error&&!(e instanceof F)){let t=B(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(Q(t,e.name,e.message))}else console.error(e);return}if(i instanceof Error&&!(i instanceof F)){let e=B(i,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(Q(e,i.name,i.message))}else console.error(i)}le.on("uncaughtException",i=>{ot(i),le.exit(2)});le.on("unhandledRejection",i=>{ot(i),le.exit(3)});import{exit as Ii}from"process";import{exec as Fr}from"child_process";import*as dt from"node:readline";import{resolve as kr}from"path";import{stdout as ue}from"process";import{xterm as Pe}from"@remotex-labs/xansi/xterm.component";var Sr=`
13
+ `),n.join("")}var F=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=B(e,t),this.formattedStack=Q(this.errorMetadata,e.name,e.message)}};function ot(i){if(i instanceof AggregateError){console.error("AggregateError:",i.message);for(let e of i.errors)if(e instanceof Error&&!(e instanceof F)){let t=B(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(Q(t,e.name,e.message))}else console.error(e);return}if(i instanceof Error&&!(i instanceof F)){let e=B(i,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(Q(e,i.name,i.message))}else console.error(i)}le.on("uncaughtException",i=>{ot(i),le.exit(2)});le.on("unhandledRejection",i=>{ot(i),le.exit(3)});import{exit as ki}from"process";import{exec as Nr}from"child_process";import*as dt from"node:readline";import{resolve as kr}from"path";import{stdout as ue}from"process";import{xterm as Pe}from"@remotex-labs/xansi/xterm.component";var Sr=`
14
14
  ______ _ _ _
15
15
  | ___ \\ (_) | | |
16
16
  __ _| |_/ /_ _ _| | __| |
@@ -19,30 +19,30 @@ __ _| |_/ /_ _ _| | __| |
19
19
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
20
20
  `;function st(){return`
21
21
  \r${Pe.burntOrange(Sr)}
22
- \rVersion: ${Pe.brightPink("3.0.1")}
23
- \r`}function at(){return Pe.lightCoral("[xBuild]")}import{relative as Cr}from"@remotex-labs/xmap";import{inject as $r}from"@remotex-labs/xinject";import{stripAnsi as Er}from"@remotex-labs/xansi";import{cursorTo as Tr,clearScreenDown as Mr}from"readline";import{xterm as Lr}from"@remotex-labs/xansi/xterm.component";import{xterm as R}from"@remotex-labs/xansi/xterm.component";var fe=R.hex("#a6da95"),Jn=R.hex("#cad3f5"),w=R.hex("#91d7e3"),T=R.hex("#eed49f"),N=R.hex("#f5a97f"),pe=R.hex("#ed8796"),D=R.hex("#c6a0f6"),m=R.hex("#939ab7");var q={verbose:0,info:1,warning:2,error:3,silent:4};function M(i,e=w.dim("\u2192")){return`${at()} ${e} ${w(i)}`}function ft(i){return Er(i).length}function X(i,e){return i+" ".repeat(Math.max(0,e-ft(i)))}function Rr(i){if(i.includes("://"))return i;let e=i.startsWith(".")?kr($r(u).frameworkRoot,i):u.resolve(i);return Cr(process.cwd(),e)}function Dr(i,e=0,t=0){if(!i)return"";let r=m.dim(":");return`${N(Rr(i))}${r}${T(String(e))}${r}${T(String(t))}`}function Pr(i,e){let t=`${process.cwd()}/`,r=[];return i.formatCode&&r.push("",...i.formatCode.split(`
24
- `).map(n=>`${e}${Lr.dim(n)}`)),i.stack.length>1&&r.push("",...i.stack.map(n=>`${e}${m.dim(n.format.replaceAll(t,""))}`)),r.length>0?[...r,""]:r}function Ar(i,e){let t=i.id?.startsWith("TS")??!1,r=t&&!e?void 0:B(i,{linesAfter:1,linesBefore:1,withFrameworkFrames:!0}),n=t?void 0:r?.stack[0],o=n??i.location;return{id:i.id??"",detail:e&&r?Pr(r," ".repeat(2)):[],location:Dr(n?.fileName??i.location?.file,o?.line,o?.column)}}function te(i,e,t,r,n=!1){if(i.length<1)return;let o=0,s=0,a=[];for(let l of i){let f=Ar(l,n);o=Math.max(o,ft(f.location)),s=Math.max(s,f.id.length),a.push(f)}let c=[`
22
+ \rVersion: ${Pe.brightPink("3.0.2")}
23
+ \r`}function at(){return Pe.lightCoral("[xBuild]")}import{inject as Cr}from"@remotex-labs/xinject";import{stripAnsi as $r}from"@remotex-labs/xansi";import{cursorTo as Er,clearScreenDown as Tr}from"readline";import{dirname as Mr,relative as Rr}from"@remotex-labs/xmap";import{xterm as Lr}from"@remotex-labs/xansi/xterm.component";import{xterm as L}from"@remotex-labs/xansi/xterm.component";var fe=L.hex("#a6da95"),Qn=L.hex("#cad3f5"),w=L.hex("#91d7e3"),T=L.hex("#eed49f"),N=L.hex("#f5a97f"),pe=L.hex("#ed8796"),D=L.hex("#c6a0f6"),m=L.hex("#939ab7");var q={verbose:0,info:1,warning:2,error:3,silent:4};function M(i,e=w.dim("\u2192")){return`${at()} ${e} ${w(i)}`}function ft(i){return $r(i).length}function X(i,e){return i+" ".repeat(Math.max(0,e-ft(i)))}function Dr(i){if(i.includes("://"))return i;let e=Cr(u).frameworkRoot;if(i.includes(Mr(e)))return i;let t=i.startsWith(".")?kr(e,i):u.resolve(i);return Rr(process.cwd(),t)}function Pr(i,e=0,t=0){if(!i)return"";let r=m.dim(":");return`${N(Dr(i))}${r}${T(String(e))}${r}${T(String(t))}`}function Ar(i,e){let t=`${process.cwd()}/`,r=[];return i.formatCode&&r.push("",...i.formatCode.split(`
24
+ `).map(n=>`${e}${Lr.dim(n)}`)),i.stack.length>1&&r.push("",...i.stack.map(n=>`${e}${m.dim(n.format.replaceAll(t,""))}`)),r.length>0?[...r,""]:r}function Or(i,e){let t=i.id?.startsWith("TS")??!1,r=t&&!e?void 0:B(i,{linesAfter:1,linesBefore:1,withFrameworkFrames:!0}),n=t?void 0:r?.stack[0],o=n??i.location;return{id:i.id??"",detail:e&&r?Ar(r," ".repeat(2)):[],location:Pr(n?.fileName??i.location?.file,o?.line,o?.column)}}function te(i,e,t,r,n=!1){if(i.length<1)return;let o=0,s=0,a=[];for(let l of i){let f=Or(l,n);o=Math.max(o,ft(f.location)),s=Math.max(s,f.id.length),a.push(f)}let c=[`
25
25
  ${t(e)} ${m.dim(`(${a.length})`)}`];for(let[l,{id:f,location:p,detail:S}]of a.entries()){let d=s>0?`${X(t(f),s)} `:"";c.push(`${" "}${t(r)} ${X(p,o)} ${d}${m(i[l].text??"")}`),c.push(...S)}console.log(c.join(`
26
26
  `))}function me(){let i=Math.max(0,ue.rows-2);i>0&&console.log(`
27
- `.repeat(i)),Tr(ue,0,0),Mr(ue)}function de(){return ue.columns||100}function Ae(i){return i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(2)} KB`:`${(i/1048576).toFixed(2)} MB`}function pt(i,e=6){let t=Object.entries(i.outputs).sort(([,f],[,p])=>p.bytes-f.bytes);if(t.length<1)return;let r=t.slice(0,e),n=r.map(([,{bytes:f}])=>Ae(f)),o=Math.max(...n.map(f=>f.length)),s=t.reduce((f,[,{bytes:p}])=>f+p,0),a=de()-" ".length-o-4,c=` ${fe("Outputs")} ${m.dim(`(${t.length})`)}`,l=[`
27
+ `.repeat(i)),Er(ue,0,0),Tr(ue)}function de(){return ue.columns||100}function Ae(i){return i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(2)} KB`:`${(i/1048576).toFixed(2)} MB`}function pt(i,e=6){let t=Object.entries(i.outputs).sort(([,f],[,p])=>p.bytes-f.bytes);if(t.length<1)return;let r=t.slice(0,e),n=r.map(([,{bytes:f}])=>Ae(f)),o=Math.max(...n.map(f=>f.length)),s=t.reduce((f,[,{bytes:p}])=>f+p,0),a=de()-" ".length-o-4,c=` ${fe("Outputs")} ${m.dim(`(${t.length})`)}`,l=[`
28
28
  ${X(c,de()-o-1)}${T.dim(Ae(s))}`];for(let[f,[p]]of r.entries())l.push(`${" "}${w.dim("\u2192")} ${X(N(p),a+1)}`+T.dim(n[f].padStart(o)));if(t.length>e){let f=t.slice(e).reduce((S,[,{bytes:d}])=>S+d,0),p=m.dim(`${"\xB7"} ${t.length-e} more`);l.push(`${" "} ${X(p,a+1)}${T.dim(Ae(f).padStart(o))}`)}console.log(l.join(`
29
- `))}import{platform as Nr,stdin as H,stdout as k,exit as Vr}from"process";import{xterm as Hr}from"@remotex-labs/xansi/xterm.component";import{ANSI as L,moveCursor as Oe,writeRaw as P}from"@remotex-labs/xansi";import{ShadowRenderer as _r}from"@remotex-labs/xansi/shadow.service";var Ur={darwin:"open",win32:"start"},Wr=[{key:"h",describe:"show this menu",server:!1},{key:"b",describe:"run the build",server:!1},{key:"r",describe:"reload and rebuild",server:!1},{key:"v",describe:"toggle verbose",server:!1},{key:"c",describe:"clear the screen",server:!1},{key:"o",describe:"open it in a browser",server:!0},{key:"q",describe:"quit",server:!1}],I,mt="",z,re;function qr(){return new Promise(i=>{let e=t=>{let r=/\[(\d+);\d+R/.exec(t.toString());r&&(H.off("data",e),i(Number(r[1])))};H.on("data",e),P("\x1B[6n"),setTimeout(()=>(H.off("data",e),i(k.rows)),100).unref()})}function zr(i){Fr(`${Ur[Nr]??"xdg-open"} ${i}`)}function Kr(){let i=[`
30
- \u{1F680} ${D("Shortcuts")}`];for(let{key:e,describe:t,server:r}of Wr)(!r||I?.url)&&i.push(`${" "}${m.dim("press")} ${Hr.bold(e)} ${m.dim(`to ${t}`)}`);return`${i.join(`
29
+ `))}import{platform as Vr,stdin as H,stdout as k,exit as Hr}from"process";import{xterm as _r}from"@remotex-labs/xansi/xterm.component";import{ANSI as R,moveCursor as Oe,writeRaw as P}from"@remotex-labs/xansi";import{ShadowRenderer as Ur}from"@remotex-labs/xansi/shadow.service";var Wr={darwin:"open",win32:"start"},qr=[{key:"h",describe:"show this menu",server:!1},{key:"b",describe:"run the build",server:!1},{key:"r",describe:"reload and rebuild",server:!1},{key:"v",describe:"toggle verbose",server:!1},{key:"c",describe:"clear the screen",server:!1},{key:"o",describe:"open it in a browser",server:!0},{key:"q",describe:"quit",server:!1}],I,mt="",z,re;function zr(){return new Promise(i=>{let e=t=>{let r=/\[(\d+);\d+R/.exec(t.toString());r&&(H.off("data",e),i(Number(r[1])))};H.on("data",e),P("\x1B[6n"),setTimeout(()=>(H.off("data",e),i(k.rows)),100).unref()})}function Kr(i){Nr(`${Wr[Vr]??"xdg-open"} ${i}`)}function Gr(){let i=[`
30
+ \u{1F680} ${D("Shortcuts")}`];for(let{key:e,describe:t,server:r}of qr)(!r||I?.url)&&i.push(`${" "}${m.dim("press")} ${_r.bold(e)} ${m.dim(`to ${t}`)}`);return`${i.join(`
31
31
  `)}
32
- `}function ie(i=!1){if(!z)return;let e=[mt||`${w.dim("\u21BB")} ${m("watching")}`];I?.url&&e.push(N(I.url)),I?.logLevel==="verbose"&&e.push(D("verbose")),e.push(m.dim("press h for shortcuts")),P(L.SAVE_CURSOR),z.writeText(0,0,` ${e.join(m.dim(` ${"\xB7"} `))}`,!0),z.render(i),P(L.RESTORE_CURSOR)}function gt(i){mt=i,ie()}async function ht(i){if(!H.isTTY||!k.isTTY||re)return;I=i,H.setRawMode(!0),P(L.HIDE_CURSOR);let e=await qr();e>=k.rows&&P(`
33
- `),ut(Math.min(e,k.rows-1)),dt.emitKeypressEvents(H),H.on("keypress",(t,r)=>Gr(r)),k.on("resize",()=>ut()),re=setInterval(()=>ie(!0),300).unref(),process.on("exit",yt)}function yt(){re&&(clearInterval(re),re=void 0,z=void 0,P(`\x1B[r${Oe(k.rows,1)}${L.CLEAR_LINE}${L.SHOW_CURSOR}`))}function ut(i){if(k.rows<4)return z=void 0,P(`\x1B[r${L.CLEAR_LINE}`);let e=k.rows-1,t=i===void 0?L.RESTORE_CURSOR:Oe(i,1);z=new _r(1,de(),e,1),P(`${L.SAVE_CURSOR}\x1B[1;${e}r${Oe(k.rows,1)}${L.CLEAR_LINE}${t}`),ie(!0)}async function Gr(i){switch(i.ctrl&&(i.name==="c"||i.name==="d")&&(i.name="q"),i.name){case"q":yt(),k.write(`${m("Stopped.")}
34
- `,()=>Vr(process.exitCode?Number(process.exitCode):0));return;case"c":return me(),ie(!0);case"h":return console.log(Kr());case"v":return I?.toggleVerbose(),ie(!0);case"o":I?.url&&zr(I.url);return;case"b":return I?.rebuild("rebuilding");case"r":return I?.rebuild("reloading",!0)}}import{Injectable as ki,inject as Ci}from"@remotex-labs/xinject";import{Injectable as Qr}from"@remotex-labs/xinject";import{BehaviorSubject as Xr}from"@remotex-labs/xobservable";function je(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}function vt(i){if(!je(i))return!1;let e=Object.getPrototypeOf(i);return e===null||Object.getPrototypeOf(e)===null}function C(i,...e){if(!e.length)return i;let t=e.shift();if(je(i)&&je(t)){for(let r in t){let n=t[r],o=i[r];Array.isArray(n)&&Array.isArray(o)?Object.assign(i,{[r]:[...o,...n]}):vt(n)?Object.assign(i,{[r]:C(vt(o)?o:{},n)}):Object.assign(i,{[r]:n})}return C(i,...e)}return i}function he(i,e,t=!0){return i===e||Object.is(i,e)?!0:i===null||e===null?!1:i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.source===e.source&&i.flags===e.flags:URL&&i instanceof URL&&e instanceof URL?i.href===e.href:typeof i=="object"&&typeof e=="object"?Jr(i,e,t):!1}function Yr(i,e){return i==null||typeof i!="object"&&typeof i!="function"?!1:e in i||Object.prototype.hasOwnProperty.call(i,e)}function Jr(i,e,t=!0){if(Array.isArray(i)&&Array.isArray(e))return t&&i.length!==e.length?!1:i.every((o,s)=>he(o,e[s],t));let r=Object.keys(i),n=Object.keys(e);if(t&&r.length!==n.length)return!1;for(let o of r)if(!Yr(e,o)||!he(i[o],e[o],t))return!1;return!0}function ye(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString()+"n":t)}import{map as Zr,distinctUntilChanged as ei}from"@remotex-labs/xobservable";var bt=Object.freeze({common:Object.freeze({types:!0,logOverride:{},declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd(),legalComments:"none"})})});var $=class{constructor(e=bt){this.initialConfig=e;this.config$=new Xr(C({},e))}initialConfig;config$;getValue(e){return e?e(this.config$.value):this.config$.value}subscribe(e){return this.config$.subscribe(e)}select(e){return this.config$.pipe(Zr(e),ei((t,r)=>he(t,r)))}patch(e){let t=C({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(C({},this.initialConfig,e))}};$=b([Qr({scope:"singleton"})],$);import v from"typescript";import{Injectable as yi}from"@remotex-labs/xinject";import{normalize as vi,relative as bi,dirname as xi}from"@remotex-labs/xmap";import{existsSync as ti}from"fs";import{parseSync as ri}from"oxc-parser";import{inject as ii}from"@remotex-labs/xinject";import{mkdir as ni,writeFile as oi}from"fs/promises";import{join as Fe,dirname as Ne,relative as si}from"@remotex-labs/xmap";function A(i,e,t){let r=i.end;for(;r<e.length;){let n=e.charCodeAt(r);if(n!==32&&n!==9)break;r++}e.charCodeAt(r)===13&&r++,e.charCodeAt(r)===10&&r++,t.push({start:i.start,end:r})}function K(i,e){if(e.length<1)return i;e.sort((o,s)=>o.start-s.start);let t=new Array(e.length*2+1),r=0,n=0;for(let o=0;o<e.length;o++){let s=e[o];s.start<n||(t[r++]=i.slice(n,s.start),t[r++]=s.text??"",n=s.end)}return t[r++]=i.slice(n),t.length=r,t.join("")}function xt(i,e,t,r){if(!i)return;let n=r.resolve(i.value,e);if(!n||n.isExternalLibraryImport)return;let{extension:o,relativeFileName:s}=n,a=o?s.slice(0,-o.length):s;t.push({end:i.end,start:i.start,text:`'${a}.js'`})}function St(i,e,t="",r){if(!t)return t;let n=[];for(let o of i.program.body)switch(o.type){case"ImportDeclaration":case"ExportAllDeclaration":case"ExportNamedDeclaration":xt(o.source,e,n,r);break;case"TSImportEqualsDeclaration":o.moduleReference.type==="TSExternalModuleReference"&&xt(o.moduleReference.expression,e,n,r)}return K(t,n)}var wt=`/**
32
+ `}function ie(i=!1){if(!z)return;let e=[mt||`${w.dim("\u21BB")} ${m("watching")}`];I?.url&&e.push(N(I.url)),I?.logLevel==="verbose"&&e.push(D("verbose")),e.push(m.dim("press h for shortcuts")),P(R.SAVE_CURSOR),z.writeText(0,0,` ${e.join(m.dim(` ${"\xB7"} `))}`,!0),z.render(i),P(R.RESTORE_CURSOR)}function gt(i){mt=i,ie()}async function ht(i){if(!H.isTTY||!k.isTTY||re)return;I=i,H.setRawMode(!0),P(R.HIDE_CURSOR);let e=await zr();e>=k.rows&&P(`
33
+ `),ut(Math.min(e,k.rows-1)),dt.emitKeypressEvents(H),H.on("keypress",(t,r)=>Yr(r)),k.on("resize",()=>ut()),re=setInterval(()=>ie(!0),300).unref(),process.on("exit",yt)}function yt(){re&&(clearInterval(re),re=void 0,z=void 0,P(`\x1B[r${Oe(k.rows,1)}${R.CLEAR_LINE}${R.SHOW_CURSOR}`))}function ut(i){if(k.rows<4)return z=void 0,P(`\x1B[r${R.CLEAR_LINE}`);let e=k.rows-1,t=i===void 0?R.RESTORE_CURSOR:Oe(i,1);z=new Ur(1,de(),e,1),P(`${R.SAVE_CURSOR}\x1B[1;${e}r${Oe(k.rows,1)}${R.CLEAR_LINE}${t}`),ie(!0)}async function Yr(i){switch(i.ctrl&&(i.name==="c"||i.name==="d")&&(i.name="q"),i.name){case"q":yt(),k.write(`${m("Stopped.")}
34
+ `,()=>Hr(process.exitCode?Number(process.exitCode):0));return;case"c":return me(),ie(!0);case"h":return console.log(Gr());case"v":return I?.toggleVerbose(),ie(!0);case"o":I?.url&&Kr(I.url);return;case"b":return I?.rebuild("rebuilding");case"r":return I?.rebuild("reloading",!0)}}import{Injectable as Ci,inject as $i}from"@remotex-labs/xinject";import{Injectable as Xr}from"@remotex-labs/xinject";import{BehaviorSubject as Zr}from"@remotex-labs/xobservable";function je(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}function vt(i){if(!je(i))return!1;let e=Object.getPrototypeOf(i);return e===null||Object.getPrototypeOf(e)===null}function C(i,...e){if(!e.length)return i;let t=e.shift();if(je(i)&&je(t)){for(let r in t){let n=t[r],o=i[r];Array.isArray(n)&&Array.isArray(o)?Object.assign(i,{[r]:[...o,...n]}):vt(n)?Object.assign(i,{[r]:C(vt(o)?o:{},n)}):Object.assign(i,{[r]:n})}return C(i,...e)}return i}function he(i,e,t=!0){return i===e||Object.is(i,e)?!0:i===null||e===null?!1:i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.source===e.source&&i.flags===e.flags:URL&&i instanceof URL&&e instanceof URL?i.href===e.href:typeof i=="object"&&typeof e=="object"?Qr(i,e,t):!1}function Jr(i,e){return i==null||typeof i!="object"&&typeof i!="function"?!1:e in i||Object.prototype.hasOwnProperty.call(i,e)}function Qr(i,e,t=!0){if(Array.isArray(i)&&Array.isArray(e))return t&&i.length!==e.length?!1:i.every((o,s)=>he(o,e[s],t));let r=Object.keys(i),n=Object.keys(e);if(t&&r.length!==n.length)return!1;for(let o of r)if(!Jr(e,o)||!he(i[o],e[o],t))return!1;return!0}function ye(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString()+"n":t)}import{map as ei,distinctUntilChanged as ti}from"@remotex-labs/xobservable";var bt=Object.freeze({common:Object.freeze({types:!0,logOverride:{},declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd(),legalComments:"none"})})});var $=class{constructor(e=bt){this.initialConfig=e;this.config$=new Zr(C({},e))}initialConfig;config$;getValue(e){return e?e(this.config$.value):this.config$.value}subscribe(e){return this.config$.subscribe(e)}select(e){return this.config$.pipe(ei(e),ti((t,r)=>he(t,r)))}patch(e){let t=C({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(C({},this.initialConfig,e))}};$=b([Xr({scope:"singleton"})],$);import v from"typescript";import{Injectable as vi}from"@remotex-labs/xinject";import{normalize as bi,relative as xi,dirname as Si}from"@remotex-labs/xmap";import{existsSync as ri}from"fs";import{parseSync as ii}from"oxc-parser";import{inject as ni}from"@remotex-labs/xinject";import{mkdir as oi,writeFile as si}from"fs/promises";import{join as Fe,dirname as Ne,relative as ai}from"@remotex-labs/xmap";function A(i,e,t){let r=i.end;for(;r<e.length;){let n=e.charCodeAt(r);if(n!==32&&n!==9)break;r++}e.charCodeAt(r)===13&&r++,e.charCodeAt(r)===10&&r++,t.push({start:i.start,end:r})}function K(i,e){if(e.length<1)return i;e.sort((o,s)=>o.start-s.start);let t=new Array(e.length*2+1),r=0,n=0;for(let o=0;o<e.length;o++){let s=e[o];s.start<n||(t[r++]=i.slice(n,s.start),t[r++]=s.text??"",n=s.end)}return t[r++]=i.slice(n),t.length=r,t.join("")}function xt(i,e,t,r){if(!i)return;let n=r.resolve(i.value,e);if(!n||n.isExternalLibraryImport)return;let{extension:o,relativeFileName:s}=n,a=o?s.slice(0,-o.length):s;t.push({end:i.end,start:i.start,text:`'${a}.js'`})}function St(i,e,t="",r){if(!t)return t;let n=[];for(let o of i.program.body)switch(o.type){case"ImportDeclaration":case"ExportAllDeclaration":case"ExportNamedDeclaration":xt(o.source,e,n,r);break;case"TSImportEqualsDeclaration":o.moduleReference.type==="TSExternalModuleReference"&&xt(o.moduleReference.expression,e,n,r)}return K(t,n)}var wt=`/**
35
35
  * This file was automatically generated by xBuild.
36
36
  * DO NOT EDIT MANUALLY.
37
37
  */
38
- `;var ve=class{constructor(e){this.ts=e}ts;cache=new Map;filesCache=ii(h);emitted=new Map;clear(){this.cache.clear(),this.emitted.clear()}touch(e){let t=this.filesCache.resolve(e),r=this.filesCache.touch(t),n=this.cache.get(t);if(n?.version===r.version)return n;let o=this.build(t,r.version);return this.cache.set(t,o),o}async emit(e,t){let r=[],n=[],o=new Set,s=new Map;for(let[c,l]of Object.entries(e))s.set(this.filesCache.resolve(l),c);let a=[...s.keys()];for(;a.length>0;){let c=a.pop();if(o.has(c)||c.endsWith(".d.ts"))continue;o.add(c);let l=this.touch(c);for(let p of l.projectDependencies)o.has(p)||a.push(p);let f=this.outputPath(c,t,s.get(c));this.emitted.get(f)===l.version&&ti(f)||(this.emitted.set(f,l.version),r.push(f),n.push(l.declaration))}return this.write(r,n)}async emitBundle(e,t){let r=this.ts.config.options,n=this.filesCache.resolve(t??r.declarationDir??r.outDir??".");return this.write(Object.keys(e).map(o=>Fe(n,`${o}.d.ts`)),Object.values(e).map(o=>this.bundle(o)))}bundle(e){let t=this.filesCache.resolve(e),r=this.touch(t);return this.render(this.collectClosure(t,r),this.collectSurface(t,r))}async write(e,t){if(e.length<1)return e;let r=new Set(e.map(n=>Ne(n)));return await Promise.all([...r].map(n=>ni(n,{recursive:!0}))),await Promise.all(e.map((n,o)=>oi(n,t[o],"utf-8"))),e}outputPath(e,t,r){let{declarationDir:n,outDir:o,rootDir:s}=this.ts.config.options,a=t??n??o,c=a?this.filesCache.resolve(a):Ne(e);if(r)return Fe(c,`${r}.d.ts`);let l=s?this.filesCache.resolve(s):Ne(e);return Fe(c,si(l,e).replace(/\.([cm]?)tsx?$/,".d.$1ts"))}collectClosure(e,t){let r=new Set([e]),n=[],o=[...t.projectDependencies];for(;o.length>0;){let s=o.pop();if(r.has(s))continue;r.add(s);let a=this.touch(s);n.push(a);for(let c of a.projectDependencies)r.has(c)||o.push(c)}return n.push(t),n}collectSurface(e,t){let r=new Set,n=new Set,o=new Set([e]),s=[t];for(;s.length>0;){let a=s.pop();for(let c of a.projectExports.exports)r.add(this.clause(c));for(let[c,l]of Object.entries(a.packageExports)){l.star&&n.add(`export * from '${c}';`),l.named?.length&&n.add(`export { ${l.named.map(f=>this.clause(f)).join(", ")} } from '${c}';`);for(let f of l.namespaces??[])n.add(`export * as ${f} from '${c}';`)}for(let c of a.projectExports.star)o.has(c)||(o.add(c),s.push(this.touch(c)))}return{exports:r,statements:n}}mergeImports(e){let t=new Map;for(let r of e)for(let[n,o]of Object.entries(r.packageImports)){let s=t.get(n);s||t.set(n,s={side:!1,named:new Set,namespaces:new Set}),o.side&&(s.side=!0),s.default??=o.default;for(let a of o.namespaces??[])s.namespaces.add(a);for(let a of o.named??[])s.named.add(this.clause(a))}return t}renderImports(e){let t=[];for(let[r,n]of e){n.side&&t.push(`import '${r}';`);for(let s of n.namespaces)t.push(`import * as ${s} from '${r}';`);let o=[];n.default&&o.push(n.default),n.named.size>0&&o.push(`{ ${[...n.named].sort().join(", ")} }`),o.length>0&&t.push(`import ${o.join(", ")} from '${r}';`)}return t}render(e,t){let r=[wt],n=this.renderImports(this.mergeImports(e));n.length>0&&r.push(...n,"");for(let o of e){let s=o.content.trim();s&&r.push(s,"")}return t.exports.size>0&&r.push(`export {
38
+ `;var ve=class{constructor(e){this.ts=e}ts;cache=new Map;filesCache=ni(h);emitted=new Map;clear(){this.cache.clear(),this.emitted.clear()}touch(e){let t=this.filesCache.resolve(e),r=this.filesCache.touch(t),n=this.cache.get(t);if(n?.version===r.version)return n;let o=this.build(t,r.version);return this.cache.set(t,o),o}async emit(e,t){let r=[],n=[],o=new Set,s=new Map;for(let[c,l]of Object.entries(e))s.set(this.filesCache.resolve(l),c);let a=[...s.keys()];for(;a.length>0;){let c=a.pop();if(o.has(c)||c.endsWith(".d.ts"))continue;o.add(c);let l=this.touch(c);for(let p of l.projectDependencies)o.has(p)||a.push(p);let f=this.outputPath(c,t,s.get(c));this.emitted.get(f)===l.version&&ri(f)||(this.emitted.set(f,l.version),r.push(f),n.push(l.declaration))}return this.write(r,n)}async emitBundle(e,t){let r=this.ts.config.options,n=this.filesCache.resolve(t??r.declarationDir??r.outDir??".");return this.write(Object.keys(e).map(o=>Fe(n,`${o}.d.ts`)),Object.values(e).map(o=>this.bundle(o)))}bundle(e){let t=this.filesCache.resolve(e),r=this.touch(t);return this.render(this.collectClosure(t,r),this.collectSurface(t,r))}async write(e,t){if(e.length<1)return e;let r=new Set(e.map(n=>Ne(n)));return await Promise.all([...r].map(n=>oi(n,{recursive:!0}))),await Promise.all(e.map((n,o)=>si(n,t[o],"utf-8"))),e}outputPath(e,t,r){let{declarationDir:n,outDir:o,rootDir:s}=this.ts.config.options,a=t??n??o,c=a?this.filesCache.resolve(a):Ne(e);if(r)return Fe(c,`${r}.d.ts`);let l=s?this.filesCache.resolve(s):Ne(e);return Fe(c,ai(l,e).replace(/\.([cm]?)tsx?$/,".d.$1ts"))}collectClosure(e,t){let r=new Set([e]),n=[],o=[...t.projectDependencies];for(;o.length>0;){let s=o.pop();if(r.has(s))continue;r.add(s);let a=this.touch(s);n.push(a);for(let c of a.projectDependencies)r.has(c)||o.push(c)}return n.push(t),n}collectSurface(e,t){let r=new Set,n=new Set,o=new Set([e]),s=[t];for(;s.length>0;){let a=s.pop();for(let c of a.projectExports.exports)r.add(this.clause(c));for(let[c,l]of Object.entries(a.packageExports)){l.star&&n.add(`export * from '${c}';`),l.named?.length&&n.add(`export { ${l.named.map(f=>this.clause(f)).join(", ")} } from '${c}';`);for(let f of l.namespaces??[])n.add(`export * as ${f} from '${c}';`)}for(let c of a.projectExports.star)o.has(c)||(o.add(c),s.push(this.touch(c)))}return{exports:r,statements:n}}mergeImports(e){let t=new Map;for(let r of e)for(let[n,o]of Object.entries(r.packageImports)){let s=t.get(n);s||t.set(n,s={side:!1,named:new Set,namespaces:new Set}),o.side&&(s.side=!0),s.default??=o.default;for(let a of o.namespaces??[])s.namespaces.add(a);for(let a of o.named??[])s.named.add(this.clause(a))}return t}renderImports(e){let t=[];for(let[r,n]of e){n.side&&t.push(`import '${r}';`);for(let s of n.namespaces)t.push(`import * as ${s} from '${r}';`);let o=[];n.default&&o.push(n.default),n.named.size>0&&o.push(`{ ${[...n.named].sort().join(", ")} }`),o.length>0&&t.push(`import ${o.join(", ")} from '${r}';`)}return t}render(e,t){let r=[wt],n=this.renderImports(this.mergeImports(e));n.length>0&&r.push(...n,"");for(let o of e){let s=o.content.trim();s&&r.push(s,"")}return t.exports.size>0&&r.push(`export {
39
39
  ${[...t.exports].sort().join(`,
40
40
  `)}
41
41
  };`),r.push(...t.statements),t.exports.size<1&&t.statements.size<1&&r.push("export {};"),`${r.join(`
42
42
  `)}
43
- `}clause(e){return e.alias?`${e.name} as ${e.alias}`:e.name}emitDeclaration(e){let t=this.ts.languageService;return!t.getProgram()?.getSourceFile(e)&&(this.ts.touchFiles([e]),!t.getProgram()?.getSourceFile(e))?"":t.getEmitOutput(e,!0,!0).outputFiles.find(r=>r.name.endsWith(".d.ts"))?.text??""}build(e,t){let r=this.emitDeclaration(e),n={edits:[],target:e,parsed:ri(e,r,{sourceType:"module"}),content:r,bundleEdits:[],packageImports:Object.create(null),packageExports:Object.create(null),projectExports:{star:new Set,exports:[],namespace:Object.create(null)},projectDependencies:new Set},o=[],{body:s}=n.parsed.program;for(let a of s)this.strip(a,n)&&o.push(a.start);return this.pruneComments(n,s,o),{version:t,content:K(r,n.bundleEdits),declaration:K(r,n.edits),packageImports:n.packageImports,packageExports:n.packageExports,projectExports:n.projectExports,projectDependencies:n.projectDependencies}}strip(e,t){switch(e.type){case"ImportDeclaration":return this.stripImport(e,t),!1;case"ExportAllDeclaration":return this.stripStarExport(e,t),!1;case"ExportNamedDeclaration":return this.stripNamedExport(e,t);case"ExportDefaultDeclaration":return this.stripDefaultExport(e,t);case"TSImportEqualsDeclaration":return this.stripImportEquals(e,t);case"TSExportAssignment":case"TSNamespaceExportDeclaration":return A(e,t.content,t.bundleEdits),!1;default:return!0}}stripImport(e,t){if(A(e,t.content,t.bundleEdits),this.link(e.source,t))return;let r=t.packageImports[e.source.value]??={};if(e.specifiers.length<1){r.side=!0;return}for(let n of e.specifiers)switch(n.type){case"ImportDefaultSpecifier":r.default??=n.local.name;break;case"ImportNamespaceSpecifier":(r.namespaces??=[]).push(n.local.name);break;default:(r.named??=[]).push(this.binding(this.nameOf(n.imported),n.local.name))}}stripImportEquals(e,t){let{moduleReference:r}=e;if(r.type!=="TSExternalModuleReference")return!0;A(e,t.content,t.bundleEdits);let n=r.expression;return this.link(n,t)||((t.packageImports[n.value]??={}).namespaces??=[]).push(e.id.name),!1}stripNamedExport(e,t){let{exports:r}=t.projectExports;if(e.declaration)return this.collectDeclared(e.declaration,r),t.bundleEdits.push({start:e.start,end:e.declaration.start}),!0;A(e,t.content,t.bundleEdits);let n=e.source&&!this.link(e.source,t)?(t.packageExports[e.source.value]??={}).named??=[]:r;for(let o of e.specifiers)n.push(this.binding(this.nameOf(o.local),this.nameOf(o.exported)));return!1}stripStarExport(e,t){A(e,t.content,t.bundleEdits);let r=this.link(e.source,t),n=e.exported?this.nameOf(e.exported):null;if(r){n?t.projectExports.namespace[n]=r:t.projectExports.star.add(r);return}let o=t.packageExports[e.source.value]??={};n?(o.namespaces??=[]).push(n):o.star=!0}stripDefaultExport(e,t){let{declaration:r}=e,n=this.defaultBinding(r);return n&&t.projectExports.exports.push({name:n,alias:"default"}),n&&r.type!=="Identifier"?(t.bundleEdits.push({start:e.start,end:r.start,text:"declare "}),!0):(A(e,t.content,t.bundleEdits),!1)}pruneComments(e,t,r){let{content:n,bundleEdits:o}=e,s=0,a=0;for(let c of e.parsed.comments)if(!(c.type!=="Block"||c.value.charCodeAt(0)!==42)){for(;s<t.length&&t[s].end<=c.start;)s++;if(!(s<t.length&&t[s].start<c.start)){for(;a<r.length&&r[a]<c.end;)a++;a<r.length&&this.blank(n,c.end,r[a])||A(c,n,o)}}}link(e,t){let r=this.ts.resolve(e.value,t.target);if(!r||r.isExternalLibraryImport)return null;let{extension:n,relativeFileName:o,resolvedFileName:s}=r,a=this.filesCache.resolve(s);return t.projectDependencies.add(a),t.edits.push({end:e.end,start:e.start,text:`'${n?o.slice(0,-n.length):o}.d.ts'`}),a}collectDeclared(e,t){if(e.type==="VariableDeclaration"){for(let r of e.declarations)r.id.type==="Identifier"&&t.push({name:r.id.name});return}"id"in e&&e.id&&"name"in e.id&&t.push({name:e.id.name})}defaultBinding(e){return e.type==="Identifier"?e.name:"id"in e?e.id?.name:void 0}nameOf(e){return"name"in e?e.name:JSON.stringify(e.value)}binding(e,t){return e===t?{name:e}:{name:e,alias:t}}blank(e,t,r){for(let n=t;n<r;n++){let o=e.charCodeAt(n);if(o!==32&&o!==9&&o!==10&&o!==13)return!1}return!0}};import G from"typescript";import{relative as gi}from"@remotex-labs/xmap";import{inject as hi}from"@remotex-labs/xinject";import{readdirSync as ai}from"fs";import{join as ci}from"@remotex-labs/xmap";var Ve={64:")",43:")+",42:")*",63:")?"};function He(i){return".+^$()|\\{}[]*?".includes(i)?"\\"+i:i}function g(i,e){return i.charCodeAt(e)}function li(i,e){return(e===0||g(i,e-1)===47)&&(e+2===i.length||g(i,e+2)===47)}function ne(i){return`(?:${i})`}function _e(i,e){let t=e+1,r=g(i,t);for((r===33||r===94)&&t++,g(i,t)===93&&t++;t<i.length&&g(i,t)!==93;)t+=g(i,t)===92?2:1;return t}function fi(i,e){for(let t=e,r=0;t<i.length;t++){let n=g(i,t);if(n===92)t++;else if(n===40)r++;else{if(n===41&&--r===0)return t;n===91&&(t=_e(i,t))}}return-1}function pi(i,e){let t=!1;for(let r=e+1,n=0;r<i.length;r++){let o=g(i,r);if(o===92)r++;else if(o===123)n++;else if(o===125){if(n===0)return t?r:-1;n--}else o===44&&n===0?t=!0:o===91&&(r=_e(i,r))}return-1}function ui(i,e){let t=_e(i,e);if(t>=i.length)return["\\[",e+1];let r=e+1,n="[",o=g(i,r);for((o===33||o===94)&&(n+="^/",r++),g(i,r)===93&&(n+="\\]",r++);r<t;r++)g(i,r)===92?n+="\\"+i[++r]:g(i,r)===94?n+="\\^":n+=i[r];return[n+"]",t+1]}function di(i,e){for(let t=e;t<i.length;t++){if(g(i,t)===47)return t;g(i,t)===92&&t++}return i.length}function oe(i,e=!1,t=0,r={}){let{dot:n=!1}=r,o="",s=0,a=e,c=n?"":"(?!\\.)",l=c+"[^/]"+"+",f=ne(l+"(?:/"+l+")*")+"?";for(;s<i.length;){let p=g(i,s),S=g(i,s+1);if(S===40&&(p===33||Ve[p])){let d=fi(i,s+1);if(p!==33){let W=d===-1?i.length:d,ae=oe(i.slice(s+2,W),a,124,r);o+="(?:"+ae+Ve[p],s=W+1;continue}if(d!==-1){let W=oe(i.slice(s+2,d),a,124,r),ae=di(i,d+1),tt=oe(i.slice(d+1,ae),!1,0,r);o+=ne((a?c:"")+`(?!${ne(W)+tt+"(?:$|/)"})`+"[^/]*?"+tt),s=ae;continue}}switch(p){case 47:o+="/",s++,a=!0;break;case 92:o+=s+1<i.length?He(i[s+1]):"\\\\",s+=2;break;case 63:o+=a&&!n?"[^./]":"[^/]",s++;break;case 42:if(S===42&&t!==124&&(s>0||e)&&li(i,s)){let d=s===0&&t===0?"(?:[A-Za-z]:)?/?":"";g(i,s+2)===47?(o+=d+ne(l+"/")+"*",s+=3,a=!0):(o+=d+f,s+=2)}else o+=(a?c:"")+"[^/]*",s++;break;case 123:{let d=pi(i,s);d===-1?(o+="\\{",s++):(o+=ne(oe(i.slice(s+1,d),a,44,r)),s=d+1);break}case 91:{let[d,W]=ui(i,s);o+=(a&&!n&&d!=="\\["?"(?!\\.)":"")+d,s=W;break}case 124:case 44:t===p?(o+="|",a=e):o+=He(i[s]),s++;break;default:o+=He(i[s]),s++}}return o}function mi(i,e={}){return new RegExp("^"+oe(i,!0,0,e)+"$",e.flags)}function se(i,e={}){let t=[],r=[];for(let n of i){let o=!1;for(;g(n,0)===33&&g(n,1)!==40;)o=!o,n=n.slice(1);(o?r:t).push(mi(n,e))}return n=>(t.length===0||t.some(o=>o.test(n)))&&!r.some(o=>o.test(n))}function It(i,e,t={}){let r=u.resolve(i),n=se(e,t),o=t.dot||e.some(c=>g(c,0)===46||c.includes("/.")),s=[],a=[""];for(;a.length>0;){let c=a.pop(),l;try{l=ai(c?ci(r,c):r,{withFileTypes:!0})}catch{continue}for(let f of l){if(!o&&g(f.name,0)===46)continue;let p=c?`${c}/${f.name}`:f.name;f.isDirectory()?a.push(p):n(p)&&s.push(p)}}return s}var be=class{constructor(e){this.config=e;this.reload()}config;filesCache=hi(h);trackedFiles=new Set;exclusions=new Map;matches;get tracked(){return this.trackedFiles}get ignoreSourceFile(){return e=>this.isExcluded(e.fileName)}set options(e){this.config=e,this.reload()}clearTracked(){this.trackedFiles.clear(),this.refreshFiles(this.config.fileNames)}reload(){this.matches=this.compileExclude(this.config.raw?.exclude),this.exclusions.clear(),this.clearTracked()}refresh(e){return this.filesCache.refresh(this.track(e))}refreshFiles(e=this.trackedFiles){for(let t of e)this.isExcluded(t)||this.refresh(t)}getCompilationSettings(){return this.config.options}fileExists(e){return G.sys.fileExists(e)}readFile(e,t){return this.filesCache.touch(e,t).snapshot?.text}readDirectory(e,t,r,n,o){return G.sys.readDirectory(e,t,r,n,o)}getDirectories(e){return G.sys.getDirectories(e)}directoryExists(e){return G.sys.directoryExists(e)}getCurrentDirectory(){return G.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackedFiles]}getDefaultLibFileName(e){return G.getDefaultLibFilePath(e)}getScriptVersion(e){return this.filesCache.touch(this.track(e)).version.toString()}getScriptSnapshot(e){return this.filesCache.touch(e).snapshot}realpath(e){return this.filesCache.resolve(e)}compileExclude(e){return e&&e.length>0?se(e):()=>!1}isExcluded(e){let t=this.filesCache.resolve(e),r=this.exclusions.get(t);return r===void 0&&this.exclusions.set(t,r=this.matches(gi(process.cwd(),t))),r}track(e){let t=this.filesCache.resolve(e);return this.trackedFiles.add(t),t}};var y=class{constructor(e="tsconfig.json"){this.configPath=e;this.parsedConfig=this.parseConfig(),this.languageHostService=new be(this.parsedConfig),this.configVersion=this.languageHostService.filesCache.touch(this.configPath).version,this.resolutionCache=this.createResolutionCache(),this.languageService=v.createLanguageService(this.languageHostService,v.createDocumentRegistry(!0)),this.declaration=new ve(this)}configPath;languageService;languageHostService;diagnosticsCache=new Map;builderHost={createHash:v.sys.createHash,readFile:(e,t)=>this.languageHostService.readFile(e,t),getCurrentDirectory:()=>v.sys.getCurrentDirectory(),useCaseSensitiveFileNames:()=>v.sys.useCaseSensitiveFileNames};declaration;parsedConfig;configVersion;resolutionCache;builder;static reload(e=!1){let t=[];for(let[r,n]of y.cache)n.instance.refresh(e)&&t.push(r);return t}get config(){return this.parsedConfig}check(e){let t=this.languageService.getProgram();if(!t)return[];let r=this.languageHostService.ignoreSourceFile,n=s=>s.fileName.includes("node_modules")?!0:r(s),o;for(this.builder=v.createEmitAndSemanticDiagnosticsBuilderProgram(t,this.builderHost,this.builder);o=this.builder.getSemanticDiagnosticsOfNextAffectedFile(void 0,n);)if("fileName"in o.affected){let s=o.affected;this.diagnosticsCache.set(s.fileName,[...o.result,...this.builder.getSyntacticDiagnostics(s),...this.languageService.getSuggestionDiagnostics(s.fileName)].map(a=>this.formatDiagnostic(a)))}return this.reconcileDiagnostics(t,e??this.diagnosticsCache.keys())}async emit(e,t){return t??=this.config.options.outDir??"dist",this.declaration.emit(e,t)}async emitBundle(e,t){return t??=this.config.options.outDir??"dist",this.declaration.emitBundle(e,t)}touchFiles(e){this.languageHostService.refreshFiles(e)}resolve(e,t){let r=t?this.languageHostService.filesCache.resolve(xi(t)):process.cwd(),o=this.resolutionCache.getOrCreateCacheForDirectory(r).get(e,void 0)?.resolvedModule;if(o)return o;let s=v.resolveModuleName(e,t??"",this.parsedConfig.options,this.languageHostService,this.resolutionCache).resolvedModule;if(s){let a=bi(r,s.resolvedFileName);s.container=r,s.relativeFileName=a.startsWith(".")?a:`./${a}`}return s}dispose(){let e=y.cache.get(this.configPath);e&&(e.refCount--,!(e.refCount>0)&&(this.languageService.dispose(),y.cache.delete(this.configPath)))}[Symbol.dispose??Symbol.for("Symbol.dispose")](){this.dispose()}static acquire(e="tsconfig.json"){let t=vi(e),r=y.cache.get(t);if(r)return r.refCount++,r.instance;let n=new y(t);return y.cache.set(t,{instance:n,refCount:1}),n}refresh(e=!1){let{version:t}=this.languageHostService.filesCache.touch(this.configPath);return!e&&t===this.configVersion?!1:(this.configVersion=t,this.parsedConfig=this.parseConfig(),this.languageHostService.options=this.parsedConfig,this.resolutionCache=this.createResolutionCache(),this.declaration.clear(),this.diagnosticsCache.clear(),this.builder=void 0,!0)}createResolutionCache(){return v.createModuleResolutionCache(v.sys.getCurrentDirectory(),e=>this.languageHostService.realpath(e),this.parsedConfig.options)}reconcileDiagnostics(e,t){let r=this.languageHostService.filesCache,n=[];for(let o of t){let s=r.resolve(o),a=this.diagnosticsCache.get(s);a&&(e.getSourceFile(s)?n.push(...a):this.diagnosticsCache.delete(s))}return n}formatDiagnostic(e){let t={message:v.flattenDiagnosticMessageText(e.messageText,`
44
- `),category:e.category};if(e.file&&e.start!==void 0){let{line:r,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=r+1,t.column=n+1,t.code=e.code}return t}parseConfig(){let e=v.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...v.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:v.ScriptTarget.ESNext,module:v.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:v.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,noEmit:!0,rootDir:e.options?.rootDir??process.cwd(),isolatedModules:!1,useCaseSensitiveFileNames:!0},e}};ce(y,"cache",new Map),y=b([yi({factory(i){return y.acquire(i)}})],y);var Y=class{constructor(e){this.build=e;this.restoreLevel=this.logLevel!=="verbose"?this.logLevel:"info"}build;config$=Ci($);serverUrl;restoreLevel;set logLevel(e){this.config$.patch({logLevel:e})}get logLevel(){return this.config$.getValue().logLevel??"info"}get url(){return this.serverUrl??""}set url(e){this.serverUrl=e}buildEvent(e){if(e.type==="start")return this.say(`${w.dim("\u2192")} ${m("building")} ${D(e.context.variantName)}`,`${M("build")} ${D(e.context.variantName)}`);let{errors:t,warnings:r,info:n,verbose:o,metafile:s}=e.buildResult,a=!s;a?process.exitCode=1:process.exitCode=0,this.groups({error:t,warning:r,info:n,verbose:o}),s&&pt(s,this.logLevel==="verbose"?1/0:void 0);let c=a?pe("\xD7"):fe("\u2713"),l=a?T(e.context.variantName):D(e.context.variantName);this.say(`${c} ${l} ${m.dim(`in ${e.duration} ms`)}`,`
45
- ${M("build",c)} ${l} ${m.dim(`in ${e.duration} ms`)}`)}serverEvent(e){switch(e.type){case"start":return this.url=e.url,console.log(`${M("serve")} ${N(e.url)}`);case"stop":this.serverUrl=void 0,e.running&&console.log(`${M("serve")} ${m("stopped")}`);return;case"request":this.logLevel==="verbose"&&console.log(`${M("serve")} ${m.dim(e.url)}`);return;case"error":if(e.url?.includes("favicon"))return;console.log(`${M("serve",pe("\xD7"))} ${m(e.error.message)}`)}}diagnostics(e){let t=!1;for(let[r,n]of Object.entries(e)){let o=n.error.length+n.warning.length+n.info.length+n.verbose.length;t||=n.error.length>0,console.log(`${M("type-check")} ${D(r)} ${m.dim(`${o} to look at`)}`),this.groups(n),console.log("")}Ii(t?1:0)}async rebuild(e,t=!1){me(),y.reload(t),this.say(`${w.dim("\u21BB")} ${m(e)}`,`${M("rebuild",w.dim("\u21BB"))} ${m(e)}`),await this.build()}toggleVerbose(){return this.logLevel==="verbose"?this.logLevel=this.restoreLevel:(this.restoreLevel=this.logLevel,this.logLevel="verbose"),this.logLevel}say(e,t){console.log(t),gt(e)}groups(e){let t=q[this.logLevel],r=this.logLevel==="verbose";q.error>=t&&te(e.error,"Errors",pe,"\xD7",!0),q.warning>=t&&te(e.warning,"Warnings",T,"\u2022",r),q.info>=t&&te(e.info,"Info",w,"\u2192",r),q.verbose>=t&&te(e.verbose,"Verbose",m,"\xB7",r)}};Y=b([ki({scope:"singleton"})],Y);import Ct from"yargs";import{hideBin as Ei}from"yargs/helpers";import{Injectable as Ti}from"@remotex-labs/xinject";var $i="config.xbuild.ts",xe={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:$i},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string"},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},clean:{describe:"Clean build artifacts",type:"boolean",default:!1}},kt=[["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 O=class{parseConfigFile(e){return Ct(e).help(!1).version(!1).options({config:xe.config}).parseSync()}enhancedParse(e,t={}){let r=Ct(Ei(e)).locale("en"),n=r.showHelp;return r.showHelp=function(o){return this.group(Object.keys(xe),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},r.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(xe).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),kt.forEach(([o,s])=>{r.example(o,s)}),r.parseSync()}};O=b([Ti({scope:"singleton"})],O);import{inject as et}from"@remotex-labs/xinject";import*as Mt from"http";import*as Lt from"https";import{extname as Et}from"path";import{readFileSync as Tt}from"fs";var $t=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{join as Se}from"@remotex-labs/xmap";import{inject as Li}from"@remotex-labs/xinject";import{Subject as Ri}from"@remotex-labs/xobservable";import{readdir as Di,stat as Pi,readFile as Ai}from"fs/promises";var we=class{constructor(e,t){this.config=e;this.rootDir=u.resolve(t),this.config.port||=0,this.config.host||="localhost"}config;server;events$=new Ri;rootDir;framework=Li(u);get pipe(){return this.events$.pipe.bind(this.events$)}get subscribe(){return this.events$.subscribe.bind(this.events$)}async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server)return this.events$.next({type:"stop",running:!1});await new Promise((e,t)=>{this.server.close(r=>{r?t(r):e()})}),this.server=void 0,this.events$.next({type:"stop",running:!0})}async restart(){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=Mt.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort();let t={host:this.config.host,port:this.config.port,url:`http://${this.config.host}:${this.config.port}`};this.config.onStart?.(t),this.events$.next({...t,type:"start"}),e()})})}startHttpsServer(){return new Promise(e=>{let t={key:Tt(this.config.key??Se(this.framework.frameworkRoot,"..","certs","server.key")),cert:Tt(this.config.cert??Se(this.framework.frameworkRoot,"..","certs","server.crt"))};this.server=Lt.createServer(t,(r,n)=>{this.handleRequest(r,n,()=>this.defaultResponse(r,n))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort();let r={host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`};this.config.onStart?.(r),this.events$.next({...r,type:"start"}),e()})})}handleRequest(e,t,r){try{this.events$.next({type:"request",url:e.url??""}),this.config.onRequest?this.config.onRequest(e,t,r):r()}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 r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",n=Se(this.rootDir,r);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await Pi(n);o.isDirectory()?await this.handleDirectory(n,r,t):o.isFile()&&await this.handleFile(n,t)}catch(o){this.events$.next({type:"error",error:o,url:e.url}),this.sendNotFound(t)}}async handleDirectory(e,t,r){let o=(await Di(e)).map(l=>{let f=Se(t,l),p=Et(l).slice(1)||"folder";return p==="folder"?`
43
+ `}clause(e){return e.alias?`${e.name} as ${e.alias}`:e.name}emitDeclaration(e){let t=this.ts.languageService;return!t.getProgram()?.getSourceFile(e)&&(this.ts.touchFiles([e]),!t.getProgram()?.getSourceFile(e))?"":t.getEmitOutput(e,!0,!0).outputFiles.find(r=>r.name.endsWith(".d.ts"))?.text??""}build(e,t){let r=this.emitDeclaration(e),n={edits:[],target:e,parsed:ii(e,r,{sourceType:"module"}),content:r,bundleEdits:[],packageImports:Object.create(null),packageExports:Object.create(null),projectExports:{star:new Set,exports:[],namespace:Object.create(null)},projectDependencies:new Set},o=[],{body:s}=n.parsed.program;for(let a of s)this.strip(a,n)&&o.push(a.start);return this.pruneComments(n,s,o),{version:t,content:K(r,n.bundleEdits),declaration:K(r,n.edits),packageImports:n.packageImports,packageExports:n.packageExports,projectExports:n.projectExports,projectDependencies:n.projectDependencies}}strip(e,t){switch(e.type){case"ImportDeclaration":return this.stripImport(e,t),!1;case"ExportAllDeclaration":return this.stripStarExport(e,t),!1;case"ExportNamedDeclaration":return this.stripNamedExport(e,t);case"ExportDefaultDeclaration":return this.stripDefaultExport(e,t);case"TSImportEqualsDeclaration":return this.stripImportEquals(e,t);case"TSExportAssignment":case"TSNamespaceExportDeclaration":return A(e,t.content,t.bundleEdits),!1;default:return!0}}stripImport(e,t){if(A(e,t.content,t.bundleEdits),this.link(e.source,t))return;let r=t.packageImports[e.source.value]??={};if(e.specifiers.length<1){r.side=!0;return}for(let n of e.specifiers)switch(n.type){case"ImportDefaultSpecifier":r.default??=n.local.name;break;case"ImportNamespaceSpecifier":(r.namespaces??=[]).push(n.local.name);break;default:(r.named??=[]).push(this.binding(this.nameOf(n.imported),n.local.name))}}stripImportEquals(e,t){let{moduleReference:r}=e;if(r.type!=="TSExternalModuleReference")return!0;A(e,t.content,t.bundleEdits);let n=r.expression;return this.link(n,t)||((t.packageImports[n.value]??={}).namespaces??=[]).push(e.id.name),!1}stripNamedExport(e,t){let{exports:r}=t.projectExports;if(e.declaration)return this.collectDeclared(e.declaration,r),t.bundleEdits.push({start:e.start,end:e.declaration.start}),!0;A(e,t.content,t.bundleEdits);let n=e.source&&!this.link(e.source,t)?(t.packageExports[e.source.value]??={}).named??=[]:r;for(let o of e.specifiers)n.push(this.binding(this.nameOf(o.local),this.nameOf(o.exported)));return!1}stripStarExport(e,t){A(e,t.content,t.bundleEdits);let r=this.link(e.source,t),n=e.exported?this.nameOf(e.exported):null;if(r){n?t.projectExports.namespace[n]=r:t.projectExports.star.add(r);return}let o=t.packageExports[e.source.value]??={};n?(o.namespaces??=[]).push(n):o.star=!0}stripDefaultExport(e,t){let{declaration:r}=e,n=this.defaultBinding(r);return n&&t.projectExports.exports.push({name:n,alias:"default"}),n&&r.type!=="Identifier"?(t.bundleEdits.push({start:e.start,end:r.start,text:"declare "}),!0):(A(e,t.content,t.bundleEdits),!1)}pruneComments(e,t,r){let{content:n,bundleEdits:o}=e,s=0,a=0;for(let c of e.parsed.comments)if(!(c.type!=="Block"||c.value.charCodeAt(0)!==42)){for(;s<t.length&&t[s].end<=c.start;)s++;if(!(s<t.length&&t[s].start<c.start)){for(;a<r.length&&r[a]<c.end;)a++;a<r.length&&this.blank(n,c.end,r[a])||A(c,n,o)}}}link(e,t){let r=this.ts.resolve(e.value,t.target);if(!r||r.isExternalLibraryImport)return null;let{extension:n,relativeFileName:o,resolvedFileName:s}=r,a=this.filesCache.resolve(s);return t.projectDependencies.add(a),t.edits.push({end:e.end,start:e.start,text:`'${n?o.slice(0,-n.length):o}.d.ts'`}),a}collectDeclared(e,t){if(e.type==="VariableDeclaration"){for(let r of e.declarations)r.id.type==="Identifier"&&t.push({name:r.id.name});return}"id"in e&&e.id&&"name"in e.id&&t.push({name:e.id.name})}defaultBinding(e){return e.type==="Identifier"?e.name:"id"in e?e.id?.name:void 0}nameOf(e){return"name"in e?e.name:JSON.stringify(e.value)}binding(e,t){return e===t?{name:e}:{name:e,alias:t}}blank(e,t,r){for(let n=t;n<r;n++){let o=e.charCodeAt(n);if(o!==32&&o!==9&&o!==10&&o!==13)return!1}return!0}};import G from"typescript";import{relative as hi}from"@remotex-labs/xmap";import{inject as yi}from"@remotex-labs/xinject";import{readdirSync as ci}from"fs";import{join as li}from"@remotex-labs/xmap";var Ve={64:")",43:")+",42:")*",63:")?"};function He(i){return".+^$()|\\{}[]*?".includes(i)?"\\"+i:i}function g(i,e){return i.charCodeAt(e)}function fi(i,e){return(e===0||g(i,e-1)===47)&&(e+2===i.length||g(i,e+2)===47)}function ne(i){return`(?:${i})`}function _e(i,e){let t=e+1,r=g(i,t);for((r===33||r===94)&&t++,g(i,t)===93&&t++;t<i.length&&g(i,t)!==93;)t+=g(i,t)===92?2:1;return t}function pi(i,e){for(let t=e,r=0;t<i.length;t++){let n=g(i,t);if(n===92)t++;else if(n===40)r++;else{if(n===41&&--r===0)return t;n===91&&(t=_e(i,t))}}return-1}function ui(i,e){let t=!1;for(let r=e+1,n=0;r<i.length;r++){let o=g(i,r);if(o===92)r++;else if(o===123)n++;else if(o===125){if(n===0)return t?r:-1;n--}else o===44&&n===0?t=!0:o===91&&(r=_e(i,r))}return-1}function di(i,e){let t=_e(i,e);if(t>=i.length)return["\\[",e+1];let r=e+1,n="[",o=g(i,r);for((o===33||o===94)&&(n+="^/",r++),g(i,r)===93&&(n+="\\]",r++);r<t;r++)g(i,r)===92?n+="\\"+i[++r]:g(i,r)===94?n+="\\^":n+=i[r];return[n+"]",t+1]}function mi(i,e){for(let t=e;t<i.length;t++){if(g(i,t)===47)return t;g(i,t)===92&&t++}return i.length}function oe(i,e=!1,t=0,r={}){let{dot:n=!1}=r,o="",s=0,a=e,c=n?"":"(?!\\.)",l=c+"[^/]"+"+",f=ne(l+"(?:/"+l+")*")+"?";for(;s<i.length;){let p=g(i,s),S=g(i,s+1);if(S===40&&(p===33||Ve[p])){let d=pi(i,s+1);if(p!==33){let W=d===-1?i.length:d,ae=oe(i.slice(s+2,W),a,124,r);o+="(?:"+ae+Ve[p],s=W+1;continue}if(d!==-1){let W=oe(i.slice(s+2,d),a,124,r),ae=mi(i,d+1),tt=oe(i.slice(d+1,ae),!1,0,r);o+=ne((a?c:"")+`(?!${ne(W)+tt+"(?:$|/)"})`+"[^/]*?"+tt),s=ae;continue}}switch(p){case 47:o+="/",s++,a=!0;break;case 92:o+=s+1<i.length?He(i[s+1]):"\\\\",s+=2;break;case 63:o+=a&&!n?"[^./]":"[^/]",s++;break;case 42:if(S===42&&t!==124&&(s>0||e)&&fi(i,s)){let d=s===0&&t===0?"(?:[A-Za-z]:)?/?":"";g(i,s+2)===47?(o+=d+ne(l+"/")+"*",s+=3,a=!0):(o+=d+f,s+=2)}else o+=(a?c:"")+"[^/]*",s++;break;case 123:{let d=ui(i,s);d===-1?(o+="\\{",s++):(o+=ne(oe(i.slice(s+1,d),a,44,r)),s=d+1);break}case 91:{let[d,W]=di(i,s);o+=(a&&!n&&d!=="\\["?"(?!\\.)":"")+d,s=W;break}case 124:case 44:t===p?(o+="|",a=e):o+=He(i[s]),s++;break;default:o+=He(i[s]),s++}}return o}function gi(i,e={}){return new RegExp("^"+oe(i,!0,0,e)+"$",e.flags)}function se(i,e={}){let t=[],r=[];for(let n of i){let o=!1;for(;g(n,0)===33&&g(n,1)!==40;)o=!o,n=n.slice(1);(o?r:t).push(gi(n,e))}return n=>(t.length===0||t.some(o=>o.test(n)))&&!r.some(o=>o.test(n))}function It(i,e,t={}){let r=u.resolve(i),n=se(e,t),o=t.dot||e.some(c=>g(c,0)===46||c.includes("/.")),s=[],a=[""];for(;a.length>0;){let c=a.pop(),l;try{l=ci(c?li(r,c):r,{withFileTypes:!0})}catch{continue}for(let f of l){if(!o&&g(f.name,0)===46)continue;let p=c?`${c}/${f.name}`:f.name;f.isDirectory()?a.push(p):n(p)&&s.push(p)}}return s}var be=class{constructor(e){this.config=e;this.reload()}config;filesCache=yi(h);trackedFiles=new Set;exclusions=new Map;matches;get tracked(){return this.trackedFiles}get ignoreSourceFile(){return e=>this.isExcluded(e.fileName)}set options(e){this.config=e,this.reload()}clearTracked(){this.trackedFiles.clear(),this.refreshFiles(this.config.fileNames)}reload(){this.matches=this.compileExclude(this.config.raw?.exclude),this.exclusions.clear(),this.clearTracked()}refresh(e){return this.filesCache.refresh(this.track(e))}refreshFiles(e=this.trackedFiles){for(let t of e)this.isExcluded(t)||this.refresh(t)}getCompilationSettings(){return this.config.options}fileExists(e){return G.sys.fileExists(e)}readFile(e,t){return this.filesCache.touch(e,t).snapshot?.text}readDirectory(e,t,r,n,o){return G.sys.readDirectory(e,t,r,n,o)}getDirectories(e){return G.sys.getDirectories(e)}directoryExists(e){return G.sys.directoryExists(e)}getCurrentDirectory(){return G.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackedFiles]}getDefaultLibFileName(e){return G.getDefaultLibFilePath(e)}getScriptVersion(e){return this.filesCache.touch(this.track(e)).version.toString()}getScriptSnapshot(e){return this.filesCache.touch(e).snapshot}realpath(e){return this.filesCache.resolve(e)}compileExclude(e){return e&&e.length>0?se(e):()=>!1}isExcluded(e){let t=this.filesCache.resolve(e),r=this.exclusions.get(t);return r===void 0&&this.exclusions.set(t,r=this.matches(hi(process.cwd(),t))),r}track(e){let t=this.filesCache.resolve(e);return this.trackedFiles.add(t),t}};var y=class{constructor(e="tsconfig.json"){this.configPath=e;this.parsedConfig=this.parseConfig(),this.languageHostService=new be(this.parsedConfig),this.configVersion=this.languageHostService.filesCache.touch(this.configPath).version,this.resolutionCache=this.createResolutionCache(),this.languageService=v.createLanguageService(this.languageHostService,v.createDocumentRegistry(!0)),this.declaration=new ve(this)}configPath;languageService;languageHostService;diagnosticsCache=new Map;builderHost={createHash:v.sys.createHash,readFile:(e,t)=>this.languageHostService.readFile(e,t),getCurrentDirectory:()=>v.sys.getCurrentDirectory(),useCaseSensitiveFileNames:()=>v.sys.useCaseSensitiveFileNames};declaration;parsedConfig;configVersion;resolutionCache;builder;static reload(e=!1){let t=[];for(let[r,n]of y.cache)n.instance.refresh(e)&&t.push(r);return t}get config(){return this.parsedConfig}check(e){let t=this.languageService.getProgram();if(!t)return[];let r=this.languageHostService.ignoreSourceFile,n=s=>s.fileName.includes("node_modules")?!0:r(s),o;for(this.builder=v.createEmitAndSemanticDiagnosticsBuilderProgram(t,this.builderHost,this.builder);o=this.builder.getSemanticDiagnosticsOfNextAffectedFile(void 0,n);)if("fileName"in o.affected){let s=o.affected;this.diagnosticsCache.set(s.fileName,[...o.result,...this.builder.getSyntacticDiagnostics(s),...this.languageService.getSuggestionDiagnostics(s.fileName)].map(a=>this.formatDiagnostic(a)))}return this.reconcileDiagnostics(t,e??this.diagnosticsCache.keys())}async emit(e,t){return t??=this.config.options.outDir??"dist",this.declaration.emit(e,t)}async emitBundle(e,t){return t??=this.config.options.outDir??"dist",this.declaration.emitBundle(e,t)}touchFiles(e){this.languageHostService.refreshFiles(e)}resolve(e,t){let r=t?this.languageHostService.filesCache.resolve(Si(t)):process.cwd(),o=this.resolutionCache.getOrCreateCacheForDirectory(r).get(e,void 0)?.resolvedModule;if(o)return o;let s=v.resolveModuleName(e,t??"",this.parsedConfig.options,this.languageHostService,this.resolutionCache).resolvedModule;if(s){let a=xi(r,s.resolvedFileName);s.container=r,s.relativeFileName=a.startsWith(".")?a:`./${a}`}return s}dispose(){let e=y.cache.get(this.configPath);e&&(e.refCount--,!(e.refCount>0)&&(this.languageService.dispose(),y.cache.delete(this.configPath)))}[Symbol.dispose??Symbol.for("Symbol.dispose")](){this.dispose()}static acquire(e="tsconfig.json"){let t=bi(e),r=y.cache.get(t);if(r)return r.refCount++,r.instance;let n=new y(t);return y.cache.set(t,{instance:n,refCount:1}),n}refresh(e=!1){let{version:t}=this.languageHostService.filesCache.touch(this.configPath);return!e&&t===this.configVersion?!1:(this.configVersion=t,this.parsedConfig=this.parseConfig(),this.languageHostService.options=this.parsedConfig,this.resolutionCache=this.createResolutionCache(),this.declaration.clear(),this.diagnosticsCache.clear(),this.builder=void 0,!0)}createResolutionCache(){return v.createModuleResolutionCache(v.sys.getCurrentDirectory(),e=>this.languageHostService.realpath(e),this.parsedConfig.options)}reconcileDiagnostics(e,t){let r=this.languageHostService.filesCache,n=[];for(let o of t){let s=r.resolve(o),a=this.diagnosticsCache.get(s);a&&(e.getSourceFile(s)?n.push(...a):this.diagnosticsCache.delete(s))}return n}formatDiagnostic(e){let t={message:v.flattenDiagnosticMessageText(e.messageText,`
44
+ `),category:e.category};if(e.file&&e.start!==void 0){let{line:r,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=r+1,t.column=n+1,t.code=e.code}return t}parseConfig(){let e=v.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...v.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:v.ScriptTarget.ESNext,module:v.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:v.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,noEmit:!0,rootDir:e.options?.rootDir??process.cwd(),isolatedModules:!1,useCaseSensitiveFileNames:!0},e}};ce(y,"cache",new Map),y=b([vi({factory(i){return y.acquire(i)}})],y);var Y=class{constructor(e){this.build=e;this.restoreLevel=this.logLevel!=="verbose"?this.logLevel:"info"}build;config$=$i($);serverUrl;restoreLevel;set logLevel(e){this.config$.patch({logLevel:e})}get logLevel(){return this.config$.getValue().logLevel??"info"}get url(){return this.serverUrl??""}set url(e){this.serverUrl=e}buildEvent(e){if(e.type==="start")return this.say(`${w.dim("\u2192")} ${m("building")} ${D(e.context.variantName)}`,`${M("build")} ${D(e.context.variantName)}`);let{errors:t,warnings:r,info:n,verbose:o,metafile:s}=e.buildResult,a=!s;a?process.exitCode=1:process.exitCode=0,this.groups({error:t,warning:r,info:n,verbose:o}),s&&pt(s,this.logLevel==="verbose"?1/0:void 0);let c=a?pe("\xD7"):fe("\u2713"),l=a?T(e.context.variantName):D(e.context.variantName);this.say(`${c} ${l} ${m.dim(`in ${e.duration} ms`)}`,`
45
+ ${M("build",c)} ${l} ${m.dim(`in ${e.duration} ms`)}`)}serverEvent(e){switch(e.type){case"start":return this.url=e.url,console.log(`${M("serve")} ${N(e.url)}`);case"stop":this.serverUrl=void 0,e.running&&console.log(`${M("serve")} ${m("stopped")}`);return;case"request":this.logLevel==="verbose"&&console.log(`${M("serve")} ${m.dim(e.url)}`);return;case"error":if(e.url?.includes("favicon"))return;console.log(`${M("serve",pe("\xD7"))} ${m(e.error.message)}`)}}diagnostics(e){let t=!1;for(let[r,n]of Object.entries(e)){let o=n.error.length+n.warning.length+n.info.length+n.verbose.length;t||=n.error.length>0,console.log(`${M("type-check")} ${D(r)} ${m.dim(`${o} to look at`)}`),this.groups(n),console.log("")}ki(t?1:0)}async rebuild(e,t=!1){me(),y.reload(t),this.say(`${w.dim("\u21BB")} ${m(e)}`,`${M("rebuild",w.dim("\u21BB"))} ${m(e)}`),await this.build()}toggleVerbose(){return this.logLevel==="verbose"?this.logLevel=this.restoreLevel:(this.restoreLevel=this.logLevel,this.logLevel="verbose"),this.logLevel}say(e,t){console.log(t),gt(e)}groups(e){let t=q[this.logLevel],r=this.logLevel==="verbose";q.error>=t&&te(e.error,"Errors",pe,"\xD7",!0),q.warning>=t&&te(e.warning,"Warnings",T,"\u2022",r),q.info>=t&&te(e.info,"Info",w,"\u2192",r),q.verbose>=t&&te(e.verbose,"Verbose",m,"\xB7",r)}};Y=b([Ci({scope:"singleton"})],Y);import Ct from"yargs";import{hideBin as Ti}from"yargs/helpers";import{Injectable as Mi}from"@remotex-labs/xinject";var Ei="config.xbuild.ts",xe={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:Ei},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string"},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},clean:{describe:"Clean build artifacts",type:"boolean",default:!1}},kt=[["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 O=class{parseConfigFile(e){return Ct(e).help(!1).version(!1).options({config:xe.config}).parseSync()}enhancedParse(e,t={}){let r=Ct(Ti(e)).locale("en"),n=r.showHelp;return r.showHelp=function(o){return this.group(Object.keys(xe),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},r.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(xe).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),kt.forEach(([o,s])=>{r.example(o,s)}),r.parseSync()}};O=b([Mi({scope:"singleton"})],O);import{inject as et}from"@remotex-labs/xinject";import*as Mt from"http";import*as Rt from"https";import{extname as Et}from"path";import{readFileSync as Tt}from"fs";var $t=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{join as Se}from"@remotex-labs/xmap";import{inject as Li}from"@remotex-labs/xinject";import{Subject as Di}from"@remotex-labs/xobservable";import{readdir as Pi,stat as Ai,readFile as Oi}from"fs/promises";var we=class{constructor(e,t){this.config=e;this.rootDir=u.resolve(t),this.config.port||=0,this.config.host||="localhost"}config;server;events$=new Di;rootDir;framework=Li(u);get pipe(){return this.events$.pipe.bind(this.events$)}get subscribe(){return this.events$.subscribe.bind(this.events$)}async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server)return this.events$.next({type:"stop",running:!1});await new Promise((e,t)=>{this.server.close(r=>{r?t(r):e()})}),this.server=void 0,this.events$.next({type:"stop",running:!0})}async restart(){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=Mt.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort();let t={host:this.config.host,port:this.config.port,url:`http://${this.config.host}:${this.config.port}`};this.config.onStart?.(t),this.events$.next({...t,type:"start"}),e()})})}startHttpsServer(){return new Promise(e=>{let t={key:Tt(this.config.key??Se(this.framework.frameworkRoot,"..","certs","server.key")),cert:Tt(this.config.cert??Se(this.framework.frameworkRoot,"..","certs","server.crt"))};this.server=Rt.createServer(t,(r,n)=>{this.handleRequest(r,n,()=>this.defaultResponse(r,n))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort();let r={host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`};this.config.onStart?.(r),this.events$.next({...r,type:"start"}),e()})})}handleRequest(e,t,r){try{this.events$.next({type:"request",url:e.url??""}),this.config.onRequest?this.config.onRequest(e,t,r):r()}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 r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",n=Se(this.rootDir,r);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await Ai(n);o.isDirectory()?await this.handleDirectory(n,r,t):o.isFile()&&await this.handleFile(n,t)}catch(o){this.events$.next({type:"error",error:o,url:e.url}),this.sendNotFound(t)}}async handleDirectory(e,t,r){let o=(await Pi(e)).map(l=>{let f=Se(t,l),p=Et(l).slice(1)||"folder";return p==="folder"?`
46
46
  <a href="/${f}" class="folder-row">
47
47
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
48
48
  <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
@@ -52,7 +52,7 @@ ${M("build",c)} ${l} ${m.dim(`in ${e.duration} ms`)}`)}serverEvent(e){switch(e.t
52
52
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
53
53
  <div class="meta"><div class="name">${l}</div><div class="sub">${p}</div></div>
54
54
  </a>
55
- `}).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=$t.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));r.writeHead(200,{"Content-Type":"text/html"}),r.end(c)}async handleFile(e,t){let r=Et(e).slice(1)||"txt",n=this.getContentType(r),o=await Ai(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){this.events$.next({type:"error",error:t}),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{inject as Xi}from"@remotex-labs/xinject";var j=class extends F{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{Subject as Zi}from"@remotex-labs/xobservable";import{parseSync as Zt}from"oxc-parser";import{relative as Qi}from"@remotex-labs/xmap";import{inject as Qe}from"@remotex-labs/xinject";function Oi(i,e,t){if(e===void 0)return t;if(Object.hasOwn(i,e))return i[e];for(let r in i)try{if(new RegExp(`^(?:${r})$`).test(e))return i[r]}catch{if(e===r)return i[r]}return t}function We(i,e,t,r){let n=Oi(e,t.id,r);n!=="silent"&&i[n].push(t)}function Rt(i,e,t,r,n){for(let o of t)n&&(o.pluginName=n),We(i,e,o,r)}import{parseSync as ji}from"oxc-parser";import{inject as Bi}from"@remotex-labs/xinject";var _="$$",Ie="$$if",x=(r=>(r.ifdef=`${_}ifdef`,r.ifndef=`${_}ifndef`,r.inline=`${_}inline`,r))(x||{}),Dt=new Set(["false","null","undefined"]),Pt=new Set(["id","label","local","params","exported","imported"]);function ke(i,e){let t=i[e];return t!==void 0&&!Dt.has(t.trim())}function At(i,e,t,r){let{call:n,suffix:o}=t,s=n.arguments[1],a=i.slice(s.start,s.end);if(s.type!=="ArrowFunctionExpression"&&s.type!=="FunctionExpression")return`${r}const ${e} = ${a}${o};`;if(o)return`${r}const ${e} = (${a})${o};`;let{body:c}=s,l=s.params.map(S=>i.slice(S.start,S.end)).join(", "),f=s.returnType?i.slice(s.returnType.start,s.returnType.end):"",p=`${r}${s.async?"async ":""}function ${e}(${l})${f}`;return c?c.type==="BlockStatement"?`${p} ${i.slice(c.start,c.end)}`:`${p} { return ${i.slice(c.start,c.end)}; }`:`${p} {}`}function Ot(i,e,t){let{call:r,suffix:n}=e,o=r.arguments[1],s=i.slice(o.start,o.end),a=t?";":"";if(o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return`${s}${n}${a}`;if(n||!t)return`(${s})${n||"()"}${a}`;let{body:c}=o;return c?c.type!=="BlockStatement"?`${i.slice(c.start,c.end)};`:i.slice(c.start+1,c.end-1).trim():""}function jt(i,e){let t=new Set,r=Bi(h);for(let n of i){let o=r.touch(n).snapshot?.text;if(!o?.includes(Ie))continue;let{program:s}=ji(n,o,{sourceType:"module"});for(let a of s.body)if(a.type==="ExportNamedDeclaration"&&a.declaration?.type==="VariableDeclaration")for(let c of a.declaration.declarations){let l=c.init;if(l?.type!=="CallExpression"||l.callee.type!=="Identifier")continue;let f=l.callee.name;if(f!==x.ifdef&&f!==x.ifndef)continue;let p=l.arguments[0];p?.type!=="Literal"||typeof p.value!="string"||c.id.type==="Identifier"&&f===x.ifdef!==ke(e,p.value)&&t.add(c.id.name)}}return t}import{visitorKeys as qi}from"oxc-parser";import{createRequire as _i}from"module";import{inject as Ui}from"@remotex-labs/xinject";import{Script as Fi,createContext as Ni}from"vm";async function Ce(i,e={},t={},r=!1){let n={},o=Object.getOwnPropertyDescriptors(globalThis);delete o.globalThis,r&&delete o.console,Object.defineProperties(n,o),Object.assign(n,e);let s=Ni(n);return await new Fi(i,t).runInContext(s,{breakOnSigint:!0,displayErrors:!1})}import{cwd as Bt}from"process";import{build as ze}from"esbuild";import{dirname as Vi,basename as Hi}from"@remotex-labs/xmap";var qe={write:!1,bundle:!0,minify:!0,outdir:"dist",format:"cjs",target:"esnext",logLimit:0,logLevel:"silent",platform:"browser",sourcemap:"external"};async function Ft(i={}){return await ze({absWorkingDir:Bt(),...qe,...i,metafile:!0})}async function $e(i,e,t={}){return await ze({absWorkingDir:Bt(),...qe,...t,stdin:{loader:"ts",contents:i,resolveDir:Vi(e),sourcefile:Hi(e)},write:!1,metafile:!0,sourcemap:"external"})}async function Ke(i={}){return await ze({...i,write:!1,bundle:!0,outdir:"tmp",outfile:void 0,metafile:!0,packages:"external",logLevel:"silent"})}function Wi(i){return i==null?"undefined":typeof i=="function"?i.toString():typeof i=="number"||typeof i=="boolean"?String(i):ye(i)??"undefined"}async function Nt(i,e){let t=i.target+".inline",r=i.code.slice(e.arguments[0].start,e.arguments[0].end),[n,o]=(await $e(`module.exports = (${r})();`,t,{format:"cjs",platform:"node",packages:"external"})).outputFiles,s={exports:void 0};Ui(u).addSourceMap(t,n.text,!0);let a=await Ce(o.text,{module:s,require:_i(i.target)},{filename:t});return Wi(a??s.exports)}function Vt(i){return typeof i=="object"&&i!==null&&typeof i.type=="string"}function Ee(i,e,t=null,r=""){if(e(i,t,r))return;let n=qi[i.type];for(let o of n??[]){let s=i[o];if(Array.isArray(s))for(let a of s)Vt(a)&&Ee(a,e,i,o);else Vt(s)&&Ee(s,e,i,o)}}function qt(i,e,t,r){let{code:n}=i,o=1,s=0;for(let a=n.indexOf(`
55
+ `}).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=$t.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));r.writeHead(200,{"Content-Type":"text/html"}),r.end(c)}async handleFile(e,t){let r=Et(e).slice(1)||"txt",n=this.getContentType(r),o=await Oi(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){this.events$.next({type:"error",error:t}),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{inject as Zi}from"@remotex-labs/xinject";var j=class extends F{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{Subject as en}from"@remotex-labs/xobservable";import{parseSync as Zt}from"oxc-parser";import{relative as Xi}from"@remotex-labs/xmap";import{inject as Qe}from"@remotex-labs/xinject";function ji(i,e,t){if(e===void 0)return t;if(Object.hasOwn(i,e))return i[e];for(let r in i)try{if(new RegExp(`^(?:${r})$`).test(e))return i[r]}catch{if(e===r)return i[r]}return t}function We(i,e,t,r){let n=ji(e,t.id,r);n!=="silent"&&i[n].push(t)}function Lt(i,e,t,r,n){for(let o of t)n&&(o.pluginName=n),We(i,e,o,r)}import{parseSync as Bi}from"oxc-parser";import{inject as Fi}from"@remotex-labs/xinject";var _="$$",Ie="$$if",x=(r=>(r.ifdef=`${_}ifdef`,r.ifndef=`${_}ifndef`,r.inline=`${_}inline`,r))(x||{}),Dt=new Set(["false","null","undefined"]),Pt=new Set(["id","label","local","params","exported","imported"]);function ke(i,e){let t=i[e];return t!==void 0&&!Dt.has(t.trim())}function At(i,e,t,r){let{call:n,suffix:o}=t,s=n.arguments[1],a=i.slice(s.start,s.end);if(s.type!=="ArrowFunctionExpression"&&s.type!=="FunctionExpression")return`${r}const ${e} = ${a}${o};`;if(o)return`${r}const ${e} = (${a})${o};`;let{body:c}=s,l=s.params.map(S=>i.slice(S.start,S.end)).join(", "),f=s.returnType?i.slice(s.returnType.start,s.returnType.end):"",p=`${r}${s.async?"async ":""}function ${e}(${l})${f}`;return c?c.type==="BlockStatement"?`${p} ${i.slice(c.start,c.end)}`:`${p} { return ${i.slice(c.start,c.end)}; }`:`${p} {}`}function Ot(i,e,t){let{call:r,suffix:n}=e,o=r.arguments[1],s=i.slice(o.start,o.end),a=t?";":"";if(o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return`${s}${n}${a}`;if(n||!t)return`(${s})${n||"()"}${a}`;let{body:c}=o;return c?c.type!=="BlockStatement"?`${i.slice(c.start,c.end)};`:i.slice(c.start+1,c.end-1).trim():""}function jt(i,e){let t=new Set,r=Fi(h);for(let n of i){let o=r.touch(n).snapshot?.text;if(!o?.includes(Ie))continue;let{program:s}=Bi(n,o,{sourceType:"module"});for(let a of s.body)if(a.type==="ExportNamedDeclaration"&&a.declaration?.type==="VariableDeclaration")for(let c of a.declaration.declarations){let l=c.init;if(l?.type!=="CallExpression"||l.callee.type!=="Identifier")continue;let f=l.callee.name;if(f!==x.ifdef&&f!==x.ifndef)continue;let p=l.arguments[0];p?.type!=="Literal"||typeof p.value!="string"||c.id.type==="Identifier"&&f===x.ifdef!==ke(e,p.value)&&t.add(c.id.name)}}return t}import{visitorKeys as zi}from"oxc-parser";import{createRequire as Ui}from"module";import{inject as Wi}from"@remotex-labs/xinject";import{Script as Ni,createContext as Vi}from"vm";async function Ce(i,e={},t={},r=!1){let n={},o=Object.getOwnPropertyDescriptors(globalThis);delete o.globalThis,r&&delete o.console,Object.defineProperties(n,o),Object.assign(n,e);let s=Vi(n);return await new Ni(i,t).runInContext(s,{breakOnSigint:!0,displayErrors:!1})}import{cwd as Bt}from"process";import{build as ze}from"esbuild";import{dirname as Hi,basename as _i}from"@remotex-labs/xmap";var qe={write:!1,bundle:!0,minify:!0,outdir:"dist",format:"cjs",target:"esnext",logLimit:0,logLevel:"silent",platform:"browser",sourcemap:"external"};async function Ft(i={}){return await ze({absWorkingDir:Bt(),...qe,...i,metafile:!0})}async function $e(i,e,t={}){return await ze({absWorkingDir:Bt(),...qe,...t,stdin:{loader:"ts",contents:i,resolveDir:Hi(e),sourcefile:_i(e)},write:!1,metafile:!0,sourcemap:"external"})}async function Ke(i={}){return await ze({...i,write:!1,bundle:!0,outdir:"tmp",outfile:void 0,metafile:!0,packages:"external",logLevel:"silent"})}function qi(i){return i==null?"undefined":typeof i=="function"?i.toString():typeof i=="number"||typeof i=="boolean"?String(i):ye(i)??"undefined"}async function Nt(i,e){let t=i.target+".inline",r=i.code.slice(e.arguments[0].start,e.arguments[0].end),[n,o]=(await $e(`module.exports = (${r})();`,t,{format:"cjs",platform:"node",packages:"external"})).outputFiles,s={exports:void 0};Wi(u).addSourceMap(t,n.text,!0);let a=await Ce(o.text,{module:s,require:Ui(i.target)},{filename:t});return qi(a??s.exports)}function Vt(i){return typeof i=="object"&&i!==null&&typeof i.type=="string"}function Ee(i,e,t=null,r=""){if(e(i,t,r))return;let n=zi[i.type];for(let o of n??[]){let s=i[o];if(Array.isArray(s))for(let a of s)Vt(a)&&Ee(a,e,i,o);else Vt(s)&&Ee(s,e,i,o)}}function qt(i,e,t,r){let{code:n}=i,o=1,s=0;for(let a=n.indexOf(`
56
56
  `);a!==-1&&a<e;a=n.indexOf(`
57
- `,a+1))o++,s=a+1;r.location={file:i.target,line:o,column:e-s},We(i.logs,i.overrides,r,t)}function E(i,e,t){return i.edits.push({start:e.start,end:e.end,text:t}),!0}function zt(i,e,t,r){let n={start:e.start,end:e.end,text:""};return i.edits.push(n),i.pending.push(Nt(i,t).then(o=>{n.text=r(o)},o=>{n.text=r("undefined"),qt(i,t.start,"error",{detail:o,id:"macro-inline",text:`${x.inline} failed: ${o?.message??String(o)}`})})),!0}function Ht(i){if(i.type!=="CallExpression"||i.callee.type!=="Identifier")return!1;let{name:e}=i.callee;if(e===x.inline)return i.arguments.length===1;if(e!==x.ifdef&&e!==x.ifndef||i.arguments.length!==2)return!1;let t=i.arguments[0];return t.type==="Literal"&&typeof t.value=="string"}function Ge(i,e){let t=e.arguments[0],r=t.type==="Literal"?String(t.value):"";return e.callee.name===x.ifdef===ke(i.defines,r)}function _t(i,e){return e.type==="CallExpression"&&e.callee.type==="Identifier"&&i.dropped.has(e.callee.name)}function Te(i,e){if(e){if(Ht(e))return{call:e,suffix:""};if(e.type==="TSAsExpression")return Te(i,e.expression);if(!(e.type!=="CallExpression"||!Ht(e.callee)))return{call:e.callee,suffix:i.code.slice(e.callee.end,e.end)}}}function Kt(i,e){let t=e.type==="ExportNamedDeclaration"?e.declaration:e;if(t?.type!=="VariableDeclaration"||t.declarations.length!==1)return;let{id:r,init:n}=t.declarations[0];if(r.type!=="Identifier")return;let o=Te(i,n);return o&&[r,o]}function zi(i,e){let t=[],r=[],n=!1;for(let s of e.specifiers){let a=i.code.slice(s.start,s.end);s.type!=="ImportSpecifier"?r.push(a):i.dropped.has(s.local.name)?n=!0:t.push(a)}if(!n)return!1;let o=i.code.slice(e.source.start,e.source.end);return t.length>0&&r.push(`{ ${t.join(", ")} }`),r.length<1?E(i,e,`import ${o};`):E(i,e,`import ${r.join(", ")} from ${o};`)}function Ki(i,e){let{specifiers:t}=e,r=t.filter(({local:n})=>!i.dropped.has(n.type==="Literal"?n.value:n.name));return r.length===t.length?!1:r.length<1?E(i,e,""):E(i,e,`export { ${r.map(n=>i.code.slice(n.start,n.end)).join(", ")} };`)}function Ut(i,e){let t=Kt(i,e);if(!t)return!1;let[r,n]=t,{call:o,suffix:s}=n,a=e.type==="ExportNamedDeclaration"?"export ":"";return r.name.startsWith("$$")||qt(i,r.start,"warning",{id:"macro-prefix",text:`Macro '${r.name}' does not start with the '${"$$"}' prefix to avoid conflicts`}),o.callee.name===x.inline?zt(i,e,o,c=>`${a}const ${r.name} = ${c}${s};`):E(i,e,Ge(i,o)?At(i.code,r.name,n,a):"")}function Wt(i,e,t,r){let{call:n,suffix:o}=t;return n.callee.name===x.inline?zt(i,e,n,s=>r?"":`${s}${o}`):Ge(i,n)?E(i,e,Ot(i.code,t,r)):E(i,e,r?"":"undefined")}function Gi(i,e,t,r){switch(e.type){case"Identifier":return!i.dropped.has(e.name)||!t?!1:!(r==="key"||r==="property"?!("computed"in t)||!t.computed:Pt.has(r))&&E(i,e,"undefined");case"ImportDeclaration":return zi(i,e);case"ExportNamedDeclaration":return Ut(i,e)?!0:e.source||e.specifiers.length<1?!1:Ki(i,e);case"VariableDeclaration":return Ut(i,e);case"ExpressionStatement":{if(_t(i,e.expression))return E(i,e,"");let n=Te(i,e.expression);return n!==void 0&&Wt(i,e,n,!0)}case"CallExpression":case"TSAsExpression":{if(_t(i,e))return E(i,e,"undefined");let n=Te(i,e);return n!==void 0&&Wt(i,e,n,!1)}}return!1}async function Gt(i,e,t,r){if(t.length<1||e.includes("node_modules"))return t;let{dropped:n}=r.stage;if(n.size<1&&!t.includes("$$"))return t;let o={target:e,dropped:n,code:t,logs:r.logs,edits:[],pending:[],defines:r.options.define??{},overrides:r.overrides};return t.includes(Ie)&&Ee(i.program,s=>{let a=Kt(o,s);if(!a)return!1;let[c,{call:l}]=a;return l.callee.name!==x.inline&&!Ge(o,l)&&n.add(c.name),!1}),Ee(i.program,Gi.bind(null,o)),o.pending.length>0&&await Promise.all(o.pending),K(t,o.edits)}import{cwd as Ye}from"process";import{relative as Yi}from"@remotex-labs/xmap";function Yt(i,e=Ye()){if(i===void 0)return;if(!Array.isArray(i)){if(typeof i!="object"||i===null)throw new Error("Unsupported entry points format");return i}let t={};if(i.length<1)return t;if(typeof i[0]=="object"){for(let o of i)t[o.out]=o.in;return t}let r=Yi(Ye(),u.resolve(e)),n=r&&r!=="."?`${r}/`:"";for(let o of It(Ye(),i)){let s=n&&o.startsWith(n)?o.slice(n.length):o,a=s.lastIndexOf(".");t[a>s.lastIndexOf("/")+1?s.slice(0,a):s]=o}return t}var Jt=["banner","footer","define"],Qt=["warning","error","info"];import{parseErrorStack as Ji}from"@remotex-labs/xmap/parser.component";function Xt(i){if(i===null||typeof i!="object")return!1;let e=i.errors;if(!Array.isArray(e)||e.length===0)return!1;let t=e[0];return t!==null&&typeof t=="object"&&"detail"in t}function Je(i,e="",t=""){let r={detail:i,id:e,pluginName:t},n=Ji(i),o=n.stack[0];return r.text=n.message,o?.fileName&&o.line&&o.column&&(r.location={line:o.line,file:o.fileName,column:o.column,namespace:"file"}),r}var U=class i{constructor(e,t,r={}){this.name=e;this.events$=t;this.argv=r;i.instances.set(e,this),this.configUnsubscribe=Qe($).select(n=>({common:n.common,variant:n.variants?.[this.name]})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}name;events$;argv;static filesModel=Qe(h);static instances=new Map;configUnsubscribe;hooks=[];isDisposed=!1;typescriptModule;buildConfig;static has(e){return i.instances.has(e)}static get(){return i.instances.values()}async check(){let{metafile:e}=await Ke({...this.buildConfig.esbuild,plugins:void 0}),t={info:[],verbose:[],error:[],warning:[]};return this.diagnostics(this.typescriptModule.check(new Set(Object.keys(e.inputs))),t),t}async build(){if(this.isDisposed)throw new j(`Variant ${this.name} is disposed`);let e={info:[],verbose:[],error:[],warning:[]},t=await Ft({...this.buildConfig.esbuild,plugins:[this.lifecycle(e)],logLimit:0,logLevel:"silent"}).catch(()=>({}));return this.toResult(t,e)}dispose(){this.isDisposed=!0,this.configUnsubscribe?.(),this.typescriptModule?.dispose?.(),i.instances.delete(this.name)}[Symbol.dispose](){this.dispose()}collect(e,t,r,n){t?.length&&Rt(e,this.buildConfig.logOverride,t,r,n)}fail(e,t,r=this.name){e.error.push(Je(t instanceof Error?t:new Error(String(t)),"",r))}toResult(e,t){return Object.assign(e,{info:t.info,errors:t.error,verbose:t.verbose,warnings:t.warning})}async dispatch(e,t,r=()=>!1){for(let n of this.hooks)try{let o=await t(n);if(!o)continue;if(this.collect(e,o.errors,"error",n.name),this.collect(e,o.warnings,"warning",n.name),r(o))return o}catch(o){this.fail(e,o,n.name)}}async declarations(e){let{declaration:t}=this.buildConfig,r=e.options.entryPoints,n=(typeof t=="object"?t.outDir:void 0)??e.options.outdir;e.options.bundle?await this.typescriptModule.emitBundle(r,n):await this.typescriptModule.emit(r,n)}handleConfigChange({common:e,variant:t}){if(!t)return this.dispose();let r=this.typescriptModule,n=C({},e??{},t);this.typescriptModule=Qe(y,n.esbuild.tsconfig),n.esbuild.entryPoints=Yt(n.esbuild.entryPoints),n.logOverride??={},r?.dispose(),this.buildConfig=n,this.hooks=[...n.plugins??[],{name:this.name,...n.lifecycle}]}injectTextBlock(e,t){let r=this.buildConfig[t];if(!r)return;let n=e[t]??={};for(let[o,s]of Object.entries(r)){let a=typeof s=="function"?s(this.name,this.argv):s;a!=null&&(n[o]=ye(a))}}diagnostics(e,t,r=!0){for(let{category:n,code:o,message:s,file:a,line:c,column:l}of e){let f={text:s};o!==void 0&&(f.id=`TS${o}`),a&&(f.location={file:a,line:c,column:l});let p=Qt[n]??"verbose";f.detail={code:o,category:n,message:s},this.collect(t,[f],p==="error"&&!r?"warning":p,"typescript")}}async start(e,t){let{logs:r}=e;if(await this.dispatch(r,n=>n.onStart?.({context:e,esbuild:t})),this.buildConfig.types&&r.error.length<1){let n=this.buildConfig.types,o=typeof n=="object"?n.failOnError:!0;this.diagnostics(this.typescriptModule.check(e.stage.reachableFiles),e.logs,o)}return{errors:r.error}}async resolve(e,t){return await this.dispatch(e.logs,n=>n.onResolve?.({context:e,args:t}),()=>!0)??{errors:e.logs.error}}async load(e,t){let r=i.filesModel.resolve(t.path),n="default",o=i.filesModel.touch(r).snapshot?.text??"";try{let a=Zt(r,o,{sourceType:"module"});if(o=await Gt(a,r,o,e),!e.options.bundle){let c=Zt(r,o,{sourceType:"module"});o=St(c,r,o,this.typescriptModule)}}catch(a){this.fail(e.logs,a)}let s={};return await this.dispatch(e.logs,a=>a.onLoad?.({context:e,contents:o,loader:n,args:t}),a=>(s={...s,...a},n=a.loader??n,a.contents!==void 0&&(o=typeof a.contents=="string"?a.contents:Buffer.from(a.contents).toString()),!1)),{...s,contents:o,loader:n,errors:[],warnings:[]}}async end(e,t){this.collect(e.logs,t.errors.filter(n=>!n.pluginName),"error"),this.collect(e.logs,t.warnings.filter(n=>!n.pluginName),"warning");let r={context:e,duration:Date.now()-e.stage.startTime.getTime(),buildResult:this.toResult(t,e.logs)};if(e.logs.error.length<1)try{this.buildConfig.declaration&&await this.declarations(e)}catch(n){Je(n,"",this.name)}await this.dispatch(e.logs,async n=>{r.buildResult.errors.length<1&&await n.onSuccess?.(r),await n.onEnd?.(r)}),this.events$.next({...r,type:"end"})}async setup(e,t){let r=t.initialOptions;try{for(let o of Jt)this.injectTextBlock(r,o);let n=await this.buildDependencyMap();e.stage.reachableFiles=new Set(Object.values(n)),r.bundle||(r.entryPoints=n),e.stage.dropped=jt(e.stage.reachableFiles,r.define??{})}catch(n){Xt(n)&&n.errors?e.logs.error.push(...n.errors):this.fail(e.logs,n,"")}await this.dispatch(e.logs,n=>n.onSetup?.(e))}async buildDependencyMap(){let e=this.typescriptModule.config.options.rootDir,{metafile:t}=await Ke({...this.buildConfig.esbuild,plugins:void 0});return Object.fromEntries(Object.keys(t.inputs).map(r=>{let n=Qi(e,i.filesModel.resolve(r)),o=n.lastIndexOf(".");return[o>0?n.slice(0,o):n,r]}))}lifecycle(e){return{name:this.name,setup:async t=>{let r={logs:e,argv:this.argv,options:t.initialOptions,overrides:this.buildConfig.logOverride,variantName:this.name,stage:{startTime:new Date,dropped:new Set,reachableFiles:new Set}};t.onEnd(this.end.bind(this,r)),t.onStart(this.start.bind(this,r,t.esbuild)),t.onLoad({filter:/.*/},this.load.bind(this,r)),t.onResolve({filter:/.*/},this.resolve.bind(this,r)),await this.setup(r,t),this.events$.next({context:r,esbuild:t.esbuild,type:"start"})}}}};var Me=class{constructor(e,t={}){this.argv=t;this.config$.patch(e),this.config$.subscribe(this.parseVariants.bind(this))}argv;events$=new Zi;config$=Xi($);get pipe(){return this.events$.pipe.bind(this.events$)}get subscribe(){return this.events$.subscribe.bind(this.events$)}set configuration(e){this.config$.reload(e)}async build(e){let t=new Map(Array.from(U.get(),a=>[a.name,a])),r=new Map,n=Promise.withResolvers(),o=(a,c=[])=>{if(c.includes(a))throw new j(`Circular dependency detected: ${[...c,a].join(" \u2192 ")}`);if(!t.has(a))throw new j(`Variant "${c.at(-1)}" depends on "${a}", which is not a variant`);if(!r.has(a)){let l=this.getDependOn(a);r.set(a,Promise.all([n.promise,...l.map(f=>o(f,[...c,a]))]).then(([,...f])=>{let p=l.filter((S,d)=>Object.keys(f[d]?.metafile?.outputs??{}).length<1);return p.length?this.skipped(a,p):t.get(a).build()}))}return r.get(a)},s=Array.from(e?.filter(a=>t.has(a))??t.keys(),a=>o(a));return n.resolve(),Promise.all(s)}async typeChack(e){let t={};for(let r of U.get())(!e||e.includes(r.name))&&(t[r.name]=await r.check());return t}async reload(){y.reload()}parseVariants(e){if(!e)throw new j("Variants are not defined in the configuration");for(let t of Object.keys(e.variants??[]))U.has(t)||new U(t,this.events$,this.argv)}skipped(e,t){let r=t.map(c=>`"${c}"`).join(", "),n=[{id:"dependency-failed",text:`Variant "${e}" was not built, because ${r} failed`,notes:[],detail:void 0,location:null,pluginName:e}],o=this.config$.getValue().variants?.[e],s={info:[],verbose:[],error:n,warning:[]},a={info:s.info,verbose:s.verbose,errors:s.error,warnings:s.warning};return this.events$.next({type:"end",duration:0,context:{argv:this.argv,logs:s,options:o?.esbuild??{},overrides:o?.logOverride??{},variantName:e,stage:{startTime:new Date,dropped:new Set,reachableFiles:new Set}},buildResult:a}),a}getDependOn(e){return[this.config$.getValue().variants?.[e]?.dependOn??[]].flat()}};import{Injectable as en}from"@remotex-labs/xinject";import{Subject as tn}from"@remotex-labs/xobservable";import{resolve as rn,join as er,relative as nn}from"@remotex-labs/xmap";import{watch as on,realpathSync as sn,readdirSync as an,lstatSync as cn,statSync as ln}from"fs";var J=class extends tn{constructor(t,r){super();this.options=r;this.base=rn(t),this.matcher=se(this.options?.filter??[],{dot:this.options?.dot??!1})}options;base;matcher;watchers=new Map;pending=new Map;subscriptions=0;timer;subscribe(t,r,n){let o=super.subscribe(t,r,n);return++this.subscriptions===1&&this.start(),this.toUnsubscribe(()=>{o(),--this.subscriptions===0&&this.stop()})}get debounce(){return this.options?.debounce??150}start(){this.watch(this.base,this.ignored.bind(this),this.options?.recursive),this.options?.followSymlinks&&this.watchSymlinks(this.base)}stop(){this.timer&&clearTimeout(this.timer);for(let t of this.watchers.values())t.close();this.timer=void 0,this.pending.clear(),this.watchers.clear()}flush(){if(this.timer=void 0,this.pending.size===0)return;let t=Object.fromEntries(this.pending);this.pending.clear();try{this.next(t)}catch{}}watcherClose(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t))}watcherEvent(t,r){let n=nn(this.base,r),o=cn(r,{throwIfNoEntry:!1}),s=o?.isSymbolicLink()?ln(r,{throwIfNoEntry:!1}):o;if(o?.isSymbolicLink()){if(!s)return;t==="rename"&&this.watcherClose(r),s.isFile()&&this.matcher(r)?this.watch(r):s.isDirectory()&&this.options?.recursive&&this.watch(r,this.ignored.bind(this),!0)}if(!this.matcher(n))return;this.timer?this.timer.refresh():this.timer=setTimeout(this.flush.bind(this),this.debounce);let a;s?a=s.birthtimeMs===s.mtimeMs?0:1:(this.watcherClose(r),a=2),this.pending.set(n,{type:a,stats:s})}watch(t,r,n=!1){if(this.watchers.has(t)||this.ignored(t))return;let o=on(sn(t),{recursive:n,ignore:r},(s,a)=>{if(!a)return;let c=t.includes(a)?t:er(t,a);this.watcherEvent(s,c)});o.on("error",s=>{this.watcherClose(t),this.error(s)}),this.watchers.set(t,o)}ignored(t){return!!(!t||t.endsWith("~")||!this.options?.dot&&t&&t.split(/[/\\]/).some(r=>r.startsWith(".")))}watchSymlinks(t){let r=[t];for(;r.length;){let n=r.pop(),o;try{o=an(n,{withFileTypes:!0})}catch{continue}for(let s of o){let a=er(s.parentPath??n,s.name);this.ignored(a)||(s.isSymbolicLink()?this.watch(a,this.ignored.bind(this),this.options?.recursive):this.options?.recursive&&s.isDirectory()&&r.push(a))}}}};J=b([en({scope:"singleton"})],J);import{resolve as fn}from"path";import pn from"node:process";import{createRequire as un}from"module";import{dirname as dn}from"@remotex-labs/xmap";import{inject as Xe}from"@remotex-labs/xinject";async function tr(i,e,t={},r=!1){let n={exports:{config:{},default:{}}};return await Ce(i,{require:un(fn(e)),module:n,$argv:t},{filename:e},r),n.exports.config??n.exports.default??{}}async function Ze(i,e={}){let r=Xe(h).touch(i).snapshot?.text;if(!r)return{};let[n,o]=(await $e(r,i,{minify:!1,format:"cjs",outdir:dn(i),platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,minifyWhitespace:!0,minifyIdentifiers:!1})).outputFiles,s=Xe(O);Xe(u).addSourceMap(i,n.text,!0);let a=await tr(o.text,i,{},!0),c=s.enhancedParse(pn.argv,a.userArgv??{});Object.assign(e,c);let l=await tr(o.text,i,c);return C({},{watch:{filter:["**/*.{js,ts,json}","!**/*.d.ts"],recursive:!0}},l)}function gn(i,e){e.entryPoints&&(i.variants={argv:{esbuild:{entryPoints:e.entryPoints}}})}function ir(i,e){let t=i.common?.esbuild?.outdir??"dist",r=Object.values(i.variants??{});t&&i.watch?.filter?.push(`!${t}/**`);for(let n of r)e.types!==void 0&&(n.types=e.types),e.outdir!==void 0&&(n.esbuild.outdir=e.outdir),e.bundle!==void 0&&(n.esbuild.minify=e.bundle),e.minify!==void 0&&(n.esbuild.minify=e.minify),e.tsconfig!==void 0&&(n.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(n.esbuild.platform=e.platform),e.declaration!==void 0&&(n.declaration=e.declaration),e.failOnError!==void 0&&(n.types={failOnError:e.failOnError}),n.esbuild.outdir&&n.esbuild.outdir!==t&&i.watch?.filter?.push(`!${n.esbuild.outdir}/**`)}async function rr(i,e){e.clean&&mn("dist",{recursive:!0,force:!0}),await i.build(e.build)}async function hn(i,e,t){if(!((e.serve??!1)!==!1||i.serve?.start))return;let n=i.serve?.dir||e.serve||"dist",o=new we({...i.serve},n);o.subscribe(t.serverEvent.bind(t)),await o.start()}async function yn(i,e,t,r){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let o=et(h),s=o.touch(t.config).version;new J(process.cwd(),e.watch).subscribe(async c=>{if(o.refreshAll(),s!==o.touch(t.config).version){s=o.touch(t.config).version;let f=await Ze(t.config);ir(f,t),i.configuration=f}let l=Object.keys(c).length;await r.rebuild(`${l} ${l===1?"file":"files"} changed`)}),await ht(r)}async function vn(){console.log(st());let e=et(O).parseConfigFile(process.argv),t={},r=await Ze(e.config,t);gn(r,t),ir(r,t);let n=new Me(r,t),o=et(Y,rr.bind({},n,t));n.subscribe(o.buildEvent.bind(o)),t.typeCheck&&o.diagnostics(await n.typeChack(t.build)),await hn(r,t,o),await yn(n,r,t,o),await rr(n,t)}await vn();export{ir as applyCommandLineOverrides,gn as configureEntryPoints,hn as startServer,yn as startWatchMode};
57
+ `,a+1))o++,s=a+1;r.location={file:i.target,line:o,column:e-s},We(i.logs,i.overrides,r,t)}function E(i,e,t){return i.edits.push({start:e.start,end:e.end,text:t}),!0}function zt(i,e,t,r){let n={start:e.start,end:e.end,text:""};return i.edits.push(n),i.pending.push(Nt(i,t).then(o=>{n.text=r(o)},o=>{n.text=r("undefined"),qt(i,t.start,"error",{detail:o,id:"macro-inline",text:`${x.inline} failed: ${o?.message??String(o)}`})})),!0}function Ht(i){if(i.type!=="CallExpression"||i.callee.type!=="Identifier")return!1;let{name:e}=i.callee;if(e===x.inline)return i.arguments.length===1;if(e!==x.ifdef&&e!==x.ifndef||i.arguments.length!==2)return!1;let t=i.arguments[0];return t.type==="Literal"&&typeof t.value=="string"}function Ge(i,e){let t=e.arguments[0],r=t.type==="Literal"?String(t.value):"";return e.callee.name===x.ifdef===ke(i.defines,r)}function _t(i,e){return e.type==="CallExpression"&&e.callee.type==="Identifier"&&i.dropped.has(e.callee.name)}function Te(i,e){if(e){if(Ht(e))return{call:e,suffix:""};if(e.type==="TSAsExpression")return Te(i,e.expression);if(!(e.type!=="CallExpression"||!Ht(e.callee)))return{call:e.callee,suffix:i.code.slice(e.callee.end,e.end)}}}function Kt(i,e){let t=e.type==="ExportNamedDeclaration"?e.declaration:e;if(t?.type!=="VariableDeclaration"||t.declarations.length!==1)return;let{id:r,init:n}=t.declarations[0];if(r.type!=="Identifier")return;let o=Te(i,n);return o&&[r,o]}function Ki(i,e){let t=[],r=[],n=!1;for(let s of e.specifiers){let a=i.code.slice(s.start,s.end);s.type!=="ImportSpecifier"?r.push(a):i.dropped.has(s.local.name)?n=!0:t.push(a)}if(!n)return!1;let o=i.code.slice(e.source.start,e.source.end);return t.length>0&&r.push(`{ ${t.join(", ")} }`),r.length<1?E(i,e,`import ${o};`):E(i,e,`import ${r.join(", ")} from ${o};`)}function Gi(i,e){let{specifiers:t}=e,r=t.filter(({local:n})=>!i.dropped.has(n.type==="Literal"?n.value:n.name));return r.length===t.length?!1:r.length<1?E(i,e,""):E(i,e,`export { ${r.map(n=>i.code.slice(n.start,n.end)).join(", ")} };`)}function Ut(i,e){let t=Kt(i,e);if(!t)return!1;let[r,n]=t,{call:o,suffix:s}=n,a=e.type==="ExportNamedDeclaration"?"export ":"";return r.name.startsWith("$$")||qt(i,r.start,"warning",{id:"macro-prefix",text:`Macro '${r.name}' does not start with the '${"$$"}' prefix to avoid conflicts`}),o.callee.name===x.inline?zt(i,e,o,c=>`${a}const ${r.name} = ${c}${s};`):E(i,e,Ge(i,o)?At(i.code,r.name,n,a):"")}function Wt(i,e,t,r){let{call:n,suffix:o}=t;return n.callee.name===x.inline?zt(i,e,n,s=>r?"":`${s}${o}`):Ge(i,n)?E(i,e,Ot(i.code,t,r)):E(i,e,r?"":"undefined")}function Yi(i,e,t,r){switch(e.type){case"Identifier":return!i.dropped.has(e.name)||!t?!1:!(r==="key"||r==="property"?!("computed"in t)||!t.computed:Pt.has(r))&&E(i,e,"undefined");case"ImportDeclaration":return Ki(i,e);case"ExportNamedDeclaration":return Ut(i,e)?!0:e.source||e.specifiers.length<1?!1:Gi(i,e);case"VariableDeclaration":return Ut(i,e);case"ExpressionStatement":{if(_t(i,e.expression))return E(i,e,"");let n=Te(i,e.expression);return n!==void 0&&Wt(i,e,n,!0)}case"CallExpression":case"TSAsExpression":{if(_t(i,e))return E(i,e,"undefined");let n=Te(i,e);return n!==void 0&&Wt(i,e,n,!1)}}return!1}async function Gt(i,e,t,r){if(t.length<1||e.includes("node_modules"))return t;let{dropped:n}=r.stage;if(n.size<1&&!t.includes("$$"))return t;let o={target:e,dropped:n,code:t,logs:r.logs,edits:[],pending:[],defines:r.options.define??{},overrides:r.overrides};return t.includes(Ie)&&Ee(i.program,s=>{let a=Kt(o,s);if(!a)return!1;let[c,{call:l}]=a;return l.callee.name!==x.inline&&!Ge(o,l)&&n.add(c.name),!1}),Ee(i.program,Yi.bind(null,o)),o.pending.length>0&&await Promise.all(o.pending),K(t,o.edits)}import{cwd as Ye}from"process";import{relative as Ji}from"@remotex-labs/xmap";function Yt(i,e=Ye()){if(i===void 0)return;if(!Array.isArray(i)){if(typeof i!="object"||i===null)throw new Error("Unsupported entry points format");return i}let t={};if(i.length<1)return t;if(typeof i[0]=="object"){for(let o of i)t[o.out]=o.in;return t}let r=Ji(Ye(),u.resolve(e)),n=r&&r!=="."?`${r}/`:"";for(let o of It(Ye(),i)){let s=n&&o.startsWith(n)?o.slice(n.length):o,a=s.lastIndexOf(".");t[a>s.lastIndexOf("/")+1?s.slice(0,a):s]=o}return t}var Jt=["banner","footer","define"],Qt=["warning","error","info"];import{parseErrorStack as Qi}from"@remotex-labs/xmap/parser.component";function Xt(i){if(i===null||typeof i!="object")return!1;let e=i.errors;if(!Array.isArray(e)||e.length===0)return!1;let t=e[0];return t!==null&&typeof t=="object"&&"detail"in t}function Je(i,e="",t=""){let r={detail:i,id:e,pluginName:t},n=Qi(i),o=n.stack[0];return r.text=n.message,o?.fileName&&o.line&&o.column&&(r.location={line:o.line,file:o.fileName,column:o.column,namespace:"file"}),r}var U=class i{constructor(e,t,r={}){this.name=e;this.events$=t;this.argv=r;i.instances.set(e,this),this.configUnsubscribe=Qe($).select(n=>({common:n.common,variant:n.variants?.[this.name]})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}name;events$;argv;static filesModel=Qe(h);static instances=new Map;configUnsubscribe;hooks=[];isDisposed=!1;typescriptModule;buildConfig;static has(e){return i.instances.has(e)}static get(){return i.instances.values()}async check(){let{metafile:e}=await Ke({...this.buildConfig.esbuild,plugins:void 0}),t={info:[],verbose:[],error:[],warning:[]};return this.diagnostics(this.typescriptModule.check(new Set(Object.keys(e.inputs))),t),t}async build(){if(this.isDisposed)throw new j(`Variant ${this.name} is disposed`);let e={argv:this.argv,options:{},overrides:this.buildConfig.logOverride,variantName:this.name,logs:{info:[],error:[],verbose:[],warning:[]},stage:{startTime:new Date,dropped:new Set,reachableFiles:new Set}},t=await Ft({...this.buildConfig.esbuild,plugins:[this.lifecycle(e)],logLimit:0,logLevel:"silent"}).catch(()=>(e.stage.start||this.events$.next({context:e,type:"end",duration:Date.now()-e.stage.startTime.getTime(),buildResult:this.toResult({errors:[],warnings:[],metafile:void 0,outputFiles:void 0,mangleCache:void 0},e.logs)}),{}));return this.toResult(t,e.logs)}dispose(){this.isDisposed=!0,this.configUnsubscribe?.(),this.typescriptModule?.dispose?.(),i.instances.delete(this.name)}[Symbol.dispose](){this.dispose()}collect(e,t,r,n){t?.length&&Lt(e,this.buildConfig.logOverride,t,r,n)}fail(e,t,r=this.name){e.error.push(Je(t instanceof Error?t:new Error(String(t)),"",r))}toResult(e,t){return Object.assign(e,{info:t.info,errors:t.error,verbose:t.verbose,warnings:t.warning})}async dispatch(e,t,r=()=>!1){for(let n of this.hooks)try{let o=await t(n);if(!o)continue;if(this.collect(e,o.errors,"error",n.name),this.collect(e,o.warnings,"warning",n.name),r(o))return o}catch(o){this.fail(e,o,n.name)}}async declarations(e){let{declaration:t}=this.buildConfig,r=e.options.entryPoints,n=(typeof t=="object"?t.outDir:void 0)??e.options.outdir;e.options.bundle?await this.typescriptModule.emitBundle(r,n):await this.typescriptModule.emit(r,n)}handleConfigChange({common:e,variant:t}){if(!t)return this.dispose();let r=this.typescriptModule,n=C({},e??{},t);this.typescriptModule=Qe(y,n.esbuild.tsconfig),n.esbuild.entryPoints=Yt(n.esbuild.entryPoints),n.logOverride??={},r?.dispose(),this.buildConfig=n,this.hooks=[...n.plugins??[],{name:this.name,...n.lifecycle}]}injectTextBlock(e,t){let r=this.buildConfig[t];if(!r)return;let n=e[t]??={};for(let[o,s]of Object.entries(r)){let a=typeof s=="function"?s(this.name,this.argv):s;a!=null&&(n[o]=t!=="define"&&typeof a=="string"?a:ye(a))}}diagnostics(e,t,r=!0){for(let{category:n,code:o,message:s,file:a,line:c,column:l}of e){let f={text:s};o!==void 0&&(f.id=`TS${o}`),a&&(f.location={file:a,line:c,column:l});let p=Qt[n]??"verbose";f.detail={code:o,category:n,message:s},this.collect(t,[f],p==="error"&&!r?"warning":p,"typescript")}}async start(e,t){let{logs:r}=e;if(e.stage.start=!0,await this.dispatch(r,n=>n.onStart?.({context:e,esbuild:t})),this.buildConfig.types&&r.error.length<1){let n=this.buildConfig.types,o=typeof n=="object"?n.failOnError:!0;this.diagnostics(this.typescriptModule.check(e.stage.reachableFiles),e.logs,o)}return{errors:r.error}}async resolve(e,t){return await this.dispatch(e.logs,n=>n.onResolve?.({context:e,args:t}),()=>!0)??{errors:e.logs.error}}async load(e,t){let r=i.filesModel.resolve(t.path),n="default",o=i.filesModel.touch(r).snapshot?.text??"";try{let a=Zt(r,o,{sourceType:"module"});if(o=await Gt(a,r,o,e),!e.options.bundle){let c=Zt(r,o,{sourceType:"module"});o=St(c,r,o,this.typescriptModule)}}catch(a){this.fail(e.logs,a)}let s={};return await this.dispatch(e.logs,a=>a.onLoad?.({context:e,contents:o,loader:n,args:t}),a=>(s={...s,...a},n=a.loader??n,a.contents!==void 0&&(o=typeof a.contents=="string"?a.contents:Buffer.from(a.contents).toString()),!1)),{...s,contents:o,loader:n,errors:[],warnings:[]}}async end(e,t){this.collect(e.logs,t.errors.filter(n=>!n.pluginName),"error"),this.collect(e.logs,t.warnings.filter(n=>!n.pluginName),"warning");let r={context:e,duration:Date.now()-e.stage.startTime.getTime(),buildResult:this.toResult(t,e.logs)};if(e.logs.error.length<1)try{this.buildConfig.declaration&&await this.declarations(e)}catch(n){Je(n,"",this.name)}await this.dispatch(e.logs,async n=>{r.buildResult.errors.length<1&&await n.onSuccess?.(r),await n.onEnd?.(r)}),this.events$.next({...r,type:"end"})}async setup(e,t){let r=t.initialOptions;try{for(let o of Jt)this.injectTextBlock(r,o);let n=await this.buildDependencyMap();e.stage.reachableFiles=new Set(Object.values(n)),r.bundle||(r.entryPoints=n),e.stage.dropped=jt(e.stage.reachableFiles,r.define??{})}catch(n){Xt(n)&&n.errors?e.logs.error.push(...n.errors):this.fail(e.logs,n,"")}await this.dispatch(e.logs,n=>n.onSetup?.(e))}async buildDependencyMap(){let e=this.typescriptModule.config.options.rootDir,{metafile:t}=await Ke({...this.buildConfig.esbuild,plugins:void 0});return Object.fromEntries(Object.keys(t.inputs).map(r=>{let n=Xi(e,i.filesModel.resolve(r)),o=n.lastIndexOf(".");return[o>0?n.slice(0,o):n,r]}))}lifecycle(e){return{name:this.name,setup:async t=>{e.options=t.initialOptions,t.onEnd(this.end.bind(this,e)),t.onStart(this.start.bind(this,e,t.esbuild)),t.onLoad({filter:/.*/},this.load.bind(this,e)),t.onResolve({filter:/.*/},this.resolve.bind(this,e)),await this.setup(e,t),this.events$.next({context:e,esbuild:t.esbuild,type:"start"})}}}};var Me=class{constructor(e,t={}){this.argv=t;this.config$.patch(e),this.config$.subscribe(this.parseVariants.bind(this))}argv;events$=new en;config$=Zi($);get pipe(){return this.events$.pipe.bind(this.events$)}get subscribe(){return this.events$.subscribe.bind(this.events$)}set configuration(e){this.config$.reload(e)}async build(e){let t=new Map(Array.from(U.get(),a=>[a.name,a])),r=new Map,n=Promise.withResolvers(),o=(a,c=[])=>{if(c.includes(a))throw new j(`Circular dependency detected: ${[...c,a].join(" \u2192 ")}`);if(!t.has(a))throw new j(`Variant "${c.at(-1)}" depends on "${a}", which is not a variant`);if(!r.has(a)){let l=this.getDependOn(a);r.set(a,Promise.all([n.promise,...l.map(f=>o(f,[...c,a]))]).then(([,...f])=>{let p=l.filter((S,d)=>Object.keys(f[d]?.metafile?.outputs??{}).length<1);return p.length?this.skipped(a,p):t.get(a).build()}))}return r.get(a)},s=Array.from(e?.filter(a=>t.has(a))??t.keys(),a=>o(a));return n.resolve(),Promise.all(s)}async typeChack(e){let t={};for(let r of U.get())(!e||e.includes(r.name))&&(t[r.name]=await r.check());return t}async reload(){y.reload()}parseVariants(e){if(!e)throw new j("Variants are not defined in the configuration");for(let t of Object.keys(e.variants??[]))U.has(t)||new U(t,this.events$,this.argv)}skipped(e,t){let r=t.map(c=>`"${c}"`).join(", "),n=[{id:"dependency-failed",text:`Variant "${e}" was not built, because ${r} failed`,notes:[],detail:void 0,location:null,pluginName:e}],o=this.config$.getValue().variants?.[e],s={info:[],verbose:[],error:n,warning:[]},a={info:s.info,verbose:s.verbose,errors:s.error,warnings:s.warning};return this.events$.next({type:"end",duration:0,context:{argv:this.argv,logs:s,options:o?.esbuild??{},overrides:o?.logOverride??{},variantName:e,stage:{startTime:new Date,dropped:new Set,reachableFiles:new Set}},buildResult:a}),a}getDependOn(e){return[this.config$.getValue().variants?.[e]?.dependOn??[]].flat()}};import{Injectable as tn}from"@remotex-labs/xinject";import{Subject as rn}from"@remotex-labs/xobservable";import{resolve as nn,join as er,relative as on}from"@remotex-labs/xmap";import{watch as sn,realpathSync as an,readdirSync as cn,lstatSync as ln,statSync as fn}from"fs";var J=class extends rn{constructor(t,r){super();this.options=r;this.base=nn(t),this.matcher=se(this.options?.filter??[],{dot:this.options?.dot??!1})}options;base;matcher;watchers=new Map;pending=new Map;subscriptions=0;timer;subscribe(t,r,n){let o=super.subscribe(t,r,n);return++this.subscriptions===1&&this.start(),this.toUnsubscribe(()=>{o(),--this.subscriptions===0&&this.stop()})}get debounce(){return this.options?.debounce??150}start(){this.watch(this.base,this.ignored.bind(this),this.options?.recursive),this.options?.followSymlinks&&this.watchSymlinks(this.base)}stop(){this.timer&&clearTimeout(this.timer);for(let t of this.watchers.values())t.close();this.timer=void 0,this.pending.clear(),this.watchers.clear()}flush(){if(this.timer=void 0,this.pending.size===0)return;let t=Object.fromEntries(this.pending);this.pending.clear();try{this.next(t)}catch{}}watcherClose(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t))}watcherEvent(t,r){let n=on(this.base,r),o=ln(r,{throwIfNoEntry:!1}),s=o?.isSymbolicLink()?fn(r,{throwIfNoEntry:!1}):o;if(o?.isSymbolicLink()){if(!s)return;t==="rename"&&this.watcherClose(r),s.isFile()&&this.matcher(r)?this.watch(r):s.isDirectory()&&this.options?.recursive&&this.watch(r,this.ignored.bind(this),!0)}if(!this.matcher(n))return;this.timer?this.timer.refresh():this.timer=setTimeout(this.flush.bind(this),this.debounce);let a;s?a=s.birthtimeMs===s.mtimeMs?0:1:(this.watcherClose(r),a=2),this.pending.set(n,{type:a,stats:s})}watch(t,r,n=!1){if(this.watchers.has(t)||this.ignored(t))return;let o=sn(an(t),{recursive:n,ignore:r},(s,a)=>{if(!a)return;let c=t.includes(a)?t:er(t,a);this.watcherEvent(s,c)});o.on("error",s=>{this.watcherClose(t),this.error(s)}),this.watchers.set(t,o)}ignored(t){return!!(!t||t.endsWith("~")||!this.options?.dot&&t&&t.split(/[/\\]/).some(r=>r.startsWith(".")))}watchSymlinks(t){let r=[t];for(;r.length;){let n=r.pop(),o;try{o=cn(n,{withFileTypes:!0})}catch{continue}for(let s of o){let a=er(s.parentPath??n,s.name);this.ignored(a)||(s.isSymbolicLink()?this.watch(a,this.ignored.bind(this),this.options?.recursive):this.options?.recursive&&s.isDirectory()&&r.push(a))}}}};J=b([tn({scope:"singleton"})],J);import{resolve as pn}from"path";import un from"node:process";import{createRequire as dn}from"module";import{dirname as mn}from"@remotex-labs/xmap";import{inject as Xe}from"@remotex-labs/xinject";async function tr(i,e,t={},r=!1){let n={exports:{config:{},default:{}}};return await Ce(i,{require:dn(pn(e)),module:n,$argv:t},{filename:e},r),n.exports.config??n.exports.default??{}}async function Ze(i,e={}){let r=Xe(h).touch(i).snapshot?.text;if(!r)return{};let[n,o]=(await $e(r,i,{minify:!1,format:"cjs",outdir:mn(i),platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,minifyWhitespace:!0,minifyIdentifiers:!1})).outputFiles,s=Xe(O);Xe(u).addSourceMap(i,n.text,!0);let a=await tr(o.text,i,{},!0),c=s.enhancedParse(un.argv,a.userArgv??{});Object.assign(e,c);let l=await tr(o.text,i,c);return C({},{watch:{filter:["**/*.{js,ts,json}","!**/*.d.ts"],recursive:!0}},l)}function hn(i,e){e.entryPoints&&(i.variants={argv:{esbuild:{entryPoints:e.entryPoints}}})}function ir(i,e){let t=i.common?.esbuild?.outdir??"dist",r=Object.values(i.variants??{});t&&i.watch?.filter?.push(`!${t}/**`);for(let n of r)e.types!==void 0&&(n.types=e.types),e.outdir!==void 0&&(n.esbuild.outdir=e.outdir),e.bundle!==void 0&&(n.esbuild.minify=e.bundle),e.minify!==void 0&&(n.esbuild.minify=e.minify),e.tsconfig!==void 0&&(n.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(n.esbuild.platform=e.platform),e.declaration!==void 0&&(n.declaration=e.declaration),e.failOnError!==void 0&&(n.types={failOnError:e.failOnError}),n.esbuild.outdir&&n.esbuild.outdir!==t&&i.watch?.filter?.push(`!${n.esbuild.outdir}/**`)}async function rr(i,e){e.clean&&gn("dist",{recursive:!0,force:!0}),await i.build(e.build)}async function yn(i,e,t){if(!((e.serve??!1)!==!1||i.serve?.start))return;let n=i.serve?.dir||e.serve||"dist",o=new we({...i.serve},n);o.subscribe(t.serverEvent.bind(t)),await o.start()}async function vn(i,e,t,r){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let o=et(h),s=o.touch(t.config).version;new J(process.cwd(),e.watch).subscribe(async c=>{if(o.refreshAll(),s!==o.touch(t.config).version){s=o.touch(t.config).version;let f=await Ze(t.config);ir(f,t),i.configuration=f}let l=Object.keys(c).length;await r.rebuild(`${l} ${l===1?"file":"files"} changed`)}),await ht(r)}async function bn(){console.log(st());let e=et(O).parseConfigFile(process.argv),t={},r=await Ze(e.config,t);hn(r,t),ir(r,t);let n=new Me(r,t),o=et(Y,rr.bind({},n,t));n.subscribe(o.buildEvent.bind(o)),t.typeCheck&&o.diagnostics(await n.typeChack(t.build)),await yn(r,t,o),await vn(n,r,t,o),await rr(n,t)}await bn();export{ir as applyCommandLineOverrides,hn as configureEntryPoints,yn as startServer,vn as startWatchMode};
58
58
  //# sourceMappingURL=bash.js.map