@remotex-labs/xbuild 2.1.1 → 2.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bash.d.ts +153 -71
- package/dist/bash.js +51 -45
- package/dist/bash.js.map +4 -4
- package/dist/index.d.ts +152 -70
- package/dist/index.js +21 -20
- package/dist/index.js.map +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var
|
|
2
|
-
${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=I(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=
|
|
3
|
-
${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return E(process.cwd())}getDistDir(){return E(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new
|
|
4
|
-
`);return{getPositionWithCode:(s,a,l
|
|
5
|
-
`),source:e,name:null,startLine:
|
|
6
|
-
${e}: ${
|
|
7
|
-
`+
|
|
1
|
+
var Ot=Object.create;var we=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Ue=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),re=r=>{throw TypeError(r)};var Rt=(r,e,t)=>e in r?we(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var He=(r,e)=>we(r,"name",{value:e,configurable:!0});var O=r=>[,,,Ot(r?.[Ue("metadata")]??null)],qe=["class","method","getter","setter","accessor","field","value","get","set"],te=r=>r!==void 0&&typeof r!="function"?re("Function expected"):r,At=(r,e,t,i,n)=>({kind:qe[r],name:e,metadata:i,addInitializer:o=>t._?re("Already initialized"):n.push(te(o||null))}),Mt=(r,e)=>Rt(e,Ue("metadata"),r[3]),P=(r,e,t,i)=>{for(var n=0,o=r[e>>1],s=o&&o.length;n<s;n++)e&1?o[n].call(t):i=o[n].call(t,i);return i},R=(r,e,t,i,n,o)=>{var s,a,c,l,f,p=e&7,m=!!(e&8),h=!!(e&16),$=p>3?r.length+1:p?m?1:2:0,D=qe[p+5],j=p>3&&(r[$-1]=[]),be=r[$]||(r[$]=[]),x=p&&(!h&&!m&&(n=n.prototype),p<5&&(p>3||!h)&&Pt(p<4?n:{get[t](){return _e(this,o)},set[t](w){return ze(this,o,w)}},t));p?h&&p<4&&He(o,(p>2?"set ":p>1?"get ":"")+t):He(n,t);for(var ee=i.length-1;ee>=0;ee--)l=At(p,t,c={},r[3],be),p&&(l.static=m,l.private=h,f=l.access={has:h?w=>Nt(n,w):w=>t in w},p^3&&(f.get=h?w=>(p^1?_e:jt)(w,n,p^4?o:x.get):w=>w[t]),p>2&&(f.set=h?(w,Se)=>ze(w,n,Se,p^4?o:x.set):(w,Se)=>w[t]=Se)),a=(0,i[ee])(p?p<4?h?o:x[D]:p>4?void 0:{get:x.get,set:x.set}:n,l),c._=1,p^4||a===void 0?te(a)&&(p>4?j.unshift(a):p?h?o=a:x[D]=a:n=a):typeof a!="object"||a===null?re("Object expected"):(te(s=a.get)&&(x.get=s),te(s=a.set)&&(x.set=s),te(s=a.init)&&j.unshift(s));return p||Mt(r,n),x&&we(n,t,x),h?p^4?o:x:n};var Ce=(r,e,t)=>e.has(r)||re("Cannot "+t),Nt=(r,e)=>Object(e)!==e?re('Cannot use the "in" operator on this value'):r.has(e),_e=(r,e,t)=>(Ce(r,e,"read from private field"),t?t.call(r):e.get(r));var ze=(r,e,t,i)=>(Ce(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),jt=(r,e,t)=>(Ce(r,e,"access private method"),t);var Ie=new Map,We=new Map;function $t(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Dt(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Bt(r){return typeof r=="object"&&r!==null&&"useValue"in r}function A(r){return function(e){We.set(e,r||{})}}function Ee(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if($t(i))t.push(u(i.useClass,...Ee(i.providers)));else if(Dt(i))t.push(i.useFactory(...Ee(i.providers)));else if(Bt(i))t.push(i.useValue);else if(typeof i=="function")t.push(u(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function u(r,...e){if(Ie.has(r))return Ie.get(r);let t=We.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Ee(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Ie.set(r,n),n}function Ke(r){return e=>new B(t=>e.subscribe({next:i=>{try{let n=r(i);t.next?.(n)}catch(n){t.error?.(n)}},error:i=>t.error?.(i),complete:()=>t.complete?.()}))}function Ge(r=(e,t)=>e===t){return e=>new B(t=>{let i=!1,n;return e.subscribe({next:o=>{try{if(!i){n=o,i=!0,t.next?.(o);return}r(n,o)||(n=o,t.next?.(o))}catch(s){t.error?.(s)}},error:o=>t.error?.(o),complete:()=>t.complete?.()})})}var B=class{constructor(e){this.handler=e}subscribe(e,t,i){let n=this.createSafeObserver(e,t,i),o;try{o=this.handler(n)}catch(s){return n.error?.(s),()=>{}}return()=>{try{o?.()}catch(s){n.error?.(s)}}}pipe(...e){return e.length===0?this:e.reduce((t,i)=>i(t),this)}createSafeObserver(e,t,i){return typeof e=="function"?{next:e,error:t,complete:i}:e||{}}};var ie=class extends B{isCompleted=!1;observers=new Set;constructor(){super(e=>{if(this.isCompleted){e.complete?.();return}return this.observers.add(e),()=>this.observers.delete(e)})}next(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.next?.(e)}catch(n){t.push(n);try{i.error?.(n)}catch{}}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in next()`)}error(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.error?.(e)}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in error()`)}complete(){if(this.isCompleted)return;let e=[];for(let t of[...this.observers])try{t.complete?.()}catch(i){e.push(i)}if(this.observers.clear(),this.isCompleted=!0,e.length>0)throw new AggregateError(e,`${e.length} observer(s) failed in complete()`)}};var ne=class extends ie{lastValue;constructor(e){super(),this.lastValue=typeof e=="function"?e():e}get value(){return this.lastValue}subscribe(e,t,i){if(this.isCompleted)return()=>{};let n=this.createSafeObserver(e,t,i),o=super.subscribe(n);return n.next?.(this.lastValue),o}next(e){this.isCompleted||(this.lastValue=e,super.next(e))}};function ae(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function L(r,...e){if(!e.length)return r;let t=e.shift();if(ae(r)&&ae(t)){for(let i in t){let n=t[i],o=r[i];Array.isArray(n)&&Array.isArray(o)?Object.assign(r,{[i]:[...o,...n]}):ae(n)?Object.assign(r,{[i]:L(ae(o)?o:{},n)}):Object.assign(r,{[i]:n})}return L(r,...e)}return r}function ce(r,e,t=!0){return r===e||Object.is(r,e)?!0:r===null||e===null?!1:r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.source===e.source&&r.flags===e.flags:URL&&r instanceof URL&&e instanceof URL?r.href===e.href:typeof r=="object"&&typeof e=="object"?Vt(r,e,t):!1}function Lt(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function Vt(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>ce(o,e[s],t));let i=Object.keys(r),n=Object.keys(e);if(t&&i.length!==n.length)return!1;for(let o of i)if(!Lt(e,o)||!ce(r[o],e[o],t))return!1;return!0}var Ht="tsconfig.json",Xe=Object.freeze({verbose:!1,common:Object.freeze({types:!0,declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",tsconfig:Ht,absWorkingDir:process.cwd()})})});var Je,Te;Je=[A({scope:"singleton"})];var b=class{constructor(e=Xe){this.initialConfig=e;this.config$=new ne(L({},e))}config$;getValue(e){return e?e(this.config$.value):this.config$.value}subscribe(e){return this.config$.subscribe(e)}select(e){return this.config$.pipe(Ke(e),Ge((t,i)=>ce(t,i)))}patch(e){let t=L({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(L({},this.initialConfig,e))}};Te=O(null),b=R(Te,0,"ConfigurationService",Je,b),P(Te,1,b);import{cwd as Ut}from"process";import{readdirSync as qt}from"fs";import{matchesGlob as Fe}from"path";import*as oe from"path";import*as W from"path/posix";var _t=/\\/g,zt=/\/+/g;function E(r){if(!r)return"";let e=String(r);return e=e.replace(_t,"/"),e=e.replace(zt,"/"),e}function Ye(r){return W.normalize(E(r))}function v(...r){return W.join(...r.map(E))}function I(...r){return E(oe.resolve(...r))}function T(r){return E(oe.dirname(r))}function F(r,e){return W.relative(E(r),E(e))||"."}function Wt(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function le(r,e){for(let t of e)if(Fe(r,t))return!0;return!1}function Kt(r,e){let t=r+"/**";for(let i of e)if(Fe(r,i)||Fe(t,i))return!0;return!1}function $i(r,e,t){return le(r,e)?!le(r,t):!1}function Qe(r,e){let{include:t,exclude:i}=Wt(e),n=Object.create(null),s=Ut().length+1,a=r.length+1,c=i.length>0;function l(f){let p;try{p=qt(f,{withFileTypes:!0})}catch{return}let m=p.length;for(let h=0;h<m;h++){let $=p[h],D=v(f,$.name),j=D.slice(a);if($.isDirectory()){(!c||!Kt(j,i))&&l(D);continue}if(!(c&&le(j,i))&&le(j,t)){let be=D.slice(s),x=j.lastIndexOf("."),ee=x>0?j.slice(0,x):j;n[ee]=be}}}return l(r),n}var K=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};import{xterm as se}from"@remotex-labs/xansi/xterm.component";import Gt from"typescript";import{readFileSync as Xt,statSync as Jt}from"fs";var Ze,ke;Ze=[A({scope:"singleton"})];var y=class{resolvedPathCache=new Map;snapshotsByPath=new Map;clear(){this.snapshotsByPath.clear(),this.resolvedPathCache.clear()}getSnapshot(e){return this.snapshotsByPath.get(this.resolve(e))}getOrTouchFile(e){return this.snapshotsByPath.get(this.resolve(e))??this.touchFile(e)}getTrackedFilePaths(){return[...this.snapshotsByPath.keys()]}touchFile(e){let t=this.resolve(e),i=this.snapshotsByPath.get(t);i||(i={version:0,mtimeMs:0,contentSnapshot:void 0},this.snapshotsByPath.set(t,i));try{let o=Jt(t).mtimeMs;if(o===i.mtimeMs)return{...i};let s=Xt(t,"utf-8"),a=s?Gt.ScriptSnapshot.fromString(s):void 0;i.version++,i.mtimeMs=o,i.contentSnapshot=a}catch{(i.contentSnapshot!==void 0||i.version>0)&&(i.version++,i.mtimeMs=0,i.contentSnapshot=void 0)}return{...i}}resolve(e){let t=this.resolvedPathCache.get(e);if(t)return t;let i=I(e);return this.resolvedPathCache.set(e,i),i}};ke=O(null),y=R(ke,0,"FilesModel",Ze,y),P(ke,1,y);import{readFileSync as Yt}from"fs";import{SourceService as Qt}from"@remotex-labs/xmap";var et,Oe;et=[A({scope:"singleton"})];var C=class{filePath;distPath;rootPath;sourceMaps=new Map;constructor(){this.filePath=import.meta.filename,this.setSourceFile(this.filePath),this.rootPath=this.getRootDir(),this.distPath=this.getDistDir()}isFrameworkFile(e){let{source:t,sourceRoot:i}=e,n=t?.toLowerCase();return!!(t&&n.includes("xbuild")&&!n.includes("xbuild.config")||i&&i.includes("xBuild"))}getSourceMap(e){if(e=I(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=I(t);try{return this.initializeSourceMap(e,i)}catch(n){throw new Error(`Failed to initialize SourceService: ${i}
|
|
2
|
+
${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=I(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=Yt(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t}
|
|
3
|
+
${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return E(process.cwd())}getDistDir(){return E(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Qt(e,t);this.sourceMaps.set(t,i)}};Oe=O(null),C=R(Oe,0,"FrameworkService",et,C),P(Oe,1,C);import{parseErrorStack as tt}from"@remotex-labs/xmap/parser.component";import{highlightCode as Zt}from"@remotex-labs/xmap/highlighter.component";import{Bias as er}from"@remotex-labs/xmap";import{formatErrorCode as tr}from"@remotex-labs/xmap/formatter.component";var rr=/\s{2,}/g,ir=/^https?:\/\//,nr=/^file:\/\//;function or(r){return r instanceof Error?tt(r):r.detail instanceof Error?tt(r.detail):r.location?{name:"esBuildMessage",message:r.text??"",rawStack:"",stack:[{source:`@${r.location.file}`,line:r.location.line,column:r.location.column,fileName:r.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:r.text??"",rawStack:""}}function sr(r){let e=r.fileName??"",t=this.framework.getSourceMap(e);if(t)return t;let i=this.files.getOrTouchFile(e),n=i?.contentSnapshot?.text;if(!i||!n)return null;let o=n.split(`
|
|
4
|
+
`);return{getPositionWithCode:(s,a,c,l)=>{let f=l?.linesBefore??3,p=l?.linesAfter??3,m=Math.max(s-f,0),h=Math.min(s+p,o.length);return{line:s,column:a+1,code:o.slice(m,h).join(`
|
|
5
|
+
`),source:e,name:null,startLine:m,endLine:h,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function ar(r){return tr({...r,code:Zt(r.code)},{color:se.brightPink})}function Pe(r){let e=r.fileName;if(e?.includes(this.framework.rootPath)&&(e=F(this.framework.rootPath,e)),!e)return r.source??"";let t=r.line&&r.column?se.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${se.darkGray(e)} ${t}`.replace(rr," ").trim()}function cr(r,e){let{source:t,sourceRoot:i,line:n}=e;if(!t)return r.fileName?r.fileName.replace(nr,""):"";let o=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(o>0)return`${t.substring(o)}#L${n}`;if(ir.test(t))return`${t}#L${n}`;if(i){let s=F(T(this.framework.distPath),v(this.framework.distPath,t));return`${i}${s}#L${n}`}return`${t}#L${n}`}function lr(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=ar(e)),Pe.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:cr.call(this,r,e)})}function pr(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=sr.call(this,r);if(!t)return Pe.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,er.LOWER_BOUND,e);return i?!this.withFrameworkFrames&&this.framework.isFrameworkFile(i)?"":(this.lineOffset&&(i.line+=this.lineOffset,i.startLine+=this.lineOffset,i.endLine+=this.lineOffset),this.line=i.line,this.column=i.column,lr.call(this,r,i)):Pe.call(this,r)}function G(r,e,t=0){let i=u(b).getValue(a=>a.verbose)??!1,n={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(y),framework:u(C),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:or(r).stack.map(a=>pr.call(n,a,e)).filter(Boolean),code:n.code,line:n.line??0,column:n.column??0,source:n.source,formatCode:n.formatCode}}function X(r,e,t,i=[]){let n=[`
|
|
6
|
+
${e}: ${se.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(`
|
|
7
|
+
`+se.gray(o.text));return r.formatCode&&n.push(`
|
|
8
8
|
|
|
9
9
|
${r.formatCode}`),r.stacks.length&&n.push(`
|
|
10
10
|
|
|
11
11
|
Enhanced Stack Trace:
|
|
12
12
|
${r.stacks.join(`
|
|
13
13
|
`)}
|
|
14
|
-
`),n.join("")}var S=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=
|
|
14
|
+
`),n.join("")}var S=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=G(e,t),this.formattedStack=X(this.errorMetadata,e.name,e.message)}};var _=class extends S{constructor(e){super(e.text??"","esBuildError"),this.errorMetadata=G(e,{withFrameworkFrames:!0}),this.stack=X(this.errorMetadata,this.name,this.message,e.notes)}};var J=class r extends S{constructor(t,i){if(t instanceof S)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
|
|
15
15
|
${t}
|
|
16
|
-
`}return this.formattedStack||this.stack}};function
|
|
16
|
+
`}return this.formattedStack||this.stack}};function fr(r){return r instanceof S?r:r.detail instanceof S||r.detail instanceof K?r.detail:r.detail&&("errors"in r.detail||r.detail instanceof AggregateError)?new J(r.detail,{withFrameworkFrames:!0}):r.detail instanceof Error?new J(r.detail,{withFrameworkFrames:!0}):r.location?new _(r):new J(new Error(r.text))}function pe(r=[],e){for(let t of r)e.push(fr(t))}function Re(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return pe(r.errors,e.errors),pe(r.warnings,e.warnings),e}function Y(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as ot from"http";import*as st from"https";import{extname as it}from"path";import{readFileSync as nt}from"fs";var rt=`<!doctype html>
|
|
17
17
|
<html lang="en">
|
|
18
18
|
<head>
|
|
19
19
|
<meta charset="utf-8"/>
|
|
@@ -331,27 +331,28 @@ ${t}
|
|
|
331
331
|
});
|
|
332
332
|
</script>
|
|
333
333
|
</html>
|
|
334
|
-
`;import{xterm as
|
|
334
|
+
`;import{xterm as dr}from"@remotex-labs/xansi/xterm.component";function z(){return dr.lightCoral("[xBuild]")}import{readdir as mr,stat as gr,readFile as hr}from"fs/promises";import{xterm as fe}from"@remotex-labs/xansi/xterm.component";var Ae=class{constructor(e,t){this.config=e;this.rootDir=I(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(C);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(z(),fe.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(z(),fe.dim("Server stopped.")),this.server=void 0}async restart(){console.log(z(),fe.burntOrange("Restarting server...")),await this.stop(),await this.start()}setActualPort(){if(this.config.port===0){let e=this.server.address();e&&typeof e=="object"&&e.port&&(this.config.port=e.port)}}startHttpServer(){return new Promise(e=>{this.server=ot.createServer((t,i)=>{this.handleRequest(t,i,()=>this.defaultResponse(t,i))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`http://${this.config.host}:${this.config.port}`}),e()})})}startHttpsServer(){return new Promise(e=>{let t={key:nt(this.config.key??v(this.framework.distPath,"..","certs","server.key")),cert:nt(this.config.cert??v(this.framework.distPath,"..","certs","server.crt"))};this.server=st.createServer(t,(i,n)=>{this.handleRequest(i,n,()=>this.defaultResponse(i,n))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`}),e()})})}handleRequest(e,t,i){try{this.config.verbose&&console.log(`${z()} Request ${fe.lightCoral(e.url?.toString()??"")}`),this.config.onRequest?this.config.onRequest(e,t,i):i()}catch(n){this.sendError(t,n)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",cjs:"application/javascript",mjs:"application/javascript",ts:"text/plain",map:"application/json",json:"application/json",png:"image/png",jpg:"image/jpeg",gif:"image/gif",txt:"text/plain"}[e]||"application/octet-stream"}async defaultResponse(e,t){let i=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",n=v(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await gr(n);o.isDirectory()?await this.handleDirectory(n,i,t):o.isFile()&&await this.handleFile(n,t)}catch(o){let s=o.message;s.includes("favicon")||console.log(z(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await mr(e)).map(l=>{let f=v(t,l),p=it(l).slice(1)||"folder";return p==="folder"?`
|
|
335
335
|
<a href="/${f}" class="folder-row">
|
|
336
336
|
<div class="icon"><i class="fa-solid fa-folder"></i></div>
|
|
337
|
-
<div class="meta"><div class="name">${
|
|
337
|
+
<div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
|
|
338
338
|
</a>
|
|
339
339
|
`:`
|
|
340
340
|
<a href="/${f}" class="file-row">
|
|
341
341
|
<div class="icon"><i class="fa-solid fa-file-code"></i></div>
|
|
342
|
-
<div class="meta"><div class="name">${
|
|
342
|
+
<div class="meta"><div class="name">${l}</div><div class="sub">${p}</div></div>
|
|
343
343
|
</a>
|
|
344
|
-
`}).join("");o?o=`<div class="list">${o}</div>`:o='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(
|
|
344
|
+
`}).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=rt.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=it(e).slice(1)||"txt",n=this.getContentType(i),o=await hr(e);t.writeHead(200,{"Content-Type":n}),t.end(o)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(z(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as at}from"path";import{stat as vr,watch as yr}from"fs/promises";var Me=class{excludes;include;debounceTimer=null;framework=u(C);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=yr(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Ye(n);if(o.endsWith("~")||!this.include.some(a=>at(o,a))||this.excludes.some(a=>at(o,a)))continue;let s=v(this.framework.rootPath,o);try{if(!(await vr(s)).isFile())continue}catch{}t.add(o),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};var M=class extends S{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as jr}from"esbuild";import{writeFile as $r,mkdir as Dr}from"fs/promises";import d from"typescript";import xr from"typescript";var br=/^#!.*(\r?\n)?/,Sr=/export {};\n?/g,wr=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,Cr=/^export\s+(?:default\s+)?/gm,Ir=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function Er(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(br,""):r}function Tr(r){return r.includes("export {}")?r.replace(Sr,""):r}function Fr(r){return r=r.replace(Ir,""),r.replace(wr,"$1")}function ct(r){return r.replace(Cr,"")}function kr(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function ue(r){return kr(r)&&(r=Er(r),r=Tr(r),r=Fr(r)),r}function Ne(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||T(r),s=i||T(r),c=F(s,r).replace(/\.tsx?$/,".d.ts"),l=xr.sys.resolvePath(`${o}/${c}`);return E(l)}var lt,je;lt=[A({scope:"singleton"})];var U=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(y);constructor(){this.printer=d.createPrinter({newLine:d.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!d.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(d.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(d.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=d.factory.createNodeArray(n),s=this.printer.printList(d.ListFormat.MultiLine,o,e),a=ct(ue(s));for(let c of i)if(c.includes(" as ")){let[l,f]=c.split(" as ");a=a.replace(new RegExp(`\\b${f}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:n,moduleSpecifier:o}=e;if(!n||!o)return;let s=this.resolveModule(o,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:f}=n;if(!f)return;d.isNamespaceImport(f)?i.push(f.name.text):d.isNamedImports(f)&&this.addNamedElements(i,f.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:l}=n;l&&(d.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:d.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(d.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}d.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};je=O(null),U=R(je,0,"GraphModel",lt,U),P(je,1,U);import V from"typescript";import{mkdir as Or,writeFile as Pr}from"fs/promises";var pt=`/**
|
|
345
345
|
* This file was automatically generated by xBuild.
|
|
346
346
|
* DO NOT EDIT MANUALLY.
|
|
347
347
|
*/
|
|
348
|
-
`;var de=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(
|
|
349
|
-
`)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[
|
|
348
|
+
`;var de=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(U);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let n=this.languageHostService.getCompilationSettings();t&&(n={...n,outDir:t}),await Promise.all(Object.entries(e).map(async([o,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=v(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Or(T(i),{recursive:!0}),await Pr(i,o,"utf-8")}async getBundleContent(e,t){let i=new Set,n=new Set([e]),o=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let f=t.getSourceFile(l);if(!f)continue;let p=this.graphModel.scan(f,this.languageService,this.languageHostService);if(o.add(p),a.has(l)){n.add(p);for(let m of p.internalExports.star)a.add(m)}for(let m of p.internalDeps)i.has(m)||s.push(m);c+=p.content}return c+=e.content,this.parseContent(c,o,n)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[n,o]of Object.entries(i.externalImports.default)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});let s=t.get(n);s.default||(s.default=o)}for(let[n,o]of Object.entries(i.externalImports.named)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});for(let s of o)t.get(n).named.add(s)}for(let[n,o]of Object.entries(i.externalImports.namespace))t.has(o)||t.set(o,{named:new Set,namespace:new Map}),t.get(o).namespace.set(n,o)}return t}generateImportStatements(e){let t=[];for(let[i,{default:n,named:o,namespace:s}]of e){let a=[];if(n&&a.push(n),o.size>0&&a.push(`{ ${Array.from(o).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let n=[...i.internalExports.exports],o=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(o.push(...c.declarations),o.push(`const ${s} = { ${c.exports.join(", ")} };`),n.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);n.push(...a.exports),o.push(...a.declarations)}return{exports:n,declarations:o}}collectBundleExports(e){let t=[],i=[],n=[];for(let o of e){t.push(...o.internalExports.exports);for(let[s,a]of Object.entries(o.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of o.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(o.externalExports.namespace))n.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(o.externalExports.exports))n.push(`export { ${a.join(`,
|
|
349
|
+
`)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[pt],o=this.collectExternalImports(t),s=this.generateImportStatements(o);n.push(...s),s.length>0&&n.push("");let{exports:a,declarations:c,externalExports:l}=this.collectBundleExports(i);if(c.length>0&&(n.push(...c),n.push("")),n.push(e),a.length>0){let f=Array.from(new Set(a)).sort();n.push(`export {
|
|
350
350
|
${f.join(`,
|
|
351
351
|
`)}
|
|
352
|
-
};`)}return
|
|
353
|
-
`)}};import{mkdir as
|
|
354
|
-
`)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};je=O(null),N=R(je,0,"TypescriptService",lt,N),P(je,1,N);var Q=N;import{cwd as De}from"process";import{build as pt}from"esbuild";var Rr={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function ft(r,e,t={}){return await pt({absWorkingDir:De(),...Rr,...t,stdin:{loader:"ts",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ut(r,e={}){try{return await pt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(J(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw pe(t.errors,i.errors),i}throw t}}function dt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Je(r,e)),t}else if(e&&typeof e=="object")return e;throw new M("Unsupported entry points format")}var he=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new M(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new Q(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ar(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(J(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?L({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new W("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Nr(e,{recursive:!0}),await Mr(v(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new M(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new M("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=dt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new Q(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await ut(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=F(this.typescriptModule.config.options.rootDir,I(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as jr}from"fs/promises";var ve=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(y);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=I(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await jr(s,"utf8");for(let l of this.loadHooks.values()){let c=await l({contents:i,loader:n,args:e,...t});c&&(c.contents!==void 0&&(i=c.contents),c.loader&&(n=c.loader),c.errors&&o.errors.push(...c.errors),c.warnings&&o.warnings.push(...c.warnings))}return{contents:i,loader:n,...o}}};import h from"typescript";import H from"typescript";var Dr="$$ifdef";function Br(r,e,t,i=!1){let n=i?"export function ":"function ";return H.isArrowFunction(e)||H.isFunctionExpression(e)?$r(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function $r(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Lr(e,t);return`${i}${r}(${n})${o} ${s}`}function Lr(r,e){let t=r.body.getText(e);return H.isArrowFunction(r)&&!H.isBlock(r.body)?`{ return ${t}; }`:t}function Vr(r,e){return H.isArrowFunction(r)||H.isFunctionExpression(r)?`(${r.getText(e)})()`:`(() => { return ${r.getText(e)}; })()`}function mt(r,e,t){let i=r in t&&!!t[r];return e===Dr===i}function gt(r,e,t,i){let[n,o]=e.arguments;if(!H.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!mt(a,s,i.defines))return"";let l=r.name.getText(i.sourceFile);return Br(l,o,i.sourceFile,t)}function ht(r,e,t){let[i,n]=r;if(!H.isStringLiteral(i))return!1;let o=i.text;return mt(o,e,t.defines)?Vr(n,t.sourceFile):""}import k from"typescript";import{createRequire as zr}from"module";var ye=class extends S{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=K(e,{},t),this.stack=G(this.errorMetadata,this.name,this.message)}};import{Script as Hr,createContext as _r}from"vm";async function vt(r,e={},t={}){let i=new Hr(r,t),n=_r(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function yt(r,e,t){let[i,n]=(await ft(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=zr(e.sourceFile.fileName),a=await vt(n.text,Ur(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){qr(o,e,i.text,t)}return"undefined"}function Ur(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:T(r),__filename:r}}function qr(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(C).setSource(t,e.sourceFile.fileName);let s=new ye(r,o);e.errors.push({text:s.message,detail:s})}function Wr(r,e){let t=null,i=n=>{if(!t){if(k.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}k.isVariableStatement(n)&&(t=Kr(n,r),t)||k.forEachChild(n,i)}};return i(e),t}function Kr(r,e){for(let t of r.declarationList.declarations)if(k.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(k.isArrowFunction(t.initializer)||k.isFunctionExpression(t.initializer)))return t.initializer;return null}function xt(r){return`module.exports = (${r})();`}function Gr(r){return r&k.NodeFlags.Const?"const":r&k.NodeFlags.Let?"let":"var"}function bt(r,e){return r?k.isIdentifier(r)?Xr(r,e):k.isArrowFunction(r)||k.isFunctionExpression(r)?{node:r,data:xt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xr(r,e){let t=Wr(r.text,e.sourceFile);return t?{node:t,data:xt(t.getText(e.sourceFile))}:(Jr(r.text,e,r),{data:"",node:r})}function Jr(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function St(r,e,t,i,n){let o=t.arguments[0],s=bt(o,n);if(!s)return!1;let a=await yt(s.data,n,s.node),l=Gr(e.declarationList.flags),c=i?"export ":"",f=r.name.getText(n.sourceFile);return`${c}${l} ${f} = ${a};`}async function Be(r,e){let t=r[0],i=bt(t,e);return i?yt(i.data,e,i.node):!1}var Yr=/\.(ts|js)$/,D=["$$ifdef","$$ifndef","$$inline"];async function Qr(r,e,t){for(let i of r.declarationList.declarations){let n=i.initializer;if(!n||!h.isCallExpression(n)||!h.isIdentifier(n.expression))continue;let o=n.expression.text;if(!D.includes(o))continue;let s=o==D[2]?1:2;if(!D.includes(o))continue;if(n.arguments.length<s||n.arguments.length>s)throw new Error(`Invalid macro call: ${o} with ${n.arguments.length} arguments`);let a=r.modifiers?.some(c=>c.kind===h.SyntaxKind.ExportKeyword)??!1,l=!1;o===D[2]?l=await St(i,r,n,a,t):l=gt(i,n,a,t),l!==!1&&e.add({replacement:l,end:r.getEnd(),start:r.getStart(t.sourceFile)})}}async function Zr(r,e,t){let i=r.expression;if(!h.isIdentifier(i.expression))return;let n=i.expression.text,o=n==D[2]?1:2;if(!D.includes(n))return;if(i.arguments.length<o||i.arguments.length>o)throw new Error(`Invalid macro call: ${n} with ${i.arguments.length} arguments`);let s=!1;n==D[2]?s=await Be(i.arguments,t):s=ht(i.arguments,n,t),s!==!1&&e.add({replacement:s,end:r.getEnd(),start:r.getStart(t.sourceFile)})}async function ei(r){let e=new Set,t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let n=[r.sourceFile];for(;n.length>0;){let s=n.pop(),a=s?.kind;if(!a)continue;if(t.size>0){if(a===h.SyntaxKind.CallExpression){let c=s;h.isIdentifier(c.expression)&&t.has(c.expression.text)&&e.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===h.SyntaxKind.Identifier){let c=s;if(t.has(c.text)){let f=s.parent??s;if(f&&!h.isImportSpecifier(f)&&!h.isExportSpecifier(f)){let p=f?.getText(r.sourceFile);(!h.isCallExpression(f)||f.expression!==s)&&(!p||D.every(g=>!p.includes(g)))&&e.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}if(i){if(a===h.SyntaxKind.VariableStatement)await Qr(s,e,r);else if(a===h.SyntaxKind.ExpressionStatement){let c=s;h.isCallExpression(c.expression)&&await Zr(c,e,r)}else if(a===h.SyntaxKind.CallExpression){let c=s;if(h.isIdentifier(c.expression)&&c.expression.text===D[2]){let f=s.parent;if(!f||!h.isVariableDeclaration(f)&&!h.isExpressionStatement(f)){let p=await Be(c.arguments,r);p!==!1&&e.add({replacement:p,end:s.getEnd(),start:s.getStart(r.sourceFile)})}}}}let l=s.getChildren(r.sourceFile);for(let c=l.length-1;c>=0;c--)n.push(l[c])}if(e.size===0)return r.contents;let o=Array.from(e);o.sort((s,a)=>a.start-s.start);for(let{start:s,end:a,replacement:l}of o)r.contents=r.contents.slice(0,s)+l+r.contents.slice(a);return r.contents}async function wt(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Yr.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let l=o.toString(),c={stage:n,errors:[],contents:l,warnings:[],defines:r.config.define??{},sourceFile:a};return a&&(l=await ei(c)),r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var Ct="$$",It=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*['"]([^'"]+)['"]/g;function ti(r,e,t,i){let n=1;for(let o=0;o<i;o++)r[o]===`
|
|
355
|
-
`&&n++;
|
|
356
|
-
`,
|
|
352
|
+
};`)}return l.length>0&&n.push(...l),n.join(`
|
|
353
|
+
`)}};import{mkdir as Rr,writeFile as Ar}from"fs/promises";import{xterm as Mr}from"@remotex-labs/xansi/xterm.component";var me=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Mr.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=Ne(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=Ne(e.fileName,t);n=ue(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await Rr(T(o),{recursive:!0}),await Ar(o,n,"utf8")}};import Q from"typescript";var ge=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Q.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=Q.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(y);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Q.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return Q.getDefaultLibFilePath(e)}getScriptVersion(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.version.toString():"0"}hasScriptSnapshot(e){return this.trackFiles.has(this.filesCache.resolve(e))}getScriptSnapshot(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.contentSnapshot:this.touchFile(e).contentSnapshot}resolveModuleName(e,t){return Q.resolveModuleName(e,t,this.compilerOptions,Q.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),c=F(t,a);return n.replace(o,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var ft,$e;ft=[A({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new me(n,i),this.bundlerService=new de(n,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=N.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=N.serviceCache.get(e);t&&(t.refCount--,N.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=N.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new ge(e.options),i=V.createLanguageService(t,V.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,n),n}parseConfig(){let e=V.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...V.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:V.ScriptTarget.ESNext,module:V.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:V.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:V.flattenDiagnosticMessageText(e.messageText,`
|
|
354
|
+
`)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};$e=O(null),N=R($e,0,"TypescriptService",ft,N),P($e,1,N);var Z=N;import{cwd as De}from"process";import{build as ut}from"esbuild";var Nr={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function dt(r,e,t={}){return await ut({absWorkingDir:De(),...Nr,...t,stdin:{loader:"ts",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function mt(r,e={}){try{return await ut({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(Y(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw pe(t.errors,i.errors),i}throw t}}function gt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Qe(r,e)),t}else if(e&&typeof e=="object")return e;throw new M("Unsupported entry points format")}var he=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new M(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new Z(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await jr(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(Y(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?L({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new K("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Dr(e,{recursive:!0}),await $r(v(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new M(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new M("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=gt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new Z(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await mt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=F(this.typescriptModule.config.options.rootDir,I(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Br}from"fs/promises";var ve=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(y);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=I(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await Br(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import g from"typescript";import{highlightCode as Ct}from"@remotex-labs/xmap/highlighter.component";import H from"typescript";var Lr="$$ifdef";function Vr(r,e,t,i=!1){let n=i?"export function ":"function ";return H.isArrowFunction(e)||H.isFunctionExpression(e)?Hr(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Hr(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=_r(e,t);return`${i}${r}(${n})${o} ${s}`}function _r(r,e){let t=r.body.getText(e);return H.isArrowFunction(r)&&!H.isBlock(r.body)?`{ return ${t}; }`:t}function zr(r,e,t="",i="();"){return H.isArrowFunction(r)||H.isFunctionExpression(r)?`${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function ht(r,e,t){let i=r in t&&!!t[r];return e===Lr===i}function vt(r,e,t,i){let[n,o]=e.arguments;if(!H.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!ht(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Vr(c,o,i.sourceFile,t)}function ye(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!H.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!ht(a,c,e.defines))return"";let l="",f=t?.name.getText(e.sourceFile);return f&&(l=i?`export const ${f} = `:`const ${f} = `),zr(s,e.sourceFile,l,n)}import k from"typescript";import{createRequire as Wr}from"module";var xe=class extends S{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=G(e,{},t),this.stack=X(this.errorMetadata,this.name,this.message)}};import{Script as Ur,createContext as qr}from"vm";async function yt(r,e={},t={}){let i=new Ur(r,t),n=qr(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function xt(r,e,t){let[i,n]=(await dt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=Wr(e.sourceFile.fileName),a=await yt(n.text,Kr(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){Gr(o,e,i.text,t)}return"undefined"}function Kr(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:T(r),__filename:r}}function Gr(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(C).setSource(t,e.sourceFile.fileName);let s=new xe(r,o);e.errors.push({text:s.message,detail:s})}function Xr(r,e){let t=null,i=n=>{if(!t){if(k.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}k.isVariableStatement(n)&&(t=Jr(n,r),t)||k.forEachChild(n,i)}};return i(e),t}function Jr(r,e){for(let t of r.declarationList.declarations)if(k.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(k.isArrowFunction(t.initializer)||k.isFunctionExpression(t.initializer)))return t.initializer;return null}function bt(r){return`module.exports = (${r})();`}function Yr(r){return r&k.NodeFlags.Const?"const":r&k.NodeFlags.Let?"let":"var"}function St(r,e){return r?k.isIdentifier(r)?Qr(r,e):k.isArrowFunction(r)||k.isFunctionExpression(r)?{node:r,data:bt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Qr(r,e){let t=Xr(r.text,e.sourceFile);return t?{node:t,data:bt(t.getText(e.sourceFile))}:(Zr(r.text,e,r),{data:"",node:r})}function Zr(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function wt(r,e,t,i,n){let o=t.arguments[0],s=St(o,n);if(!s)return!1;let a=await xt(s.data,n,s.node),c=Yr(e.declarationList.flags),l=i?"export ":"",f=r.name.getText(n.sourceFile);return`${l}${c} ${f} = ${a};`}async function Be(r,e){let t=r[0],i=St(t,e);return i?xt(i.data,e,i.node):!1}var ei=/\.(ts|js)$/,q=["$$ifdef","$$ifndef","$$inline"];function Le(r,e){return q.some(t=>r.getText(e).includes(t))}function It(r){return r===q[2]?1:2}async function ti(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.initializer;if(!a||(g.isCallExpression(a)&&g.isIdentifier(a.expression)?s=a:g.isCallExpression(a)&&g.isCallExpression(a.expression)&&g.isIdentifier(a.expression.expression)?(s=a.expression,o=`(${a.arguments.map(p=>p.getText(t.sourceFile)).join(", ")})`):g.isAsExpression(a)&&g.isCallExpression(a.expression)&&g.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(s.arguments.length!==It(c)){let{line:f,character:p}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new _({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:f+1,column:p}})}let l=r.modifiers?.some(f=>f.kind===g.SyntaxKind.ExportKeyword)??!1;c===q[2]?i=await wt(n,r,s,l,t):o?i=ye(s,t,n,l,o):i=vt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return!!i}async function ri(r,e,t){let i=r.expression;if(!i.expression||!g.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!q.includes(n))return!1;if(i.arguments.length!==It(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new _({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==q[2]?o=await Be(i.arguments,t):o=ye(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),!!o}async function ii(r,e,t){if(!g.isCallExpression(r)||!Le(r,t.sourceFile))return!1;let i=r;if(!g.isIdentifier(i.expression))return!1;if(i.expression.text===q[2]){let s=await Be(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=ye(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function ni(r){let e=r.stage.defineMetadata.disabledMacroNames,t=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!t&&e.size===0)return r.contents;let i=[r.sourceFile],n=new Set;for(;i.length>0;){let s=i.pop(),a=s?.kind;if(!s||!a||t&&(a===g.SyntaxKind.VariableStatement&&await ti(s,n,r)||a===g.SyntaxKind.ExpressionStatement&&Le(s,r.sourceFile)&&await ri(s,n,r)||a===g.SyntaxKind.CallExpression&&Le(s,r.sourceFile)&&await ii(s,n,r)))continue;if(e.size>0){if(a===g.SyntaxKind.CallExpression){let l=s;g.isIdentifier(l.expression)&&e.has(l.expression.text)&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===g.SyntaxKind.Identifier){let l=s;if(e.has(l.text)){let f=s.parent??s;if(f&&!g.isImportSpecifier(f)&&!g.isExportSpecifier(f)){let p=f?.getText(r.sourceFile);(!g.isCallExpression(f)||f.expression!==s)&&(!p||q.every(m=>!p.includes(m)))&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}let c=s.getChildren(r.sourceFile);for(let l=c.length-1;l>=0;l--)i.push(c[l])}if(n.size===0)return r.contents;let o=Array.from(n);o.sort((s,a)=>a.start-s.start),r.stage.replacementInfo=[];for(let{start:s,end:a,replacement:c}of o)r.stage.replacementInfo.push({source:Ct(r.contents.slice(s,a)),replacement:Ct(c)}),r.contents=r.contents.slice(0,s)+c+r.contents.slice(a);return r.contents}async function Et(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!ei.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:a},l=await ni(c);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var Tt="$$",Ft=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function oi(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
|
|
355
|
+
`&&n++;let o=r.lastIndexOf(`
|
|
356
|
+
`,i-1)+1;return{file:t,line:n,column:r.indexOf(e,o)-o}}function si(r,e){let t=r.lastIndexOf(`
|
|
357
|
+
`,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function kt(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(y),o=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);Ft.lastIndex=0;for(let f of c.matchAll(Ft)){let p=f.index;if(si(c,p))continue;let[,m,h,$]=f;if(t.filesWithMacros.add(l),!m)continue;let D=!!o[$];h==="ifndef"===D&&t.disabledMacroNames.add(m),m.startsWith(Tt)||i.push({text:`Macro function '${m}' not start with '${Tt}' prefix to avoid conflicts`,location:oi(c,m,a,p)})}}return{warnings:i}}var Ve=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(b);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=Re(a))}catch(a){if(Y(a)||a instanceof AggregateError){let c=Re({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await kt(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new M("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new ve(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new he(e,t,this.config.variants[e],this.argv),t.onLoad(Et.bind({},this.variants[e]),"build-service")}}};function Ds(r){u(b).reload(r)}function Bs(r){u(b).patch(r)}export{Ve as BuildService,Ae as ServerModule,Me as WatchService,Qe as collectFilesFromGlob,Re as enhancedBuildResult,Y as isBuildResultError,Kt as isDirectoryExcluded,le as matchesAny,fr as normalizeMessageToError,Ds as overwriteConfig,Wt as parseGlobs,Bs as patchConfig,pe as processEsbuildMessages,$i as shouldIncludeFile};
|
|
357
358
|
//# sourceMappingURL=index.js.map
|