@remotex-labs/xbuild 2.1.2 → 2.1.3

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,7 +21,7 @@ __ _| |_/ /_ _ _| | __| |
21
21
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
22
22
  `;function Pe(){return`
23
23
  \r${rt.burntOrange(ri)}
24
- \rVersion: ${rt.brightPink("2.1.2")}
24
+ \rVersion: ${rt.brightPink("2.1.3")}
25
25
  \r`}function F(){return rt.lightCoral("[xBuild]")}var ii="tsconfig.json",ni="config.xbuild.ts",Ae={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ni},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string",default:ii},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},Mt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Bt,nt;Bt=[A({scope:"singleton"})];var Q=class{parseConfigFile(e){return it(e).help(!1).version(!1).options({config:Ae.config}).parseSync()}parseUserArgv(e,t){return t?it(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=it(oi(e)).locale("en"),n=i.showHelp;return i.showHelp=function(o){return console.log(Pe()),this.group(Object.keys(Ae),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",o=>o.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Ae).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),Mt.forEach(([o,s])=>{i.example(o,s)}),i.parseSync()}};nt=O(null),Q=P(nt,0,"ArgvModule",Bt,Q),k(nt,1,Q);import gt from"readline";import{exec as on}from"child_process";import{cwd as si}from"process";import{readdirSync as ai}from"fs";import{matchesGlob as ot}from"path";function ci(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function Nt(r,e){for(let t of e)if(ot(r,t))return!0;return!1}function li(r,e){let t=r+"/**";for(let i of e)if(ot(r,i)||ot(t,i))return!0;return!1}function Re(r,e){let{include:t,exclude:i}=ci(e),n=Object.create(null),s=si().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=ai(p,{withFileTypes:!0})}catch{return}let m=f.length;for(let g=0;g<m;g++){let B=f[g],W=x(p,B.name),H=W.slice(a);if(B.isDirectory()){(!c||!li(H,i))&&l(W);continue}if(!(c&&Nt(H,i))&&Nt(H,t)){let Ge=W.slice(s),C=H.lastIndexOf("."),ue=C>0?H.slice(0,C):H;n[ue]=Ge}}}return l(r),n}var U=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var Z=class extends v{constructor(e){super(e.text??"","esBuildError"),this.errorMetadata=_(e,{withFrameworkFrames:!0}),this.stack=V(this.errorMetadata,this.name,this.message,e.notes)}};var z=class r extends v{constructor(t,i){if(t instanceof v)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
26
26
  ${t}
27
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>
@@ -362,7 +362,7 @@ ${t}
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}async function Zi(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!re.includes(n))return!1;if(i.arguments.length!==sr(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new Z({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==re[2]?o=await ft(i.arguments,t):o=_e(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),!!o}async function en(r,e,t){if(!h.isCallExpression(r)||!pt(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===re[2]){let s=await ft(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=_e(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function tn(r){let e=r.stage.defineMetadata.disabledMacroNames,t=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!t&&e.size===0)return r.contents;let i=[r.sourceFile],n=new Set;for(;i.length>0;){let s=i.pop(),a=s?.kind;if(!s||!a||t&&(a===h.SyntaxKind.VariableStatement&&await Qi(s,n,r)||a===h.SyntaxKind.ExpressionStatement&&pt(s,r.sourceFile)&&await Zi(s,n,r)||a===h.SyntaxKind.CallExpression&&pt(s,r.sourceFile)&&await en(s,n,r)))continue;if(e.size>0){if(a===h.SyntaxKind.CallExpression){let l=s;h.isIdentifier(l.expression)&&e.has(l.expression.text)&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===h.SyntaxKind.Identifier){let l=s;if(e.has(l.text)){let p=s.parent??s;if(p&&!h.isImportSpecifier(p)&&!h.isExportSpecifier(p)){let f=p?.getText(r.sourceFile);(!h.isCallExpression(p)||p.expression!==s)&&(!f||re.every(m=>!f.includes(m)))&&n.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}let c=s.getChildren(r.sourceFile);for(let l=c.length-1;l>=0;l--)i.push(c[l])}if(n.size===0)return r.contents;let o=Array.from(n);o.sort((s,a)=>a.start-s.start),r.stage.replacementInfo=[];for(let{start:s,end:a,replacement:c}of o)r.stage.replacementInfo.push({source:or(r.contents.slice(s,a)),replacement:or(c)}),r.contents=r.contents.slice(0,s)+c+r.contents.slice(a);return r.contents}async function ar(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Ji.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:a},l=await tn(c);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var cr="$$",lr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function rn(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
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]===`
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
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