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