@remotex-labs/xbuild 2.1.3 → 2.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bash.js CHANGED
@@ -21,10 +21,10 @@ __ _| |_/ /_ _ _| | __| |
21
21
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
22
22
  `;function Pe(){return`
23
23
  \r${rt.burntOrange(ri)}
24
- \rVersion: ${rt.brightPink("2.1.3")}
25
- \r`}function F(){return rt.lightCoral("[xBuild]")}var ii="tsconfig.json",ni="config.xbuild.ts",Ae={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ni},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string",default:ii},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},Mt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Bt,nt;Bt=[A({scope:"singleton"})];var Q=class{parseConfigFile(e){return it(e).help(!1).version(!1).options({config:Ae.config}).parseSync()}parseUserArgv(e,t){return t?it(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=it(oi(e)).locale("en"),n=i.showHelp;return i.showHelp=function(o){return console.log(Pe()),this.group(Object.keys(Ae),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",o=>o.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Ae).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),Mt.forEach(([o,s])=>{i.example(o,s)}),i.parseSync()}};nt=O(null),Q=P(nt,0,"ArgvModule",Bt,Q),k(nt,1,Q);import gt from"readline";import{exec as on}from"child_process";import{cwd as si}from"process";import{readdirSync as ai}from"fs";import{matchesGlob as ot}from"path";function ci(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function Nt(r,e){for(let t of e)if(ot(r,t))return!0;return!1}function li(r,e){let t=r+"/**";for(let i of e)if(ot(r,i)||ot(t,i))return!0;return!1}function Re(r,e){let{include:t,exclude:i}=ci(e),n=Object.create(null),s=si().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=ai(p,{withFileTypes:!0})}catch{return}let m=f.length;for(let g=0;g<m;g++){let B=f[g],W=x(p,B.name),H=W.slice(a);if(B.isDirectory()){(!c||!li(H,i))&&l(W);continue}if(!(c&&Nt(H,i))&&Nt(H,t)){let Ge=W.slice(s),C=H.lastIndexOf("."),ue=C>0?H.slice(0,C):H;n[ue]=Ge}}}return l(r),n}var U=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var Z=class extends v{constructor(e){super(e.text??"","esBuildError"),this.errorMetadata=_(e,{withFrameworkFrames:!0}),this.stack=V(this.errorMetadata,this.name,this.message,e.notes)}};var z=class r extends v{constructor(t,i){if(t instanceof v)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
24
+ \rVersion: ${rt.brightPink("2.1.4")}
25
+ \r`}function F(){return rt.lightCoral("[xBuild]")}var ii="tsconfig.json",ni="config.xbuild.ts",Ae={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ni},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string",default:ii},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},Mt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Bt,nt;Bt=[A({scope:"singleton"})];var Z=class{parseConfigFile(e){return it(e).help(!1).version(!1).options({config:Ae.config}).parseSync()}parseUserArgv(e,t){return t?it(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=it(oi(e)).locale("en"),n=i.showHelp;return i.showHelp=function(o){return console.log(Pe()),this.group(Object.keys(Ae),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",o=>o.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Ae).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),Mt.forEach(([o,s])=>{i.example(o,s)}),i.parseSync()}};nt=O(null),Z=P(nt,0,"ArgvModule",Bt,Z),k(nt,1,Z);import gt from"readline";import{exec as on}from"child_process";import{cwd as si}from"process";import{readdirSync as ai}from"fs";import{matchesGlob as ot}from"path";function ci(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function Nt(r,e){for(let t of e)if(ot(r,t))return!0;return!1}function li(r,e){let t=r+"/**";for(let i of e)if(ot(r,i)||ot(t,i))return!0;return!1}function Re(r,e){let{include:t,exclude:i}=ci(e),n=Object.create(null),s=si().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=ai(p,{withFileTypes:!0})}catch{return}let m=f.length;for(let g=0;g<m;g++){let B=f[g],W=x(p,B.name),H=W.slice(a);if(B.isDirectory()){(!c||!li(H,i))&&l(W);continue}if(!(c&&Nt(H,i))&&Nt(H,t)){let Ge=W.slice(s),C=H.lastIndexOf("."),ue=C>0?H.slice(0,C):H;n[ue]=Ge}}}return l(r),n}var U=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var ee=class extends v{constructor(e){super(e.text??"","esBuildError"),this.errorMetadata=_(e,{withFrameworkFrames:!0}),this.stack=V(this.errorMetadata,this.name,this.message,e.notes)}};var z=class r extends v{constructor(t,i){if(t instanceof v)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
26
26
  ${t}
27
- `}return this.formattedStack||this.stack}};function fi(r){return r instanceof v?r:r.detail instanceof v||r.detail instanceof U?r.detail:r.detail&&("errors"in r.detail||r.detail instanceof AggregateError)?new z(r.detail,{withFrameworkFrames:!0}):r.detail instanceof Error?new z(r.detail,{withFrameworkFrames:!0}):r.location?new Z(r):new z(new Error(r.text))}function xe(r=[],e){for(let t of r)e.push(fi(t))}function be(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return xe(r.errors,e.errors),xe(r.warnings,e.warnings),e}function ee(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Ht from"http";import*as _t from"https";import{extname as jt}from"path";import{readFileSync as Lt}from"fs";var Dt=`<!doctype html>
27
+ `}return this.formattedStack||this.stack}};function fi(r){return r instanceof v?r:r.detail instanceof v||r.detail instanceof U?r.detail:r.detail&&("errors"in r.detail||r.detail instanceof AggregateError)?new z(r.detail,{withFrameworkFrames:!0}):r.detail instanceof Error?new z(r.detail,{withFrameworkFrames:!0}):r.location?new ee(r):new z(new Error(r.text))}function xe(r=[],e){for(let t of r)e.push(fi(t))}function be(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return xe(r.errors,e.errors),xe(r.warnings,e.warnings),e}function te(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Ht from"http";import*as _t from"https";import{extname as jt}from"path";import{readFileSync as Lt}from"fs";var Dt=`<!doctype html>
28
28
  <html lang="en">
29
29
  <head>
30
30
  <meta charset="utf-8"/>
@@ -352,24 +352,24 @@ ${t}
352
352
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
353
353
  <div class="meta"><div class="name">${l}</div><div class="sub">${f}</div></div>
354
354
  </a>
355
- `}).join("");o?o=`<div class="list">${o}</div>`:o='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(l=>(s+=`${l}/`,`<li><a href="${s}">${l}</a></li>`)).join(""),c=Dt.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=jt(e).slice(1)||"txt",n=this.getContentType(i),o=await mi(e);t.writeHead(200,{"Content-Type":n}),t.end(o)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(F(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as Vt}from"path";import{stat as gi,watch as hi}from"fs/promises";var Ce=class{excludes;include;debounceTimer=null;framework=u(S);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=hi(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Et(n);if(o.endsWith("~")||!this.include.some(a=>Vt(o,a))||this.excludes.some(a=>Vt(o,a)))continue;let s=x(this.framework.rootPath,o);try{if(!(await gi(s)).isFile())continue}catch{}t.add(o),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};var N=class extends v{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as Ri}from"esbuild";import{writeFile as $i,mkdir as Mi}from"fs/promises";import d from"typescript";import vi from"typescript";var yi=/^#!.*(\r?\n)?/,xi=/export {};\n?/g,bi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,Si=/^export\s+(?:default\s+)?/gm,Ci=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function wi(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(yi,""):r}function Ii(r){return r.includes("export {}")?r.replace(xi,""):r}function Ei(r){return r=r.replace(Ci,""),r.replace(bi,"$1")}function Ut(r){return r.replace(Si,"")}function Ti(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function Me(r){return Ti(r)&&(r=wi(r),r=Ii(r),r=Ei(r)),r}function st(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||$(r),s=i||$(r),c=T(s,r).replace(/\.tsx?$/,".d.ts"),l=vi.sys.resolvePath(`${o}/${c}`);return R(l)}var zt,at;zt=[A({scope:"singleton"})];var te=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(b);constructor(){this.printer=d.createPrinter({newLine:d.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!d.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(d.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(d.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=d.factory.createNodeArray(n),s=this.printer.printList(d.ListFormat.MultiLine,o,e),a=Ut(Me(s));for(let c of i)if(c.includes(" as ")){let[l,p]=c.split(" as ");a=a.replace(new RegExp(`\\b${p}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:n,moduleSpecifier:o}=e;if(!n||!o)return;let s=this.resolveModule(o,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:p}=n;if(!p)return;d.isNamespaceImport(p)?i.push(p.name.text):d.isNamedImports(p)&&this.addNamedElements(i,p.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:l}=n;l&&(d.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:d.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(d.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}d.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};at=O(null),te=P(at,0,"GraphModel",zt,te),k(at,1,te);import K from"typescript";import{mkdir as Fi,writeFile as Oi}from"fs/promises";var Wt=`/**
355
+ `}).join("");o?o=`<div class="list">${o}</div>`:o='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(l=>(s+=`${l}/`,`<li><a href="${s}">${l}</a></li>`)).join(""),c=Dt.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=jt(e).slice(1)||"txt",n=this.getContentType(i),o=await mi(e);t.writeHead(200,{"Content-Type":n}),t.end(o)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(F(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as Vt}from"path";import{stat as gi,watch as hi}from"fs/promises";var Ce=class{excludes;include;debounceTimer=null;framework=u(S);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=hi(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Et(n);if(o.endsWith("~")||!this.include.some(a=>Vt(o,a))||this.excludes.some(a=>Vt(o,a)))continue;let s=x(this.framework.rootPath,o);try{if(!(await gi(s)).isFile())continue}catch{}t.add(o),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};var N=class extends v{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as Ri}from"esbuild";import{writeFile as $i,mkdir as Mi}from"fs/promises";import d from"typescript";import vi from"typescript";var yi=/^#!.*(\r?\n)?/,xi=/export {};\n?/g,bi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,Si=/^export\s+(?:default\s+)?/gm,Ci=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function wi(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(yi,""):r}function Ii(r){return r.includes("export {}")?r.replace(xi,""):r}function Ei(r){return r=r.replace(Ci,""),r.replace(bi,"$1")}function Ut(r){return r.replace(Si,"")}function Ti(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function Me(r){return Ti(r)&&(r=wi(r),r=Ii(r),r=Ei(r)),r}function st(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||$(r),s=i||$(r),c=T(s,r).replace(/\.tsx?$/,".d.ts"),l=vi.sys.resolvePath(`${o}/${c}`);return R(l)}var zt,at;zt=[A({scope:"singleton"})];var re=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(b);constructor(){this.printer=d.createPrinter({newLine:d.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!d.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(d.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(d.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=d.factory.createNodeArray(n),s=this.printer.printList(d.ListFormat.MultiLine,o,e),a=Ut(Me(s));for(let c of i)if(c.includes(" as ")){let[l,p]=c.split(" as ");a=a.replace(new RegExp(`\\b${p}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:n,moduleSpecifier:o}=e;if(!n||!o)return;let s=this.resolveModule(o,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:p}=n;if(!p)return;d.isNamespaceImport(p)?i.push(p.name.text):d.isNamedImports(p)&&this.addNamedElements(i,p.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:l}=n;l&&(d.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:d.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(d.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}d.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};at=O(null),re=P(at,0,"GraphModel",zt,re),k(at,1,re);import K from"typescript";import{mkdir as Fi,writeFile as Oi}from"fs/promises";var Wt=`/**
356
356
  * This file was automatically generated by xBuild.
