UNPKG

jitar

Version:

Distributed runtime for JavaScript and TypeScript to chop monolithic applications into micros.

2 lines 57.9 kB
#!/usr/bin/env node import{promises as e}from"node:fs";import t from"node:path";import{fileURLToPath as r}from"node:url";import{L as s,E as a,P as n,a as i,b as o,c,d as u,e as l,f as h,g as d,h as p,i as m,B as g,N as w,F as f,j as y,A as v,O as b,k as M,l as x,T as S,U as k,S as P,V as A,m as z,R,n as C,o as E,p as H,q as O,r as N,s as T,t as I,u as j,v as $,w as L,x as W,C as q,y as B,z as F,D,G as V}from"./ConfigurationManager-B7adTVpS.js";import K from"node:crypto";import U from"express";import"glob";import"mime-types";import"dotenv";class _ extends Error{constructor(e){super(`Missing argument '${e}'`)}}class G{#e;#t;constructor(e){this.#e=e[2],this.#t=this.#r(e)}getCommand(){return this.#e}containsKey(e){return this.#t.has(e)}getRequiredArgument(e){const t=this.#t.get(e);if(void 0===t)throw new _(e);return t}getOptionalArgument(e,t){return this.#t.get(e)??t}#r(e){const t=e.slice(3),r=new Map;return t.forEach(e=>{const[t,s]=e.split("=");r.set(t.trim(),s?.trim())}),r}}class J{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#s;constructor(e){this.#s=e}async execute(e){for(const t of this.#s.values())if(e.containsKey(t.name))return this.#a(t);this.#n()}#n(){console.log("\njitar <command>\n"),console.log("Available commands:");const e=[...this.#s.values()],t=e.map(e=>e.name),r=this.#i(t);for(const t of e){const e=t.name.padEnd(r," "),s=t.description;console.log(` ${e} ${s}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#a(e){console.log(`\n${e.description}\n`);const t=e.options;if(0===t.length)return void console.log("No options available.\n");console.log("Options:");const r=t.map(e=>e.key),s=this.#i(r);for(const e of t){const t=e.key.padEnd(s," "),r=e.description,a=e.defaultValue?`default: ${e.defaultValue}`:"no default value",n=e.required?"required":`optional - ${a}`;console.log(` ${t} ${r} (${n})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class X{name="about";description="Shows information about Jitar.";options=[];async execute(e){console.log("\nJitar is a JavaScript Distributed Runtime created and maintained by Masking Technology.\n\nMore information can be found at:\n- https://jitar.dev\n- https://masking.tech\n")}}class Q{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class Z extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class Y extends Error{constructor(e){super(`Unknown template: ${e}`)}}const ee=/^[a-zA-Z.\-_]+$/;class te{#o;#c;constructor(e="./"){this.#o=this.#u(),this.#c=this.#l(e)}async init(e,t){this.#h(e,"project"),this.#h(t,"template");if(!1===await this.#d(t))throw new Y(t);await this.#p(e,t)}#u(){const e=t.dirname(r(import.meta.url));return t.join(e,"templates")}#l(e){return t.resolve(e)}#h(e,t){if(!1===ee.test(e))throw new Z(e,t)}async#d(r){try{const s=t.join(this.#o,r);return(await e.stat(s)).isDirectory()}catch{return!1}}#p(r,s){const a=t.join(this.#o,s),n=t.join(this.#c,r);return e.cp(a,n,{recursive:!0,force:!0})}}class re{name="init";description="Initializes a new Jitar project from a template.";options=[{key:"--name",required:!0,description:"Project name used for creating the project folder"},{key:"--template",required:!0,description:"Template to use [react, vue, backend]"},{key:"--location",required:!1,description:"The root location of the project",defaultValue:"./"}];async execute(e){const t=e.getRequiredArgument("--name"),r=e.getRequiredArgument("--template"),s=e.getOptionalArgument("--location",void 0);this.#m(t,r),await this.#g(t,r,s),this.#w(t)}#m(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#g(e,t,r){return new te(r).init(e,t)}#w(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}class se extends Error{#f;#y;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#f=e,this.#y=t}get url(){return this.#f}get reason(){return this.#y}}class ae{#v;constructor(e){this.#v=e}async import(e){const t=this.#v.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new se(t,r)}}}class ne{#b;constructor(e){this.#b=e}locate(e){return`file://${e.startsWith("/")?this.#b.getAbsoluteLocation(`.${e}`):this.#b.getAbsoluteLocation(e)}`}}class ie extends ae{constructor(e){super(new ne(e))}}class oe{#b;#M;constructor(e,t){this.#b=e,this.#M=t}get fileManager(){return this.#b}get importManager(){return this.#M}async filter(...e){return(await Promise.all(e.map(e=>this.#b.filter(e)))).flat().map(e=>this.#b.getRelativeLocation(e))}exists(e){return this.#b.exists(e)}read(e){return this.#b.read(e)}import(e){return this.#M.import(e)}}class ce extends oe{constructor(e){const t=new s(e);super(t,new ie(t))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new ce(t)}}class ue{merge(e,t){const r=void 0!==e.construct?[e.construct]:[],s=[...this.#x(e.fields,t.fields),...r,...this.#x(e.methods,t.methods),...this.#x(e.getters,t.getters),...this.#x(e.setters,t.setters)];return new a(e.identifier,t.identifier,s)}#x(e,t){const r=new Map;return t.forEach(e=>r.set(e.identifier,e)),e.forEach(e=>r.set(e.identifier,e)),[...r.values()]}}class le{#S=new n;#k=new ue;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,a]of r){if("function"!=typeof a.toString)continue;const r=a.toString();if(r.startsWith("class"))s.push(this.fromClass(a,t));else if(r.startsWith("function"))s.push(this.fromFunction(a));else{const t=new i(e,!1),a=new o(r);s.push(new c("var",t,a))}}return new u(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#P(e):this.#A(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const a=this.fromClass(s,!0);return this.#k.merge(r,a)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#S.parseFunction(t)}createInstance(e,t=[]){return new e(...t)}getClass(e){return e.constructor}getParentClass(e){return Object.getPrototypeOf(e)}isClassObject(e){return this.isClass(e.constructor)}isFunctionObject(e){return this.isFunction(e.constructor)}isClass(e){return e.toString().startsWith("class")}isFunction(e){return e.toString().startsWith("function")||e.toString().startsWith("async function")}#P(e){const t=e.toString();return this.#S.parseClass(t)}#A(e){const t=this.createInstance(e),r=this.#z(e,t);return new a(e.name,void 0,r)}#z(e,t){return[...this.#R(t),...this.#C(e)]}#R(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],a=void 0!==t?new o(String(t)):void 0,n=new l(e,"public","instance",a);s.push(n)}return s}#C(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],a=s.value;if(a instanceof Function==!1)continue;const n=this.fromFunction(a);"constructor"===n.identifier?r.push(new h(n.parameters,n.body)):void 0!==s.get?r.push(new d(n.identifier,"public","instance",n.body)):void 0!==s.set?r.push(new p(n.identifier,"public","instance",n.parameters[0],n.body)):r.push(new m(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return r}}const he="normal",de="dry",pe=200,me=400,ge=401,we=402,fe=403,ye=404,ve=418,be=500,Me=501;class xe extends g{#E;constructor(e){super(`Invalid version number '${e}'`),this.#E=e}get number(){return this.#E}}class Se extends w{#H;constructor(e){super(`Procedure '${e}' not found`),this.#H=e}get fqn(){return this.#H}}class ke extends f{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Pe extends g{#O;constructor(e){super(`Unknown parameter ${e}`),this.#O=e}get parameterName(){return this.#O}}class Ae extends g{#O;constructor(e){super(`Missing value for parameter '${e}'`),this.#O=e}get parameterName(){return this.#O}}class ze extends g{#O;constructor(e){super(`Invalid value for parameter '${e}'`),this.#O=e}get parameterName(){return this.#O}}class Re{extract(e,t){const r=this.#N(e,t),s=[];for(const t of e){const e=this.#T(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Pe(e)}return s}#N(e,t){const r=new Map;for(const[s,a]of t){if(this.#I(s)){const t=this.#j(s);!0===this.#$(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#I(e){return e.startsWith("*")}#j(e){return e.substring(1)}#$(e,t){return void 0!==e.find(e=>e.name===t)}#T(e,t,r){return e instanceof y?this.#L(e,t,r):this.#W(e,t)}#L(e,t,r){const s=t.get(e.name);if(this.#q(e,s,r))throw new Ae(e.name);if(this.#B(e,s,r))throw new ze(e.name);return t.delete(e.name),s}#W(e,t){return e instanceof v?this.#F(e,t):this.#D(e,t)}#F(e,t){const r=this.#V(e,t);return void 0!==r?Object.values(r):void 0}#D(e,t){return this.#V(e,t)}#V(e,t){const r=e instanceof v,s={},a=[];let n=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#T(o,t,e);void 0!==u?n=!0:!1===o.isOptional&&a.push(o.name),s[c]=u}if(!0===n&&a.length>0)throw new Ae(a[0]);return n?s:void 0}#q(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#B(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof v&&t instanceof Array==!1||r instanceof b&&t instanceof Object==!1)}}class Ce{toStatus(e){return e instanceof g?me:e instanceof f?fe:e instanceof w?ye:e instanceof M?Me:e instanceof x?we:e instanceof S?ve:e instanceof k?ge:be}fromStatus(e,t){switch(e){case me:return new g(t);case fe:return new f(t);case ye:return new w(t);case Me:return new M(t);case we:return new x(t);case ve:return new S(t);case ge:return new k(t);default:return new P(t)}}}const Ee=/^\d+(?:\.\d+){0,2}$/;class He{parse(e){if(0===e.trim().length)return A.DEFAULT;if(!1===Ee.test(e))throw new xe(e);const t=e.split(".");switch(t.length){case 1:return new A(Number.parseInt(t[0]));case 2:return new A(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new A(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class Oe extends w{#H;#K;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#H=e,this.#K=t}get fqn(){return this.#H}get version(){return this.#K}}class Ne extends P{constructor(){super("Invalid segment")}}class Te{#U=new Map;addSegment(e){this.#U.set(e.id,e)}clearSegments(){this.#U.clear()}getClassNames(){const e=new Set;for(const t of this.#U.values()){t.getClasses().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasClass(e){return this.getClassNames().includes(e)}getClass(e){for(const t of this.#U.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#U.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#U.values()){t.getExposedProcedures().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}getProcedure(e){for(const t of this.#U.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Ie{#_;#G;#J=new Re;#X=new Ce;#Q=new Te;constructor(e,t=[]){this.#_=e,this.#G=t}async start(){return this.#Z()}async stop(){return this.#Y()}async loadSegment(e){const t=await this.#_.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof z==!1)throw new Ne;this.#Q.addSegment(e)}getClassNames(){return this.#Q.getClassNames()}hasClass(e){return this.#Q.hasClass(e)}getClass(e){return this.#Q.getClass(e)}getClassByImplementation(e){return this.#Q.getClassByImplementation(e)}getProcedureNames(){return this.#Q.getProcedureNames()}hasProcedure(e){return this.#Q.hasProcedure(e)}getProcedure(e){return this.#Q.getProcedure(e)}async run(e){const t=this.#ee(e.fqn,e.version),r=this.#J.extract(t.parameters,e.args);return e.mode===de?new R(pe,void 0):this.#te(e,t,r)}async#Z(){await Promise.all(this.#G.map(e=>this.loadSegment(e)))}#Y(){this.#Q.clearSegments()}#ee(e,t){const r=this.#Q.getProcedure(e);if(void 0===r)throw new Se(e);const s=r.getImplementation(t);if(void 0===s)throw new Oe(r.fqn,t.toString());return s}async#te(e,t,r){try{const s=await t.executable.call(e,...r);return new R(pe,s)}catch(e){const t=this.#X.toStatus(e);return new R(t,e)}}}let je=class{#re;#se=new C;constructor(e){this.#re=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,a=t.modules.map(e=>this.#ae(e,s,r));await Promise.all(a)}async#ae(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#ne(e,t,r);const a=s.map(s=>this.#ie(e,t,s,r)),n=s[0].getModule(e.filename),i=n?.hasImplementations()?this.#oe(e,s):Promise.resolve();await Promise.all([...a,i]),this.#re.delete(e.filename)}async#ne(e,t,r){const s=e.filename,a=new E(e,t,r).generate();return this.#re.write(s,a)}async#ie(e,t,r,s){const a=this.#se.addSubExtension(e.filename,r.name),n=new E(e,t,s,r).generate();return this.#re.write(a,n)}async#oe(e,t){const r=this.#se.addSubExtension(e.filename,"remote"),s=new H(e,t).generate();return this.#re.write(r,s)}};const $e=["Segment","Class","Procedure","Implementation","Version","NamedParameter","ArrayParameter","ObjectParameter"];class Le{#ce;#se=new C;#ue=new He;constructor(e){this.#ce=e}generate(){const e=this.#le(),t=this.#he(),r=this.#de();return new u([...e,t,r]).toString()}#le(){return[this.#pe(),...this.#me()]}#pe(){const e=$e.map(e=>new N(e));return new O(e,"jitar")}#me(){const e=[],t=this.#ce.name,r=this.#ce.getSegmentedModules();for(const s of r){const r=`./${this.#se.addSubExtension(s.filename,t)}`;if(0===s.members.length){const t=new O([],r);e.push(t);continue}const a=s.members.map(e=>new N(e.importKey,e.id)),n=new O(a,r);e.push(n)}return e}#he(){const e=new N("segment","default");return new T([e],void 0)}#de(){const e=[],t=this.#ce.name,r=this.#ce.classes,s=this.#ce.procedures;e.push(`new Segment("${t}")`);for(const t of r)e.push(`\t.addClass(new Class("${t.fqn}", ${t.id}))`);for(const t of s){e.push(`\t.addProcedure(new Procedure("${t.fqn}")`);for(const r of t.implementations){const t=this.#ge(r.version),s=this.#we(r.model);e.push(`\t\t.addImplementation(new Implementation(${t}, "${r.access}", ${s}, ${r.id}))`)}e.push("\t)")}const a=e.join("\n"),n=new o(a),u=new i("segment");return new c("const",u,n)}#ge(e){const t=this.#ue.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#we(e){return`[${this.#fe(e.parameters).join(", ")}]`}#fe(e){const t=[];for(const r of e)t.push(this.#ye(r));return t}#ye(e){return e.binding instanceof I?this.#ve(e):e.binding instanceof j?this.#be(e):this.#Me(e)}#Me(e){return`new NamedParameter("${e.binding}", ${void 0!==e.initializer})`}#ve(e){const t=e.binding;return`new ArrayParameter([${this.#fe(t.elements).join(", ")}])`}#be(e){const t=e.binding;return`new ObjectParameter([${this.#fe(t.elements).join(", ")}])`}}let We=class{#re;#xe;constructor(e,t){this.#re=e,this.#xe=t}async build(e){const t=e.segmentation.segments.map(e=>this.#Se(e));await Promise.all(t)}async#Se(e){const t=`${e.name}.segment.js`,r=new Le(e).generate();await this.#re.write(t,r),this.#xe.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}};class qe{#ke;#Pe;constructor(e,t){const r=e.target;this.#ke=new je(r),this.#Pe=new We(r,t)}async build(e){await Promise.all([this.#ke.build(e),this.#Pe.build(e)])}}const Be=0,Fe=1,De=2,Ve=3,Ke=4;class Ue{#Ae;#ze;constructor(e=Fe,t=console){this.#Ae=e,this.#ze=t}debug(...e){if(this.#Ae>Be)return;const t=this.#Re("DEBUG",e);this.#ze.debug(t)}info(...e){if(this.#Ae>Fe)return;const t=this.#Re("INFO",e);this.#ze.info(t)}warn(...e){if(this.#Ae>De)return;const t=this.#Re("WARN",e);this.#ze.warn(t)}error(...e){if(this.#Ae>Ve)return;const t=this.#Re("ERROR",e);this.#ze.error(t)}fatal(...e){const t=this.#Re("FATAL",e);this.#ze.error(t)}#Re(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Ce(e)).join(" ")}`}#Ce(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#Ee(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#He(t)}${r}`}#Ee(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Ce(e,t)).join(",\n")}\n${this.#He(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#He(e){return" ".repeat(e)}}class _e extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class Ge{parse(e){switch(e.toUpperCase()){case"DEBUG":return Be;case"INFO":return Fe;case"WARN":return De;case"ERROR":return Ve;case"FATAL":return Ke;default:throw new _e(e)}}}class Je{#xe;#se;#b;#Oe;#Ne;constructor(e,t){this.#xe=new Ue(t),this.#se=new C;const r=this.#se.makePathAbsolute(e.source,e.meta.root),a=this.#se.makePathAbsolute(e.target,e.meta.root),n=this.#se.makePathAbsolute(e.resources,e.meta.root),i=this.#se.makePathAbsolute(e.segments,e.meta.root);this.#b=new $(new s(r),new s(a),new s(n),new s(i),e.build.ignore),this.#Oe=new L(this.#b),this.#Ne=new qe(this.#b,this.#xe)}async build(){const e=this.#b.source,t=this.#b.resource,r=this.#b.segment,s=await e.filterWithIgnores(W.MODULE_PATTERN,this.#b.sourceIgnores),a=await t.filter(W.RESOURCE_PATTERN),n=await r.filter(W.SEGMENT_PATTERN),i=await this.#Oe.read(s,a,n);return this.#Ne.build(i)}}class Xe{name="build";description="Builds the application (creates segment bundles).";options=[{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getOptionalArgument("--log-level",void 0),a=this.#Te(s),n=new q;await n.configureEnvironment(t);const i=await n.getRuntimeConfiguration(r);return new Je(i,a).build()}#Te(e){if(void 0===e)return;return(new Ge).parse(e)}}const Qe="content-type",Ze="x-content-type-options",Ye="x-jitar-content-type",et="x-jitar-procedure-version",tt="x-powered-by",rt="nosniff",st="application/json",at="application/octet-stream";class nt extends Error{constructor(){super("Invalid worker id")}}class it{#f;#Ie;#X=new Ce;#je=new B;constructor(e,t){this.#f=e,this.#Ie=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#f}/${e}`,r=await this.#$e(t,{method:"GET"}),s=r.headers.get(Qe)??at,a=await r.arrayBuffer(),n=Buffer.from(a);return new F(e,s,n)}async isHealthy(){const e=`${this.#f}/health/status`,t=await this.#$e(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#f}/health`,t=await this.#$e(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#f}/workers`,a={url:e,procedureNames:t,trustKey:r},n={method:"POST",headers:{"Content-Type":st},body:JSON.stringify(a)},i=await this.#$e(s,n),o=i.headers.get(Qe);if(null===o||!1===o.includes(st))throw new nt;const c=await i.json();if(!1===this.#je.validate(c,{id:{type:"string",required:!0}}).valid)throw new nt;return c.id}async reportWorker(e,t){const r=`${this.#f}/workers/${e}/report`,s={state:t},a={method:"POST",headers:{"Content-Type":st},body:JSON.stringify(s)};await this.#$e(r,a)}async removeWorker(e){const t=`${this.#f}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":st}};await this.#$e(t,r)}async run(e){e.setHeader(Qe,st);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[et]=s;const a=`${this.#f}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:r,body:await this.#Le(t)},i=await this.#$e(a,n,!1),o=i.status,c=await this.#We(i),u=this.#qe(i);return new R(o,c,u)}async#$e(e,t,r=!0){const s=await this.#Ie.execute(e,t);if(r&&this.#Be(s)){const e=await this.#We(s);throw this.#X.fromStatus(s.status,String(e))}return s}#Be(e){return e.status<200||e.status>399}async#Le(e){return JSON.stringify(e)}async#We(e){const t=e.headers.get(Ye)??e.headers.get(Qe);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const r=await e.text();return t?.includes("boolean")?"true"===r:t?.includes("number")?Number(r):r}#qe(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class ot{async execute(e,t){return fetch(e,t)}}class ct{#Ie;constructor(e=new ot){this.#Ie=e}build(e){return new it(e,this.#Ie)}}const ut={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class lt{get url(){throw new M}get state(){return ut.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ut.AVAILABLE}provide(e){throw new M}}class ht{get url(){throw new M}get state(){return ut.AVAILABLE}get trustKey(){throw new M}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ut.AVAILABLE}getProcedureNames(){throw new M}hasProcedure(e){throw new M}run(e){throw new M}}class dt{#Fe=ut.STOPPED;get state(){return this.#Fe}set state(e){this.#Fe=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#De(ut.STOPPED)}isStopped(){return this.#Ve(ut.STOPPED)}isAvailable(){return this.#Ve(ut.AVAILABLE)}setStarting(){this.#Fe=ut.STARTING}setAvailable(){this.#Fe=ut.AVAILABLE}setUnavailable(){this.#Fe=ut.UNAVAILABLE}setAvailability(e){return this.#Fe=e?ut.AVAILABLE:ut.UNAVAILABLE,this.#Fe}setStopping(){this.#Fe=ut.STOPPING}setStopped(){this.#Fe=ut.STOPPED}#Ve(...e){return e.includes(this.#Fe)}#De(...e){return!1===this.#Ve(...e)}}class pt extends k{constructor(){super("Invalid trust key")}}class mt{#f;#Ke;#Ue;#_e;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Ue=e.healthManager,this.#_e=e.workerManager}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await this.#Ue.start(),this.#_e.start(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{this.#_e.stop(),await this.#Ue.stop()})}async isHealthy(){return this.#Ue.isHealthy()}async getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async addWorker(e){if(this.#Je(e.trustKey))throw new pt;return await e.start(),this.#_e.addWorker(e)}getWorker(e){return this.#_e.getWorker(e)}async reportWorker(e,t){return this.#_e.reportWorker(e,t)}async removeWorker(e){return this.#_e.removeWorker(e).stop()}getProcedureNames(){return this.#_e.getProcedureNames()}hasProcedure(e){return this.#_e.hasProcedure(e)}async run(e){return this.#_e.run(e)}#Je(e){return void 0!==this.#Ke&&e!==this.#Ke}}class gt{#f;#Xe;#Ge=new dt;constructor(e){this.#f=e.url,this.#Xe=e.remote}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}getProcedureNames(){throw new M}hasProcedure(e){throw new M}addWorker(e){return this.#Xe.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Xe.reportWorker(e,t)}removeWorker(e){return this.#Xe.removeWorker(e)}run(e){return this.#Xe.run(e)}}class wt extends P{#Qe;constructor(e){super(`No worker available for procedure '${e}'`),this.#Qe=e}get name(){return this.#Qe}}class ft{#Ze=[];#Ye=0;get workers(){return this.#Ze}addWorker(e){this.#Ze.includes(e)||this.#Ze.push(e)}removeWorker(e){const t=this.#Ze.indexOf(e);-1!==t&&this.#Ze.splice(t,1)}getNextWorker(){const e=this.#Ze.filter(e=>e.isAvailable());if(0!==e.length)return this.#Ye>=e.length&&(this.#Ye=0),e[this.#Ye++];this.#Ye=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new wt(e.fqn);return t.run(e)}}class yt{generate(){return K.randomUUID()}}class vt extends P{#et;constructor(e){super(`Unknown worker id '${e}'`),this.#et=e}get id(){return this.#et}}class bt{#Ze=new Map;#tt=new Map;#rt=new yt;#st;constructor(e,t){this.#st=e.create(()=>this.#at(),t)}get workers(){return[...this.#Ze.values()]}get balancers(){return this.#tt}start(){this.#st.start()}stop(){this.#st.stop()}getProcedureNames(){const e=this.workers.map(e=>e.getProcedureNames());return[...new Set(e.flat()).values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}addWorker(e){e.id=this.#rt.generate(),this.#Ze.set(e.id,e);for(const t of e.getProcedureNames()){this.#nt(t).addWorker(e)}return e.id}getWorker(e){const t=this.#Ze.get(e);if(void 0===t)throw new vt(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#Ze.delete(e);for(const e of t.getProcedureNames()){const r=this.#it(e);void 0!==r&&r.removeWorker(t)}return t}#it(e){return this.#tt.get(e)}#nt(e){let t=this.#it(e);return void 0===t&&(t=new ft,this.#tt.set(e,t)),t}async run(e){const t=this.#it(e.fqn);if(void 0===t)throw new Se(e.fqn);return t.run(e)}async#at(){const e=this.workers.map(e=>this.#ot(e));await Promise.allSettled(e)}async#ot(e){await e.updateState()===ut.STOPPED&&this.removeWorker(e.id)}}class Mt{#f;#ct;#ut;#Ge=new dt;constructor(e){this.#f=e.url,this.#ct=e.provider,this.#ut=e.runner}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){return this.#ut.trustKey}get provider(){return this.#ct}get runner(){return this.#ut}async start(){return this.#Ge.start(async()=>{await Promise.all([this.#ct.start(),this.#ut.start()]),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await Promise.allSettled([this.#ut.stop(),this.#ct.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#ct.isHealthy(),this.#ut.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#ct.getHealth(),this.#ut.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}provide(e){return this.#ct.provide(e)}getProcedureNames(){return this.#ut.getProcedureNames()}hasProcedure(e){return this.#ut.hasProcedure(e)}run(e){return this.#ut.run(e)}}class xt{#f;#Ue;#lt;#ht;#dt;#pt;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ue=e.healthManager,this.#lt=e.sourcingManager,this.#ht=e.assets,this.#dt=e.indexFilename??"index.html",this.#pt=e.serveIndexOnNotFound??false}get url(){return this.#f}get state(){return this.#Ge.state}async start(){return this.#Ge.start(async()=>{await this.#Ue.start(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Ue.stop()})}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async provide(e){if(this.#mt(e))return this.provide(this.#dt);if(!1===this.#ht.has(e))throw new D(e);return this.#lt.read(e)}#mt(e){return""===e||e!==this.#dt&&(this.#pt&&!1===this.#ht.has(e))}}class St{#f;#Xe;#Ge=new dt;constructor(e){this.#f=e.url,this.#Xe=e.remote}get url(){return this.#f}get state(){return this.#Ge.state}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}provide(e){return this.#Xe.provide(e)}}class kt extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class Pt extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class At extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class zt extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Rt{#gt=[];addSerializer(e){e.parent=this,this.#gt.unshift(e)}async serialize(e){const t=this.#gt.find(t=>t.canSerialize(e));if(void 0===t)throw new zt(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#gt.find(t=>t.canDeserialize(e));if(void 0===t)throw new At(typeof e);return t.deserialize(e)}}class Ct extends Error{constructor(){super("Parent serializer not set")}}class Et{#wt;set parent(e){this.#wt=e}serializeOther(e){if(void 0===this.#wt)throw new Ct;return this.#wt.serialize(e)}deserializeOther(e){if(void 0===this.#wt)throw new Ct;return this.#wt.deserialize(e)}}class Ht extends Et{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const r of e)t.push(await this.serializeOther(r));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Ot extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Nt extends Et{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new Ot(e.value)}}}class Tt extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class It extends Et{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Tt(e.base64)}}}const jt=new le;class $t extends Et{#ft;constructor(e){super(),this.#ft=e}canSerialize(e){return e instanceof Object&&jt.isClassObject(e)}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"class"===t.name&&"string"==typeof t.key&&t.args instanceof Object&&t.args.constructor===Object&&t.fields instanceof Object&&t.fields.constructor===Object}async serialize(e){const t=jt.getClass(e),r=jt.fromClass(t,!0),s=this.#yt(r),a=this.#ft.resolveKey(t);if(void 0===a)throw new kt(t.name);return{serialized:!0,key:a,name:"class",args:await this.#vt(r,s,e),fields:await this.#bt(r,s,e)}}#yt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#vt(e,t,r){const s={};for(const[a,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(r[n]):void 0;s[a.toString()]=t}return s}async#bt(e,t,r){const s={};for(const a of e.writable){const n=a.identifier;t.includes(n)||!1===e.canRead(n)||(s[n]=await this.serializeOther(r[n]))}return s}async deserialize(e){const t=await this.#Mt(e);if(void 0===t)throw new kt(e.key);if(t instanceof Function==!1)throw new Pt(e.key);const r=await this.#xt(t,e.args),s=jt.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#xt(e,t){const r=jt.fromClass(e,!0).construct,s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),a=t[s];return this.deserializeOther(a)});return Promise.all(s)}async#Mt(e){return globalThis[e.key]??this.#ft.resolveClass(e.key)}}class Lt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class Wt extends Et{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new Lt(e.value);return t}}class qt extends Et{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class Bt extends Et{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],r=[];for(const[s,a]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(a));return{serialized:!0,name:"Map",entries:{keys:t,values:r}}}async deserialize(e){const t=e.entries.keys,r=e.entries.values,s=new Map;for(let e=0;e<t.length;e++){const a=await this.deserializeOther(t[e]),n=await this.deserializeOther(r[e]);s.set(a,n)}return s}}class Ft extends Et{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.serializeOther(s)}return t}async deserialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.deserializeOther(s)}return t}}class Dt extends Et{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class Vt extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Kt extends Et{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new Vt(e.source,e.flags)}}}class Ut extends Et{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const r of e.values())t.push(await this.serializeOther(r));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const _t=new le;class Gt extends Et{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,r=new DataView(e.buffer),s=[];for(let e=0;e<r.byteLength;e++)s.push(r.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:s}}async deserialize(e){const t=e.type,r=e.bytes,s=new ArrayBuffer(r.length),a=new DataView(s);for(let e=0;e<r.length;e++)a.setUint8(e,r[e]);const n=globalThis[t];return _t.createInstance(n,[s])}}class Jt extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class Xt extends Et{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new Jt(e.value)}}}class Qt{static build(e){const t=new Rt;return t.addSerializer(new Dt),t.addSerializer(new Ft),void 0!==e&&t.addSerializer(new $t(e)),t.addSerializer(new qt),t.addSerializer(new Kt),t.addSerializer(new Nt),t.addSerializer(new Xt),t.addSerializer(new Wt),t.addSerializer(new Ut),t.addSerializer(new Bt),t.addSerializer(new Ht),t.addSerializer(new Gt),"undefined"!=typeof Buffer&&t.addSerializer(new It),t}}class Zt{#St;constructor(e){this.#St=e}resolveKey(e){const t=this.#St.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#St.getClass(e);return t?.implementation}}class Yt extends k{constructor(){super("Request not trusted")}}const er="X-Jitar-Trust-Key",tr="X-Jitar-Data-Encoding",rr="serialized";class sr{#et;#f;#Ke;#kt;#Pt;#St;#Ue;#At;#zt;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#kt=e.gateway,this.#Pt=!0===e.registerAtGateway,this.#St=e.executionManager,this.#Ue=e.healthManager;const t=e.scheduleManager;this.#At=t.create(()=>this.#Rt(),e.reportInterval);const r=new Zt(this.#St);this.#zt=Qt.build(r)}get id(){return this.#et}set id(e){this.#et=e}get state(){return this.#Ge.state}get url(){return this.#f}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await Promise.all([this.#St.start(),this.#Ue.start()]),void 0!==this.#kt&&(await this.#kt.start(),this.#Pt&&(this.#et=await this.#kt.addWorker(this),this.#At.start())),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{void 0!==this.#kt&&(void 0!==this.#et&&(this.#At.stop(),await this.#kt.removeWorker(this.#et)),await this.#kt.stop()),await Promise.all([this.#Ue.stop(),this.#St.stop()])})}getProcedureNames(){return this.#St.getProcedureNames()}hasProcedure(e){return this.#St.hasProcedure(e)}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}isAvailable(){return this.#Ge.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async reportState(e){if(void 0!==this.#kt&&void 0!==this.#et)return this.#kt.reportWorker(this.#et,e)}async run(e){return this.#Ct(e)?this.#Et(e):this.#Ht(e)}#Ct(e){return void 0===this.#kt||this.#St.hasProcedure(e.fqn)}async#Et(e){const t=this.#St.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#Ot(r))throw new Se(e.fqn);if(this.#Nt(e,r))throw new Yt;const s=e.getHeader(tr);s===rr&&(e=await this.#Tt(e)),e.removeHeader(tr);const a=await this.#St.run(e);return s===rr?this.#It(a):a}#Ot(e){return void 0===e||e.private}#Nt(e,t){if(t.public)return!1;const r=e.getHeader(er);return this.#Ke!==r}async#Ht(e){(e=await this.#jt(e)).setHeader(tr,rr),void 0!==this.#Ke&&e.setHeader(er,this.#Ke);const t=await this.#kt.run(e);return this.#$t(t)}async#jt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#zt.serialize(s);t.set(r,e)}return new V(e.fqn,e.version,t,e.headers,e.mode)}async#Tt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#zt.deserialize(s);t.set(r,e)}return new V(e.fqn,e.version,t,e.headers,e.mode)}async#It(e){const t=await this.#zt.serialize(e.result);return new R(e.status,t,e.headers)}async#$t(e){const t=await this.#zt.deserialize(e.result);return new R(e.status,t,e.headers)}async#Rt(){const e=await this.updateState();return this.reportState(e)}}class ar extends dt{#Lt;#Wt;#qt=Date.now();#Bt=Date.now();constructor(e=6e3,t=18e3){super(),this.#Lt=e,this.#Wt=t}report(e){this.#qt=Date.now(),this.state=e}update(){this.#Bt=Date.now();const e=this.#Bt-this.#qt;return e>=this.#Lt&&(this.state=e>=this.#Wt?ut.STOPPED:ut.UNAVAILABLE),this.state}}class nr{#et;#f;#Ke;#Ft;#Xe;#Ge;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Ft=e.procedureNames,this.#Xe=e.remote,this.#Ge=new ar(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#et}set id(e){this.#et=e}get state(){return this.#Ge.state}get url(){return this.#f}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}getProcedureNames(){return[...this.#Ft.values()]}hasProcedure(e){return this.#Ft.has(e)}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}isAvailable(){return this.#Ge.isAvailable()}async updateState(){return this.#Ge.update()}async reportState(e){this.#Ge.report(e)}run(e){return this.#Xe.run(e)}}class ir{#Dt;#Lt;#Wt;constructor(e,t,r){this.#Dt=e,this.#Lt=t,this.#Wt=r}build(e,t,r){const s=this.#Dt.build(e),a=new Set(t),n=this.#Lt,i=this.#Wt;return new nr({url:e,trustKey:r,remote:s,procedureNames:a,unavailableThreshold:n,stoppedThreshold:i})}}class or{#ut;constructor(e){this.#ut=e}async handle(e,t){return this.#ut.run(e)}}class cr{#ue=new He;constructor(){this.#Vt()}#Vt(){const e=globalThis;e.__run=this.#Kt.bind(this),e.ProcedureNotAccessible=ke}async#Kt(e,t,r,s){const a=this.#ue.parse(t),n=new Map(Object.entries(r)),i=s instanceof V?s.headers:new Map,o=new V(e,a,n,i,he),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==pe)throw u.result;return u.result}}const ur="starting",lr="started",hr="stopping",dr="stopped";class pr extends P{constructor(){super("Invalid health check")}}class mr{#Fe=dr;#Ut=new Map;#_;#_t;constructor(e,t=[]){this.#_=e,this.#_t=t}get state(){return this.#Fe}async start(){if(this.#Fe===dr)try{this.#Fe=ur,await this.#Gt(),this.#Fe=lr}catch(e){throw this.#Fe=dr,e}}async stop(){if(this.#Fe===lr)try{this.#Fe=hr,this.clearHealthChecks(),this.#Fe=dr}catch(e){throw this.#Fe=lr,e}}async loadHealthCheck(e){const t=await this.#Jt(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new pr;this.#Ut.set(e.name,e)}clearHealthChecks(){this.#Ut.clear()}async isHealthy(){const e=[];for(const t of this.#Ut.values()){const r=this.#Xt(t);e.push(r)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,r]of this.#Ut){const s=this.#Xt(r).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(s)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#Qt(e,t))).then(()=>t)}async#Gt(){(await Promise.all(this.#_t.map(e=>this.#Jt(e)))).forEach(e=>this.addHealthCheck(e))}async#Jt(e){return(await this.#_.import(e)).default}#Qt(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#Xt(e){const t=e.isHealthy(),r=e.timeout;if(void 0===r)return t;const s=new Promise(e=>{setTimeout(e,r)}).then(()=>!1);return Promise.race([s,t])}}const gr="starting",wr="started",fr="stopping",yr="stopped";class vr extends P{constructor(){super("Invalid middleware")}}class br{#Fe=yr;#Zt=[];#_;#Yt;constructor(e,t=[]){this.#_=e,this.#Yt=t}get state(){return this.#Fe}async start(){if(this.#Fe===yr)try{this.#Fe=gr,await this.#er(),this.#Fe=wr}catch(e){throw this.#Fe=yr,e}}async stop(){if(this.#Fe===wr)try{this.#Fe=fr,this.clearMiddlewares(),this.#Fe=yr}catch(e){throw this.#Fe=wr,e}}async loadMiddleware(e){const t=await this.#tr(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new vr;this.#Zt.push(e)}getMiddleware(e){return this.#Zt.find(t=>t instanceof e)}clearMiddlewares(){this.#Zt=[]}handle(e){return this.#rr(e,0)()}async#er(){(await Promise.all(this.#Yt.map(e=>this.#tr(e)))).forEach(e=>this.addMiddleware(e))}async#tr(e){return(await this.#_.import(e)).default}#rr(e,t){const r=this.#Zt[t];if(void 0===r)return async()=>new R(pe);const s=this.#rr(e,t+1);return async()=>await r.handle(e,s)}}class Mr{#xe;#sr;#ar;#nr=null;constructor(e,t,r=5e3){this.#xe=e,this.#sr=t,this.#ar=r}start(){this.#ir()}stop(){null!==this.#nr&&(clearTimeout(this.#nr),this.#nr=null)}#ir(){this.#nr=setTimeout(async()=>{null!==this.#nr&&(await this.#or(),this.#ir())},this.#ar),this.#nr.unref()}async#or(){try{await this.#sr()}catch(e){this.#xe.warn("Scheduled task failed",e)}}}class xr{#cr=[];#xe;constructor(e){this.#xe=e}create(e,t){const r=new Mr(this.#xe,e,t);return this.#cr.push(r),r}remove(e){const t=this.#cr.indexOf(e);t<0||this.#cr.splice(t,1)}startAll(){this.#cr.forEach(e=>e.start())}stopAll(){this.#cr.forEach(e=>e.stop())}}const Sr="application/null",kr="application/undefined",Pr="application/boolean",Ar="application/number",zr="application/json",Rr="text/plain",Cr=200,Er=400,Hr=401,Or=402,Nr=403,Tr=404,Ir=418,jr=500,$r=501;class Lr extends cr{#ur;#lr;#hr;#dr;#xe;#ue=new He;constructor(e){super(),this.#ur=e.proxy,this.#lr=e.remoteWorkerBuilder,this.#hr=e.resourceManager,this.#dr=e.middlewareManager,this.#xe=e.logger}get proxy(){return this.#ur}getTrustKey(){return this.#ur.trustKey}async start(){await this.#pr(),this.#xe.info(`Server started at ${this.#ur.url}`),this.#ur.runner instanceof sr&&this.#xe.info("RPC procedures:",this.#ur.runner.getProcedureNames())}async stop(){await this.#mr(),this.#xe.info("Server stopped")}async getHealth(){try{const e=await this.#ur.getHealth();return this.#xe.debug("Got health"),this.#gr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to get health:",t),this.#wr(e)}}async isHealthy(){try{const e=await this.#ur.isHealthy();return this.#xe.debug("Got health status"),this.#fr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to get health status:",t),this.#wr(e)}}async provide(e){try{const t=await this.#ur.provide(e.filename);return this.#xe.info("Provided file:",e.filename),this.#yr(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.warn("Failed to provide file:",t),this.#wr(e)}}async run(e){try{const t=this.#vr(e),r=await this.#dr.handle(t);return this.#xe.info("Ran request:",t.fqn),this.#br(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed run request:",t),this.#wr(e)}}async runInternal(e){return this.#ur.run(e)}async addWorker(e){try{const t=this.#Mr(),r=this.#lr.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#xe.info("Added worker:",r.url),this.#xr({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to add worker:",t),this.#wr(e)}}async reportWorker(e){try{const t=this.#Sr(e.state),r=this.#Mr();return await r.reportWorker(e.id,t),this.#xe.debug("Reported worker:",e.id),this.#xr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to report worker:",t),this.#wr(e)}}async removeWorker(e){try{const t=this.#Mr();return await t.removeWorker(e.id),this.#xe.info("Removed worker:",e.id),this.#xr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to remove worker:",t),this.#wr(e)}}async#pr(){await this.#hr.start(),await Promise.all([this.#ur.start(),this.#dr.start()]);const e=new or(this.#ur);this.#dr.addMiddleware(e)}async#mr(){await Promise.all([this.#dr.stop(),this.#ur.stop()]),await this.#hr.stop()}#vr(e){const t=this.#kr(e.fqn),r=this.#Pr(e.version),s=this.#Ar(e.args),a=this.#zr(e.headers);return new V(t,r,s,a,e.mode)}#kr(e){if(0===e.length)throw new g("Missing procedure name");if(e.includes(".."))throw new g("Invalid procedure name");return e}#Pr(e){return"string"!=typeof e?A.DEFAULT:this.#ue.parse(e)}#Ar(e){return new Map(Object.entries(e))}#zr(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();t.set(e,a)}return t}#Sr(e){if(!1===Object.values(ut).includes(e))throw new g("Invalid state value");return e}#gr(e){return{result:Object.fromEntries(e),contentType:zr,headers:{},status:Cr}}#fr(e){return{result:e,contentType:Pr,headers:{},status:Cr}}#yr(e){return{result:e.content,contentType:e.type,headers:{},status:Cr}}#br(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Rr(t),headers:this.#Cr(e.headers),status:e.status}}#wr(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Rr(t),headers:{},status:this.#Er(e)}}#xr(e){return{result:e,contentType:this.#Rr(e),headers:{},status:Cr}}#Rr(e){if(void 0===e)return kr;if(null===e)return Sr;switch(typeof e){case"boolean":return Pr;case"number":return Ar;case"object":return zr;default:return Rr}}#Cr(e){return Object.fromEntries(e)}#Er(e){return e instanceof g?Er:e instanceof f?Nr:e instanceof w?Tr:e instanceof M?$r:e instanceof x?Or:e instanceof S?Ir:e instanceof k?Hr:jr}#Mr(){const e=this.#ur.runner;if(e instanceof mt==!1)throw new g("Cannot remove worker from remote gateway");return e}}class Wr extends Error{constructor(){super("Unknown service configured")}}class qr{#lt;#Hr;#Or;constructor(e,t=[],r=[]){this.#lt=e,this.#Hr=t,this.#Or=r}async start(){return this.#Nr()}async stop(){return this.#Tr()}#Nr(){return this.#Ir(this.#Hr)}#Tr(){return this.#Ir(this.#Or)}async#Ir(e){await Promise.all(e.map(e=>this.#lt.import(e)))}}class Br{#lt;#Dt;constructor(e,t){this.#lt=e,this.#Dt=t}async build(e,t){const r=e.setUp,s=e.tearDown,a=e.middleware,n=e.healthChecks,i=new Ue(t),o=this.#jr(n),c=this.#$r(i),u=await this.#Lr(e,o,c),l=this.#lt,h=this.#Wr(r,s),d=this.#qr(a),p=this.#Br(e);return new Lr({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#Lr(e,t,r){if(void 0!==e.gateway)return this.#Fr(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#Dr(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Vr(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Kr(e.url,e.proxy);if(void 0!==e.standalone)return this.#Ur(e.url,e.standalone,t,r);throw new Wr}async#Fr(e,t,r,s){const a=new lt,n=this.#_r(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}async#Dr(e,t,r,s){const a=new lt,n=this.#Gr(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}async#Vr(e,t,r){const s=await this.#Jr(e,t,r),a=new ht;return new Mt({url:e,provider:s,runner:a})}#_r(e,t,r,s){const a=t.trustKey,n=t.monitorInterval,i=new bt(s,n);return new mt({url:e,trustKey:a,healthManager:r,workerManager:i})}#Xr(e){const t=this.#Dt.build(e);return new gt({url:e,remote:t})}#Gr(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Xr(t.gateway):void