357
357
  * DO NOT EDIT MANUALLY.
358
358
  */
359
- `;var Be=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(te);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let n=this.languageHostService.getCompilationSettings();t&&(n={...n,outDir:t}),await Promise.all(Object.entries(e).map(async([o,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=x(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Fi($(i),{recursive:!0}),await Oi(i,o,"utf-8")}async getBundleContent(e,t){let i=new Set,n=new Set([e]),o=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let p=t.getSourceFile(l);if(!p)continue;let f=this.graphModel.scan(p,this.languageService,this.languageHostService);if(o.add(f),a.has(l)){n.add(f);for(let m of f.internalExports.star)a.add(m)}for(let m of f.internalDeps)i.has(m)||s.push(m);c+=f.content}return c+=e.content,this.parseContent(c,o,n)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[n,o]of Object.entries(i.externalImports.default)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});let s=t.get(n);s.default||(s.default=o)}for(let[n,o]of Object.entries(i.externalImports.named)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});for(let s of o)t.get(n).named.add(s)}for(let[n,o]of Object.entries(i.externalImports.namespace))t.has(o)||t.set(o,{named:new Set,namespace:new Map}),t.get(o).namespace.set(n,o)}return t}generateImportStatements(e){let t=[];for(let[i,{default:n,named:o,namespace:s}]of e){let a=[];if(n&&a.push(n),o.size>0&&a.push(`{ ${Array.from(o).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let n=[...i.internalExports.exports],o=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(o.push(...c.declarations),o.push(`const ${s} = { ${c.exports.join(", ")} };`),n.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);n.push(...a.exports),o.push(...a.declarations)}return{exports:n,declarations:o}}collectBundleExports(e){let t=[],i=[],n=[];for(let o of e){t.push(...o.internalExports.exports);for(let[s,a]of Object.entries(o.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of o.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(o.externalExports.namespace))n.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(o.externalExports.exports))n.push(`export { ${a.join(`,
359
+ `;var Be=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(re);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let n=this.languageHostService.getCompilationSettings();t&&(n={...n,outDir:t}),await Promise.all(Object.entries(e).map(async([o,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=x(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Fi($(i),{recursive:!0}),await Oi(i,o,"utf-8")}async getBundleContent(e,t){let i=new Set,n=new Set([e]),o=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let p=t.getSourceFile(l);if(!p)continue;let f=this.graphModel.scan(p,this.languageService,this.languageHostService);if(o.add(f),a.has(l)){n.add(f);for(let m of f.internalExports.star)a.add(m)}for(let m of f.internalDeps)i.has(m)||s.push(m);c+=f.content}return c+=e.content,this.parseContent(c,o,n)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[n,o]of Object.entries(i.externalImports.default)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});let s=t.get(n);s.default||(s.default=o)}for(let[n,o]of Object.entries(i.externalImports.named)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});for(let s of o)t.get(n).named.add(s)}for(let[n,o]of Object.entries(i.externalImports.namespace))t.has(o)||t.set(o,{named:new Set,namespace:new Map}),t.get(o).namespace.set(n,o)}return t}generateImportStatements(e){let t=[];for(let[i,{default:n,named:o,namespace:s}]of e){let a=[];if(n&&a.push(n),o.size>0&&a.push(`{ ${Array.from(o).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let n=[...i.internalExports.exports],o=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(o.push(...c.declarations),o.push(`const ${s} = { ${c.exports.join(", ")} };`),n.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);n.push(...a.exports),o.push(...a.declarations)}return{exports:n,declarations:o}}collectBundleExports(e){let t=[],i=[],n=[];for(let o of e){t.push(...o.internalExports.exports);for(let[s,a]of Object.entries(o.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of o.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(o.externalExports.namespace))n.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(o.externalExports.exports))n.push(`export { ${a.join(`,
360
360
  `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[Wt],o=this.collectExternalImports(t),s=this.generateImportStatements(o);n.push(...s),s.length>0&&n.push("");let{exports:a,declarations:c,externalExports:l}=this.collectBundleExports(i);if(c.length>0&&(n.push(...c),n.push("")),n.push(e),a.length>0){let p=Array.from(new Set(a)).sort();n.push(`export {
361
361
  ${p.join(`,
362
362
  `)}
363
363
  };`)}return l.length>0&&n.push(...l),n.join(`
364
364
  `)}};import{mkdir as ki,writeFile as Pi}from"fs/promises";import{xterm as Ai}from"@remotex-labs/xansi/xterm.component";var Ne=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Ai.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=st(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=st(e.fileName,t);n=Me(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await ki($(o),{recursive:!0}),await Pi(o,n,"utf8")}};import ne from"typescript";var De=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ne.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=ne.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(b);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ne.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return ne.getDefaultLibFilePath(e)}getScriptVersion(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.version.toString():"0"}hasScriptSnapshot(e){return this.trackFiles.has(this.filesCache.resolve(e))}getScriptSnapshot(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.contentSnapshot:this.touchFile(e).contentSnapshot}resolveModuleName(e,t){return ne.resolveModuleName(e,t,this.compilerOptions,ne.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),c=T(t,a);return n.replace(o,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var Gt,ct;Gt=[A({providers:[{useValue:"tsconfig.json"}]})];var D=class D{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new Ne(n,i),this.bundlerService=new Be(n,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=D.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=D.serviceCache.get(e);t&&(t.refCount--,D.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=D.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new De(e.options),i=K.createLanguageService(t,K.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return D.serviceCache.set(this.configPath,n),n}parseConfig(){let e=K.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...K.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:K.ScriptTarget.ESNext,module:K.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:K.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:K.flattenDiagnosticMessageText(e.messageText,`
365
- `)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};ct=O(null),D=P(ct,0,"TypescriptService",Gt,D),k(ct,1,D);var oe=D;import{cwd as je}from"process";import{build as lt}from"esbuild";var qt={write:!1,bundle:!0,minify:!0,outdir:`${je()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Kt(r,e={}){try{return await lt({absWorkingDir:je(),...qt,...e,metafile:!0,entryPoints:r})}catch(t){if(ee(t)){let i=new AggregateError([],"Failed to build entryPoints");throw xe(t.errors,i.errors),i}throw t}}async function Xt(r,e,t={}){return await lt({absWorkingDir:je(),...qt,...t,stdin:{loader:"ts",contents:r,resolveDir:je(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Yt(r,e={}){try{return await lt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(ee(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw xe(t.errors,i.errors),i}throw t}}function Jt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Re(r,e)),t}else if(e&&typeof e=="object")return e;throw new N("Unsupported entry points format")}var Le=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new N(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new oe(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(y);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ri(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(ee(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?q({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new U("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Mi(e,{recursive:!0}),await $i(x(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new N(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new N("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=Jt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new oe(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await Yt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=T(this.typescriptModule.config.options.rootDir,w(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Bi}from"fs/promises";var He=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(b);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=w(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await Bi(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import h from"typescript";import{highlightCode as or}from"@remotex-labs/xmap/highlighter.component";import X from"typescript";var Ni="$$ifdef";function Di(r,e,t,i=!1){let n=i?"export function ":"function ";return X.isArrowFunction(e)||X.isFunctionExpression(e)?ji(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function ji(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Li(e,t);return`${i}${r}(${n})${o} ${s}`}function Li(r,e){let t=r.body.getText(e);return X.isArrowFunction(r)&&!X.isBlock(r.body)?`{ return ${t}; }`:t}function Hi(r,e,t="",i="();"){return X.isArrowFunction(r)||X.isFunctionExpression(r)?`${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Qt(r,e,t){let i=r in t&&!!t[r];return e===Ni===i}function Zt(r,e,t,i){let[n,o]=e.arguments;if(!X.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!Qt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Di(c,o,i.sourceFile,t)}function _e(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!X.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!Qt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),Hi(s,e.sourceFile,l,n)}import M from"typescript";import{createRequire as Ui}from"module";var Ve=class extends v{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=_(e,{},t),this.stack=V(this.errorMetadata,this.name,this.message)}};import{Script as _i,createContext as Vi}from"vm";async function er(r,e={},t={}){let i=new _i(r,t),n=Vi(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function tr(r,e,t){let[i,n]=(await Xt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=Ui(e.sourceFile.fileName),a=await er(n.text,zi(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){Wi(o,e,i.text,t)}return"undefined"}function zi(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:$(r),__filename:r}}function Wi(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(S).setSource(t,e.sourceFile.fileName);let s=new Ve(r,o);e.errors.push({text:s.message,detail:s})}function Gi(r,e){let t=null,i=n=>{if(!t){if(M.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}M.isVariableStatement(n)&&(t=qi(n,r),t)||M.forEachChild(n,i)}};return i(e),t}function qi(r,e){for(let t of r.declarationList.declarations)if(M.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(M.isArrowFunction(t.initializer)||M.isFunctionExpression(t.initializer)))return t.initializer;return null}function rr(r){return`module.exports = (${r})();`}function Ki(r){return r&M.NodeFlags.Const?"const":r&M.NodeFlags.Let?"let":"var"}function ir(r,e){return r?M.isIdentifier(r)?Xi(r,e):M.isArrowFunction(r)||M.isFunctionExpression(r)?{node:r,data:rr(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xi(r,e){let t=Gi(r.text,e.sourceFile);return t?{node:t,data:rr(t.getText(e.sourceFile))}:(Yi(r.text,e,r),{data:"",node:r})}function Yi(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=T(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function nr(r,e,t,i,n){let o=t.arguments[0],s=ir(o,n);if(!s)return!1;let a=await tr(s.data,n,s.node),c=Ki(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(n.sourceFile);return`${l}${c} ${p} = ${a};`}async function ft(r,e){let t=r[0],i=ir(t,e);return i?tr(i.data,e,i.node):!1}var Ji=/\.(ts|js)$/,re=["$$ifdef","$$ifndef","$$inline"];function pt(r,e){return re.some(t=>r.getText(e).includes(t))}function sr(r){return r===re[2]?1:2}async function Qi(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,o=`(${a.arguments.map(f=>f.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(s.arguments.length!==sr(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new Z({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:p+1,column:f}})}let l=r.modifiers?.some(p=>p.kind===h.SyntaxKind.ExportKeyword)??!1;c===re[2]?i=await nr(n,r,s,l,t):o?i=_e(s,t,n,l,o):i=Zt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function Zi(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!re.includes(n))return!1;if(i.arguments.length!==sr(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new Z({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==re[2]?o=await ft(i.arguments,t):o=_e(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),o!==!1}async function en(r,e,t){if(!h.isCallExpression(r)||!pt(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===re[2]){let s=await ft(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=_e(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function tn(r){let e=r.stage.defineMetadata.disabledMacroNames,t=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!t&&e.size===0)return r.contents;let i=[r.sourceFile],n=new Set;for(;i.length>0;){let s=i.pop(),a=s?.kind;if(!s||!a||t&&(a===h.SyntaxKind.VariableStatement&&await Qi(s,n,r)||a===h.SyntaxKind.ExpressionStatement&&pt(s,r.sourceFile)&&await Zi(s,n,r)||a===h.SyntaxKind.CallExpression&&pt(s,r.sourceFile)&&await en(s,n,r)))continue;if(e.size>0){if(a===h.SyntaxKind.CallExpression){let l=s;h.isIdentifier(l.expression)&&e.has(l.expression.text)&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===h.SyntaxKind.Identifier){let l=s;if(e.has(l.text)){let p=s.parent??s;if(p&&!h.isImportSpecifier(p)&&!h.isExportSpecifier(p)){let f=p?.getText(r.sourceFile);(!h.isCallExpression(p)||p.expression!==s)&&(!f||re.every(m=>!f.includes(m)))&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}let c=s.getChildren(r.sourceFile);for(let l=c.length-1;l>=0;l--)i.push(c[l])}if(n.size===0)return r.contents;let o=Array.from(n);o.sort((s,a)=>a.start-s.start),r.stage.replacementInfo=[];for(let{start:s,end:a,replacement:c}of o)r.stage.replacementInfo.push({source:or(r.contents.slice(s,a)),replacement:or(c)}),r.contents=r.contents.slice(0,s)+c+r.contents.slice(a);return r.contents}async function ar(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Ji.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:a},l=await tn(c);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var cr="$$",lr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function rn(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
365
+ `)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};ct=O(null),D=P(ct,0,"TypescriptService",Gt,D),k(ct,1,D);var oe=D;import{cwd as je}from"process";import{build as lt}from"esbuild";var qt={write:!1,bundle:!0,minify:!0,outdir:`${je()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Kt(r,e={}){try{return await lt({absWorkingDir:je(),...qt,...e,metafile:!0,entryPoints:r})}catch(t){if(te(t)){let i=new AggregateError([],"Failed to build entryPoints");throw xe(t.errors,i.errors),i}throw t}}async function Xt(r,e,t={}){return await lt({absWorkingDir:je(),...qt,...t,stdin:{loader:"ts",contents:r,resolveDir:je(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Yt(r,e={}){try{return await lt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(te(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw xe(t.errors,i.errors),i}throw t}}function Jt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Re(r,e)),t}else if(e&&typeof e=="object")return e;throw new N("Unsupported entry points format")}var Le=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new N(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new oe(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(y);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ri(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(te(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?q({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new U("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Mi(e,{recursive:!0}),await $i(x(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new N(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new N("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=Jt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new oe(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await Yt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=T(this.typescriptModule.config.options.rootDir,w(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Bi}from"fs/promises";var He=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(b);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=w(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await Bi(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import h from"typescript";import{highlightCode as or}from"@remotex-labs/xmap/highlighter.component";import X from"typescript";var Ni="$$ifdef";function Di(r,e,t,i=!1){let n=i?"export function ":"function ";return X.isArrowFunction(e)||X.isFunctionExpression(e)?ji(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function ji(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Li(e,t);return`${i}${r}(${n})${o} ${s}`}function Li(r,e){let t=r.body.getText(e);return X.isArrowFunction(r)&&!X.isBlock(r.body)?`{ return ${t}; }`:t}function Hi(r,e,t="",i="();"){return X.isArrowFunction(r)||X.isFunctionExpression(r)?`${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Qt(r,e,t){let i=r in t&&!!t[r];return e===Ni===i}function Zt(r,e,t,i){let[n,o]=e.arguments;if(!X.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!Qt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Di(c,o,i.sourceFile,t)}function _e(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!X.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!Qt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),Hi(s,e.sourceFile,l,n)}import M from"typescript";import{createRequire as Ui}from"module";var Ve=class extends v{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=_(e,{},t),this.stack=V(this.errorMetadata,this.name,this.message)}};import{Script as _i,createContext as Vi}from"vm";async function er(r,e={},t={}){let i=new _i(r,t),n=Vi(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function tr(r,e,t){let[i,n]=(await Xt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=Ui(e.sourceFile.fileName),a=await er(n.text,zi(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){Wi(o,e,i.text,t)}return"undefined"}function zi(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:$(r),__filename:r}}function Wi(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(S).setSource(t,e.sourceFile.fileName);let s=new Ve(r,o);e.errors.push({text:s.message,detail:s})}function Gi(r,e){let t=null,i=n=>{if(!t){if(M.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}M.isVariableStatement(n)&&(t=qi(n,r),t)||M.forEachChild(n,i)}};return i(e),t}function qi(r,e){for(let t of r.declarationList.declarations)if(M.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(M.isArrowFunction(t.initializer)||M.isFunctionExpression(t.initializer)))return t.initializer;return null}function rr(r){return`module.exports = (${r})();`}function Ki(r){return r&M.NodeFlags.Const?"const":r&M.NodeFlags.Let?"let":"var"}function ir(r,e){return r?M.isIdentifier(r)?Xi(r,e):M.isArrowFunction(r)||M.isFunctionExpression(r)?{node:r,data:rr(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xi(r,e){let t=Gi(r.text,e.sourceFile);return t?{node:t,data:rr(t.getText(e.sourceFile))}:(Yi(r.text,e,r),{data:"",node:r})}function Yi(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=T(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function nr(r,e,t,i,n){let o=t.arguments[0],s=ir(o,n);if(!s)return!1;let a=await tr(s.data,n,s.node),c=Ki(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(n.sourceFile);return`${l}${c} ${p} = ${a};`}async function ft(r,e){let t=r[0],i=ir(t,e);return i?tr(i.data,e,i.node):!1}var Ji=/\.(ts|js)$/,Y=["$$ifdef","$$ifndef","$$inline"];function pt(r,e){return Y.some(t=>r.getText(e).includes(t))}function sr(r){return r===Y[2]?1:2}async function Qi(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,o=`(${a.arguments.map(f=>f.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(!Y.includes(c))continue;if(s.arguments.length!==sr(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new ee({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:p+1,column:f}})}let l=r.modifiers?.some(p=>p.kind===h.SyntaxKind.ExportKeyword)??!1;c===Y[2]?i=await nr(n,r,s,l,t):o?i=_e(s,t,n,l,o):i=Zt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function Zi(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!Y.includes(n))return!1;if(i.arguments.length!==sr(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new ee({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==Y[2]?o=await ft(i.arguments,t):o=_e(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),o!==!1}async function en(r,e,t){if(!h.isCallExpression(r)||!pt(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===Y[2]){let s=await ft(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=_e(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function tn(r){let e=r.stage.defineMetadata.disabledMacroNames,t=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!t&&e.size===0)return r.contents;let i=[r.sourceFile],n=new Set;for(;i.length>0;){let s=i.pop(),a=s?.kind;if(!s||!a||t&&(a===h.SyntaxKind.VariableStatement&&await Qi(s,n,r)||a===h.SyntaxKind.ExpressionStatement&&pt(s,r.sourceFile)&&await Zi(s,n,r)||a===h.SyntaxKind.CallExpression&&pt(s,r.sourceFile)&&await en(s,n,r)))continue;if(e.size>0){if(a===h.SyntaxKind.CallExpression){let l=s;h.isIdentifier(l.expression)&&e.has(l.expression.text)&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===h.SyntaxKind.Identifier){let l=s;if(e.has(l.text)){let p=s.parent??s;if(p&&!h.isImportSpecifier(p)&&!h.isExportSpecifier(p)){let f=p?.getText(r.sourceFile);(!h.isCallExpression(p)||p.expression!==s)&&(!f||Y.every(m=>!f.includes(m)))&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}let c=s.getChildren(r.sourceFile);for(let l=c.length-1;l>=0;l--)i.push(c[l])}if(n.size===0)return r.contents;let o=Array.from(n);o.sort((s,a)=>a.start-s.start),r.stage.replacementInfo=[];for(let{start:s,end:a,replacement:c}of o)r.stage.replacementInfo.push({source:or(r.contents.slice(s,a)),replacement:or(c)}),r.contents=r.contents.slice(0,s)+c+r.contents.slice(a);return r.contents}async function ar(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Ji.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:a},l=await tn(c);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var cr="$$",lr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function rn(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
366
366
  `&&n++;let o=r.lastIndexOf(`
367
367
  `,i-1)+1;return{file:t,line:n,column:r.indexOf(e,o)-o}}function nn(r,e){let t=r.lastIndexOf(`
368
- `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function fr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(b),o=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);lr.lastIndex=0;for(let p of c.matchAll(lr)){let f=p.index;if(nn(c,f))continue;let[,m,g,B]=p;if(t.filesWithMacros.add(l),!m)continue;let W=!!o[B];g==="ifndef"===W&&t.disabledMacroNames.add(m),m.startsWith(cr)||i.push({text:`Macro function '${m}' not start with '${cr}' prefix to avoid conflicts`,location:rn(c,m,a,f)})}}return{warnings:i}}var we=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(y);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=be(a))}catch(a){if(ee(a)||a instanceof AggregateError){let c=be({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await fr(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new N("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new He(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Le(e,t,this.config.variants[e],this.argv),t.onLoad(ar.bind({},this.variants[e]),"build-service")}}};function pr(r){u(y).reload(r)}function ur(r){u(y).patch(r)}import{platform as sn,exit as an,stdin as Ue,stdout as dt}from"process";import{xterm as ze}from"@remotex-labs/xansi/xterm.component";var ut={SIGINT:"",SIGQUIT:""},I={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},dr={win32:"start",darwin:"open",linux:"xdg-open"};function cn(r=!1){let e=["\u{1F680} Shortcuts"],t=ze.dim(" press "),i=(n,o)=>{e.push(`${t}${ze.bold(n)}${ze.dim(o)}`)};return r&&(i(I.SHOW_URL," to show server url"),i(I.OPEN_BROWSER," to open in browser")),i(I.VERBOSE," to enable / disable verbose mode"),i(I.RELOAD," to reload"),i(I.CLEAR," to clear console"),i(I.QUIT,` to quit
368
+ `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function fr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(b),o=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);lr.lastIndex=0;for(let p of c.matchAll(lr)){let f=p.index;if(nn(c,f))continue;let[,m,g,B]=p;if(t.filesWithMacros.add(l),!m)continue;let W=!!o[B];g==="ifndef"===W&&t.disabledMacroNames.add(m),m.startsWith(cr)||i.push({text:`Macro function '${m}' not start with '${cr}' prefix to avoid conflicts`,location:rn(c,m,a,f)})}}return{warnings:i}}var we=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(y);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=be(a))}catch(a){if(te(a)||a instanceof AggregateError){let c=be({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await fr(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new N("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new He(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Le(e,t,this.config.variants[e],this.argv),t.onLoad(ar.bind({},this.variants[e]),"build-service")}}};function pr(r){u(y).reload(r)}function ur(r){u(y).patch(r)}import{platform as sn,exit as an,stdin as Ue,stdout as dt}from"process";import{xterm as ze}from"@remotex-labs/xansi/xterm.component";var ut={SIGINT:"",SIGQUIT:""},I={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},dr={win32:"start",darwin:"open",linux:"xdg-open"};function cn(r=!1){let e=["\u{1F680} Shortcuts"],t=ze.dim(" press "),i=(n,o)=>{e.push(`${t}${ze.bold(n)}${ze.dim(o)}`)};return r&&(i(I.SHOW_URL," to show server url"),i(I.OPEN_BROWSER," to open in browser")),i(I.VERBOSE," to enable / disable verbose mode"),i(I.RELOAD," to reload"),i(I.CLEAR," to clear console"),i(I.QUIT,` to quit
369
369
  `),e.join(`
370
370
  `)}function mt(){let r=Math.max(0,dt.rows-2);r>0&&console.log(`
371
371
  `.repeat(r)),gt.cursorTo(dt,0,0),gt.clearScreenDown(dt)}function ln(r){let e=dr[sn]??"xdg-open";on(`${e} ${r}`)}function fn(r,e,t,i,n){if(e?.name)switch((e.sequence===I.QUIT||r===ut.SIGINT||r===ut.SIGQUIT)&&(console.log(`
372
- \u{1F44B} Exiting...`),an(1)),e.name){case I.CLEAR:mt();break;case I.VERBOSE:let o=u(y).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${o?"DISABLED":"ENABLED"}`),ur({verbose:!o});break;case I.RELOAD:mt(),t();break;case I.HELP:mt(),console.log(i);break;case I.SHOW_URL:n&&console.log(`${F()} ${ze.canaryYellow(n)}`);break;case I.OPEN_BROWSER:n&&ln(n);break}}function mr(r,e){if(!Ue.isTTY)return;let t=cn(!!e);console.log(t),Ue.setRawMode(!0),gt.emitKeypressEvents(Ue),Ue.on("keypress",(i,n)=>{fn(i,n,r,t,e)})}import{existsSync as pn}from"fs";import{runInThisContext as un}from"vm";import{createRequire as dn}from"module";var mn={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function ht(r){if(!r||!pn(r))return{};u(b).touchFile(r);let[e,t]=(await Kt([r],{...mn,outdir:"tmp"})).outputFiles;u(S).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=dn(w(r)),await un(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}import{xterm as Y}from"@remotex-labs/xansi/xterm.component";var gr=Y.hex("#80a36b"),Ie=Y.hex("#dcdfe4"),se=Y.hex("#5798cd"),j=Y.hex("#e5c07b"),Ee=Y.hex("#56b6c2"),J=Y.hex("#e06c75"),ae=Y.hex("#c678dd"),ce=Y.hex("#a5a7ab");import{xterm as vt}from"@remotex-labs/xansi/xterm.component";var L=" ",yt=1024,hr=yt*1024,yr="\u2014",pe="\u2192",le="\xD7",gn="\u2022";function fe(r,e=se.dim(pe)){return`${F()} ${e} ${se(r)}`}function hn(r){return r<yt?`${r} B`:r<hr?`${(r/yt).toFixed(2)} KB`:`${(r/hr).toFixed(2)} MB`}function xr(r){let e=r.file?T(process.cwd(),r.file):"(unknown)",t=j(String((r.line??0)+1)),i=j(String((r.column??0)+1));return`${Ee(e)}:${t}:${i}`}function vn(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
372
+ \u{1F44B} Exiting...`),an(1)),e.name){case I.CLEAR:mt();break;case I.VERBOSE:let o=u(y).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${o?"DISABLED":"ENABLED"}`),ur({verbose:!o});break;case I.RELOAD:mt(),t();break;case I.HELP:mt(),console.log(i);break;case I.SHOW_URL:n&&console.log(`${F()} ${ze.canaryYellow(n)}`);break;case I.OPEN_BROWSER:n&&ln(n);break}}function mr(r,e){if(!Ue.isTTY)return;let t=cn(!!e);console.log(t),Ue.setRawMode(!0),gt.emitKeypressEvents(Ue),Ue.on("keypress",(i,n)=>{fn(i,n,r,t,e)})}import{existsSync as pn}from"fs";import{runInThisContext as un}from"vm";import{createRequire as dn}from"module";var mn={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function ht(r){if(!r||!pn(r))return{};u(b).touchFile(r);let[e,t]=(await Kt([r],{...mn,outdir:"tmp"})).outputFiles;u(S).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=dn(w(r)),await un(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}import{xterm as J}from"@remotex-labs/xansi/xterm.component";var gr=J.hex("#80a36b"),Ie=J.hex("#dcdfe4"),se=J.hex("#5798cd"),j=J.hex("#e5c07b"),Ee=J.hex("#56b6c2"),Q=J.hex("#e06c75"),ae=J.hex("#c678dd"),ce=J.hex("#a5a7ab");import{xterm as vt}from"@remotex-labs/xansi/xterm.component";var L=" ",yt=1024,hr=yt*1024,yr="\u2014",pe="\u2192",le="\xD7",gn="\u2022";function fe(r,e=se.dim(pe)){return`${F()} ${e} ${se(r)}`}function hn(r){return r<yt?`${r} B`:r<hr?`${(r/yt).toFixed(2)} KB`:`${(r/hr).toFixed(2)} MB`}function xr(r){let e=r.file?T(process.cwd(),r.file):"(unknown)",t=j(String((r.line??0)+1)),i=j(String((r.column??0)+1));return`${Ee(e)}:${t}:${i}`}function vn(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
373
373
  `),i=e.metadata.stacks.join(`
374
374
  `);r.push("");for(let n of t)r.push(`${L}${n}`);r.push(""),r.push(`${L}Enhanced Stack Trace:`),r.push(` ${i}`)}function yn(r){if(!r.metadata?.formatCode)return;let e=r.metadata.formatCode.split(`
375
375
  `).map(i=>`${L}${i}`).join(`
@@ -378,20 +378,20 @@ ${t}
378
378
  ${e}
379
379
 
380
380
  ${L}Enhanced Stack Trace:
381
- ${t}`)}function xn(r,e,t){let i=xr(r),n=t(`TS${r.code}`),o=ce(r.message);return`${L}${e} ${i} ${Ie(pe)} ${n} ${Ie(yr)} ${o}`}function br(r,e,t=J){let i=xr(r),n=t(`TS${r.code}`),o=ce(r.message);console.log(`${L}${e} ${i}`,Ie(pe),`${n} ${Ie(yr)} ${o}`)}function bn(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`
381
+ ${t}`)}function xn(r,e,t){let i=xr(r),n=t(`TS${r.code}`),o=ce(r.message);return`${L}${e} ${i} ${Ie(pe)} ${n} ${Ie(yr)} ${o}`}function br(r,e,t=Q){let i=xr(r),n=t(`TS${r.code}`),o=ce(r.message);console.log(`${L}${e} ${i}`,Ie(pe),`${n} ${Ie(yr)} ${o}`)}function bn(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`
382
382
  ${L}${j(t)} ${j("TypesError")}: ${ce(e.message||"Type checking warning")}`),1;for(let n of e.diagnostics)r.push(xn(n,j(t),vt.deepOrange));return i}function Sn(r,e,t,i){r.push(`
383
- ${L}${i(t)} ${e}`),e instanceof v&&vn(r,e)}function Cn(r,e,t,i){return e instanceof U?bn(r,e,t):(Sn(r,e,t,i),1)}function vr(r,e){if(r.length===0)return;let t=e==="Errors",i=t?le:gn,n=t?J:j,o=0,s=[""];for(let a of r)o+=Cn(s,a,i,n);s.push(""),s[0]=`
383
+ ${L}${i(t)} ${e}`),e instanceof v&&vn(r,e)}function Cn(r,e,t,i){return e instanceof U?bn(r,e,t):(Sn(r,e,t,i),1)}function vr(r,e){if(r.length===0)return;let t=e==="Errors",i=t?le:gn,n=t?Q:j,o=0,s=[""];for(let a of r)o+=Cn(s,a,i,n);s.push(""),s[0]=`
384
384
  ${n(e)} (${o})
385
385
  `,console.log(s.join(`
386
386
  `))}function wn(r){let e=Object.entries(r.outputs),t=e.length,i=[];i.push(`
387
387
  ${gr("Outputs")} (${t})`);for(let[n,o]of e){let s=j.dim(hn(o.bytes));i.push(`${L}${se(pe)} ${Ee(n)}: ${s}`)}i.push(""),console.log(i.join(`
388
- `))}function Te(r){if(r instanceof AggregateError)for(let e of r.errors)Te(e);else if(r instanceof U)for(let e of r.diagnostics)br(e,J(le));else r instanceof v?(console.log(`
389
- ${L}${J(le)} ${r}`),yn(r)):r instanceof Error?Te(new z(r)):Te(new z(new Error(String(r))))}function In(r,e){let t=e.length>0,i=t?j(r):ae(r),n=t?J(le):se.dim(pe),o=fe("completed",n);if(console.log(`${o} ${i}`),t){console.log("");for(let s of e)br(s,J(le));console.log("")}}function Sr(r){for(let[e,t]of Object.entries(r))In(e,t)}function Cr({variantName:r}){console.log(`${fe("build")} ${ae(r)}`)}function wr({variantName:r,duration:e,buildResult:t,stage:i}){let{errors:n,warnings:o,metafile:s}=be(t),a=!!s,c=a?ae(r):j(r),l=a?se.dim(pe):J(le),p=fe("completed",l),f=vt.dim(`in ${e} ms`);console.log(`${p} ${c} ${f}`),vr(n,"Errors"),vr(o,"Warnings"),u(y).getValue().verbose&&i?.replacementInfo&&Array.isArray(i.replacementInfo)&&i.replacementInfo.forEach(({source:g,replacement:B})=>{console.log(fe("Macro replacement:")+`
388
+ `))}function Te(r){if(r instanceof AggregateError)for(let e of r.errors)Te(e);else if(r instanceof U)for(let e of r.diagnostics)br(e,Q(le));else r instanceof v?(console.log(`
389
+ ${L}${Q(le)} ${r}`),yn(r)):r instanceof Error?Te(new z(r)):Te(new z(new Error(String(r))))}function In(r,e){let t=e.length>0,i=t?j(r):ae(r),n=t?Q(le):se.dim(pe),o=fe("completed",n);if(console.log(`${o} ${i}`),t){console.log("");for(let s of e)br(s,Q(le));console.log("")}}function Sr(r){for(let[e,t]of Object.entries(r))In(e,t)}function Cr({variantName:r}){console.log(`${fe("build")} ${ae(r)}`)}function wr({variantName:r,duration:e,buildResult:t,stage:i}){let{errors:n,warnings:o,metafile:s}=be(t),a=!!s,c=a?ae(r):j(r),l=a?se.dim(pe):Q(le),p=fe("completed",l),f=vt.dim(`in ${e} ms`);console.log(`${p} ${c} ${f}`),vr(n,"Errors"),vr(o,"Warnings"),u(y).getValue().verbose&&i?.replacementInfo&&Array.isArray(i.replacementInfo)&&i.replacementInfo.forEach(({source:g,replacement:B})=>{console.log(fe("Macro replacement:")+`
390
390
  `),console.log(`${vt.dim(g)}
391
391
 
392
392
  ${B}
393
393
  `)}),a&&wn(s)}var Fn=["!node_modules/**","!dist/**","!bundle/**","!**/*.d.ts"],On=["dist","dist/**",".git/**",".idea/**","node_modules/**"];function kn(r,e){if(!e.entryPoints)return;let t=[...e.entryPoints,...Fn];e.outdir&&t.push(`!${e.outdir}/**`,`!${e.outdir}`),r.common?.esbuild?.outdir&&t.push(`!${r.common.esbuild.outdir}/**`,`!${r.common.esbuild.outdir}`),r.variants={argv:{esbuild:{entryPoints:Re(Tn(),t)}}}}function Pn(r,e){e.verbose!==void 0&&(r.verbose=e.verbose);let t=Object.values(r.variants??{});for(let i of t)e.types!==void 0&&(i.types=e.types),e.outdir!==void 0&&(i.esbuild.outdir=e.outdir),e.bundle!==void 0&&(i.esbuild.minify=e.bundle),e.minify!==void 0&&(i.esbuild.minify=e.minify),e.tsconfig!==void 0&&(i.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(i.esbuild.platform=e.platform),e.declaration!==void 0&&(i.declaration=e.declaration),e.failOnError!==void 0&&(i.types={failOnError:e.failOnError})}function An(r){let e=[...On];r.common?.esbuild?.outdir&&e.push(r.common.esbuild.outdir,`${r.common.esbuild.outdir}/**`);let t=Object.values(r.variants??{});for(let i of t)i.esbuild.outdir&&e.push(i.esbuild.outdir,`${i.esbuild.outdir}/**`);return e}async function Rn(r,e){if(!((e.serve??!1)!==!1||r.serve?.start))return;let i,n=r.serve?.dir||e.serve||"dist",o={...r.serve,onStart({host:a,port:c,url:l}){i=l,console.log(`${fe("serve")} ${ae(n)} ${Ee(l)}
394
394
  `),r.serve?.onStart?.({host:a,port:c,url:l})}};return await new Se(o,n).start(),i}async function We(r,e){try{let t=x(process.cwd(),"dist");if(En(t,{recursive:!0,force:!0}),e.typeCheck){let i=await r.typeChack();Sr(i)}else await r.build(e.build)}catch(t){Te(t)}}async function $n(r,e,t,i){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let o=An(e),s=new Ce(o);mr(async()=>{await We(r,t)},i),await We(r,t),await s.start(async a=>{if(r.touchFiles(a),a.includes(t.config)){let c=await ht(t.config);r.reload(c)}console.log(`
395
395
  ${F()} ${ce("Rebuilding")}: files (${a.length})
396
- `),await We(r,t)})}async function Mn(){console.log(Pe());let r=u(Q),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await ht(e.config),i=r.enhancedParse(process.argv,t.userArgv),n=r.parseUserArgv(process.argv,t.userArgv);kn(t,i),Pn(t,i),pr(t);let o=new we(n);o.onEnd=wr,o.onStart=Cr;let s=await Rn(t,i);await $n(o,t,i,s),await We(o,i)}Mn();
396
+ `),await We(r,t)})}async function Mn(){console.log(Pe());let r=u(Z),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await ht(e.config),i=r.enhancedParse(process.argv,t.userArgv),n=r.parseUserArgv(process.argv,t.userArgv);kn(t,i),Pn(t,i),pr(t);let o=new we(n);o.onEnd=wr,o.onStart=Cr;let s=await Rn(t,i);await $n(o,t,i,s),await We(o,i)}Mn();
397
397
  //# sourceMappingURL=bash.js.map