jitar 0.11.1 → 0.11.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/ConfigurationManager-DE4YOzeh.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/lib.d.ts +4 -0
- package/dist/lib.js +1 -1
- package/package.json +2 -2
- package/dist/ConfigurationManager-D8N-pXTY.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e,{promises as t}from"node:fs";import s from"node:path";import{glob as r}from"glob";import i from"mime-types";import n from"dotenv";const o={MODULE_PATTERN:"**/*.js",RESOURCE_PATTERN:"**/*.json",SEGMENT_PATTERN:"**/*.json"};class a extends Error{constructor(e){super(`Invalid location '${e}'`)}}class c extends Error{constructor(e){super(`File could not be found from '${e}'`)}}class u{#e;#t;#s;constructor(e,t,s){this.#e=e,this.#t=t,this.#s=s}get location(){return this.#e}get type(){return this.#t}get content(){return this.#s}get size(){return this.#s.length}}class l{#e;#r;#i;constructor(e,t){const s=t.resolve(e);this.#e=t.normalize(e),this.#r=t.normalize(s),this.#i=t}getAbsoluteLocation(e){const t=this.#i.isAbsolute(e)?e:this.#i.join(this.#e,e),s=this.#i.resolve(t),r=this.#i.normalize(s);return this.#n(r,e),r}getRelativeLocation(e){const t=this.#i.relative(this.#e,e);return this.#i.normalize(t)}normalizeLocation(e){return this.#i.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#i.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#i.exists(t))throw new c(e);return this.#i.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#i.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#i.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new u(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#i.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#i.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#i.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#i.normalize(e);return(await this.#i.filter(t,s)).map(e=>this.#i.normalize(e))}async filterWithIgnores(e,t){const s=await this.filter(e),r=t.map(e=>this.filter(e)),i=await Promise.all(r),n=new Set(i.flat());return s.filter(e=>!1===n.has(e))}#n(e,t){if(!1===e.startsWith(this.#r))throw new a(t)}}class h{copy(e,s){return t.cp(e,s,{recursive:!0,force:!0})}delete(e){return t.rm(e,{recursive:!0,force:!0})}async exists(e){try{return await t.stat(e),!0}catch{return!1}}isAbsolute(e){return s.isAbsolute(e)}isDirectory(t){try{return e.statSync(t).isDirectory()}catch{return!1}}filter(e,t){return r(`${e}/${t}`)}join(...e){return s.join(...e)}read(e){return t.readFile(e)}resolve(e){return s.resolve(e)}relative(e,t){return s.relative(e,t)}normalize(e){return e.replaceAll(s.win32.sep,s.posix.sep)}async mimeType(e){const t=i.lookup(e);if(!1!==t)return t}async write(r,i){const n=s.dirname(r);return e.mkdirSync(n,{recursive:!0}),t.writeFile(r,i)}}class p extends l{constructor(e){super(e,new h)}}class m{#o;#a;#c;constructor(e,t,s){this.#o=e,this.#a=t,this.#c=s}get resources(){return this.#a}get repository(){return this.#o}get segmentation(){return this.#c}}class d{#a;constructor(e){this.#a=e}isResourceModule(e){return this.#a.includes(e)}}const f="private",g="0.0.0",E="index.js",w=".json",y="default";class b{#u=0;next(){return"$"+ ++this.#u}}const S="js",I=/\.js$/,A=[".","/","http:","https:"];class T{translatePath(e){const t=e.split("/"),s=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":s.pop();continue}s.push(e)}return s.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const s=e.split("/"),r=t.split("/");for(;s[0]===r[0];)s.shift(),r.shift();const i=r.map(()=>"..").join("/");return`${r.length>0?i:"."}/${s.join("/")}`}makePathAbsolute(e,t,s="/"){const r=""!==t?`${t}/${e}`:e;return`${s}${this.translatePath(r)}`}extractPath(e){return e.split("/").slice(0,-1).join("/")}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${S}`)?e:`${e}.${S}`}addSubExtension(e,t){return e.replace(I,`.${t}.${S}`)}isApplicationModule(e){return A.some(t=>e.startsWith(t))}}class v extends Error{constructor(e,t){super(`Failed reading resources from '${e}'`,{cause:t})}}class O{#l;#h;#p=new T;constructor(e,t){this.#l=e,this.#h=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#m(e)));return new d(t.flat())}async#m(e){try{const t=await this.#l.getContent(e);return JSON.parse(t.toString()).map(e=>this.#d(e))}catch(t){throw new v(e,t)}}#d(e){const t=this.#h.normalizeLocation(e),s=this.#h.isDirectory(t)?`${t}/${E}`:this.#p.assureExtension(t);return s.startsWith("./")?s.substring(2):s.startsWith("/")?s.substring(1):s}}let N=class{#f;#g;constructor(e,t){this.#f=e,this.#g=t}get filename(){return this.#f}get model(){return this.#g}};class R{#E;constructor(e){this.#E=e}get modules(){return this.#E}get(e){return this.#E.find(t=>t.filename===e)}}class x{}class M extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new M(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class ${}class C extends ${identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class P extends C{parameters;body;isAsync;constructor(e,t,s,r=!1){super(e),this.parameters=t,this.body=s,this.isAsync=r}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new P(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier?` ${this.identifier}`:"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function${t}(${s.join(",")})${r}`}}class L extends P{constructor(e,t,s=!1){super(void 0,e,t,s)}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new L(e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.parameters.map(e=>e.toString()),s=this.body.toString();return`${e}(${t.join(", ")})=>${s}`}}class F{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new F(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class V extends ${code;constructor(e){super(),this.code=e}clone(){return new V(this.code)}toString(){return this.code}}class D{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class j extends D{parameters;body;constructor(e,t){super("constructor","public","instance"),this.parameters=e,this.body=t}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new j(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class k extends D{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new k(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.body.toString();return`${e}get ${t}${this.identifier}()${s}`}}class B extends D{parameter;body;constructor(e,t,s,r,i){super(e,t,s),this.parameter=r,this.body=i}clone(){const e=this.parameter.clone(),t=this.body.clone();return new B(this.identifier,this.visibility,this.location,e,t)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.parameter.toString(),r=this.body.toString();return`${e}set ${t}${this.identifier}(${s})${r}`}}class q extends D{parameters;body;isAsync;constructor(e,t,s,r,i,n=!1){super(e,t,s),this.parameters=r,this.body=i,this.isAsync=n}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new q(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.isAsync?"async ":"",r=this.parameters.map(e=>e.toString()),i=this.body.toString();return`${e}${s}${t}${this.identifier}(${r.join(",")})${i}`}}class U extends D{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new U(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${e}${t}${this.identifier}${s}`}}class G extends C{parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof j)}get fields(){return this.members.filter(e=>e instanceof U)}get getters(){return this.members.filter(e=>e instanceof k)}get setters(){return this.members.filter(e=>e instanceof B)}get methods(){return this.members.filter(e=>e instanceof q)}get publicFields(){return this.fields.filter(e=>"public"===e.visibility)}get publicGetters(){return this.getters.filter(e=>"public"===e.visibility)}get publicSetters(){return this.setters.filter(e=>"public"===e.visibility)}get publicMethods(){return this.methods.filter(e=>"public"===e.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(e){return this.members.find(t=>t.is(e))}hasMember(e){return this.members.some(t=>t.is(e))}getField(e){return this.fields.find(t=>t.is(e))}hasField(e){return this.fields.some(t=>t.is(e))}getGetter(e){return this.getters.find(t=>t.is(e))}hasGetter(e){return this.getters.some(t=>t.is(e))}getSetter(e){return this.setters.find(t=>t.is(e))}hasSetter(e){return this.setters.some(t=>t.is(e))}getMethod(e){return this.methods.find(t=>t.is(e))}hasMethod(e){return this.methods.some(t=>t.is(e))}canRead(e){return this.readable.some(t=>t.is(e))}canWrite(e){return this.writable.some(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new G(this.identifier,this.parent,e)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(e=>e.toString()).join("")}}`}}class K extends ${members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new K(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class H extends ${code;constructor(e){super(),this.code=e}clone(){return new H(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class _ extends P{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new _(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier??"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function* ${t}(${s.join(",")})${r}`}}class W extends q{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new W(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier,s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}*${t}(${s.join(",")})${r}`}}class z extends x{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new z(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Y extends ${members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Y(e,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(e=>e.toString()).join(",")}} from '${this.from}';`}}class X extends C{type;binding;initializer;constructor(e,t,s){super(t.toString()),this.type=e,this.binding=t,this.initializer=s}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new X(this.type,e,t)}toString(){const e=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",t=e.endsWith(";")?"":";";return`${this.type} ${this.identifier}${e}${t}`}}class Q{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof K)}get imports(){return this.statements.filter(e=>e instanceof Y)}get expressions(){return this.statements.filter(e=>e instanceof H)}get declarations(){return this.statements.filter(e=>e instanceof C)}get variables(){return this.statements.filter(e=>e instanceof X)}get functions(){return this.statements.filter(e=>e instanceof P)}get classes(){return this.statements.filter(e=>e instanceof G)}get exported(){const e=[];for(const t of this.exports)for(const s of t.members){const t=this.getDeclaration(s.identifier);void 0!==t&&e.push(t)}return e}get exportedVariables(){return this.exported.filter(e=>e instanceof X)}get exportedFunctions(){return this.exported.filter(e=>e instanceof P)}get exportedClasses(){return this.exported.filter(e=>e instanceof G)}getExport(e){return this.exports.find(t=>t.hasMember(e))}getImport(e){return this.imports.find(t=>t.hasMember(e))}hasDeclaration(e){return this.declarations.some(t=>t.is(e))}getDeclaration(e){return this.declarations.find(t=>t.is(e))}hasVariable(e){return this.variables.some(t=>t.is(e))}getVariable(e){return this.variables.find(t=>t.is(e))}hasFunction(e){return this.functions.some(t=>t.is(e))}getFunction(e){return this.functions.find(t=>t.is(e))}hasClass(e){return this.classes.some(t=>t.is(e))}getClass(e){return this.classes.find(t=>t.is(e))}clone(){const e=this.statements.map(e=>e.clone());return new Q(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class J{identifier;alias;constructor(e,t){this.identifier=e,this.alias=t}is(e){return this.alias===e||void 0===this.alias&&this.identifier===e}clone(){return new J(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class Z extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Z(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const ee={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},te=Object.values(ee);const se=".",re="(",ie=")",ne="[",oe="]",ae="{",ce="}",ue="_",le={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},he=Object.values(le);function pe(e){return he.includes(e)}const me={UNDEFINED:void 0,NULL:null,STRING:""},de=["null","undefined"],fe=Object.values(me);function ge(e){return fe.includes(e)}const Ee={OPEN:re,CLOSE:ie};function we(e){return e===Ee.OPEN||e===Ee.CLOSE}const ye={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally",TYPEOF:"typeof",INSTANCEOF:"instanceof"},be=Object.values(ye),Se=[ye.IMPORT,ye.EXPORT,ye.VAR,ye.LET,ye.CONST,ye.FUNCTION,ye.CLASS,ye.ASYNC],Ie=[ye.VAR,ye.LET,ye.CONST,ye.FUNCTION,ye.CLASS,ye.USING],Ae=[ye.AS,ye.ASYNC,ye.GET,ye.SET,ye.OF,ye.YIELD,ye.FROM,ye.STATIC];function Te(e){return Se.includes(e)}function ve(e){return Ae.includes(e)}const Oe={OPEN:ne,CLOSE:oe};function Ne(e){return e===Oe.OPEN||e===Oe.CLOSE}const Re=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xe(e){return Re.includes(e)}const Me={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},$e=Object.values(Me);function Ce(e){return $e.includes(e)}const Pe={OPEN:ae,CLOSE:ce};function Le(e){return e===Pe.OPEN||e===Pe.CLOSE}const Fe={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},Ve={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},De=Object.values(Ve);function je(e){return De.includes(e)}class ke{#w;#y;constructor(e){this.#w=e,this.#y=0}get items(){return this.#w}get position(){return this.#y}get size(){return this.#w.length}get eol(){return this.#y>=this.#w.length}get current(){return this.#w[this.#y]}get next(){return this.#w[this.#y+1]}get previous(){return this.#w[this.#y-1]}notAtEnd(){return!1===this.eol}get(e){return this.#w[e]}step(e=1){return this.#y+=e,this.current}stepBack(e=1){return this.#y-=e,this.current}hasNext(){return this.#y+1<this.#w.length}insert(...e){this.#w.splice(this.#y,0,...e)}}class Be extends ke{constructor(e){super(e.split(""))}}class qe{#t;#b;#S;#I;constructor(e,t,s,r){this.#t=e,this.#b=t,this.#S=s,this.#I=r}get type(){return this.#t}get value(){return this.#b}get start(){return this.#S}get end(){return this.#I}isType(e){return this.#t===e}hasValue(e){return this.#b===e}toString(){return`${this.#b}`}}class Ue extends ke{}const Ge=["true","false"];const Ke=["0","1","2","3","4","5","6","7","8","9"],He=[...Ke,"a","b","c","d","e","f","A","B","C","D","E","F"],_e=["0","1"];function We(e){return Ke.includes(e)}const ze={GENERATOR:"*",PRIVATE:"#"},Ye=Object.values(ze);class Xe{tokenize(e){const t=new Be(e),s=[];let r;for(;t.notAtEnd();){const e=this.#A(t,r);if(void 0===e)break;e.isType(Fe.WHITESPACE)||e.isType(Fe.COMMENT)?t.step():(s.push(e),this.#T(e)&&(r=e),t.step())}return new Ue(s)}#T(e){return!1===[Fe.WHITESPACE,Fe.COMMENT].includes(e.type)}#A(e,t){const s=e.current,r=e.position;if(je(s)){const t=e.position;return new qe(Fe.WHITESPACE,s,r,t)}if(function(e){return te.includes(e)}(s+e.next)){const t=this.#v(e),s=e.position;return new qe(Fe.COMMENT,t,r,s)}if(this.#O(s,t)){const t=this.#N(e),s=e.position;return new qe(Fe.REGEX,t,r,s)}if(this.#R(e,t)){const t=this.#x(e),s=e.position;return new qe(Fe.NUMBER,t,r,s)}if(xe(s)){const t=this.#M(e),s=e.position;return new qe(Fe.LITERAL,t,r,s)}if(Ce(s)){const t=this.#$(e),s=e.position;return new qe(Fe.OPERATOR,t,r,s)}if(function(e){return Ye.includes(e)}(s)){const t=this.#$(e),s=e.position;return new qe(Fe.INDICATOR,t,r,s)}if(pe(s)){const t=e.position;return new qe(Fe.DIVIDER,s,r,t)}if(we(s)){const t=e.position;return new qe(Fe.GROUP,s,r,t)}if(Le(s)){const t=e.position;return new qe(Fe.SCOPE,s,r,t)}if(Ne(s)){const t=e.position;return new qe(Fe.LIST,s,r,t)}if(ge(s))return;const i=this.#C(e),n=e.position;return function(e){return be.includes(e)}(i)?new qe(Fe.KEYWORD,i,r,n):function(e){return Ge.includes(e)}(i)?new qe(Fe.BOOLEAN,i,r,n):function(e){return de.includes(e)}(i)?new qe(Fe.NOTHING,i,r,n):new qe(Fe.IDENTIFIER,i,r,n)}#v(e){const t=e.current+e.next===ee.MULTI_START,s=t?ee.MULTI_END:Ve.NEWLINE;let r=t?ee.MULTI_START:ee.SINGLE;for(e.step(2);e.notAtEnd();){const i=e.current;if((t?i+e.next:i)===s){e.step(s.length-1);break}r+=i,e.step()}return t?r+ee.MULTI_END:r.trim()}#O(e,t){return e===Me.DIVIDE&&(void 0===t||([Fe.OPERATOR,Fe.DIVIDER,Fe.KEYWORD].includes(t.type)||[Ee.OPEN,Oe.OPEN].includes(t.value)))}#P(e){return je(e)||e==se||!1===this.#L(e)}#N(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Me.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#P(r)){e.stepBack();break}t+=r,e.step()}return t}#R(e,t){const s=e.current,r=e.next;return!!We(s)||s===Me.SUBTRACT&&(!t?.isType(Fe.NUMBER)&&We(r))}#F(e,t,s){return t?!1===(r=e,He.includes(r))&&e!==ue:s?!1===function(e){return _e.includes(e)}(e)&&e!==ue:!1===We(e)&&e!==se&&e!==ue&&"e"!==e;var r}#x(e){let t=e.current;t===Me.SUBTRACT&&(t+=e.step()),e.step();const s="x"===e.current,r="b"===e.current;for((s||r)&&(t+=e.current,e.step());e.notAtEnd();){const i=e.current;if(this.#F(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#M(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const i=e.current;if(!1===r){if(i===t){s+=i;break}"\\"===i&&(r=!0)}else r=!1;s+=i,e.step()}return s}#L(e){return!1===(ge(e)||je(e)||Ce(e)||xe(e)||pe(e)||we(e)||Le(e)||Ne(e))}#C(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#L(s)){e.stepBack();break}t+=s,e.step()}return t}#$(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===Ce(s)||!1===Ce(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Qe extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Je extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Ze extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class et extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class tt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const st=new qe(Fe.NONE,"",-1,0);class rt{#V;constructor(e=[]){this.#V=e}get tokens(){return this.#V}append(...e){this.#V.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="";for(let t=0;t<this.#V.length;t++){const s=this.#V[t-1]??st,r=this.#V[t],i=this.#V[t+1]??st,n=this.#D(s,r)?" ":"",o=this.#j(r,i)?" ":"";e+=`${n}${r.value}${o}`}return e}#D(e,t){return!(!t.isType(Fe.KEYWORD)||!this.#k(e))||!(!t.isType(Fe.OPERATOR)||!e.isType(Fe.OPERATOR))}#j(e,t){return e.isType(Fe.KEYWORD)&&(t.isType(Fe.KEYWORD)||this.#k(t))}#k(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.isType(Fe.NUMBER)}}const it="default",nt="$_EXPORT";class ot{#B;constructor(e=new Xe){this.#B=e}parse(e){const t=this.#B.tokenize(e),s=this.#q(t);return new Q(s)}parseStatement(e){const t=this.#B.tokenize(e),s=this.#U(t);if(void 0===s)throw new et("a statement");return s}parseImport(e){const t=this.#B.tokenize(e),s=this.#G(t);if(s instanceof Y==!1)throw new et("an import definition");return s}parseExport(e){const t=this.#B.tokenize(e),s=this.#G(t);if(s instanceof K==!1)throw new et("an export definition");return s}parseVariable(e){const t=this.#B.tokenize(e),s=this.#G(t);if(s instanceof X==!1)throw new et("a variable definition");return s}parseFunction(e){const t=this.#B.tokenize(e),s=this.#G(t);if(s instanceof P==!1)throw new et("a function definition");return s}parseClass(e){const t=this.#B.tokenize(e),s=this.#G(t);if(s instanceof G==!1)throw new et("a class definition");return s}#q(e){const t=[];for(;e.notAtEnd();){const s=this.#U(e);void 0!==s&&t.push(s)}return t}#U(e,t=!1){const s=e.current;if(this.#K(s))return this.#H(e);if(s.isType(Fe.IDENTIFIER)){const s=e.next;return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#H(e)}if(s.isType(Fe.KEYWORD)){if(ve(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(ye.FUNCTION)||t.hasValue(Ee.OPEN));if(s.hasValue(ye.ASYNC)&&r)return e.step(),this.#U(e,!0);if(void 0===t||this.#W(t))return this.#H(e)}return s.hasValue(ye.RETURN)?this.#H(e):!1===Te(s.value)?this.#H(e):this.#G(e,t)}if(s.isType(Fe.REGEX))return this.#H(e);if(s.hasValue(Ee.OPEN)){const s=this.#z(e,Ee.OPEN,Ee.CLOSE);return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#H(e)}if(s.hasValue(Pe.OPEN))return this.#H(e);if(s.hasValue(Oe.OPEN))return this.#H(e);if(s.hasValue(Me.NOT)||s.hasValue(Me.SUBTRACT))return this.#H(e);if(!pe(s.value))throw new tt(s.value,s.start);e.step()}#K(e){return e.isType(Fe.LITERAL)||e.isType(Fe.NUMBER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.hasValue(ye.NEW)}#G(e,t=!1){const s=e.current;switch(e.step(),s.value){case ye.IMPORT:return this.#Y(e);case ye.EXPORT:return this.#X(e);case ye.CLASS:return this.#Q(e);case ye.FUNCTION:return this.#J(e,t);case ye.VAR:return this.#Z(e,"var");case ye.LET:return this.#Z(e,"let");case ye.CONST:return this.#Z(e,"const");case ye.ASYNC:return this.#U(e,!0);default:throw new Ze(s.value,s.start)}}#Y(e){const t=[];let s=e.current;if(s.isType(Fe.LITERAL)){const e=this.#ee(s.value);return new Y(t,e)}if(s.hasValue(Ee.OPEN)){s=e.step();const r=this.#ee(s.value);return e.step(2),new Y(t,r)}if(!1===s.hasValue(Pe.OPEN)){const r=s.hasValue(Me.MULTIPLY)?Me.MULTIPLY:it;let i=s.value;s=e.step(),s.hasValue(ye.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new J(r,i))}if(s.hasValue(le.SEPARATOR)&&(s=e.step()),s.hasValue(Pe.OPEN)){const r=this.#te(e);t.push(...r),s=e.current}if(!1===s.hasValue(ye.FROM))throw new Qe(ye.FROM,s.start);s=e.step();const r=this.#ee(s.value);return e.step(),new Y(t,r)}#X(e){switch(e.current.value){case ye.DEFAULT:return e.step(),this.#se(e,!0);case Pe.OPEN:return this.#re(e);default:return this.#se(e,!1)}}#se(e,t){let s=e.current,r=0;if(t&&this.#ie(e)){const t=`${nt}_${s.start}_${s.end}`;e.insert(new qe(Fe.KEYWORD,ye.CONST,0,0),new qe(Fe.IDENTIFIER,t,0,0),new qe(Fe.OPERATOR,Me.ASSIGN,0,0)),s=e.current}var i;if(s.hasValue(ye.ASYNC)&&(s=e.step(),r++),i=s.value,Ie.includes(i)&&(s=e.step(),r++,s.hasValue(ze.GENERATOR)&&(s=e.step(),r++)),s.hasValue(ye.EXTENDS)||s.hasValue(Ee.OPEN)||s.hasValue(Pe.OPEN)){const t=`${nt}_${s.start}_${s.end}`;e.insert(new qe(Fe.IDENTIFIER,t,0,0)),s=e.current}const n=this.#L(s)?s.value:"",o=t?it:void 0;let a;s=e.step(),s?.hasValue(ye.FROM)&&(s=e.step(),a=this.#ee(s.value)),r>0&&(r++,e.stepBack(r));const c=new J(n,o);return new K([c],a)}#ie(e){const t=e.current;if(this.#K(t))return!0;const s=e.next;return this.#L(t)&&s?.hasValue(Ee.OPEN)}#re(e){const t=this.#te(e);let s,r=e.current;return r?.hasValue(ye.FROM)&&(r=e.step(),s=this.#ee(r.value)),e.step(),new K(t,s)}#ee(e){return e.slice(1,-1)}#te(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Pe.CLOSE)){e.step();break}if(s.hasValue(le.SEPARATOR)){s=e.step();continue}const r=this.#ne(e);t.push(r),s=e.step()}return t}#ne(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(ye.AS)&&(t=e.step(2),r=t.value),new J(s,r)}#Z(e,t){const s=this.#oe(e),r=this.#ae(e);return e.notAtEnd()&&e.current.hasValue(le.SEPARATOR)&&(e.step(),e.insert(new qe(Fe.KEYWORD,t,0,0))),new X(t,s,r)}#oe(e){const t=e.current;return t.hasValue(Oe.OPEN)?this.#ce(e):t.hasValue(Pe.OPEN)?this.#ue(e):this.#le(e)}#ce(e){const t=this.#he(e,Oe.CLOSE);return new M(t)}#ue(e){const t=this.#he(e,Pe.CLOSE);return new Z(t)}#he(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(le.SEPARATOR)){e.step();continue}const i=this.#oe(e),n=this.#ae(e),o=new F(i,n);s.push(o)}return s}#le(e){let t=e.current,s=!1;t.hasValue(Me.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new z(r,s)}#ae(e){const t=e.current;if(!1!==t.hasValue(Me.ASSIGN))return e.step(),this.#U(e,!1);t.hasValue(le.TERMINATOR)&&e.step()}#J(e,t){let s,r=e.current,i=!1;r.hasValue(ze.GENERATOR)&&(i=!0,r=e.step()),this.#L(r)&&(s=r.value,e.step());const n=this.#he(e,Ee.CLOSE);if(r=e.current,!1===r.hasValue(Pe.OPEN))throw new Je(Pe.OPEN,r.start);const o=this.#pe(e);return i?new _(s,n,o,t):new P(s,n,o,t)}#_(e,t){let s,r,i=e.current;if(i.hasValue(Ee.OPEN))s=this.#he(e,Ee.CLOSE);else{const t=this.#le(e);s=[new F(t,void 0)]}if(i=e.current,!1===i.hasValue(Me.ARROW))throw new Je(Me.ARROW,i.start);if(i=e.step(),i.hasValue(Pe.OPEN))r=this.#pe(e);else{const t=this.#H(e);r=new V(t.code)}return new L(s,r,t)}#Q(e){let t,s,r=e.current;if(this.#L(r)&&(t=r.value,r=e.step()),r.hasValue(ye.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Pe.OPEN))throw new Je(Pe.OPEN,r.start);const i=this.#me(e);return new G(t,s,i)}#me(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Pe.CLOSE)){e.step();break}const r=this.#de(e);s.push(r),t=e.current}return s}#de(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(ze.PRIVATE))s="private";else if(t.hasValue(ye.STATIC))r="static";else{if(!t.hasValue(ye.ASYNC)){if(t.hasValue(ye.CONSTRUCTOR))return this.#fe(e);if(t.hasValue(ye.GET))return this.#ge(e,r);if(t.hasValue(ye.SET))return this.#Ee(e,r);if(t.hasValue(ze.GENERATOR))return e.step(),this.#we(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(Ee.OPEN)?this.#we(e,s,r,i,!1):this.#ye(e,s,r)}#fe(e){e.step();const t=this.#he(e,Ee.CLOSE),s=e.current;if(!1===s.hasValue(Pe.OPEN))throw new Je(Pe.OPEN,s.start);const r=this.#pe(e);return new j(t,r)}#ge(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#he(e,Ee.CLOSE).length)throw new et("an empty parameter list");if(r=e.current,!1===r.hasValue(Pe.OPEN))throw new Je(Pe.OPEN,r.start);const n=this.#pe(e);return new k(i,s,t,n)}#Ee(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#he(e,Ee.CLOSE);if(r=e.current,1!==n.length)throw new et("exactly one setter parameter");if(!1===r.hasValue(Pe.OPEN))throw new Je(Pe.OPEN,r.start);const o=this.#pe(e);return new B(i,s,t,n[0],o)}#we(e,t,s,r,i){let n=e.current;const o=n.value;e.step();const a=this.#he(e,Ee.CLOSE);if(n=e.current,!1===n.hasValue(Pe.OPEN))throw new Je(Pe.OPEN,n.start);const c=this.#pe(e);return i?new W(o,t,s,a,c,r):new q(o,t,s,a,c,r)}#ye(e,t,s){const r=e.current.value;e.step();const i=this.#ae(e);return new U(r,t,s,i)}#pe(e){const t=this.#be(e,Pe.OPEN,Pe.CLOSE).generate();return new V(t)}#H(e){const t=new rt;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Oe.OPEN)){const r=this.#be(e,Oe.OPEN,Oe.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Ee.OPEN)){const r=this.#be(e,Ee.OPEN,Ee.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Pe.OPEN)){const r=this.#be(e,Pe.OPEN,Pe.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#W(s)){s.hasValue(le.TERMINATOR)&&e.step();break}}const r=t.generate();return new H(r)}#be(e,t,s){let r=e.current;const i=new rt([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#be(e,t,s);i.merge(n),r=e.current;continue}if(r.hasValue(s))return e.step(),i.append(r),i;i.append(r),r=e.step()}return i}#z(e,t,s){const r=e.position;this.#be(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#W(e){return[le.TERMINATOR,le.SEPARATOR].includes(e.value)||[Oe.CLOSE,Ee.CLOSE,Pe.CLOSE].includes(e.value)||Te(e.value)}#L(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.KEYWORD)&&ve(e.value)}}class at extends Error{constructor(e,t){super(`Failed reading module from '${e}'`,{cause:t})}}class ct{#h;#p=new T;constructor(e){this.#h=e}rewrite(e,t){e.imports.forEach(e=>this.#Se(e,t)),e.exports.forEach(e=>this.#Ie(e,t))}#Se(e,t){const s=this.#h.normalizeLocation(e.from);!1!==this.#p.isApplicationModule(s)&&(e.from=this.#Ae(t,s))}#Ie(e,t){if(void 0===e.from)return;const s=this.#h.normalizeLocation(e.from);!1!==this.#p.isApplicationModule(s)&&(e.from=this.#Ae(t,s))}#Ae(e,t){const s=this.#p.extractPath(e),r=this.#p.makePathAbsolute(t,s,"");return this.#h.isDirectory(r)?`${t}/${E}`:this.#p.assureExtension(t)}}let ut=class{#h;#Te;#ve;constructor(e,t=new ot){this.#h=e,this.#Te=t,this.#ve=new ct(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new R(t)}async read(e){try{const t=this.#h.getRelativeLocation(e),s=await this.#Oe(e),r=this.#Te.parse(s);return this.#ve.rewrite(r,t),new N(t,r)}catch(t){throw new at(e,t)}}async#Oe(e){return(await this.#h.getContent(e)).toString()}},lt=class{#Ne;#E=new Map;#Re=new Map;#xe=new Map;constructor(e){this.#Ne=e}get name(){return this.#Ne}get modules(){return[...this.#E.values()]}get classes(){return[...this.#Re.values()]}get procedures(){return[...this.#xe.values()]}hasModule(e){return this.#E.has(e)}getModule(e){return this.#E.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#E.set(e.filename,e)}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}setProcedure(e){this.#xe.set(e.fqn,e)}setClass(e){this.#Re.set(e.fqn,e)}};class ht{#u;#Me;#$e;constructor(e,t,s){this.#u=e,this.#Me=t,this.#$e=s}get id(){return this.#u}get importKey(){return this.#Me}get fqn(){return this.#$e}}class pt extends ht{#g;constructor(e,t,s,r){super(e,t,s),this.#g=r}get model(){return this.#g}}class mt extends ht{#Ce;#Pe;#g;constructor(e,t,s,r,i,n){super(e,t,s),this.#Ce=r,this.#Pe=i,this.#g=n}get access(){return this.#Ce}get version(){return this.#Pe}get model(){return this.#g}}class dt{#f;#e;#Le;#Fe=[];#Ve;constructor(e,t,s,r){this.#f=e,this.#e=t,this.#Le=s,this.#Ve=r}get filename(){return this.#f}get location(){return this.#e}get imports(){return this.#Le}get members(){return this.#Fe}get classes(){return this.#Fe.filter(e=>e instanceof pt)}get implementations(){return this.#Fe.filter(e=>e instanceof mt)}get segmented(){return this.#Ve}hasClasses(){return this.#Fe.some(e=>e instanceof pt)}hasImplementations(){return this.#Fe.some(e=>e instanceof mt)}importsImplementation(e){return void 0!==this.implementations.find(t=>t.importKey===e)}addMember(e){this.#Fe.push(e)}addImports(e){const t=Object.keys(e);for(const s of t){const t=s.trim();this.#Le[t]=e[s]}}}class ft{#$e;#De=[];constructor(e,t=[]){this.#$e=e,this.#De=t}get fqn(){return this.#$e}get implementations(){return this.#De}addImplementation(e){this.#De.push(e)}}class gt{#je;constructor(e){this.#je=e}get segments(){return this.#je}getSegment(e){return this.#je.find(t=>t.name===e)}isSegmentedModule(e){return this.#je.some(t=>t.hasModule(e))}getSegments(e){return this.#je.filter(t=>t.hasModule(e))}}class Et extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class wt extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class yt extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class bt extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class St extends Error{constructor(e,t){super(`Failed reading segment from '${e}'`,{cause:t})}}class It extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class At extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class Tt{#o;#p=new T;constructor(e){this.#o=e}locate(e,t){const s=[];return{trace:s,model:this.#ke(e,t,s)}}#ke(e,t,s){s.push({filename:e,importKey:t});const r=this.#Be(e);return this.#qe(r,t)?this.#Ue(r,t,s):this.#Ge(r,t)}#Be(e){const t=this.#o.get(e);if(void 0===t)throw new At(e);return t}#qe(e,t){const s=e.model.getImport(t),r=e.model.getExport(t);return void 0!==s||void 0!==r?.from}#Ue(e,t,s){const r=this.#Ke(e,t)??this.#He(e,t),i=r?.from,n=r?.name,o=this.#p.extractPath(e.filename),a=i,c=this.#p.makePathAbsolute(a,o,"");return this.#ke(c,n,s)}#Ge(e,t){const s=this.#He(e,t);if(void 0===s)throw new It(e.filename,t);const r=e.model.getDeclaration(s.name);if(void 0===r)throw new It(e.filename,s.name);return r}#He(e,t){const s=e.model.getExport(t),r=s?.getMember(t);if(void 0!==r)return{from:s?.from,name:r.identifier}}#Ke(e,t){const s=e.model.getImport(t),r=s?.getMember(t);if(void 0!==s&&void 0!==r)return{from:s.from,name:r.identifier}}}class vt{#_e;#h;#We;#p=new T;constructor(e,t,s){this.#_e=e,this.#h=t,this.#We=new Tt(s)}async readAll(e){const t=await Promise.all(e.map(e=>this.#ze(e)));return new gt(t)}async#ze(e){try{const t=await this.#Ye(e),s=this.#Xe(e),r=new lt(s);return this.#Qe(r,t),this.#Je(r),r}catch(t){throw new St(e,t)}}#Xe(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new wt(e);return t.replace(w,"")}async#Ye(e){try{const t=await this.#_e.getContent(e);return JSON.parse(t.toString())}catch(t){const s=t instanceof Error?t.message:String(t);throw new yt(e,s)}}#Qe(e,t){for(const[s,r]of Object.entries(t))this.#Ze(e,s,r,!0)}#Ze(e,t,s,r){const i=this.#et(t),n=this.#p.extractPath(i),o=e.hasModule(i)?e.getModule(i):new dt(i,n,{},r);o.addImports(s),e.setModule(o)}#et(e){const t=e.trim(),s=this.#h.normalizeLocation(t),r=this.#h.isDirectory(s)?`${s}/${E}`:this.#p.assureExtension(s);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#Je(e){const t=new b;for(const s of e.modules)for(const r in s.imports)this.#tt(e,s,r,t)}#tt(e,t,s,r){const{model:i,trace:n}=this.#We.locate(t.filename,s),o=this.#st(t,i,s,r);this.#rt(e,t,i,o),n.shift();for(const t of n){const s={[t.importKey]:{access:o.access}};this.#Ze(e,t.filename,s,!1)}}#st(e,t,s,r){const i=e.imports[s],n=r.next(),o=i.as??t.identifier;return{id:n,importKey:s,name:o,access:i.access??f,version:i.version??g,fqn:this.#it(e,o,s)}}#it(e,t,s){return this.#nt(e)?t:this.#ot(e)&&this.#at(s)?e.location:`${e.location}/${t}`}#nt(e){return""===e.location}#ot(e){return e.filename.endsWith(E)}#at(e){return e===y}#rt(e,t,s,r){if(s instanceof G)return this.#ct(e,t,s,r);if(s instanceof P)return this.#ut(e,t,s,r);throw new bt(t.filename,r.importKey)}#ct(e,t,s,r){const i=new pt(r.id,r.importKey,r.fqn,s);t.addMember(i),e.setClass(i)}#ut(e,t,s,r){if(!1===s.isAsync)throw new Et(t.filename,r.name);const i=new mt(r.id,r.importKey,r.fqn,r.access,r.version,s);this.#lt(e,t,i)}#lt(e,t,s){const r=e.hasProcedure(s.fqn)?e.getProcedure(s.fqn):new ft(s.fqn);r.addImplementation(s),t.addMember(s),e.setProcedure(r)}}class Ot{#ht;constructor(e){this.#ht=e}async read(e,t,s){const r=this.#ht.source,i=this.#ht.resource,n=this.#ht.segment,o=new ut(r),a=await o.readAll(e),c=new O(i,r),u=await c.readAll(t),l=new vt(n,r,a),h=await l.readAll(s);return new m(a,u,h)}}class Nt extends Error{constructor(e){super(`Could not find the rewrite item: ${e}`)}}class Rt{#pt;#a;#c;#mt;#p=new T;constructor(e,t,s,r){this.#pt=e,this.#a=t,this.#c=s,this.#mt=r}generate(){const e=this.#pt.model.clone();return this.#dt(e,e.imports),this.#dt(e,e.exports),e.toString()}#dt(e,t){for(const s of t){const t=this.#ft(s);if(0===t.length)continue;const r=e.statements.indexOf(s);if(-1===r)throw new Nt(s.toString());e.statements.splice(r,1,...t)}}#ft(e){if(this.#gt(e))return[];const t=this.#Et(e);return this.#a.isResourceModule(t)?this.#wt(e,t):this.#yt(e,t)}#gt(e){return void 0===e.from||this.#bt(e)}#bt(e){return!1===this.#p.isApplicationModule(e.from)}#Et(e){const t=e.from,s=this.#p.extractPath(this.#pt.filename);return this.#p.makePathAbsolute(t,s,"")}#wt(e,t){const s=e.clone();return s.from=this.#St(t),[s]}#yt(e,t){if(0===e.members.length)return[this.#It(t,e,[])];const{segmentKeys:s,remoteKeys:r,commonKeys:i}=this.#At(t,e),n=[];return s.length>0&&n.push(this.#Tt(t,e,s)),r.length>0&&n.push(this.#vt(t,e,r)),i.length>0&&n.push(this.#It(t,e,i)),n}#At(e,t){const s=this.#Ot(e,this.#mt),r=this.#Nt(e,s),i=this.#Rt(t,s),n=this.#Rt(t,r);return{segmentKeys:i,remoteKeys:n,commonKeys:this.#xt(t,[...i,...n])}}#Ot(e,t){if(void 0===t)return[];const s=t.getModule(e);if(void 0===s)return[];return Object.keys(s.imports).filter(e=>s.importsImplementation(e))}#Nt(e,t){const s=this.#c.getSegments(e).filter(e=>e!==this.#mt).flatMap(t=>this.#Ot(e,t));return[...new Set(s)].filter(e=>!1===t.includes(e))}#Rt(e,t){return e.members.filter(e=>t.includes(e.identifier)).map(e=>e.identifier)}#xt(e,t){return e.members.filter(e=>!1===t.includes(e.identifier)).map(e=>e.identifier)}#Tt(e,t,s){const r=t.clone();return r.from=this.#St(e,this.#mt?.name),r.members=this.#Mt(t.members,s),r}#vt(e,t,s){const r=t.clone();return r.from=this.#St(e,"remote"),r.members=this.#Mt(t.members,s),r}#It(e,t,s){const r=t.clone();return r.from=this.#St(e),r.members=this.#Mt(t.members,s),r}#Mt(e,t){const s=[];for(const r of t){const t=e.find(e=>e.identifier===r);void 0!==t&&s.push(t)}return s}#St(e,t){const s=this.#p.extractPath(this.#pt.filename),r=this.#p.makePathRelative(e,s);return void 0!==t?this.#p.addSubExtension(r,t):r}}const xt={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class Mt extends Error{constructor(e="Invalid request"){super(e)}}class $t extends Error{constructor(e="Forbidden"){super(e)}}class Ct extends Error{constructor(e="Not found"){super(e)}}class Pt extends Error{constructor(e="Not implemented"){super(e)}}class Lt extends Error{constructor(e="Payment required"){super(e)}}class Ft extends Error{constructor(e="Server error"){super(e)}}class Vt extends Error{constructor(e="I'm a teapot"){super(e)}}class Dt extends Error{constructor(e="Unauthorized"){super(e)}}class jt extends Mt{#$t;constructor(e){super(`Invalid version number '${e}'`),this.#$t=e}get number(){return this.#$t}}class kt{#u;#Re=new Map;#xe=new Map;constructor(e){this.#u=e}get id(){return this.#u}addClass(e){return this.#Re.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#Re.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#Re.values()]}addProcedure(e){return this.#xe.set(e.fqn,e),this}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}getExposedProcedures(){return[...this.#xe.values()].filter(e=>e.public||e.protected)}}class Bt{static get DEFAULT(){return new Bt(0,0,0)}#Ct;#Pt;#Lt;constructor(e=0,t=0,s=0){this.#Ct=e,this.#Pt=t,this.#Lt=s}get major(){return this.#Ct}get minor(){return this.#Pt}get patch(){return this.#Lt}equals(e){return this.#Ct===e.major&&this.#Pt===e.minor&&this.#Lt===e.patch}greater(e){return this.#Ct!==e.major?this.#Ct>e.major:this.#Pt!==e.minor?this.#Pt>e.minor:this.#Lt!==e.patch&&this.#Lt>e.patch}less(e){return this.#Ct!==e.major?this.#Ct<e.major:this.#Pt!==e.minor?this.#Pt<e.minor:this.#Lt!==e.patch&&this.#Lt<e.patch}toString(){return`${this.#Ct}.${this.#Pt}.${this.#Lt}`}}class qt{#Ne;#Ft;constructor(e,t=!1){this.#Ne=e,this.#Ft=t}get name(){return this.#Ne}get isOptional(){return this.#Ft}}class Ut extends qt{}class Gt extends qt{#Vt;constructor(e,t,s){super(t??"(anonymous)",s),this.#Vt=e}get variables(){return this.#Vt}}class Kt extends Gt{}class Ht extends Gt{}class _t{#$e;#Pe;#Dt;#jt=new Map;#kt;constructor(e,t,s,r,i){this.#$e=e,this.#Pe=t,this.#Dt=s,this.#jt=r,this.#kt=i}get fqn(){return this.#$e}get version(){return this.#Pe}get args(){return this.#Dt}get headers(){return this.#jt}get mode(){return this.#kt}clearArguments(){this.#Dt.clear()}setArgument(e,t){this.#Dt.set(e,t)}getArgument(e){return this.#Dt.get(e)}hasArgument(e){return this.#Dt.has(e)}removeArgument(e){this.#Dt.delete(e)}clearHeaders(){this.#jt.clear()}setHeader(e,t){this.#jt.set(e.toLowerCase(),t)}getHeader(e){return this.#jt.get(e.toLowerCase())}hasHeader(e){return this.#jt.has(e.toLowerCase())}removeHeader(e){this.#jt.delete(e.toLowerCase())}}class Wt{#Bt;#qt;#jt;constructor(e,t=void 0,s=new Map){this.#Bt=e,this.#qt=t,this.#jt=s}get status(){return this.#Bt}get result(){return this.#qt}set result(e){this.#qt=e}get headers(){return this.#jt}clearHeaders(){this.#jt.clear()}setHeader(e,t){this.#jt.set(e.toLowerCase(),t)}getHeader(e){return this.#jt.get(e.toLowerCase())}hasHeader(e){return this.#jt.has(e.toLowerCase())}removeHeader(e){this.#jt.delete(e.toLowerCase())}}const zt=/^\d+(?:\.\d+){0,2}$/;class Yt{parse(e){if(0===e.trim().length)return Bt.DEFAULT;if(!1===zt.test(e))throw new jt(e);const t=e.split(".");switch(t.length){case 1:return new Bt(Number.parseInt(t[0]));case 2:return new Bt(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new Bt(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class Xt{#pt;#je;constructor(e,t){this.#pt=e,this.#je=t}generate(){const e=[],t=this.#Ut();for(const s of t){const t=s.access===xt.PRIVATE?this.#Gt(s):this.#Kt(s);e.push(...t)}return new Q(e).toString()}#Ut(){const e=this.#je.map(e=>e.getModule(this.#pt.filename)).flatMap(e=>e.implementations),t=new Map;for(const s of e){const e=`${s.fqn}:${s.version.toString()}`;t.set(e,s)}return[...t.values()]}#Gt(e){const t=`throw new ProcedureNotAccessible('${e.fqn}','${e.version}');`;return[this.#Ht(e),this.#_t(e,t)]}#Kt(e){const t=`return __run('${e.fqn}','${e.version}',{${this.#Wt(e.model.parameters)}},this);`;return[this.#Ht(e),this.#_t(e,t)]}#Ht(e){const t=e.model.identifier,s=e.importKey===y?y:void 0,r=new J(t,s);return new K([r],void 0)}#_t(e,t){const s=e.model.identifier,r=e.model.parameters,i=new V(`{${t}}`),n=e.model.isAsync;return new P(s,r,i,n)}#Wt(e){return this.#zt(e).join(",")}#zt(e){const t=[];for(const s of e)if(s.binding instanceof z){const e=this.#Yt(s.binding);t.push(e)}else if(s.binding instanceof M){const e=this.#zt(s.binding.elements);t.push(...e)}else if(s.binding instanceof Z){const e=this.#zt(s.binding.elements);t.push(...e)}return t}#Yt(e){return`'${e.identifier}':${e.toString()}`}}const Qt=["Segment","Class","Procedure","Implementation","Version","NamedParameter","ArrayParameter","ObjectParameter"];class Jt{#mt;#p=new T;#Xt=new Yt;constructor(e){this.#mt=e}generate(){const e=this.#Qt(),t=this.#Ht(),s=this.#Jt();return new Q([...e,t,s]).toString()}#Qt(){return[this.#Zt(),...this.#es()]}#Zt(){const e=Qt.map(e=>new J(e));return new Y(e,"jitar")}#es(){const e=this.#mt.name,t=this.#mt.getSegmentedModules(),s=[];for(const r of t){const t=`./${this.#p.addSubExtension(r.filename,e)}`;if(0===r.members.length){const e=new Y([],t);s.push(e);continue}const i=r.classes,n=r.implementations;if(i.length>0){const e=`./${r.filename}`,t=this.#ts(i,e);s.push(t)}if(n.length>0){const e=this.#ts(n,t);s.push(e)}}return s}#ts(e,t){if(0===e.length)return new Y([],t);const s=e.map(e=>new J(e.importKey,e.id));return new Y(s,t)}#Ht(){const e=new J("segment","default");return new K([e],void 0)}#Jt(){const e=[],t=this.#mt.name,s=this.#mt.classes,r=this.#mt.procedures;e.push(`new Segment("${t}")`);for(const t of s)e.push(`\t.addClass(new Class("${t.fqn}", ${t.id}))`);for(const t of r){e.push(`\t.addProcedure(new Procedure("${t.fqn}")`);for(const s of t.implementations){const t=this.#ss(s.version),r=this.#rs(s.model);e.push(`\t\t.addImplementation(new Implementation(${t}, "${s.access}", ${r}, ${s.id}))`)}e.push("\t)")}const i=e.join("\n"),n=new H(i),o=new z("segment");return new X("const",o,n)}#ss(e){const t=this.#Xt.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#rs(e){return`[${this.#is(e.parameters).join(", ")}]`}#is(e){const t=[];for(const s of e)t.push(this.#ns(s));return t}#ns(e){return e.binding instanceof M?this.#os(e):e.binding instanceof Z?this.#as(e):this.#cs(e)}#cs(e){return`new NamedParameter("${e.binding}", ${void 0!==e.initializer})`}#os(e){const t=e.binding;return`new ArrayParameter([${this.#is(t.elements).join(", ")}])`}#as(e){const t=e.binding;return`new ObjectParameter([${this.#is(t.elements).join(", ")}])`}}class Zt{#us;#ls;#hs;#mt;#ps;constructor(e,t,s,r,i){this.#us=e,this.#ls=t,this.#hs=s,this.#mt=r,this.#ps=i}get source(){return this.#us}get target(){return this.#ls}get resource(){return this.#hs}get segment(){return this.#mt}get sourceIgnores(){return this.#ps}}class es{#ms;constructor(e=!0){this.#ms=e}validate(e,t){const s=[];this.#ds("",e,t,s);return{valid:0===s.length,errors:s}}#ds(e,t,s,r){this.#ms&&this.#fs(e,t,s,r),this.#gs(e,t,s,r)}#fs(e,t,s,r){const i=Object.keys(t),n=Object.keys(s);for(const t of i)if(!1===n.includes(t)){const s=this.#Es(e,t);r.push(`Unknown field '${s}'`)}}#gs(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#Es(e,n),o=s[n],a=t[n];this.#ws(i,a,o,r)}}#ws(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#ys(e,t,s,r);case"integer":return this.#bs(e,t,s,r);case"real":return this.#Ss(e,t,s,r);case"boolean":return this.#Is(e,t,s,r);case"url":return this.#As(e,t,s,r);case"group":return this.#Ts(e,t,s,r);case"list":return this.#vs(e,t,s,r);case"enum":return this.#Os(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#ys(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#bs(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Ss(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Is(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#As(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#Ts(e,t,s,r){"object"==typeof t?this.#ds(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#vs(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const i=t;for(const t in i){const n=this.#Es(e,t),o=i[t];this.#ws(n,o,s.items,r)}}#Os(e,t,s,r){if(!1===s.options.includes(t)){const t=s.options.map(e=>String(e));r.push(`Field '${e}' is not one of: ${t.join(", ")}`)}}#Es(e,t){return""===e?t:`${e}.${t}`}}class ts{#Ns;constructor(e){this.#Ns=e}async configure(e){const t=this.#Ns.getAbsoluteLocation(e);n.config({path:t})}}class ss extends Error{constructor(e,t){super(`Invalid runtime configuration '${e}'\n${t.errors.join("\n")}`)}}const rs="./jitar.json",is="./src",ns="./dist",os="./segments",as="./resources",cs={ignore:[]},us=[],ls={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1},build:{type:"group",fields:{ignore:{type:"list",items:{type:"string"},required:!1}},required:!1}};let hs=class{#Rs;#xs;constructor(e,t){this.#Rs=e,this.#xs=t}async build(e=rs){const t=await this.#Rs.read(e),s=this.#xs.validate(t,ls);if(!1===s.valid)throw new ss(e,s);return t.source??=is,t.target??=ns,t.segments??=os,t.resources??=as,t.build??=cs,t.build.ignore??=us,t.meta={root:this.#Rs.getRootLocation(),configFile:e},t}};const ps="\n => ";class ms extends Error{constructor(e,t){const s=t.errors.join(ps);super(`Invalid server configuration '${e}'${ps}${s}`)}}const ds={indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assetRoot:{type:"string",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}},fs={gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}},gs={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:ds},standalone:{type:"group",required:!1,fields:{...ds,segments:fs.segments}},worker:{type:"group",required:!1,fields:fs},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class Es{#Rs;#xs;constructor(e,t){this.#Rs=e,this.#xs=t}async build(e){const t=await this.#Rs.read(e),s=this.#xs.validate(t,gs);if(!1===s.valid)throw new ms(e,s);return t.meta={root:this.#Rs.getRootLocation(),configFile:e},t}}class ws extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const ys=/\${([^}]*)}/g;class bs{#Ns;constructor(e){this.#Ns=e}getRootLocation(){return this.#Ns.getAbsoluteLocation(".")}async read(e){if(!1===await this.#Ns.exists(e))return{};const t=await this.#Ns.read(e);if(!1===t.type.includes("json"))throw new ws(e);const s=t.content.toString(),r=this.#Ms(s);return this.#$s(r)}#Ms(e){return e.replace(ys,(e,t)=>process.env[t]??"null")}#$s(e){return JSON.parse(e)}}class Ss{#Cs;#Ps;#Ls;constructor(e="./"){const t=new p(e),s=new bs(t),r=new es;this.#Cs=new ts(t),this.#Ps=new hs(s,r),this.#Ls=new Es(s,r)}configureEnvironment(e=".env"){return this.#Cs.configure(e)}getRuntimeConfiguration(e){return this.#Ps.build(e)}getServerConfiguration(e){return this.#Ls.build(e)}}export{Kt as A,Mt as B,Ss as C,G as E,$t as F,Jt as G,p as L,Ct as N,Ht as O,ot as P,Wt as R,Ft as S,Vt as T,Dt as U,es as V,z as a,H as b,X as c,Q as d,U as e,j as f,k as g,B as h,q as i,Ut as j,Pt as k,Lt as l,kt as m,T as n,Rt as o,Xt as p,Zt as q,Ot as r,o as s,u as t,c as u,_t as v,Yt as w,Bt as x,xt as y};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
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 q,C as B,y as F,z as W,D,G as V}from"./ConfigurationManager-D8N-pXTY.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.#q(e,t)}#L(e,t,r){const s=t.get(e.name);if(this.#B(e,s,r))throw new Ae(e.name);if(this.#F(e,s,r))throw new ze(e.name);return t.delete(e.name),s}#q(e,t){return e instanceof v?this.#W(e,t):this.#D(e,t)}#W(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}#B(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#F(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 qe=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 Be{#ke;#Pe;constructor(e,t){const r=e.target;this.#ke=new je(r),this.#Pe=new qe(r,t)}async build(e){await Promise.all([this.#ke.build(e),this.#Pe.build(e)])}}const Fe=0,We=1,De=2,Ve=3,Ke=4;class Ue{#Ae;#ze;constructor(e=We,t=console){this.#Ae=e,this.#ze=t}debug(...e){if(this.#Ae>Fe)return;const t=this.#Re("DEBUG",e);this.#ze.debug(t)}info(...e){if(this.#Ae>We)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 Fe;case"INFO":return We;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),o=new s(r),c=new s(a),u=new s(n),l=new s(i);this.#b=new $(o,c,u,l),this.#Oe=new L(this.#b),this.#Ne=new Be(this.#b,this.#xe)}async build(){const e=this.#b.source,t=this.#b.resource,r=this.#b.segment,s=await e.filter(q.MODULE_PATTERN),a=await t.filter(q.RESOURCE_PATTERN),n=await r.filter(q.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 B;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 F;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 W(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.#qe(i),u=this.#Be(i);return new R(o,c,u)}async#$e(e,t,r=!0){const s=await this.#Ie.execute(e,t);if(r&&this.#Fe(s)){const e=await this.#qe(s);throw this.#X.fromStatus(s.status,String(e))}return s}#Fe(e){return e.status<200||e.status>399}async#Le(e){return JSON.stringify(e)}async#qe(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}#Be(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{#We=ut.STOPPED;get state(){return this.#We}set state(e){this.#We=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.#We=ut.STARTING}setAvailable(){this.#We=ut.AVAILABLE}setUnavailable(){this.#We=ut.UNAVAILABLE}setAvailability(e){return this.#We=e?ut.AVAILABLE:ut.UNAVAILABLE,this.#We}setStopping(){this.#We=ut.STOPPING}setStopped(){this.#We=ut.STOPPED}#Ve(...e){return e.includes(this.#We)}#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 qt 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 Bt 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 Ft 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 Wt 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 Wt),void 0!==e&&t.addSerializer(new $t(e)),t.addSerializer(new Bt),t.addSerializer(new Kt),t.addSerializer(new Nt),t.addSerializer(new Xt),t.addSerializer(new qt),t.addSerializer(new Ut),t.addSerializer(new Ft),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;#qt;#Bt=Date.now();#Ft=Date.now();constructor(e=6e3,t=18e3){super(),this.#Lt=e,this.#qt=t}report(e){this.#Bt=Date.now(),this.state=e}update(){this.#Ft=Date.now();const e=this.#Ft-this.#Bt;return e>=this.#Lt&&(this.state=e>=this.#qt?ut.STOPPED:ut.UNAVAILABLE),this.state}}class nr{#et;#f;#Ke;#Wt;#Xe;#Ge;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Wt=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.#Wt.values()]}hasProcedure(e){return this.#Wt.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;#qt;constructor(e,t,r){this.#Dt=e,this.#Lt=t,this.#qt=r}build(e,t,r){const s=this.#Dt.build(e),a=new Set(t),n=this.#Lt,i=this.#qt;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{#We=dr;#Ut=new Map;#_;#_t;constructor(e,t=[]){this.#_=e,this.#_t=t}get state(){return this.#We}async start(){if(this.#We===dr)try{this.#We=ur,await this.#Gt(),this.#We=lr}catch(e){throw this.#We=dr,e}}async stop(){if(this.#We===lr)try{this.#We=hr,this.clearHealthChecks(),this.#We=dr}catch(e){throw this.#We=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{#We=yr;#Zt=[];#_;#Yt;constructor(e,t=[]){this.#_=e,this.#Yt=t}get state(){return this.#We}async start(){if(this.#We===yr)try{this.#We=gr,await this.#er(),this.#We=wr}catch(e){throw this.#We=yr,e}}async stop(){if(this.#We===wr)try{this.#We=fr,this.clearMiddlewares(),this.#We=yr}catch(e){throw this.#We=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 qr extends Error{constructor(){super("Unknown service configured")}}class Br{#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 Fr{#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.#qr(r,s),d=this.#Br(a),p=this.#Fr(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.#Wr(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 qr}async#Wr(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 0,i=t.reportInterval,o=void 0!==n,c=this.#Qr(t.segments);return new sr({url:e,trustKey:a,reportInterval:i,gateway:n,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#Jr(e,t,r){const s=void 0!==t.assetRoot?this.#lt.fork(t.assetRoot):this.#lt,a=await this.#Zr(s,t.assets),n=t.indexFilename,i=t.serveIndexOnNotFound;return new xt({url:e,sourcingManager:s,assets:a,indexFilename:n,serveIndexOnNotFound:i,healthManager:r})}#Yr(e){const t=this.#Dt.build(e);return new St({url:e,remote:t})}async#Kr(e,t){const r=this.#Yr(t.repository),s=this.#Xr(t.gateway);return new Mt({url:e,provider:r,runner:s})}async#Ur(e,t,r,s){const a=await this.#Jr(e,t,r),n=this.#Gr(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}#qr(e=[],t=[]){const r=e.map(e=>this.#es(e)),s=t.map(e=>this.#es(e));return new Br(this.#lt,r,s)}#jr(e=[]){const t=e.map(e=>this.#es(e));return new mr(this.#lt,t)}#Br(e=[]){const t=e.map(e=>this.#es(e));return new br(this.#lt,t)}#Qr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Ie(this.#lt,t)}#$r(e){return new xr(e)}#Fr(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new ir(this.#Dt,t,r)}async#Zr(e,t){if(void 0===t)return new Set;const r=await e.filter(...t);return new Set(r)}#es(e){return e.endsWith(".js")?e:e+".js"}}const Wr="3000",Dr=204800,Vr=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class Kr{#ts;#rs;#ss;#as;#je=new F;constructor(e,t=Wr,r=Dr){this.#ts=e,this.#rs=t,this.#ss=U(),this.#ns(r),this.#is()}async start(){return await this.#ts.start(),this.#os()}async stop(){return await this.#cs(),this.#ts.stop()}#ns(e){this.#ss.use(U.json({limit:e})),this.#ss.use(U.urlencoded({extended:!0})),this.#ss.use(this.#us.bind(this)),this.#ss.disable(tt)}#is(){this.#ss.get("/health",(e,t)=>{this.#ls(e,t)}),this.#ss.get("/health/status",(e,t)=>{this.#hs(e,t)}),this.#ss.get("/rpc/*procedure",(e,t)=>{this.#ds(e,t)}),this.#ss.post("/rpc/*procedure",(e,t)=>{this.#ps(e,t)}),this.#ss.options("/rpc/*procedure",(e,t)=>{this.#ms(e,t)}),this.#ss.post("/workers",(e,t)=>{this.#gs(e,t)}),this.#ss.post("/workers/:id/report",(e,t)=>{this.#ws(e,t)}),this.#ss.delete("/workers/:id",(e,t)=>{this.#fs(e,t)}),this.#ss.use((e,t)=>{this.#ys(e,t)})}#os(){return void 0!==this.#as?Promise.resolve():new Promise((e,t)=>{this.#as=this.#ss.listen(this.#rs,t),e()})}#cs(){return void 0===this.#as?Promise.resolve():new Promise(e=>{this.#as.close(()=>e())})}#us(e,t,r){t.setHeader(Ze,rt),r()}async#ls(e,t){const r=await this.#ts.getHealth();return this.#vs(t,r)}async#hs(e,t){const r=await this.#ts.isHealthy();return this.#vs(t,r)}async#ds(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#xs(e),n=this.#Ss(e),i=he,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#ps(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#ks(e),n=this.#Ss(e),i=he,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#ms(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#ks(e),n=this.#Ss(e),i=de,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#gs(e,t){const r=this.#ks(e),s=this.#je.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.url,n=r.procedureNames,i=r.trustKey;try{const e=await this.#ts.addWorker({url:a,procedureNames:n,trustKey:i});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ws(e,t){const r={id:e.params.id,state:e.body.state},s=this.#je.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id,n=r.state;try{const e=await this.#ts.reportWorker({id:a,state:n});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#fs(e,t){const r={id:e.params.id},s=this.#je.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id;try{const e=await this.#ts.removeWorker({id:a});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ys(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),a=await this.#ts.provide({filename:s});return this.#vs(t,a)}#bs(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Ms(e){const t=e.headers[et];return Array.isArray(t)?t[0]:t}#xs(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#ks(e){return e.body}#Ss(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();Vr.includes(e)||(t[e]=a)}return t}#vs(e,t){const r=this.#Ps(t),s=this.#As(t);e.status(r),e.setHeader(Qe,s),e.setHeader(Ye,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const a=this.#zs(t);return e.send(a)}#Ps(e){return void 0!==e.headers.location?302:e.status}#As(e){const t=e.contentType.toLowerCase();switch(t){case Pr:case Ar:case kr:case Sr:return Rr}return t}#zs(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class Ur{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{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"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),a=e.getOptionalArgument("--log-level",void 0),n=this.#Te(a),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Rs(i),c=new B;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#Cs(u,l,o,n);return this.#Es(h)}async#Cs(e,t,r,s){const[,,a]=t.url.split(":"),n=new ce(e.target),i=new ct,o=new Fr(n,i),c=await o.build(t,s);return new Kr(c,a,r)}#Es(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#Te(e){if(void 0===e)return;return(new Ge).parse(e)}#Rs(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class _r extends Error{constructor(e){super(`Command ${e} not found`)}}class Gr{#s=new Set;constructor(){this.#s.add(new J(this.#s)),this.#s.add(new X),this.#s.add(new Q),this.#s.add(new re),this.#s.add(new Xe),this.#s.add(new Ur)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new _r(e)}}class Jr{#Hs;#Os;constructor(){this.#Hs=new G(process.argv),this.#Os=new Gr}start(){const e=this.#Hs.getCommand()??"help";return this.#Os.run(e,this.#Hs)}}try{const e=new Jr;await e.start()}catch(e){const t=new Ue,r=e instanceof Error?e.message:String(e);t.fatal(r)}
|
|
2
|
+
import e from"node:process";import{promises as t}from"node:fs";import r from"node:path";import{fileURLToPath as s}from"node:url";import{L as a,E as n,P as i,a as o,b as c,c as u,d as l,e as h,f as d,g as p,h as g,i as m,N as w,F as f,B as y,j as v,A as b,O as M,k as x,l as S,T as k,U as P,S as A,m as z,R,n as E,o as C,p as H,G as O,q as T,r as N,s as I,C as j,V as $,t as L,u as B,v as W,w as F,x as q}from"./ConfigurationManager-DE4YOzeh.js";import D from"node:crypto";import V from"express";import"glob";import"mime-types";import"dotenv";class K extends Error{constructor(e){super(`Missing argument '${e}'`)}}class U{#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 K(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 _{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 G{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 J{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class X extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class Q extends Error{constructor(e){super(`Unknown template: ${e}`)}}const Z=/^[a-zA-Z.\-_]+$/;class Y{#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 Q(t);await this.#p(e,t)}#u(){const e=r.dirname(s(import.meta.url));return r.join(e,"templates")}#l(e){return r.resolve(e)}#h(e,t){if(!1===Z.test(e))throw new X(e,t)}async#d(e){try{const s=r.join(this.#o,e);return(await t.stat(s)).isDirectory()}catch{return!1}}#p(e,s){const a=r.join(this.#o,s),n=r.join(this.#c,e);return t.cp(a,n,{recursive:!0,force:!0})}}class ee{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.#g(t,r),await this.#m(t,r,s),this.#w(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#m(e,t,r){return new Y(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 te extends Error{constructor(e,t){super(`Module could not be loaded from '${e}'`,{cause:t})}}class re{#f;constructor(e){this.#f=e}async import(e){const t=this.#f.locate(e);try{return await(import(t))}catch(e){throw new te(t,e)}}}class se{#y;constructor(e){this.#y=e}locate(e){return`file://${e.startsWith("/")?this.#y.getAbsoluteLocation(`.${e}`):this.#y.getAbsoluteLocation(e)}`}}class ae extends re{constructor(e){super(new se(e))}}class ne{#y;#v;constructor(e,t){this.#y=e,this.#v=t}get fileManager(){return this.#y}get importManager(){return this.#v}async filter(...e){return(await Promise.all(e.map(e=>this.#y.filter(e)))).flat().map(e=>this.#y.getRelativeLocation(e))}exists(e){return this.#y.exists(e)}read(e){return this.#y.read(e)}import(e){return this.#v.import(e)}}class ie extends ne{constructor(e){const t=new a(e);super(t,new ae(t))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new ie(t)}}class oe{merge(e,t){const r=void 0!==e.construct?[e.construct]:[],s=[...this.#b(e.fields,t.fields),...r,...this.#b(e.methods,t.methods),...this.#b(e.getters,t.getters),...this.#b(e.setters,t.setters)];return new n(e.identifier,t.identifier,s)}#b(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 ce{#M=new i;#x=new oe;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 o(e,!1),a=new c(r);s.push(new u("var",t,a))}}return new l(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#S(e):this.#k(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const a=this.fromClass(s,!0);return this.#x.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.#M.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")}#S(e){const t=e.toString();return this.#M.parseClass(t)}#k(e){const t=this.createInstance(e),r=this.#P(e,t);return new n(e.name,void 0,r)}#P(e,t){return[...this.#A(t),...this.#z(e)]}#A(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],a=void 0!==t?new c(String(t)):void 0,n=new h(e,"public","instance",a);s.push(n)}return s}#z(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 d(n.parameters,n.body)):void 0!==s.get?r.push(new p(n.identifier,"public","instance",n.body)):void 0!==s.set?r.push(new g(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}}class ue extends Error{constructor(e,t){super(`Failed building module for '${e}'`,{cause:t})}}const le="normal",he="dry",de=200,pe=400,ge=401,me=402,we=403,fe=404,ye=418,ve=500,be=501;class Me extends w{#R;constructor(e){super(`Procedure '${e}' not found`),this.#R=e}get fqn(){return this.#R}}class xe extends f{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Se extends y{#E;constructor(e){super(`Unknown parameter ${e}`),this.#E=e}get parameterName(){return this.#E}}class ke extends y{#E;constructor(e){super(`Missing value for parameter '${e}'`),this.#E=e}get parameterName(){return this.#E}}class Pe extends y{#E;constructor(e){super(`Invalid value for parameter '${e}'`),this.#E=e}get parameterName(){return this.#E}}class Ae{extract(e,t){const r=this.#C(e,t),s=[];for(const t of e){const e=this.#H(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Se(e)}return s}#C(e,t){const r=new Map;for(const[s,a]of t){if(this.#O(s)){const t=this.#T(s);!0===this.#N(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#O(e){return e.startsWith("*")}#T(e){return e.substring(1)}#N(e,t){return void 0!==e.find(e=>e.name===t)}#H(e,t,r){return e instanceof v?this.#I(e,t,r):this.#j(e,t)}#I(e,t,r){const s=t.get(e.name);if(this.#$(e,s,r))throw new ke(e.name);if(this.#L(e,s,r))throw new Pe(e.name);return t.delete(e.name),s}#j(e,t){return e instanceof b?this.#B(e,t):this.#W(e,t)}#B(e,t){const r=this.#F(e,t);return void 0!==r?Object.values(r):void 0}#W(e,t){return this.#F(e,t)}#F(e,t){const r=e instanceof b,s={},a=[];let n=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#H(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 ke(a[0]);return n?s:void 0}#$(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#L(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof b&&t instanceof Array==!1||r instanceof M&&t instanceof Object==!1)}}class ze{toStatus(e){return e instanceof y?pe:e instanceof f?we:e instanceof w?fe:e instanceof x?be:e instanceof S?me:e instanceof k?ye:e instanceof P?ge:ve}fromStatus(e,t){switch(e){case pe:return new y(t);case we:return new f(t);case fe:return new w(t);case be:return new x(t);case me:return new S(t);case ye:return new k(t);case ge:return new P(t);default:return new A(t)}}}class Re extends w{#R;#q;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#R=e,this.#q=t}get fqn(){return this.#R}get version(){return this.#q}}class Ee extends A{constructor(){super("Invalid segment")}}class Ce extends Error{constructor(e){super("Starting execution manager failed",{cause:e})}}class He extends Error{constructor(e){super("Stopping execution manager failed",{cause:e})}}class Oe{#D=new Map;addSegment(e){this.#D.set(e.id,e)}clearSegments(){this.#D.clear()}getClassNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#D.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Te{#V;#K;#U=new Ae;#_=new ze;#G=new Oe;constructor(e,t=[]){this.#V=e,this.#K=t}async start(){try{await this.#J()}catch(e){throw new Ce(e)}}async stop(){try{return this.#X()}catch(e){throw new He(e)}}async loadSegment(e){const t=await this.#V.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof z==!1)throw new Ee;this.#G.addSegment(e)}getClassNames(){return this.#G.getClassNames()}hasClass(e){return this.#G.hasClass(e)}getClass(e){return this.#G.getClass(e)}getClassByImplementation(e){return this.#G.getClassByImplementation(e)}getProcedureNames(){return this.#G.getProcedureNames()}hasProcedure(e){return this.#G.hasProcedure(e)}getProcedure(e){return this.#G.getProcedure(e)}async run(e){const t=this.#Q(e.fqn,e.version),r=this.#U.extract(t.parameters,e.args);return e.mode===he?new R(de,void 0):this.#Z(e,t,r)}async#J(){await Promise.all(this.#K.map(e=>this.loadSegment(e)))}#X(){this.#G.clearSegments()}#Q(e,t){const r=this.#G.getProcedure(e);if(void 0===r)throw new Me(e);const s=r.getImplementation(t);if(void 0===s)throw new Re(r.fqn,t.toString());return s}async#Z(e,t,r){try{const s=await t.executable.call(e,...r);return new R(de,s)}catch(e){const t=this.#_.toStatus(e);return new R(t,e)}}}let Ne=class{#Y;#ee=new E;constructor(e){this.#Y=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,a=t.modules.map(e=>this.#te(e,s,r));await Promise.all(a)}async#te(e,t,r){try{const s=r.getSegments(e.filename);if(0===s.length)return void await this.#re(e,t,r);const a=s.filter(t=>t.getModule(e.filename)?.hasImplementations()),n=this.#re(e,t,r),i=a.map(s=>this.#se(e,t,s,r)),o=a.length>0?this.#ae(e,s):Promise.resolve();await Promise.all([n,...i,o])}catch(t){throw new ue(e.filename,t)}}async#re(e,t,r){const s=e.filename,a=new C(e,t,r).generate();return this.#Y.write(s,a)}async#se(e,t,r,s){const a=this.#ee.addSubExtension(e.filename,r.name),n=new C(e,t,s,r).generate();return this.#Y.write(a,n)}async#ae(e,t){const r=this.#ee.addSubExtension(e.filename,"remote"),s=new H(e,t).generate();return this.#Y.write(r,s)}};class Ie extends Error{constructor(e,t){super(`Failed building segment '${e}'`,{cause:t})}}let je=class{#Y;#ne;constructor(e,t){this.#Y=e,this.#ne=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ie(e));await Promise.all(t)}async#ie(e){try{const t=`${e.name}.segment.js`,r=new O(e).generate();await this.#Y.write(t,r),this.#ne.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}catch(t){throw new Ie(e.name,t)}}};class $e{#oe;#ce;constructor(e,t){const r=e.target;this.#oe=new Ne(r),this.#ce=new je(r,t)}async build(e){await Promise.all([this.#oe.build(e),this.#ce.build(e)])}}const Le=0,Be=1,We=2,Fe=3,qe=4;class De{#ue;#le;constructor(e=Be,t=console){this.#ue=e,this.#le=t}debug(...e){if(this.#ue>Le)return;const t=this.#he("DEBUG",e);this.#le.debug(t)}info(...e){if(this.#ue>Be)return;const t=this.#he("INFO",e);this.#le.info(t)}warn(...e){if(this.#ue>We)return;const t=this.#he("WARN",e);this.#le.warn(t)}error(...e){if(this.#ue>Fe)return;const t=this.#he("ERROR",e);this.#le.error(t)}fatal(...e){const t=this.#he("FATAL",e);this.#le.error(t)}#he(e,t){return`[${(new Date).toISOString()}][${e}] ${t.map(e=>this.#de(e)).join(" ")}`}#de(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#pe(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#ge(t)}${r}`}#pe(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#de(e,t)).join(",\n")}\n${this.#ge(t-1)}]`}if(e instanceof Error){const r=void 0!==e.cause?this.#de(e.cause,t+1):void 0,s=void 0!==r?`\n=>${r}`:"";return`${e.message}${s}`}return JSON.stringify(e)}#ge(e){return" ".repeat(e)}}class Ve extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class Ke{parse(e){switch(e.toUpperCase()){case"DEBUG":return Le;case"INFO":return Be;case"WARN":return We;case"ERROR":return Fe;case"FATAL":return qe;default:throw new Ve(e)}}}class Ue extends Error{constructor(e){super("Build failed",{cause:e})}}class _e{#ne;#ee;#y;#me;#we;constructor(e,t){this.#ne=new De(t),this.#ee=new E;const r=this.#ee.makePathAbsolute(e.source,e.meta.root),s=this.#ee.makePathAbsolute(e.target,e.meta.root),n=this.#ee.makePathAbsolute(e.resources,e.meta.root),i=this.#ee.makePathAbsolute(e.segments,e.meta.root);this.#y=new T(new a(r),new a(s),new a(n),new a(i),e.build.ignore),this.#me=new N(this.#y),this.#we=new $e(this.#y,this.#ne)}async build(){try{const e=this.#y.source,t=this.#y.resource,r=this.#y.segment,s=await e.filterWithIgnores(I.MODULE_PATTERN,this.#y.sourceIgnores),a=await t.filter(I.RESOURCE_PATTERN),n=await r.filter(I.SEGMENT_PATTERN),i=await this.#me.read(s,a,n);await this.#we.build(i)}catch(e){throw new Ue(e)}}}class Ge{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.#fe(s),n=new j;await n.configureEnvironment(t);const i=await n.getRuntimeConfiguration(r);return new _e(i,a).build()}#fe(e){if(void 0===e)return;return(new Ke).parse(e)}}const Je="content-type",Xe="x-content-type-options",Qe="x-jitar-content-type",Ze="x-jitar-procedure-version",Ye="x-powered-by",et="nosniff",tt="application/json",rt="application/octet-stream";class st extends Error{constructor(){super("Invalid worker id")}}class at{#ye;#ve;#_=new ze;#be=new $;constructor(e,t){this.#ye=e,this.#ve=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#ye}/${e}`,r=await this.#Me(t,{method:"GET"}),s=r.headers.get(Je)??rt,a=await r.arrayBuffer(),n=Buffer.from(a);return new L(e,s,n)}async isHealthy(){const e=`${this.#ye}/health/status`,t=await this.#Me(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#ye}/health`,t=await this.#Me(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#ye}/workers`,a={url:e,procedureNames:t,trustKey:r},n={method:"POST",headers:{"Content-Type":tt},body:JSON.stringify(a)},i=await this.#Me(s,n),o=i.headers.get(Je);if(null===o||!1===o.includes(tt))throw new st;const c=await i.json();if(!1===this.#be.validate(c,{id:{type:"string",required:!0}}).valid)throw new st;return c.id}async reportWorker(e,t){const r=`${this.#ye}/workers/${e}/report`,s={state:t},a={method:"POST",headers:{"Content-Type":tt},body:JSON.stringify(s)};await this.#Me(r,a)}async removeWorker(e){const t=`${this.#ye}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":tt}};await this.#Me(t,r)}async run(e){e.setHeader(Je,tt);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[Ze]=s;const a=`${this.#ye}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:r,body:await this.#xe(t)},i=await this.#Me(a,n,!1),o=i.status,c=await this.#Se(i),u=this.#ke(i);return new R(o,c,u)}async#Me(e,t,r=!0){const s=await this.#ve.execute(e,t);if(r&&this.#Pe(s)){const e=await this.#Se(s);throw this.#_.fromStatus(s.status,String(e))}return s}#Pe(e){return e.status<200||e.status>399}async#xe(e){return JSON.stringify(e)}async#Se(e){const t=e.headers.get(Qe)??e.headers.get(Je);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}#ke(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class nt{async execute(e,t){return fetch(e,t)}}class it{#ve;constructor(e=new nt){this.#ve=e}build(e){return new at(e,this.#ve)}}const ot={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class ct{get url(){throw new x}get state(){return ot.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ot.AVAILABLE}provide(e){throw new x}}class ut{get url(){throw new x}get state(){return ot.AVAILABLE}get trustKey(){throw new x}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ot.AVAILABLE}getProcedureNames(){throw new x}hasProcedure(e){throw new x}run(e){throw new x}}class lt{#Ae=ot.STOPPED;get state(){return this.#Ae}set state(e){this.#Ae=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.#ze(ot.STOPPED)}isStopped(){return this.#Re(ot.STOPPED)}isAvailable(){return this.#Re(ot.AVAILABLE)}setStarting(){this.#Ae=ot.STARTING}setAvailable(){this.#Ae=ot.AVAILABLE}setUnavailable(){this.#Ae=ot.UNAVAILABLE}setAvailability(e){return this.#Ae=e?ot.AVAILABLE:ot.UNAVAILABLE,this.#Ae}setStopping(){this.#Ae=ot.STOPPING}setStopped(){this.#Ae=ot.STOPPED}#Re(...e){return e.includes(this.#Ae)}#ze(...e){return!1===this.#Re(...e)}}class ht extends P{constructor(){super("Invalid trust key")}}class dt{#ye;#Ee;#Ce;#He;#Oe=new lt;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#Ce=e.healthManager,this.#He=e.workerManager}get url(){return this.#ye}get state(){return this.#Oe.state}get trustKey(){return this.#Ee}async start(){return this.#Oe.start(async()=>{await this.#Ce.start(),this.#He.start(),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{this.#He.stop(),await this.#Ce.stop()})}async isHealthy(){return this.#Ce.isHealthy()}async getHealth(){return this.#Ce.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Oe.setAvailability(e)}async addWorker(e){if(this.#Te(e.trustKey))throw new ht;return await e.start(),this.#He.addWorker(e)}getWorker(e){return this.#He.getWorker(e)}async reportWorker(e,t){return this.#He.reportWorker(e,t)}async removeWorker(e){return this.#He.removeWorker(e).stop()}getProcedureNames(){return this.#He.getProcedureNames()}hasProcedure(e){return this.#He.hasProcedure(e)}async run(e){return this.#He.run(e)}#Te(e){return void 0!==this.#Ee&&e!==this.#Ee}}class pt{#ye;#Ne;#Oe=new lt;constructor(e){this.#ye=e.url,this.#Ne=e.remote}get url(){return this.#ye}get state(){return this.#Oe.state}get trustKey(){}async start(){return this.#Oe.start(async()=>{await this.#Ne.connect(),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{await this.#Ne.disconnect()})}isHealthy(){return this.#Ne.isHealthy()}getHealth(){return this.#Ne.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Oe.setAvailability(e)}getProcedureNames(){throw new x}hasProcedure(e){throw new x}addWorker(e){return this.#Ne.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Ne.reportWorker(e,t)}removeWorker(e){return this.#Ne.removeWorker(e)}run(e){return this.#Ne.run(e)}}class gt extends A{#Ie;constructor(e){super(`No worker available for procedure '${e}'`),this.#Ie=e}get name(){return this.#Ie}}class mt{#je=[];#$e=0;get workers(){return this.#je}addWorker(e){this.#je.includes(e)||this.#je.push(e)}removeWorker(e){const t=this.#je.indexOf(e);-1!==t&&this.#je.splice(t,1)}getNextWorker(){const e=this.#je.filter(e=>e.isAvailable());if(0!==e.length)return this.#$e>=e.length&&(this.#$e=0),e[this.#$e++];this.#$e=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new gt(e.fqn);return t.run(e)}}class wt{generate(){return D.randomUUID()}}class ft extends A{#Le;constructor(e){super(`Unknown worker id '${e}'`),this.#Le=e}get id(){return this.#Le}}class yt{#je=new Map;#Be=new Map;#We=new wt;#Fe;constructor(e,t){this.#Fe=e.create(()=>this.#qe(),t)}get workers(){return[...this.#je.values()]}get balancers(){return this.#Be}start(){this.#Fe.start()}stop(){this.#Fe.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.#We.generate(),this.#je.set(e.id,e);for(const t of e.getProcedureNames()){this.#De(t).addWorker(e)}return e.id}getWorker(e){const t=this.#je.get(e);if(void 0===t)throw new ft(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#je.delete(e);for(const e of t.getProcedureNames()){const r=this.#Ve(e);void 0!==r&&r.removeWorker(t)}return t}#Ve(e){return this.#Be.get(e)}#De(e){let t=this.#Ve(e);return void 0===t&&(t=new mt,this.#Be.set(e,t)),t}async run(e){const t=this.#Ve(e.fqn);if(void 0===t)throw new Me(e.fqn);return t.run(e)}async#qe(){const e=this.workers.map(e=>this.#Ke(e));await Promise.allSettled(e)}async#Ke(e){await e.updateState()===ot.STOPPED&&this.removeWorker(e.id)}}class vt{#ye;#Ue;#_e;#Oe=new lt;constructor(e){this.#ye=e.url,this.#Ue=e.provider,this.#_e=e.runner}get url(){return this.#ye}get state(){return this.#Oe.state}get trustKey(){return this.#_e.trustKey}get provider(){return this.#Ue}get runner(){return this.#_e}async start(){return this.#Oe.start(async()=>{await Promise.all([this.#Ue.start(),this.#_e.start()]),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{await Promise.allSettled([this.#_e.stop(),this.#Ue.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#Ue.isHealthy(),this.#_e.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#Ue.getHealth(),this.#_e.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#Oe.setAvailability(e)}provide(e){return this.#Ue.provide(e)}getProcedureNames(){return this.#_e.getProcedureNames()}hasProcedure(e){return this.#_e.hasProcedure(e)}run(e){return this.#_e.run(e)}}class bt{#ye;#Ce;#Ge;#Je;#Xe;#Qe;#Oe=new lt;constructor(e){this.#ye=e.url,this.#Ce=e.healthManager,this.#Ge=e.sourcingManager,this.#Je=e.assets,this.#Xe=e.indexFilename??"index.html",this.#Qe=e.serveIndexOnNotFound??false}get url(){return this.#ye}get state(){return this.#Oe.state}async start(){return this.#Oe.start(async()=>{await this.#Ce.start(),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{await this.#Ce.stop()})}isHealthy(){return this.#Ce.isHealthy()}getHealth(){return this.#Ce.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Oe.setAvailability(e)}async provide(e){if(this.#Ze(e))return this.provide(this.#Xe);if(!1===this.#Je.has(e))throw new B(e);return this.#Ge.read(e)}#Ze(e){return""===e||e!==this.#Xe&&(this.#Qe&&!1===this.#Je.has(e))}}class Mt{#ye;#Ne;#Oe=new lt;constructor(e){this.#ye=e.url,this.#Ne=e.remote}get url(){return this.#ye}get state(){return this.#Oe.state}async start(){return this.#Oe.start(async()=>{await this.#Ne.connect(),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{await this.#Ne.disconnect()})}isHealthy(){return this.#Ne.isHealthy()}getHealth(){return this.#Ne.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Oe.setAvailability(e)}provide(e){return this.#Ne.provide(e)}}class xt extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class St extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class kt extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Pt extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class At{#Ye=[];addSerializer(e){e.parent=this,this.#Ye.unshift(e)}async serialize(e){const t=this.#Ye.find(t=>t.canSerialize(e));if(void 0===t)throw new Pt(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Ye.find(t=>t.canDeserialize(e));if(void 0===t)throw new kt(typeof e);return t.deserialize(e)}}class zt extends Error{constructor(){super("Parent serializer not set")}}class Rt{#et;set parent(e){this.#et=e}serializeOther(e){if(void 0===this.#et)throw new zt;return this.#et.serialize(e)}deserializeOther(e){if(void 0===this.#et)throw new zt;return this.#et.deserialize(e)}}class Et extends Rt{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 Ct extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Ht extends Rt{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 Ct(e.value)}}}class Ot extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Tt extends Rt{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 Ot(e.base64)}}}const Nt=new ce;class It extends Rt{#tt;constructor(e){super(),this.#tt=e}canSerialize(e){return e instanceof Object&&Nt.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=Nt.getClass(e),r=Nt.fromClass(t,!0),s=this.#rt(r),a=this.#tt.resolveKey(t);if(void 0===a)throw new xt(t.name);return{serialized:!0,key:a,name:"class",args:await this.#st(r,s,e),fields:await this.#at(r,s,e)}}#rt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#st(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#at(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.#nt(e);if(void 0===t)throw new xt(e.key);if(t instanceof Function==!1)throw new St(e.key);const r=await this.#it(t,e.args),s=Nt.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#it(e,t){const r=Nt.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#nt(e){return globalThis[e.key]??this.#tt.resolveClass(e.key)}}class jt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class $t extends Rt{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 jt(e.value);return t}}class Lt extends Rt{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 Rt{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 Wt extends Rt{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 Ft extends Rt{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 qt extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Dt extends Rt{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 qt(e.source,e.flags)}}}class Vt extends Rt{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 Kt=new ce;class Ut extends Rt{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 Kt.createInstance(n,[s])}}class _t extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class Gt extends Rt{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 _t(e.value)}}}class Jt{static build(e){const t=new At;return t.addSerializer(new Ft),t.addSerializer(new Wt),void 0!==e&&t.addSerializer(new It(e)),t.addSerializer(new Lt),t.addSerializer(new Dt),t.addSerializer(new Ht),t.addSerializer(new Gt),t.addSerializer(new $t),t.addSerializer(new Vt),t.addSerializer(new Bt),t.addSerializer(new Et),t.addSerializer(new Ut),"undefined"!=typeof Buffer&&t.addSerializer(new Tt),t}}class Xt{#ot;constructor(e){this.#ot=e}resolveKey(e){const t=this.#ot.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#ot.getClass(e);return t?.implementation}}class Qt extends P{constructor(){super("Request not trusted")}}const Zt="X-Jitar-Trust-Key",Yt="X-Jitar-Data-Encoding",er="serialized";class tr{#Le;#ye;#Ee;#ct;#ut;#ot;#Ce;#lt;#ht;#Oe=new lt;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#ct=e.gateway,this.#ut=!0===e.registerAtGateway,this.#ot=e.executionManager,this.#Ce=e.healthManager;const t=e.scheduleManager;this.#lt=t.create(()=>this.#dt(),e.reportInterval);const r=new Xt(this.#ot);this.#ht=Jt.build(r)}get id(){return this.#Le}set id(e){this.#Le=e}get state(){return this.#Oe.state}get url(){return this.#ye}get trustKey(){return this.#Ee}async start(){return this.#Oe.start(async()=>{await Promise.all([this.#ot.start(),this.#Ce.start()]),void 0!==this.#ct&&(await this.#ct.start(),this.#ut&&(this.#Le=await this.#ct.addWorker(this),this.#lt.start())),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{void 0!==this.#ct&&(void 0!==this.#Le&&(this.#lt.stop(),await this.#ct.removeWorker(this.#Le)),await this.#ct.stop()),await Promise.all([this.#Ce.stop(),this.#ot.stop()])})}getProcedureNames(){return this.#ot.getProcedureNames()}hasProcedure(e){return this.#ot.hasProcedure(e)}isHealthy(){return this.#Ce.isHealthy()}getHealth(){return this.#Ce.getHealth()}isAvailable(){return this.#Oe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Oe.setAvailability(e)}async reportState(e){if(void 0!==this.#ct&&void 0!==this.#Le)return this.#ct.reportWorker(this.#Le,e)}async run(e){return this.#pt(e)?this.#gt(e):this.#mt(e)}#pt(e){return void 0===this.#ct||this.#ot.hasProcedure(e.fqn)}async#gt(e){const t=this.#ot.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#wt(r))throw new Me(e.fqn);if(this.#ft(e,r))throw new Qt;const s=e.getHeader(Yt);s===er&&(e=await this.#yt(e)),e.removeHeader(Yt);const a=await this.#ot.run(e);return s===er?this.#vt(a):a}#wt(e){return void 0===e||e.private}#ft(e,t){if(t.public)return!1;const r=e.getHeader(Zt);return this.#Ee!==r}async#mt(e){(e=await this.#bt(e)).setHeader(Yt,er),void 0!==this.#Ee&&e.setHeader(Zt,this.#Ee);const t=await this.#ct.run(e);return this.#Mt(t)}async#bt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#ht.serialize(s);t.set(r,e)}return new W(e.fqn,e.version,t,e.headers,e.mode)}async#yt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#ht.deserialize(s);t.set(r,e)}return new W(e.fqn,e.version,t,e.headers,e.mode)}async#vt(e){const t=await this.#ht.serialize(e.result);return new R(e.status,t,e.headers)}async#Mt(e){const t=await this.#ht.deserialize(e.result);return new R(e.status,t,e.headers)}async#dt(){const e=await this.updateState();return this.reportState(e)}}class rr extends lt{#xt;#St;#kt=Date.now();#Pt=Date.now();constructor(e=6e3,t=18e3){super(),this.#xt=e,this.#St=t}report(e){this.#kt=Date.now(),this.state=e}update(){this.#Pt=Date.now();const e=this.#Pt-this.#kt;return e>=this.#xt&&(this.state=e>=this.#St?ot.STOPPED:ot.UNAVAILABLE),this.state}}class sr{#Le;#ye;#Ee;#At;#Ne;#Oe;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#At=e.procedureNames,this.#Ne=e.remote,this.#Oe=new rr(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#Le}set id(e){this.#Le=e}get state(){return this.#Oe.state}get url(){return this.#ye}get trustKey(){return this.#Ee}async start(){return this.#Oe.start(async()=>{await this.#Ne.connect(),await this.updateState()})}async stop(){return this.#Oe.stop(async()=>{await this.#Ne.disconnect()})}getProcedureNames(){return[...this.#At.values()]}hasProcedure(e){return this.#At.has(e)}isHealthy(){return this.#Ne.isHealthy()}getHealth(){return this.#Ne.getHealth()}isAvailable(){return this.#Oe.isAvailable()}async updateState(){return this.#Oe.update()}async reportState(e){this.#Oe.report(e)}run(e){return this.#Ne.run(e)}}class ar{#zt;#xt;#St;constructor(e,t,r){this.#zt=e,this.#xt=t,this.#St=r}build(e,t,r){const s=this.#zt.build(e),a=new Set(t),n=this.#xt,i=this.#St;return new sr({url:e,trustKey:r,remote:s,procedureNames:a,unavailableThreshold:n,stoppedThreshold:i})}}class nr{#_e;constructor(e){this.#_e=e}async handle(e,t){return this.#_e.run(e)}}class ir{#Rt=new F;constructor(){this.#Et()}#Et(){const e=globalThis;e.__run=this.#Ct.bind(this),e.ProcedureNotAccessible=xe}async#Ct(e,t,r,s){const a=this.#Rt.parse(t),n=new Map(Object.entries(r)),i=s instanceof W?s.headers:new Map,o=new W(e,a,n,i,le),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==de)throw u.result;return u.result}}const or="starting",cr="started",ur="stopping",lr="stopped";class hr extends A{constructor(){super("Invalid health check")}}class dr extends Error{constructor(e){super("Starting health manager failed",{cause:e})}}class pr extends Error{constructor(e){super("Stopping health manager failed",{cause:e})}}class gr{#Ae=lr;#Ht=new Map;#V;#Ot;constructor(e,t=[]){this.#V=e,this.#Ot=t}get state(){return this.#Ae}async start(){if(this.#Ae===lr)try{this.#Ae=or,await this.#Tt(),this.#Ae=cr}catch(e){throw this.#Ae=lr,new dr(e)}}async stop(){if(this.#Ae===cr)try{this.#Ae=ur,this.clearHealthChecks(),this.#Ae=lr}catch(e){throw this.#Ae=cr,new pr(e)}}async loadHealthCheck(e){const t=await this.#Nt(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new hr;this.#Ht.set(e.name,e)}clearHealthChecks(){this.#Ht.clear()}async isHealthy(){const e=[];for(const t of this.#Ht.values()){const r=this.#It(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.#Ht){const s=this.#It(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.#jt(e,t))).then(()=>t)}async#Tt(){(await Promise.all(this.#Ot.map(e=>this.#Nt(e)))).forEach(e=>this.addHealthCheck(e))}async#Nt(e){return(await this.#V.import(e)).default}#jt(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#It(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 mr="starting",wr="started",fr="stopping",yr="stopped";class vr extends A{constructor(){super("Invalid middleware")}}class br extends Error{constructor(e){super("Starting middleware manager failed",{cause:e})}}class Mr extends Error{constructor(e){super("Stopping middleware manager failed",{cause:e})}}class xr{#Ae=yr;#$t=[];#V;#Lt;constructor(e,t=[]){this.#V=e,this.#Lt=t}get state(){return this.#Ae}async start(){if(this.#Ae===yr)try{this.#Ae=mr,await this.#Bt(),this.#Ae=wr}catch(e){throw this.#Ae=yr,new br(e)}}async stop(){if(this.#Ae===wr)try{this.#Ae=fr,this.clearMiddlewares(),this.#Ae=yr}catch(e){throw this.#Ae=wr,new Mr(e)}}async loadMiddleware(e){const t=await this.#Wt(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new vr;this.#$t.push(e)}getMiddleware(e){return this.#$t.find(t=>t instanceof e)}clearMiddlewares(){this.#$t=[]}handle(e){return this.#Ft(e,0)()}async#Bt(){(await Promise.all(this.#Lt.map(e=>this.#Wt(e)))).forEach(e=>this.addMiddleware(e))}async#Wt(e){return(await this.#V.import(e)).default}#Ft(e,t){const r=this.#$t[t];if(void 0===r)return async()=>new R(de);const s=this.#Ft(e,t+1);return async()=>await r.handle(e,s)}}class Sr{#ne;#qt;#Dt;#Vt=null;constructor(e,t,r=5e3){this.#ne=e,this.#qt=t,this.#Dt=r}start(){this.#Kt()}stop(){null!==this.#Vt&&(clearTimeout(this.#Vt),this.#Vt=null)}#Kt(){this.#Vt=setTimeout(async()=>{null!==this.#Vt&&(await this.#Ut(),this.#Kt())},this.#Dt),this.#Vt.unref()}async#Ut(){try{await this.#qt()}catch(e){this.#ne.warn("Scheduled task failed",e)}}}class kr{#_t=[];#ne;constructor(e){this.#ne=e}create(e,t){const r=new Sr(this.#ne,e,t);return this.#_t.push(r),r}remove(e){const t=this.#_t.indexOf(e);t<0||this.#_t.splice(t,1)}startAll(){this.#_t.forEach(e=>e.start())}stopAll(){this.#_t.forEach(e=>e.stop())}}const Pr="application/null",Ar="application/undefined",zr="application/boolean",Rr="application/number",Er="application/json",Cr="text/plain",Hr=200,Or=400,Tr=401,Nr=402,Ir=403,jr=404,$r=418,Lr=500,Br=501;class Wr extends Error{constructor(e){super("Starting server failed",{cause:e})}}class Fr extends Error{constructor(e){super("Stopping server failed",{cause:e})}}class qr extends ir{#Gt;#Jt;#Xt;#Qt;#ne;#Rt=new F;constructor(e){super(),this.#Gt=e.proxy,this.#Jt=e.remoteWorkerBuilder,this.#Xt=e.resourceManager,this.#Qt=e.middlewareManager,this.#ne=e.logger}get proxy(){return this.#Gt}getTrustKey(){return this.#Gt.trustKey}async start(){try{await this.#Zt(),this.#ne.info(`Server started at ${this.#Gt.url}`),this.#Gt.runner instanceof tr&&this.#ne.info("RPC procedures:",this.#Gt.runner.getProcedureNames())}catch(e){throw new Wr(e)}}async stop(){try{await this.#Yt(),this.#ne.info("Server stopped")}catch(e){throw new Fr(e)}}async getHealth(){try{const e=await this.#Gt.getHealth();return this.#ne.debug("Got health"),this.#er(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ne.error(`Failed to get health (${t})`),this.#tr(e)}}async isHealthy(){try{const e=await this.#Gt.isHealthy();return this.#ne.debug("Got health status"),this.#rr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ne.error(`Failed to get health status (${t})`),this.#tr(e)}}async provide(e){try{const t=await this.#Gt.provide(e.filename);return this.#ne.info(`Provided file:' ${e.filename}`),this.#sr(t)}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.warn(`Failed to provide file: ${e.filename} (${r})`),this.#tr(t)}}async run(e){try{const t=this.#ar(e),r=await this.#Qt.handle(t);return this.#ne.info(`Ran request: ${t.fqn}`),this.#nr(r)}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed run request: ${e.fqn} (${r})`),this.#tr(t)}}async runInternal(e){return this.#Gt.run(e)}async addWorker(e){try{const t=this.#ir(),r=this.#Jt.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#ne.info(`Added worker: ${r.url}`),this.#or({id:s})}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed to add worker: ${e.url} (${r})`),this.#tr(t)}}async reportWorker(e){try{const t=this.#cr(e.state),r=this.#ir();return await r.reportWorker(e.id,t),this.#ne.debug(`Reported worker: ${e.id}`),this.#or()}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed to report worker: ${e.id} (${r})`),this.#tr(t)}}async removeWorker(e){try{const t=this.#ir();return await t.removeWorker(e.id),this.#ne.info(`Removed worker: ${e.id}`),this.#or()}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed to remove worker: ${e.id} (${r})`),this.#tr(t)}}async#Zt(){await this.#Xt.start(),await Promise.all([this.#Gt.start(),this.#Qt.start()]);const e=new nr(this.#Gt);this.#Qt.addMiddleware(e)}async#Yt(){await Promise.all([this.#Qt.stop(),this.#Gt.stop()]),await this.#Xt.stop()}#ar(e){const t=this.#ur(e.fqn),r=this.#lr(e.version),s=this.#hr(e.args),a=this.#dr(e.headers);return new W(t,r,s,a,e.mode)}#ur(e){if(0===e.length)throw new y("Missing procedure name");if(e.includes(".."))throw new y("Invalid procedure name");return e}#lr(e){return"string"!=typeof e?q.DEFAULT:this.#Rt.parse(e)}#hr(e){return new Map(Object.entries(e))}#dr(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}#cr(e){if(!1===Object.values(ot).includes(e))throw new y("Invalid state value");return e}#er(e){return{result:Object.fromEntries(e),contentType:Er,headers:{},status:Hr}}#rr(e){return{result:e,contentType:zr,headers:{},status:Hr}}#sr(e){return{result:e.content,contentType:e.type,headers:{},status:Hr}}#nr(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#pr(t),headers:this.#gr(e.headers),status:e.status}}#tr(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#pr(t),headers:{},status:this.#mr(e)}}#or(e){return{result:e,contentType:this.#pr(e),headers:{},status:Hr}}#pr(e){if(void 0===e)return Ar;if(null===e)return Pr;switch(typeof e){case"boolean":return zr;case"number":return Rr;case"object":return Er;default:return Cr}}#gr(e){return Object.fromEntries(e)}#mr(e){return e instanceof y?Or:e instanceof f?Ir:e instanceof w?jr:e instanceof x?Br:e instanceof S?Nr:e instanceof k?$r:e instanceof P?Tr:Lr}#ir(){const e=this.#Gt.runner;if(e instanceof dt==!1)throw new y("Cannot remove worker from remote gateway");return e}}class Dr extends Error{constructor(){super("Unknown service configured")}}class Vr{#Ge;#wr;#fr;constructor(e,t=[],r=[]){this.#Ge=e,this.#wr=t,this.#fr=r}async start(){return this.#yr()}async stop(){return this.#vr()}#yr(){return this.#br(this.#wr)}#vr(){return this.#br(this.#fr)}async#br(e){await Promise.all(e.map(e=>this.#Ge.import(e)))}}class Kr{#Ge;#zt;constructor(e,t){this.#Ge=e,this.#zt=t}async build(e,t){const r=e.setUp,s=e.tearDown,a=e.middleware,n=e.healthChecks,i=new De(t),o=this.#Mr(n),c=this.#xr(i),u=await this.#Sr(e,o,c),l=this.#Ge,h=this.#kr(r,s),d=this.#Pr(a),p=this.#Ar(e);return new qr({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#Sr(e,t,r){if(void 0!==e.gateway)return this.#zr(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#Rr(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Er(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Cr(e.url,e.proxy);if(void 0!==e.standalone)return this.#Hr(e.url,e.standalone,t,r);throw new Dr}async#zr(e,t,r,s){const a=new ct,n=this.#Or(e,t,r,s);return new vt({url:e,provider:a,runner:n})}async#Rr(e,t,r,s){const a=new ct,n=this.#Tr(e,t,r,s);return new vt({url:e,provider:a,runner:n})}async#Er(e,t,r){const s=await this.#Nr(e,t,r),a=new ut;return new vt({url:e,provider:s,runner:a})}#Or(e,t,r,s){const a=t.trustKey,n=t.monitorInterval,i=new yt(s,n);return new dt({url:e,trustKey:a,healthManager:r,workerManager:i})}#Ir(e){const t=this.#zt.build(e);return new pt({url:e,remote:t})}#Tr(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Ir(t.gateway):void 0,i=t.reportInterval,o=void 0!==n,c=this.#jr(t.segments);return new tr({url:e,trustKey:a,reportInterval:i,gateway:n,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#Nr(e,t,r){const s=void 0!==t.assetRoot?this.#Ge.fork(t.assetRoot):this.#Ge,a=await this.#$r(s,t.assets),n=t.indexFilename,i=t.serveIndexOnNotFound;return new bt({url:e,sourcingManager:s,assets:a,indexFilename:n,serveIndexOnNotFound:i,healthManager:r})}#Lr(e){const t=this.#zt.build(e);return new Mt({url:e,remote:t})}async#Cr(e,t){const r=this.#Lr(t.repository),s=this.#Ir(t.gateway);return new vt({url:e,provider:r,runner:s})}async#Hr(e,t,r,s){const a=await this.#Nr(e,t,r),n=this.#Tr(e,t,r,s);return new vt({url:e,provider:a,runner:n})}#kr(e=[],t=[]){const r=e.map(e=>this.#Br(e)),s=t.map(e=>this.#Br(e));return new Vr(this.#Ge,r,s)}#Mr(e=[]){const t=e.map(e=>this.#Br(e));return new gr(this.#Ge,t)}#Pr(e=[]){const t=e.map(e=>this.#Br(e));return new xr(this.#Ge,t)}#jr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Te(this.#Ge,t)}#xr(e){return new kr(e)}#Ar(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new ar(this.#zt,t,r)}async#$r(e,t){if(void 0===t)return new Set;const r=await e.filter(...t);return new Set(r)}#Br(e){return e.endsWith(".js")?e:e+".js"}}const Ur="3000",_r=204800,Gr=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class Jr{#Wr;#Fr;#qr;#Dr;#be=new $;constructor(e,t=Ur,r=_r){this.#Wr=e,this.#Fr=t,this.#qr=V(),this.#Vr(r),this.#Kr()}async start(){return await this.#Wr.start(),this.#Ur()}async stop(){return await this.#_r(),this.#Wr.stop()}#Vr(e){this.#qr.use(V.json({limit:e})),this.#qr.use(V.urlencoded({extended:!0})),this.#qr.use(this.#Gr.bind(this)),this.#qr.disable(Ye)}#Kr(){this.#qr.get("/health",(e,t)=>{this.#Jr(e,t)}),this.#qr.get("/health/status",(e,t)=>{this.#Xr(e,t)}),this.#qr.get("/rpc/*procedure",(e,t)=>{this.#Qr(e,t)}),this.#qr.post("/rpc/*procedure",(e,t)=>{this.#Zr(e,t)}),this.#qr.options("/rpc/*procedure",(e,t)=>{this.#Yr(e,t)}),this.#qr.post("/workers",(e,t)=>{this.#es(e,t)}),this.#qr.post("/workers/:id/report",(e,t)=>{this.#ts(e,t)}),this.#qr.delete("/workers/:id",(e,t)=>{this.#rs(e,t)}),this.#qr.use((e,t)=>{this.#ss(e,t)})}#Ur(){return void 0!==this.#Dr?Promise.resolve():new Promise((e,t)=>{this.#Dr=this.#qr.listen(this.#Fr,t),e()})}#_r(){return void 0===this.#Dr?Promise.resolve():new Promise(e=>{this.#Dr.close(()=>e())})}#Gr(e,t,r){t.setHeader(Xe,et),r()}async#Jr(e,t){const r=await this.#Wr.getHealth();return this.#as(t,r)}async#Xr(e,t){const r=await this.#Wr.isHealthy();return this.#as(t,r)}async#Qr(e,t){const r=this.#ns(e),s=this.#is(e),a=this.#os(e),n=this.#cs(e),i=le,o=await this.#Wr.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#Zr(e,t){const r=this.#ns(e),s=this.#is(e),a=this.#us(e),n=this.#cs(e),i=le,o=await this.#Wr.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#Yr(e,t){const r=this.#ns(e),s=this.#is(e),a=this.#us(e),n=this.#cs(e),i=he,o=await this.#Wr.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#es(e,t){const r=this.#us(e),s=this.#be.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.url,n=r.procedureNames,i=r.trustKey;try{const e=await this.#Wr.addWorker({url:a,procedureNames:n,trustKey:i});return this.#as(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ts(e,t){const r={id:e.params.id,state:e.body.state},s=this.#be.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id,n=r.state;try{const e=await this.#Wr.reportWorker({id:a,state:n});return this.#as(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#rs(e,t){const r={id:e.params.id},s=this.#be.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id;try{const e=await this.#Wr.removeWorker({id:a});return this.#as(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ss(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),a=await this.#Wr.provide({filename:s});return this.#as(t,a)}#ns(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#is(e){const t=e.headers[Ze];return Array.isArray(t)?t[0]:t}#os(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#us(e){return e.body}#cs(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();Gr.includes(e)||(t[e]=a)}return t}#as(e,t){const r=this.#ls(t),s=this.#hs(t);e.status(r),e.setHeader(Je,s),e.setHeader(Qe,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const a=this.#ds(t);return e.send(a)}#ls(e){return void 0!==e.headers.location?302:e.status}#hs(e){const t=e.contentType.toLowerCase();switch(t){case zr:case Rr:case Ar:case Pr:return Cr}return t}#ds(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class Xr{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{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"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),a=e.getOptionalArgument("--log-level",void 0),n=this.#fe(a),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#ps(i),c=new j;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#gs(u,l,o,n);return this.#ms(h)}async#gs(e,t,r,s){const[,,a]=t.url.split(":"),n=new ie(e.target),i=new it,o=new Kr(n,i),c=await o.build(t,s);return new Jr(c,a,r)}#ms(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#fe(e){if(void 0===e)return;return(new Ke).parse(e)}#ps(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class Qr extends Error{constructor(e){super(`Command ${e} not found`)}}class Zr{#s=new Set;constructor(){this.#s.add(new _(this.#s)),this.#s.add(new G),this.#s.add(new J),this.#s.add(new ee),this.#s.add(new Ge),this.#s.add(new Xr)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new Qr(e)}}class Yr{#ws;#fs;constructor(){this.#ws=new U(process.argv),this.#fs=new Zr}start(){const e=this.#ws.getCommand()??"help";return this.#fs.run(e,this.#ws)}}const es=new De;try{const e=new Yr;await e.start()}catch(t){es.fatal(t),e.exitCode=1}
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{constructor(e="Invalid request"){super(e)}}class t extends Error{constructor(e="Forbidden"){super(e)}}class s extends Error{constructor(e="Not found"){super(e)}}class r extends Error{constructor(e="Not implemented"){super(e)}}class i extends Error{constructor(e="Payment required"){super(e)}}class n extends Error{constructor(e="Server error"){super(e)}}class a extends Error{constructor(e="I'm a teapot"){super(e)}}class o extends Error{constructor(e="Unauthorized"){super(e)}}const c="private",l="protected",u="public",h="normal",d="dry",p=200,m=400,f=401,g=402,w=403,y=404,E=418,S=500,v=501;class b extends e{#e;constructor(e){super(`Invalid version number '${e}'`),this.#e=e}get number(){return this.#e}}class O extends s{#t;constructor(e){super(`Procedure '${e}' not found`),this.#t=e}get fqn(){return this.#t}}class A extends t{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class T{#s;#r=new Map;#i=new Map;constructor(e){this.#s=e}get id(){return this.#s}addClass(e){return this.#r.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#r.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#r.values()]}addProcedure(e){return this.#i.set(e.fqn,e),this}hasProcedure(e){return this.#i.has(e)}getProcedure(e){return this.#i.get(e)}getExposedProcedures(){return[...this.#i.values()].filter(e=>e.public||e.protected)}}class N{#t;#n;constructor(e,t){this.#t=e,this.#n=t}get fqn(){return this.#t}get implementation(){return this.#n}}class I{static get DEFAULT(){return new I(0,0,0)}#a;#o;#c;constructor(e=0,t=0,s=0){this.#a=e,this.#o=t,this.#c=s}get major(){return this.#a}get minor(){return this.#o}get patch(){return this.#c}equals(e){return this.#a===e.major&&this.#o===e.minor&&this.#c===e.patch}greater(e){return this.#a!==e.major?this.#a>e.major:this.#o!==e.minor?this.#o>e.minor:this.#c!==e.patch&&this.#c>e.patch}less(e){return this.#a!==e.major?this.#a<e.major:this.#o!==e.minor?this.#o<e.minor:this.#c!==e.patch&&this.#c<e.patch}toString(){return`${this.#a}.${this.#o}.${this.#c}`}}class x{#t;#l=new Map;#u;constructor(e){this.#t=e}get fqn(){return this.#t}get public(){return[...this.#l.values()].some(e=>e.public)}get protected(){return[...this.#l.values()].some(e=>e.protected)}addImplementation(e){return this.#l.set(e.version,e),this.#h(e)&&(this.#u=e),this}#h(e){return void 0===this.#u||e.version.greater(this.#u.version)}getImplementation(e){const t=this.#d(e);return this.#l.get(t)}#d(e){let t=I.DEFAULT;for(const s of this.#l.keys()){if(s.equals(e))return s;s.greater(e)||t.less(s)&&(t=s)}return t}}class C{#p;#m;#f;#g;constructor(e,t,s,r){this.#p=e,this.#m=t,this.#f=s,this.#g=r}get version(){return this.#p}get public(){return this.#m===u}get protected(){return this.#m===l}get private(){return this.#m===c}get parameters(){return this.#f}get executable(){return this.#g}}class R{#w;#y;constructor(e,t=!1){this.#w=e,this.#y=t}get name(){return this.#w}get isOptional(){return this.#y}}class M extends R{}class z extends R{#E;constructor(e,t,s){super(t??"(anonymous)",s),this.#E=e}get variables(){return this.#E}}class L extends z{}class P extends z{}class k{#t;#p;#S;#v=new Map;#b;constructor(e,t,s,r,i){this.#t=e,this.#p=t,this.#S=s,this.#v=r,this.#b=i}get fqn(){return this.#t}get version(){return this.#p}get args(){return this.#S}get headers(){return this.#v}get mode(){return this.#b}clearArguments(){this.#S.clear()}setArgument(e,t){this.#S.set(e,t)}getArgument(e){return this.#S.get(e)}hasArgument(e){return this.#S.has(e)}removeArgument(e){this.#S.delete(e)}clearHeaders(){this.#v.clear()}setHeader(e,t){this.#v.set(e.toLowerCase(),t)}getHeader(e){return this.#v.get(e.toLowerCase())}hasHeader(e){return this.#v.has(e.toLowerCase())}removeHeader(e){this.#v.delete(e.toLowerCase())}}class ${#O;#A;#v;constructor(e,t=void 0,s=new Map){this.#O=e,this.#A=t,this.#v=s}get status(){return this.#O}get result(){return this.#A}set result(e){this.#A=e}get headers(){return this.#v}clearHeaders(){this.#v.clear()}setHeader(e,t){this.#v.set(e.toLowerCase(),t)}getHeader(e){return this.#v.get(e.toLowerCase())}hasHeader(e){return this.#v.has(e.toLowerCase())}removeHeader(e){this.#v.delete(e.toLowerCase())}}class V extends e{#T;constructor(e){super(`Unknown parameter ${e}`),this.#T=e}get parameterName(){return this.#T}}class D extends e{#T;constructor(e){super(`Missing value for parameter '${e}'`),this.#T=e}get parameterName(){return this.#T}}class j extends e{#T;constructor(e){super(`Invalid value for parameter '${e}'`),this.#T=e}get parameterName(){return this.#T}}class F{extract(e,t){const s=this.#N(e,t),r=[];for(const t of e){const e=this.#I(t,s);r.push(e)}if(s.size>0){const e=s.keys().next().value;throw new V(e)}return r}#N(e,t){const s=new Map;for(const[r,i]of t){if(this.#x(r)){const t=this.#C(r);!0===this.#R(e,t)&&s.set(t,i);continue}s.set(r,i)}return s}#x(e){return e.startsWith("*")}#C(e){return e.substring(1)}#R(e,t){return void 0!==e.find(e=>e.name===t)}#I(e,t,s){return e instanceof M?this.#M(e,t,s):this.#z(e,t)}#M(e,t,s){const r=t.get(e.name);if(this.#L(e,r,s))throw new D(e.name);if(this.#P(e,r,s))throw new j(e.name);return t.delete(e.name),r}#z(e,t){return e instanceof L?this.#k(e,t):this.#$(e,t)}#k(e,t){const s=this.#V(e,t);return void 0!==s?Object.values(s):void 0}#$(e,t){return this.#V(e,t)}#V(e,t){const s=e instanceof L,r={},i=[];let n=!1,a=0;for(const o of e.variables){const c=s?a++:o.name,l=this.#I(o,t,e);void 0!==l?n=!0:!1===o.isOptional&&i.push(o.name),r[c]=l}if(!0===n&&i.length>0)throw new D(i[0]);return n?r:void 0}#L(e,t,s){return void 0===t&&(!0!==e.isOptional&&!0!==s?.isOptional)}#P(e,t,s){return!1!==e.name.startsWith("...")&&(void 0===s&&t instanceof Array==!1||s instanceof L&&t instanceof Array==!1||s instanceof P&&t instanceof Object==!1)}}class B{toStatus(n){return n instanceof e?m:n instanceof t?w:n instanceof s?y:n instanceof r?v:n instanceof i?g:n instanceof a?E:n instanceof o?f:S}fromStatus(c,l){switch(c){case m:return new e(l);case w:return new t(l);case y:return new s(l);case v:return new r(l);case g:return new i(l);case E:return new a(l);case f:return new o(l);default:return new n(l)}}}const H=/^\d+(?:\.\d+){0,2}$/;class U{parse(e){if(0===e.trim().length)return I.DEFAULT;if(!1===H.test(e))throw new b(e);const t=e.split(".");switch(t.length){case 1:return new I(Number.parseInt(t[0]));case 2:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class G extends s{#t;#p;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#t=e,this.#p=t}get fqn(){return this.#t}get version(){return this.#p}}class q extends n{constructor(){super("Invalid segment")}}class W{#D=new Map;addSegment(e){this.#D.set(e.id,e)}clearSegments(){this.#D.clear()}getClassNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#D.values()){const s=t.getClassByImplementation(e);if(void 0!==s)return s}}getProcedureNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class _{#j;#F;#B=new F;#H=new B;#U=new W;constructor(e,t=[]){this.#j=e,this.#F=t}async start(){return this.#G()}async stop(){return this.#q()}async loadSegment(e){const t=await this.#j.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof T==!1)throw new q;this.#U.addSegment(e)}getClassNames(){return this.#U.getClassNames()}hasClass(e){return this.#U.hasClass(e)}getClass(e){return this.#U.getClass(e)}getClassByImplementation(e){return this.#U.getClassByImplementation(e)}getProcedureNames(){return this.#U.getProcedureNames()}hasProcedure(e){return this.#U.hasProcedure(e)}getProcedure(e){return this.#U.getProcedure(e)}async run(e){const t=this.#W(e.fqn,e.version),s=this.#B.extract(t.parameters,e.args);return e.mode===d?new $(p,void 0):this.#_(e,t,s)}async#G(){await Promise.all(this.#F.map(e=>this.loadSegment(e)))}#q(){this.#U.clearSegments()}#W(e,t){const s=this.#U.getProcedure(e);if(void 0===s)throw new O(e);const r=s.getImplementation(t);if(void 0===r)throw new G(s.fqn,t.toString());return r}async#_(e,t,s){try{const r=await t.executable.call(e,...s);return new $(p,r)}catch(e){const t=this.#H.toStatus(e);return new $(t,e)}}}class K extends n{constructor(){super("Request cancelled")}}class Y{#K;#Y;#X=[];#J=!1;#Q=0;constructor(e,t=20){this.#K=e,this.#Y=t}start(){this.#J=!0,this.#Z()}stop(){this.#J=!1,this.#ee()}run(e){return new Promise((t,s)=>{this.#X.push({request:e,resolve:t,reject:s}),this.#Z()})}#Z(){if(this.#te())return;const e=this.#X.length,t=this.#Y-this.#Q,s=Math.min(e,t);this.#se(s)}#te(){return this.#re()||this.#ie()||this.#ne()}#re(){return!1===this.#J}#ie(){return 0===this.#X.length}#ne(){return this.#Q>=this.#Y}#se(e){const t=this.#X.splice(0,e);this.#Q+=e,t.forEach(e=>this.#ae(e))}async#ae(e){try{const t=await this.#K.run(e.request);e.resolve(t)}catch(t){e.reject(t)}finally{this.#Q--,this.#Z()}}#ee(){for(;this.#X.length>0;){const e=this.#X.shift();void 0!==e&&this.#oe(e)}}#oe(e){e.reject(new K)}}const X="starting",J="available",Q="unavailable",Z="stopping",ee="stopped";class te{#ce=ee;get state(){return this.#ce}set state(e){this.#ce=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.#le(ee)}isStopped(){return this.#ue(ee)}isAvailable(){return this.#ue(J)}setStarting(){this.#ce=X}setAvailable(){this.#ce=J}setUnavailable(){this.#ce=Q}setAvailability(e){return this.#ce=e?J:Q,this.#ce}setStopping(){this.#ce=Z}setStopped(){this.#ce=ee}#ue(...e){return e.includes(this.#ce)}#le(...e){return!1===this.#ue(...e)}}class se{#he;#de;#pe=new te;constructor(e){this.#he=e.url,this.#de=e.remote}get url(){return this.#he}get state(){return this.#pe.state}get trustKey(){}async start(){return this.#pe.start(async()=>{await this.#de.connect(),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{await this.#de.disconnect()})}isHealthy(){return this.#de.isHealthy()}getHealth(){return this.#de.getHealth()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}getProcedureNames(){throw new r}hasProcedure(e){throw new r}addWorker(e){return this.#de.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#de.reportWorker(e,t)}removeWorker(e){return this.#de.removeWorker(e)}run(e){return this.#de.run(e)}}class re extends Error{#me;constructor(e){super(`Invalid location: ${e}`),this.#me=e}get location(){return this.#me}}class ie extends Error{#fe;constructor(e){super(`The file '${e}' could not be found`),this.#fe=e}get filename(){return this.#fe}}class ne{#me;#ge;#we;constructor(e,t,s){this.#me=e,this.#ge=t,this.#we=s}get location(){return this.#me}get type(){return this.#ge}get content(){return this.#we}get size(){return this.#we.length}}class ae{#me;#ye;#Ee;constructor(e,t){const s=t.resolve(e);this.#me=t.normalize(e),this.#ye=t.normalize(s),this.#Ee=t}getAbsoluteLocation(e){const t=this.#Ee.isAbsolute(e)?e:this.#Ee.join(this.#me,e),s=this.#Ee.resolve(t),r=this.#Ee.normalize(s);return this.#Se(r,e),r}getRelativeLocation(e){const t=this.#Ee.relative(this.#me,e);return this.#Ee.normalize(t)}normalizeLocation(e){return this.#Ee.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#Ee.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#Ee.exists(t))throw new ie(e);return this.#Ee.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#Ee.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#Ee.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new ne(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#Ee.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#Ee.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#Ee.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#Ee.normalize(e);return(await this.#Ee.filter(t,s)).map(e=>this.#Ee.normalize(e))}#Se(e,t){if(!1===e.startsWith(this.#ye))throw new re(t)}}class oe extends Error{constructor(){super("Remote files are not supported")}}class ce{copy(e,t){throw new oe}delete(e){throw new oe}exists(e){throw new oe}async filter(e,t){return[]}isAbsolute(e){return e.startsWith("/")}isDirectory(e){throw new oe}join(...e){throw new oe}read(e){throw new oe}resolve(e){return e}relative(e,t){throw new oe}normalize(e){return e}mimeType(e){throw new oe}write(e,t){throw new oe}}class le extends ae{constructor(e){super(e,new ce)}}class ue extends Error{#he;#ve;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#he=e,this.#ve=t}get url(){return this.#he}get reason(){return this.#ve}}class he{#be;constructor(e){this.#be=e}async import(e){const t=this.#be.locate(e);try{return await import(t)}catch(e){const s=e instanceof Error?e.message:String(e);throw new ue(t,s)}}}class de{constructor(e){}locate(e){throw new ue(e,"Remote module loading is not allowed")}}class pe extends he{constructor(e){super(new de(e))}}class me{#Oe;#Ae;constructor(e,t){this.#Oe=e,this.#Ae=t}get fileManager(){return this.#Oe}get importManager(){return this.#Ae}async filter(...e){return(await Promise.all(e.map(e=>this.#Oe.filter(e)))).flat().map(e=>this.#Oe.getRelativeLocation(e))}exists(e){return this.#Oe.exists(e)}read(e){return this.#Oe.read(e)}import(e){return this.#Ae.import(e)}}class fe extends me{constructor(e){super(new le(e),new pe(e))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new fe(t)}}class ge extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class we extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class ye extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Ee extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Se{#Te=[];addSerializer(e){e.parent=this,this.#Te.unshift(e)}async serialize(e){const t=this.#Te.find(t=>t.canSerialize(e));if(void 0===t)throw new Ee(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Te.find(t=>t.canDeserialize(e));if(void 0===t)throw new ye(typeof e);return t.deserialize(e)}}class ve extends Error{constructor(){super("Parent serializer not set")}}class be{#Ne;set parent(e){this.#Ne=e}serializeOther(e){if(void 0===this.#Ne)throw new ve;return this.#Ne.serialize(e)}deserializeOther(e){if(void 0===this.#Ne)throw new ve;return this.#Ne.deserialize(e)}}class Oe extends be{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const s of e)t.push(await this.serializeOther(s));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Ae extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Te extends be{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 Ae(e.value)}}}class Ne extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ie extends be{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 Ne(e.base64)}}}class xe{}class Ce extends xe{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Ce(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class Re{}class Me extends Re{identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class ze extends Me{parameters;body;isAsync;constructor(e,t,s,r=!1){super(e),this.parameters=t,this.body=s,this.isAsync=r}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new ze(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier?` ${this.identifier}`:"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function${t}(${s.join(",")})${r}`}}class Le extends ze{constructor(e,t,s=!1){super(void 0,e,t,s)}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new Le(e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.parameters.map(e=>e.toString()),s=this.body.toString();return`${e}(${t.join(", ")})=>${s}`}}class Pe{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new Pe(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class ke extends Re{code;constructor(e){super(),this.code=e}clone(){return new ke(this.code)}toString(){return this.code}}class $e{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class Ve extends $e{parameters;body;constructor(e,t){super("constructor","public","instance"),this.parameters=e,this.body=t}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new Ve(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class De extends $e{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new De(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.body.toString();return`${e}get ${t}${this.identifier}()${s}`}}class je extends $e{parameter;body;constructor(e,t,s,r,i){super(e,t,s),this.parameter=r,this.body=i}clone(){const e=this.parameter.clone(),t=this.body.clone();return new je(this.identifier,this.visibility,this.location,e,t)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.parameter.toString(),r=this.body.toString();return`${e}set ${t}${this.identifier}(${s})${r}`}}class Fe extends $e{parameters;body;isAsync;constructor(e,t,s,r,i,n=!1){super(e,t,s),this.parameters=r,this.body=i,this.isAsync=n}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new Fe(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.isAsync?"async ":"",r=this.parameters.map(e=>e.toString()),i=this.body.toString();return`${e}${s}${t}${this.identifier}(${r.join(",")})${i}`}}class Be extends $e{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new Be(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${e}${t}${this.identifier}${s}`}}class He extends Me{parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof Ve)}get fields(){return this.members.filter(e=>e instanceof Be)}get getters(){return this.members.filter(e=>e instanceof De)}get setters(){return this.members.filter(e=>e instanceof je)}get methods(){return this.members.filter(e=>e instanceof Fe)}get publicFields(){return this.fields.filter(e=>"public"===e.visibility)}get publicGetters(){return this.getters.filter(e=>"public"===e.visibility)}get publicSetters(){return this.setters.filter(e=>"public"===e.visibility)}get publicMethods(){return this.methods.filter(e=>"public"===e.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(e){return this.members.find(t=>t.is(e))}hasMember(e){return this.members.some(t=>t.is(e))}getField(e){return this.fields.find(t=>t.is(e))}hasField(e){return this.fields.some(t=>t.is(e))}getGetter(e){return this.getters.find(t=>t.is(e))}hasGetter(e){return this.getters.some(t=>t.is(e))}getSetter(e){return this.setters.find(t=>t.is(e))}hasSetter(e){return this.setters.some(t=>t.is(e))}getMethod(e){return this.methods.find(t=>t.is(e))}hasMethod(e){return this.methods.some(t=>t.is(e))}canRead(e){return this.readable.some(t=>t.is(e))}canWrite(e){return this.writable.some(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new He(this.identifier,this.parent,e)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(e=>e.toString()).join("")}}`}}class Ue extends Re{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Ue(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class Ge extends Re{code;constructor(e){super(),this.code=e}clone(){return new Ge(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class qe extends ze{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new qe(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier??"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function* ${t}(${s.join(",")})${r}`}}class We extends Fe{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new We(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier,s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}*${t}(${s.join(",")})${r}`}}class _e extends xe{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new _e(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Ke extends Re{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Ke(e,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(e=>e.toString()).join(",")}} from '${this.from}';`}}class Ye extends Me{type;binding;initializer;constructor(e,t,s){super(t.toString()),this.type=e,this.binding=t,this.initializer=s}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new Ye(this.type,e,t)}toString(){const e=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",t=e.endsWith(";")?"":";";return`${this.type} ${this.identifier}${e}${t}`}}class Xe{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof Ue)}get imports(){return this.statements.filter(e=>e instanceof Ke)}get expressions(){return this.statements.filter(e=>e instanceof Ge)}get declarations(){return this.statements.filter(e=>e instanceof Me)}get variables(){return this.statements.filter(e=>e instanceof Ye)}get functions(){return this.statements.filter(e=>e instanceof ze)}get classes(){return this.statements.filter(e=>e instanceof He)}get exported(){const e=[];for(const t of this.exports)for(const s of t.members){const t=this.getDeclaration(s.identifier);void 0!==t&&e.push(t)}return e}get exportedVariables(){return this.exported.filter(e=>e instanceof Ye)}get exportedFunctions(){return this.exported.filter(e=>e instanceof ze)}get exportedClasses(){return this.exported.filter(e=>e instanceof He)}getExport(e){return this.exports.find(t=>t.hasMember(e))}getImport(e){return this.imports.find(t=>t.hasMember(e))}hasDeclaration(e){return this.declarations.some(t=>t.is(e))}getDeclaration(e){return this.declarations.find(t=>t.is(e))}hasVariable(e){return this.variables.some(t=>t.is(e))}getVariable(e){return this.variables.find(t=>t.is(e))}hasFunction(e){return this.functions.some(t=>t.is(e))}getFunction(e){return this.functions.find(t=>t.is(e))}hasClass(e){return this.classes.some(t=>t.is(e))}getClass(e){return this.classes.find(t=>t.is(e))}clone(){const e=this.statements.map(e=>e.clone());return new Xe(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class Je{identifier;alias;constructor(e,t){this.identifier=e,this.alias=t}is(e){return this.alias===e||void 0===this.alias&&this.identifier===e}clone(){return new Je(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class Qe extends xe{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Qe(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const Ze={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},et=Object.values(Ze);const tt=".",st="(",rt=")",it="[",nt="]",at="{",ot="}",ct="_",lt={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},ut=Object.values(lt);function ht(e){return ut.includes(e)}const dt={UNDEFINED:void 0,NULL:null,STRING:""},pt=["null","undefined"],mt=Object.values(dt);function ft(e){return mt.includes(e)}const gt={OPEN:st,CLOSE:rt};function wt(e){return e===gt.OPEN||e===gt.CLOSE}const yt={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally"},Et=Object.values(yt),St=[yt.IMPORT,yt.EXPORT,yt.VAR,yt.LET,yt.CONST,yt.FUNCTION,yt.CLASS,yt.ASYNC],vt=[yt.VAR,yt.LET,yt.CONST,yt.FUNCTION,yt.CLASS,yt.USING],bt=[yt.AS,yt.ASYNC,yt.GET,yt.SET,yt.OF,yt.YIELD,yt.FROM,yt.STATIC];function Ot(e){return St.includes(e)}function At(e){return bt.includes(e)}const Tt={OPEN:it,CLOSE:nt};function Nt(e){return e===Tt.OPEN||e===Tt.CLOSE}const It=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xt(e){return It.includes(e)}const Ct={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},Rt=Object.values(Ct);function Mt(e){return Rt.includes(e)}const zt={OPEN:at,CLOSE:ot};function Lt(e){return e===zt.OPEN||e===zt.CLOSE}const Pt={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},kt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},$t=Object.values(kt);function Vt(e){return $t.includes(e)}class Dt{#Ie;#xe;constructor(e){this.#Ie=e,this.#xe=0}get items(){return this.#Ie}get position(){return this.#xe}get size(){return this.#Ie.length}get eol(){return this.#xe>=this.#Ie.length}get current(){return this.#Ie[this.#xe]}get next(){return this.#Ie[this.#xe+1]}get previous(){return this.#Ie[this.#xe-1]}notAtEnd(){return!1===this.eol}get(e){return this.#Ie[e]}step(e=1){return this.#xe+=e,this.current}stepBack(e=1){return this.#xe-=e,this.current}hasNext(){return this.#xe+1<this.#Ie.length}insert(...e){this.#Ie.splice(this.#xe,0,...e)}}class jt extends Dt{constructor(e){super(e.split(""))}}class Ft{#ge;#Ce;#Re;#Me;constructor(e,t,s,r){this.#ge=e,this.#Ce=t,this.#Re=s,this.#Me=r}get type(){return this.#ge}get value(){return this.#Ce}get start(){return this.#Re}get end(){return this.#Me}isType(e){return this.#ge===e}hasValue(e){return this.#Ce===e}toString(){return`${this.#Ce}`}}class Bt extends Dt{}const Ht=["true","false"];const Ut=["0","1","2","3","4","5","6","7","8","9"],Gt=[...Ut,"a","b","c","d","e","f","A","B","C","D","E","F"],qt=["0","1"];function Wt(e){return Ut.includes(e)}const _t={GENERATOR:"*",PRIVATE:"#"},Kt=Object.values(_t);class Yt{tokenize(e){const t=new jt(e),s=[];let r;for(;t.notAtEnd();){const e=this.#ze(t,r);if(void 0===e)break;e.isType(Pt.WHITESPACE)||e.isType(Pt.COMMENT)?t.step():(s.push(e),this.#Le(e)&&(r=e),t.step())}return new Bt(s)}#Le(e){return!1===[Pt.WHITESPACE,Pt.COMMENT].includes(e.type)}#ze(e,t){const s=e.current,r=e.position;if(Vt(s)){const t=e.position;return new Ft(Pt.WHITESPACE,s,r,t)}if(function(e){return et.includes(e)}(s+e.next)){const t=this.#Pe(e),s=e.position;return new Ft(Pt.COMMENT,t,r,s)}if(this.#ke(s,t)){const t=this.#$e(e),s=e.position;return new Ft(Pt.REGEX,t,r,s)}if(this.#Ve(e,t)){const t=this.#De(e),s=e.position;return new Ft(Pt.NUMBER,t,r,s)}if(xt(s)){const t=this.#je(e),s=e.position;return new Ft(Pt.LITERAL,t,r,s)}if(Mt(s)){const t=this.#Fe(e),s=e.position;return new Ft(Pt.OPERATOR,t,r,s)}if(function(e){return Kt.includes(e)}(s)){const t=this.#Fe(e),s=e.position;return new Ft(Pt.INDICATOR,t,r,s)}if(ht(s)){const t=e.position;return new Ft(Pt.DIVIDER,s,r,t)}if(wt(s)){const t=e.position;return new Ft(Pt.GROUP,s,r,t)}if(Lt(s)){const t=e.position;return new Ft(Pt.SCOPE,s,r,t)}if(Nt(s)){const t=e.position;return new Ft(Pt.LIST,s,r,t)}if(ft(s))return;const i=this.#Be(e),n=e.position;return function(e){return Et.includes(e)}(i)?new Ft(Pt.KEYWORD,i,r,n):function(e){return Ht.includes(e)}(i)?new Ft(Pt.BOOLEAN,i,r,n):function(e){return pt.includes(e)}(i)?new Ft(Pt.NOTHING,i,r,n):new Ft(Pt.IDENTIFIER,i,r,n)}#Pe(e){const t=e.current+e.next===Ze.MULTI_START,s=t?Ze.MULTI_END:kt.NEWLINE;let r=t?Ze.MULTI_START:Ze.SINGLE;for(e.step(2);e.notAtEnd();){const i=e.current;if((t?i+e.next:i)===s){e.step(s.length-1);break}r+=i,e.step()}return t?r+Ze.MULTI_END:r.trim()}#ke(e,t){return e===Ct.DIVIDE&&(void 0===t||([Pt.OPERATOR,Pt.DIVIDER,Pt.KEYWORD].includes(t.type)||[gt.OPEN,Tt.OPEN].includes(t.value)))}#He(e){return Vt(e)||e==tt||!1===this.#Ue(e)}#$e(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Ct.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#He(r)){e.stepBack();break}t+=r,e.step()}return t}#Ve(e,t){const s=e.current,r=e.next;return!!Wt(s)||s===Ct.SUBTRACT&&(!t?.isType(Pt.NUMBER)&&Wt(r))}#Ge(e,t,s){return t?!1===(r=e,Gt.includes(r))&&e!==ct:s?!1===function(e){return qt.includes(e)}(e)&&e!==ct:!1===Wt(e)&&e!==tt&&e!==ct&&"e"!==e;var r}#De(e){let t=e.current;t===Ct.SUBTRACT&&(t+=e.step()),e.step();const s="x"===e.current,r="b"===e.current;for((s||r)&&(t+=e.current,e.step());e.notAtEnd();){const i=e.current;if(this.#Ge(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#je(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const i=e.current;if(!1===r){if(i===t){s+=i;break}"\\"===i&&(r=!0)}else r=!1;s+=i,e.step()}return s}#Ue(e){return!1===(ft(e)||Vt(e)||Mt(e)||xt(e)||ht(e)||wt(e)||Lt(e)||Nt(e))}#Be(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#Ue(s)){e.stepBack();break}t+=s,e.step()}return t}#Fe(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===Mt(s)||!1===Mt(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Xt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Jt extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Qt extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class Zt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class es extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const ts=new Ft(Pt.NONE,"",-1,0);class ss{#qe;constructor(e=[]){this.#qe=e}get tokens(){return this.#qe}append(...e){this.#qe.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="";for(let t=0;t<this.#qe.length;t++){const s=this.#qe[t-1]??ts,r=this.#qe[t],i=this.#qe[t+1]??ts,n=this.#We(s,r)?" ":"",a=this.#_e(r,i)?" ":"";e+=`${n}${r.value}${a}`}return e}#We(e,t){return!(!t.isType(Pt.KEYWORD)||!this.#Ke(e))||!(!t.isType(Pt.OPERATOR)||!e.isType(Pt.OPERATOR))}#_e(e,t){return e.isType(Pt.KEYWORD)&&(t.isType(Pt.KEYWORD)||this.#Ke(t))}#Ke(e){return e.isType(Pt.IDENTIFIER)||e.isType(Pt.BOOLEAN)||e.isType(Pt.NOTHING)||e.isType(Pt.NUMBER)}}const rs="default";class is{#Ye;constructor(e=new Yt){this.#Ye=e}parse(e){const t=this.#Ye.tokenize(e),s=this.#Xe(t);return new Xe(s)}parseStatement(e){const t=this.#Ye.tokenize(e),s=this.#Je(t);if(void 0===s)throw new Zt("a statement");return s}parseImport(e){const t=this.#Ye.tokenize(e),s=this.#Qe(t);if(s instanceof Ke==!1)throw new Zt("an import definition");return s}parseExport(e){const t=this.#Ye.tokenize(e),s=this.#Qe(t);if(s instanceof Ue==!1)throw new Zt("an export definition");return s}parseVariable(e){const t=this.#Ye.tokenize(e),s=this.#Qe(t);if(s instanceof Ye==!1)throw new Zt("a variable definition");return s}parseFunction(e){const t=this.#Ye.tokenize(e),s=this.#Qe(t);if(s instanceof ze==!1)throw new Zt("a function definition");return s}parseClass(e){const t=this.#Ye.tokenize(e),s=this.#Qe(t);if(s instanceof He==!1)throw new Zt("a class definition");return s}#Xe(e){const t=[];for(;e.notAtEnd();){const s=this.#Je(e);void 0!==s&&t.push(s)}return t}#Je(e,t=!1){const s=e.current;if(this.#Ze(s))return this.#et(e);if(s.isType(Pt.IDENTIFIER)){const s=e.next;return s?.hasValue(Ct.ARROW)?this.#tt(e,t):this.#et(e)}if(s.isType(Pt.KEYWORD)){if(At(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(yt.FUNCTION)||t.hasValue(gt.OPEN));if(s.hasValue(yt.ASYNC)&&r)return e.step(),this.#Je(e,!0);if(void 0===t||this.#st(t))return this.#et(e)}return s.hasValue(yt.RETURN)?this.#et(e):!1===Ot(s.value)?this.#et(e):this.#Qe(e,t)}if(s.isType(Pt.REGEX))return this.#et(e);if(s.hasValue(gt.OPEN)){const s=this.#rt(e,gt.OPEN,gt.CLOSE);return s?.hasValue(Ct.ARROW)?this.#tt(e,t):this.#et(e)}if(s.hasValue(zt.OPEN))return this.#et(e);if(s.hasValue(Tt.OPEN))return this.#et(e);if(s.hasValue(Ct.NOT)||s.hasValue(Ct.SUBTRACT))return this.#et(e);if(!ht(s.value))throw new es(s.value,s.start);e.step()}#Ze(e){return e.isType(Pt.LITERAL)||e.isType(Pt.NUMBER)||e.isType(Pt.BOOLEAN)||e.isType(Pt.NOTHING)||e.hasValue(yt.NEW)}#Qe(e,t=!1){const s=e.current;switch(e.step(),s.value){case yt.IMPORT:return this.#it(e);case yt.EXPORT:return this.#nt(e);case yt.CLASS:return this.#at(e);case yt.FUNCTION:return this.#ot(e,t);case yt.VAR:return this.#ct(e,"var");case yt.LET:return this.#ct(e,"let");case yt.CONST:return this.#ct(e,"const");case yt.ASYNC:return this.#Je(e,!0);default:throw new Qt(s.value,s.start)}}#it(e){const t=[];let s=e.current;if(s.isType(Pt.LITERAL)){const e=this.#lt(s.value);return new Ke(t,e)}if(s.hasValue(gt.OPEN)){s=e.step();const r=this.#lt(s.value);return e.step(2),new Ke(t,r)}if(!1===s.hasValue(zt.OPEN)){const r=s.hasValue(Ct.MULTIPLY)?Ct.MULTIPLY:rs;let i=s.value;s=e.step(),s.hasValue(yt.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new Je(r,i))}if(s.hasValue(lt.SEPARATOR)&&(s=e.step()),s.hasValue(zt.OPEN)){const r=this.#ut(e);t.push(...r),s=e.current}if(!1===s.hasValue(yt.FROM))throw new Xt(yt.FROM,s.start);s=e.step();const r=this.#lt(s.value);return e.step(),new Ke(t,r)}#nt(e){switch(e.current.value){case yt.DEFAULT:return e.step(),this.#ht(e,!0);case zt.OPEN:return this.#dt(e);default:return this.#ht(e,!1)}}#ht(e,t){let s=e.current,r=0;if(t&&this.#pt(e)){const t=`$_EXPORT_${s.start}_${s.end}`;e.insert(new Ft(Pt.KEYWORD,yt.CONST,0,0),new Ft(Pt.IDENTIFIER,t,0,0),new Ft(Pt.OPERATOR,Ct.ASSIGN,0,0)),s=e.current}var i;s.hasValue(yt.ASYNC)&&(s=e.step(),r++),i=s.value,vt.includes(i)&&(s=e.step(),r++);const n=this.#Ue(s)?s.value:"",a=t?rs:void 0;let o;s=e.step(),s?.hasValue(yt.FROM)&&(s=e.step(),o=this.#lt(s.value)),r>0&&(r++,e.stepBack(r));const c=new Je(n,a);return new Ue([c],o)}#pt(e){const t=e.current;if(this.#Ze(t))return!0;const s=e.next;return this.#Ue(t)&&s?.hasValue(gt.OPEN)}#dt(e){const t=this.#ut(e);let s,r=e.current;return r?.hasValue(yt.FROM)&&(r=e.step(),s=this.#lt(r.value)),e.step(),new Ue(t,s)}#lt(e){return e.slice(1,-1)}#ut(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(zt.CLOSE)){e.step();break}if(s.hasValue(lt.SEPARATOR)){s=e.step();continue}const r=this.#mt(e);t.push(r),s=e.step()}return t}#mt(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(yt.AS)&&(t=e.step(2),r=t.value),new Je(s,r)}#ct(e,t){const s=this.#ft(e),r=this.#gt(e);return new Ye(t,s,r)}#ft(e){const t=e.current;return t.hasValue(Tt.OPEN)?this.#wt(e):t.hasValue(zt.OPEN)?this.#yt(e):this.#Et(e)}#wt(e){const t=this.#St(e,Tt.CLOSE);return new Ce(t)}#yt(e){const t=this.#St(e,zt.CLOSE);return new Qe(t)}#St(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(lt.SEPARATOR)){e.step();continue}const i=this.#ft(e),n=this.#gt(e),a=new Pe(i,n);s.push(a)}return s}#Et(e){let t=e.current,s=!1;t.hasValue(Ct.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new _e(r,s)}#gt(e){const t=e.current;if(!1!==t.hasValue(Ct.ASSIGN))return e.step(),this.#Je(e,!1);t.hasValue(lt.TERMINATOR)&&e.step()}#ot(e,t){let s,r=e.current,i=!1;r.hasValue(_t.GENERATOR)&&(i=!0,r=e.step()),this.#Ue(r)&&(s=r.value,e.step());const n=this.#St(e,gt.CLOSE);if(r=e.current,!1===r.hasValue(zt.OPEN))throw new Jt(zt.OPEN,r.start);const a=this.#vt(e);return i?new qe(s,n,a,t):new ze(s,n,a,t)}#tt(e,t){let s,r,i=e.current;if(i.hasValue(gt.OPEN))s=this.#St(e,gt.CLOSE);else{const t=this.#Et(e);s=[new Pe(t,void 0)]}if(i=e.current,!1===i.hasValue(Ct.ARROW))throw new Jt(Ct.ARROW,i.start);if(i=e.step(),i.hasValue(zt.OPEN))r=this.#vt(e);else{const t=this.#et(e);r=new ke(t.code)}return new Le(s,r,t)}#at(e){let t,s,r=e.current;if(this.#Ue(r)&&(t=r.value,r=e.step()),r.hasValue(yt.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(zt.OPEN))throw new Jt(zt.OPEN,r.start);const i=this.#bt(e);return new He(t,s,i)}#bt(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(zt.CLOSE)){e.step();break}const r=this.#Ot(e);s.push(r),t=e.current}return s}#Ot(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(_t.PRIVATE))s="private";else if(t.hasValue(yt.STATIC))r="static";else{if(!t.hasValue(yt.ASYNC)){if(t.hasValue(yt.CONSTRUCTOR))return this.#At(e);if(t.hasValue(yt.GET))return this.#Tt(e,r);if(t.hasValue(yt.SET))return this.#Nt(e,r);if(t.hasValue(_t.GENERATOR))return e.step(),this.#It(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(gt.OPEN)?this.#It(e,s,r,i,!1):this.#xt(e,s,r)}#At(e){e.step();const t=this.#St(e,gt.CLOSE),s=e.current;if(!1===s.hasValue(zt.OPEN))throw new Jt(zt.OPEN,s.start);const r=this.#vt(e);return new Ve(t,r)}#Tt(e,t){let s="public",r=e.step();r.hasValue(_t.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#St(e,gt.CLOSE).length)throw new Zt("an empty parameter list");if(r=e.current,!1===r.hasValue(zt.OPEN))throw new Jt(zt.OPEN,r.start);const n=this.#vt(e);return new De(i,s,t,n)}#Nt(e,t){let s="public",r=e.step();r.hasValue(_t.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#St(e,gt.CLOSE);if(r=e.current,1!==n.length)throw new Zt("exactly one setter parameter");if(!1===r.hasValue(zt.OPEN))throw new Jt(zt.OPEN,r.start);const a=this.#vt(e);return new je(i,s,t,n[0],a)}#It(e,t,s,r,i){let n=e.current;const a=n.value;e.step();const o=this.#St(e,gt.CLOSE);if(n=e.current,!1===n.hasValue(zt.OPEN))throw new Jt(zt.OPEN,n.start);const c=this.#vt(e);return i?new We(a,t,s,o,c,r):new Fe(a,t,s,o,c,r)}#xt(e,t,s){const r=e.current.value;e.step();const i=this.#gt(e);return new Be(r,t,s,i)}#vt(e){const t=this.#Ct(e,zt.OPEN,zt.CLOSE).generate();return new ke(t)}#et(e){const t=new ss;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Tt.OPEN)){const r=this.#Ct(e,Tt.OPEN,Tt.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(gt.OPEN)){const r=this.#Ct(e,gt.OPEN,gt.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(zt.OPEN)){const r=this.#Ct(e,zt.OPEN,zt.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#st(s)){s.hasValue(lt.TERMINATOR)&&e.step();break}}const r=t.generate();return new Ge(r)}#Ct(e,t,s){let r=e.current;const i=new ss([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#Ct(e,t,s);i.merge(n),r=e.current;continue}if(r.hasValue(s))return e.step(),i.append(r),i;i.append(r),r=e.step()}return i}#rt(e,t,s){const r=e.position;this.#Ct(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#st(e){return[lt.TERMINATOR,lt.SEPARATOR].includes(e.value)||[Tt.CLOSE,gt.CLOSE,zt.CLOSE].includes(e.value)||Ot(e.value)}#Ue(e){return e.isType(Pt.IDENTIFIER)||e.isType(Pt.KEYWORD)&&At(e.value)}}class ns{merge(e,t){const s=void 0!==e.construct?[e.construct]:[],r=[...this.#Rt(e.fields,t.fields),...s,...this.#Rt(e.methods,t.methods),...this.#Rt(e.getters,t.getters),...this.#Rt(e.setters,t.setters)];return new He(e.identifier,t.identifier,r)}#Rt(e,t){const s=new Map;return t.forEach(e=>s.set(e.identifier,e)),e.forEach(e=>s.set(e.identifier,e)),[...s.values()]}}class as{#Mt=new is;#zt=new ns;fromModule(e,t=!1){const s=Object.entries(e),r=[];for(const[e,i]of s){if("function"!=typeof i.toString)continue;const s=i.toString();if(s.startsWith("class"))r.push(this.fromClass(i,t));else if(s.startsWith("function"))r.push(this.fromFunction(i));else{const t=new _e(e,!1),i=new Ge(s);r.push(new Ye("var",t,i))}}return new Xe(r)}fromClass(e,t=!1){const s=this.isClass(e)?this.#Lt(e):this.#Pt(e);if(!1===t)return s;const r=this.getParentClass(e);if(""===r.name)return s;const i=this.fromClass(r,!0);return this.#zt.merge(s,i)}fromObject(e,t=!0){const s=this.getClass(e);return this.fromClass(s,t)}fromFunction(e){const t=e.toString();return this.#Mt.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")}#Lt(e){const t=e.toString();return this.#Mt.parseClass(t)}#Pt(e){const t=this.createInstance(e),s=this.#kt(e,t);return new He(e.name,void 0,s)}#kt(e,t){return[...this.#$t(t),...this.#Vt(e)]}#$t(e){const t=Object.getOwnPropertyNames(e),s=e,r=[];for(const e of t){const t=s[e],i=void 0!==t?new Ge(String(t)):void 0,n=new Be(e,"public","instance",i);r.push(n)}return r}#Vt(e){const t=Object.getOwnPropertyDescriptors(e.prototype),s=[];for(const e in t){const r=t[e],i=r.value;if(i instanceof Function==!1)continue;const n=this.fromFunction(i);"constructor"===n.identifier?s.push(new Ve(n.parameters,n.body)):void 0!==r.get?s.push(new De(n.identifier,"public","instance",n.body)):void 0!==r.set?s.push(new je(n.identifier,"public","instance",n.parameters[0],n.body)):s.push(new Fe(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return s}}const os=new as;class cs extends be{#Dt;constructor(e){super(),this.#Dt=e}canSerialize(e){return e instanceof Object&&os.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=os.getClass(e),s=os.fromClass(t,!0),r=this.#jt(s),i=this.#Dt.resolveKey(t);if(void 0===i)throw new ge(t.name);return{serialized:!0,key:i,name:"class",args:await this.#Ft(s,r,e),fields:await this.#Bt(s,r,e)}}#jt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#Ft(e,t,s){const r={};for(const[i,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(s[n]):void 0;r[i.toString()]=t}return r}async#Bt(e,t,s){const r={};for(const i of e.writable){const n=i.identifier;t.includes(n)||!1===e.canRead(n)||(r[n]=await this.serializeOther(s[n]))}return r}async deserialize(e){const t=await this.#Ht(e);if(void 0===t)throw new ge(e.key);if(t instanceof Function==!1)throw new we(e.key);const s=await this.#Ut(t,e.args),r=os.createInstance(t,s);for(const t in e.fields){const s=e.fields[t];r[t]=await this.deserializeOther(s)}return r}async#Ut(e,t){const s=os.fromClass(e,!0).construct,r=(s?.parameters??[]).map((e,s)=>{const r=s.toString(),i=t[r];return this.deserializeOther(i)});return Promise.all(r)}async#Ht(e){return globalThis[e.key]??this.#Dt.resolveClass(e.key)}}class ls extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class us extends be{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 ls(e.value);return t}}class hs extends be{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 ds extends be{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=[],s=[];for(const[r,i]of e)t.push(await this.serializeOther(r)),s.push(await this.serializeOther(i));return{serialized:!0,name:"Map",entries:{keys:t,values:s}}}async deserialize(e){const t=e.entries.keys,s=e.entries.values,r=new Map;for(let e=0;e<t.length;e++){const i=await this.deserializeOther(t[e]),n=await this.deserializeOther(s[e]);r.set(i,n)}return r}}class ps extends be{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 s in e){const r=e[s];t[s]=await this.serializeOther(r)}return t}async deserialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.deserializeOther(r)}return t}}class ms extends be{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 fs extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class gs extends be{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 fs(e.source,e.flags)}}}class ws extends be{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 s of e.values())t.push(await this.serializeOther(s));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 ys=new as;class Es extends be{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,s=new DataView(e.buffer),r=[];for(let e=0;e<s.byteLength;e++)r.push(s.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:r}}async deserialize(e){const t=e.type,s=e.bytes,r=new ArrayBuffer(s.length),i=new DataView(r);for(let e=0;e<s.length;e++)i.setUint8(e,s[e]);const n=globalThis[t];return ys.createInstance(n,[r])}}class Ss extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class vs extends be{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 Ss(e.value)}}}class bs{static build(e){const t=new Se;return t.addSerializer(new ms),t.addSerializer(new ps),void 0!==e&&t.addSerializer(new cs(e)),t.addSerializer(new hs),t.addSerializer(new gs),t.addSerializer(new Te),t.addSerializer(new vs),t.addSerializer(new us),t.addSerializer(new ws),t.addSerializer(new ds),t.addSerializer(new Oe),t.addSerializer(new Es),"undefined"!=typeof Buffer&&t.addSerializer(new Ie),t}}class Os{#Gt;constructor(e){this.#Gt=e}resolveKey(e){const t=this.#Gt.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Gt.getClass(e);return t?.implementation}}class As extends o{constructor(){super("Request not trusted")}}const Ts="X-Jitar-Trust-Key",Ns="X-Jitar-Data-Encoding",Is="serialized";class xs{#s;#he;#qt;#Wt;#_t;#Gt;#Kt;#Yt;#Xt;#pe=new te;constructor(e){this.#he=e.url,this.#qt=e.trustKey,this.#Wt=e.gateway,this.#_t=!0===e.registerAtGateway,this.#Gt=e.executionManager,this.#Kt=e.healthManager;const t=e.scheduleManager;this.#Yt=t.create(()=>this.#Jt(),e.reportInterval);const s=new Os(this.#Gt);this.#Xt=bs.build(s)}get id(){return this.#s}set id(e){this.#s=e}get state(){return this.#pe.state}get url(){return this.#he}get trustKey(){return this.#qt}async start(){return this.#pe.start(async()=>{await Promise.all([this.#Gt.start(),this.#Kt.start()]),void 0!==this.#Wt&&(await this.#Wt.start(),this.#_t&&(this.#s=await this.#Wt.addWorker(this),this.#Yt.start())),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{void 0!==this.#Wt&&(void 0!==this.#s&&(this.#Yt.stop(),await this.#Wt.removeWorker(this.#s)),await this.#Wt.stop()),await Promise.all([this.#Kt.stop(),this.#Gt.stop()])})}getProcedureNames(){return this.#Gt.getProcedureNames()}hasProcedure(e){return this.#Gt.hasProcedure(e)}isHealthy(){return this.#Kt.isHealthy()}getHealth(){return this.#Kt.getHealth()}isAvailable(){return this.#pe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}async reportState(e){if(void 0!==this.#Wt&&void 0!==this.#s)return this.#Wt.reportWorker(this.#s,e)}async run(e){return this.#Qt(e)?this.#Zt(e):this.#es(e)}#Qt(e){return void 0===this.#Wt||this.#Gt.hasProcedure(e.fqn)}async#Zt(e){const t=this.#Gt.getProcedure(e.fqn),s=t?.getImplementation(e.version);if(this.#ts(s))throw new O(e.fqn);if(this.#ss(e,s))throw new As;const r=e.getHeader(Ns);r===Is&&(e=await this.#rs(e)),e.removeHeader(Ns);const i=await this.#Gt.run(e);return r===Is?this.#is(i):i}#ts(e){return void 0===e||e.private}#ss(e,t){if(t.public)return!1;const s=e.getHeader(Ts);return this.#qt!==s}async#es(e){(e=await this.#ns(e)).setHeader(Ns,Is),void 0!==this.#qt&&e.setHeader(Ts,this.#qt);const t=await this.#Wt.run(e);return this.#as(t)}async#ns(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#Xt.serialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#rs(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#Xt.deserialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#is(e){const t=await this.#Xt.serialize(e.result);return new $(e.status,t,e.headers)}async#as(e){const t=await this.#Xt.deserialize(e.result);return new $(e.status,t,e.headers)}async#Jt(){const e=await this.updateState();return this.reportState(e)}}class Cs{#K;constructor(e){this.#K=e}async handle(e,t){return this.#K.run(e)}}class Rs{#os=new U;constructor(){this.#cs()}#cs(){const e=globalThis;e.__run=this.#ls.bind(this),e.ProcedureNotAccessible=A}async#ls(e,t,s,r){const i=this.#os.parse(t),n=new Map(Object.entries(s)),a=r instanceof k?r.headers:new Map,o=new k(e,i,n,a,h),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const l=await this.runInternal(o);if(l.status!==p)throw l.result;return l.result}}class Ms extends Rs{#us;#hs;#ds=new Y(this);constructor(e){super(),this.#us=new xs({url:e.remoteUrl,gateway:new se({url:e.remoteUrl,remote:e.remote}),healthManager:e.healthManager,executionManager:e.executionManager,scheduleManager:e.scheduleManager}),this.#hs=e.middlewareManager}get worker(){return this.#us}async start(){await this.#ps(),this.#ds.start()}async stop(){this.#ds.stop(),await this.#ms()}getTrustKey(){}run(e){return this.#hs.handle(e)}async runInternal(e){return this.#ds.run(e)}async#ps(){await Promise.all([this.#us.start(),this.#hs.start()]);const e=new Cs(this.#us);this.#hs.addMiddleware(e)}async#ms(){await Promise.all([this.#hs.stop(),this.#us.stop()])}}const zs="starting",Ls="started",Ps="stopping",ks="stopped";class $s extends n{constructor(){super("Invalid health check")}}class Vs{#ce=ks;#fs=new Map;#j;#gs;constructor(e,t=[]){this.#j=e,this.#gs=t}get state(){return this.#ce}async start(){if(this.#ce===ks)try{this.#ce=zs,await this.#ws(),this.#ce=Ls}catch(e){throw this.#ce=ks,e}}async stop(){if(this.#ce===Ls)try{this.#ce=Ps,this.clearHealthChecks(),this.#ce=ks}catch(e){throw this.#ce=Ls,e}}async loadHealthCheck(e){const t=await this.#ys(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new $s;this.#fs.set(e.name,e)}clearHealthChecks(){this.#fs.clear()}async isHealthy(){const e=[];for(const t of this.#fs.values()){const s=this.#Es(t);e.push(s)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,s]of this.#fs){const r=this.#Es(s).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(r)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#Ss(e,t))).then(()=>t)}async#ws(){(await Promise.all(this.#gs.map(e=>this.#ys(e)))).forEach(e=>this.addHealthCheck(e))}async#ys(e){return(await this.#j.import(e)).default}#Ss(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#Es(e){const t=e.isHealthy(),s=e.timeout;if(void 0===s)return t;const r=new Promise(e=>{setTimeout(e,s)}).then(()=>!1);return Promise.race([r,t])}}const Ds=0,js=1,Fs=2,Bs=3;class Hs{#vs;#bs;constructor(e=js,t=console){this.#vs=e,this.#bs=t}debug(...e){if(this.#vs>Ds)return;const t=this.#Os("DEBUG",e);this.#bs.debug(t)}info(...e){if(this.#vs>js)return;const t=this.#Os("INFO",e);this.#bs.info(t)}warn(...e){if(this.#vs>Fs)return;const t=this.#Os("WARN",e);this.#bs.warn(t)}error(...e){if(this.#vs>Bs)return;const t=this.#Os("ERROR",e);this.#bs.error(t)}fatal(...e){const t=this.#Os("FATAL",e);this.#bs.error(t)}#Os(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#As(e)).join(" ")}`}#As(e,t=0){let s;switch(typeof e){case"string":s=e;break;case"object":s=this.#Ts(e,t+1);break;case"undefined":s="undefined";break;case"function":s="function";break;default:s=String(e)}return`${this.#Ns(t)}${s}`}#Ts(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#As(e,t)).join(",\n")}\n${this.#Ns(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#Ns(e){return" ".repeat(e)}}const Us="starting",Gs="started",qs="stopping",Ws="stopped";class _s extends n{constructor(){super("Invalid middleware")}}class Ks{#ce=Ws;#Is=[];#j;#xs;constructor(e,t=[]){this.#j=e,this.#xs=t}get state(){return this.#ce}async start(){if(this.#ce===Ws)try{this.#ce=Us,await this.#Cs(),this.#ce=Gs}catch(e){throw this.#ce=Ws,e}}async stop(){if(this.#ce===Gs)try{this.#ce=qs,this.clearMiddlewares(),this.#ce=Ws}catch(e){throw this.#ce=Gs,e}}async loadMiddleware(e){const t=await this.#Rs(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new _s;this.#Is.push(e)}getMiddleware(e){return this.#Is.find(t=>t instanceof e)}clearMiddlewares(){this.#Is=[]}handle(e){return this.#Ms(e,0)()}async#Cs(){(await Promise.all(this.#xs.map(e=>this.#Rs(e)))).forEach(e=>this.addMiddleware(e))}async#Rs(e){return(await this.#j.import(e)).default}#Ms(e,t){const s=this.#Is[t];if(void 0===s)return async()=>new $(p);const r=this.#Ms(e,t+1);return async()=>await s.handle(e,r)}}class Ys{#zs;#Ls;#Ps;#ks=null;constructor(e,t,s=5e3){this.#zs=e,this.#Ls=t,this.#Ps=s}start(){this.#$s()}stop(){null!==this.#ks&&(clearTimeout(this.#ks),this.#ks=null)}#$s(){this.#ks=setTimeout(async()=>{null!==this.#ks&&(await this.#Vs(),this.#$s())},this.#Ps),this.#ks.unref()}async#Vs(){try{await this.#Ls()}catch(e){this.#zs.warn("Scheduled task failed",e)}}}class Xs{#Ds=[];#zs;constructor(e){this.#zs=e}create(e,t){const s=new Ys(this.#zs,e,t);return this.#Ds.push(s),s}remove(e){const t=this.#Ds.indexOf(e);t<0||this.#Ds.splice(t,1)}startAll(){this.#Ds.forEach(e=>e.start())}stopAll(){this.#Ds.forEach(e=>e.stop())}}class Js{#js;constructor(e){this.#js=e}build(e){const t=e.remoteUrl,s=e.middleware,r=e.segments,i=new Hs(e.logLevel??Fs),n=this.#js.build(t),a=new fe(t),o=this.#Fs(a),c=this.#Bs(a,s),l=this.#Hs(a,r),u=this.#Us(i);return new Ms({remoteUrl:t,remote:n,healthManager:o,middlewareManager:c,executionManager:l,scheduleManager:u})}#Fs(e){return new Vs(e)}#Bs(e,t=[]){const s=new Ks(e);return t.forEach(e=>s.addMiddleware(e)),s}#Hs(e,t=[]){const s=new _(e);return t.forEach(e=>s.addSegment(e)),s}#Us(e){return new Xs(e)}}class Qs{#Gs;constructor(e=!0){this.#Gs=e}validate(e,t){const s=[];this.#qs("",e,t,s);return{valid:0===s.length,errors:s}}#qs(e,t,s,r){this.#Gs&&this.#Ws(e,t,s,r),this.#_s(e,t,s,r)}#Ws(e,t,s,r){const i=Object.keys(t),n=Object.keys(s);for(const t of i)if(!1===n.includes(t)){const s=this.#Ks(e,t);r.push(`Unknown field '${s}'`)}}#_s(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#Ks(e,n),a=s[n],o=t[n];this.#Ys(i,o,a,r)}}#Ys(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#Xs(e,t,s,r);case"integer":return this.#Js(e,t,s,r);case"real":return this.#Qs(e,t,s,r);case"boolean":return this.#Zs(e,t,s,r);case"url":return this.#er(e,t,s,r);case"group":return this.#tr(e,t,s,r);case"list":return this.#sr(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#Xs(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#Js(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Qs(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Zs(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#er(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#tr(e,t,s,r){"object"==typeof t?this.#qs(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#sr(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const i=t;for(const t in i){const n=this.#Ks(e,t),a=i[t];this.#Ys(n,a,s.items,r)}}#Ks(e,t){return""===e?t:`${e}.${t}`}}const Zs="content-type",er="x-jitar-content-type",tr="x-jitar-procedure-version",sr="application/json",rr="application/octet-stream";class ir extends Error{constructor(){super("Invalid worker id")}}class nr{#he;#rr;#H=new B;#ir=new Qs;constructor(e,t){this.#he=e,this.#rr=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#he}/${e}`,s=await this.#nr(t,{method:"GET"}),r=s.headers.get(Zs)??rr,i=await s.arrayBuffer(),n=Buffer.from(i);return new ne(e,r,n)}async isHealthy(){const e=`${this.#he}/health/status`,t=await this.#nr(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#he}/health`,t=await this.#nr(e,{method:"GET"}),s=await t.json();return new Map(Object.entries(s))}async addWorker(e,t,s){const r=`${this.#he}/workers`,i={url:e,procedureNames:t,trustKey:s},n={method:"POST",headers:{"Content-Type":sr},body:JSON.stringify(i)},a=await this.#nr(r,n),o=a.headers.get(Zs);if(null===o||!1===o.includes(sr))throw new ir;const c=await a.json();if(!1===this.#ir.validate(c,{id:{type:"string",required:!0}}).valid)throw new ir;return c.id}async reportWorker(e,t){const s=`${this.#he}/workers/${e}/report`,r={state:t},i={method:"POST",headers:{"Content-Type":sr},body:JSON.stringify(r)};await this.#nr(s,i)}async removeWorker(e){const t=`${this.#he}/workers/${e}`,s={method:"DELETE",headers:{"Content-Type":sr}};await this.#nr(t,s)}async run(e){e.setHeader(Zs,sr);const t=Object.fromEntries(e.args),s=Object.fromEntries(e.headers),r=e.version.toString();s[tr]=r;const i=`${this.#he}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:s,body:await this.#ar(t)},a=await this.#nr(i,n,!1),o=a.status,c=await this.#or(a),l=this.#cr(a);return new $(o,c,l)}async#nr(e,t,s=!0){const r=await this.#rr.execute(e,t);if(s&&this.#lr(r)){const e=await this.#or(r);throw this.#H.fromStatus(r.status,String(e))}return r}#lr(e){return e.status<200||e.status>399}async#ar(e){return JSON.stringify(e)}async#or(e){const t=e.headers.get(er)??e.headers.get(Zs);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const s=await e.text();return t?.includes("boolean")?"true"===s:t?.includes("number")?Number(s):s}#cr(e){const t=new Map;for(const[s,r]of e.headers)t.set(s,r);return t}}class ar{async execute(e,t){return fetch(e,t)}}class or{#rr;constructor(e=new ar){this.#rr=e}build(e){return new nr(e,this.#rr)}}export{L as ArrayParameter,e as BadRequest,N as Class,Js as ClientBuilder,t as Forbidden,or as HttpRemoteBuilder,C as Implementation,M as NamedParameter,s as NotFound,r as NotImplemented,P as ObjectParameter,i as PaymentRequired,x as Procedure,k as Request,$ as Response,T as Segment,n as ServerError,a as Teapot,o as Unauthorized,I as Version};
|
|
1
|
+
class e extends Error{constructor(e="Invalid request"){super(e)}}class t extends Error{constructor(e="Forbidden"){super(e)}}class s extends Error{constructor(e="Not found"){super(e)}}class r extends Error{constructor(e="Not implemented"){super(e)}}class i extends Error{constructor(e="Payment required"){super(e)}}class n extends Error{constructor(e="Server error"){super(e)}}class a extends Error{constructor(e="I'm a teapot"){super(e)}}class o extends Error{constructor(e="Unauthorized"){super(e)}}const c="private",l="protected",u="public",h="normal",d="dry",p=200,m=400,f=401,g=402,w=403,y=404,E=418,S=500,v=501;class b extends e{#e;constructor(e){super(`Invalid version number '${e}'`),this.#e=e}get number(){return this.#e}}class O extends s{#t;constructor(e){super(`Procedure '${e}' not found`),this.#t=e}get fqn(){return this.#t}}class A extends t{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class N{#s;#r=new Map;#i=new Map;constructor(e){this.#s=e}get id(){return this.#s}addClass(e){return this.#r.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#r.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#r.values()]}addProcedure(e){return this.#i.set(e.fqn,e),this}hasProcedure(e){return this.#i.has(e)}getProcedure(e){return this.#i.get(e)}getExposedProcedures(){return[...this.#i.values()].filter(e=>e.public||e.protected)}}class T{#t;#n;constructor(e,t){this.#t=e,this.#n=t}get fqn(){return this.#t}get implementation(){return this.#n}}class x{static get DEFAULT(){return new x(0,0,0)}#a;#o;#c;constructor(e=0,t=0,s=0){this.#a=e,this.#o=t,this.#c=s}get major(){return this.#a}get minor(){return this.#o}get patch(){return this.#c}equals(e){return this.#a===e.major&&this.#o===e.minor&&this.#c===e.patch}greater(e){return this.#a!==e.major?this.#a>e.major:this.#o!==e.minor?this.#o>e.minor:this.#c!==e.patch&&this.#c>e.patch}less(e){return this.#a!==e.major?this.#a<e.major:this.#o!==e.minor?this.#o<e.minor:this.#c!==e.patch&&this.#c<e.patch}toString(){return`${this.#a}.${this.#o}.${this.#c}`}}class I{#t;#l=new Map;#u;constructor(e){this.#t=e}get fqn(){return this.#t}get public(){return[...this.#l.values()].some(e=>e.public)}get protected(){return[...this.#l.values()].some(e=>e.protected)}addImplementation(e){return this.#l.set(e.version,e),this.#h(e)&&(this.#u=e),this}#h(e){return void 0===this.#u||e.version.greater(this.#u.version)}getImplementation(e){const t=this.#d(e);return this.#l.get(t)}#d(e){let t=x.DEFAULT;for(const s of this.#l.keys()){if(s.equals(e))return s;s.greater(e)||t.less(s)&&(t=s)}return t}}class C{#p;#m;#f;#g;constructor(e,t,s,r){this.#p=e,this.#m=t,this.#f=s,this.#g=r}get version(){return this.#p}get public(){return this.#m===u}get protected(){return this.#m===l}get private(){return this.#m===c}get parameters(){return this.#f}get executable(){return this.#g}}class R{#w;#y;constructor(e,t=!1){this.#w=e,this.#y=t}get name(){return this.#w}get isOptional(){return this.#y}}class M extends R{}class z extends R{#E;constructor(e,t,s){super(t??"(anonymous)",s),this.#E=e}get variables(){return this.#E}}class P extends z{}class L extends z{}class k{#t;#p;#S;#v=new Map;#b;constructor(e,t,s,r,i){this.#t=e,this.#p=t,this.#S=s,this.#v=r,this.#b=i}get fqn(){return this.#t}get version(){return this.#p}get args(){return this.#S}get headers(){return this.#v}get mode(){return this.#b}clearArguments(){this.#S.clear()}setArgument(e,t){this.#S.set(e,t)}getArgument(e){return this.#S.get(e)}hasArgument(e){return this.#S.has(e)}removeArgument(e){this.#S.delete(e)}clearHeaders(){this.#v.clear()}setHeader(e,t){this.#v.set(e.toLowerCase(),t)}getHeader(e){return this.#v.get(e.toLowerCase())}hasHeader(e){return this.#v.has(e.toLowerCase())}removeHeader(e){this.#v.delete(e.toLowerCase())}}class ${#O;#A;#v;constructor(e,t=void 0,s=new Map){this.#O=e,this.#A=t,this.#v=s}get status(){return this.#O}get result(){return this.#A}set result(e){this.#A=e}get headers(){return this.#v}clearHeaders(){this.#v.clear()}setHeader(e,t){this.#v.set(e.toLowerCase(),t)}getHeader(e){return this.#v.get(e.toLowerCase())}hasHeader(e){return this.#v.has(e.toLowerCase())}removeHeader(e){this.#v.delete(e.toLowerCase())}}class V extends e{#N;constructor(e){super(`Unknown parameter ${e}`),this.#N=e}get parameterName(){return this.#N}}class D extends e{#N;constructor(e){super(`Missing value for parameter '${e}'`),this.#N=e}get parameterName(){return this.#N}}class j extends e{#N;constructor(e){super(`Invalid value for parameter '${e}'`),this.#N=e}get parameterName(){return this.#N}}class F{extract(e,t){const s=this.#T(e,t),r=[];for(const t of e){const e=this.#x(t,s);r.push(e)}if(s.size>0){const e=s.keys().next().value;throw new V(e)}return r}#T(e,t){const s=new Map;for(const[r,i]of t){if(this.#I(r)){const t=this.#C(r);!0===this.#R(e,t)&&s.set(t,i);continue}s.set(r,i)}return s}#I(e){return e.startsWith("*")}#C(e){return e.substring(1)}#R(e,t){return void 0!==e.find(e=>e.name===t)}#x(e,t,s){return e instanceof M?this.#M(e,t,s):this.#z(e,t)}#M(e,t,s){const r=t.get(e.name);if(this.#P(e,r,s))throw new D(e.name);if(this.#L(e,r,s))throw new j(e.name);return t.delete(e.name),r}#z(e,t){return e instanceof P?this.#k(e,t):this.#$(e,t)}#k(e,t){const s=this.#V(e,t);return void 0!==s?Object.values(s):void 0}#$(e,t){return this.#V(e,t)}#V(e,t){const s=e instanceof P,r={},i=[];let n=!1,a=0;for(const o of e.variables){const c=s?a++:o.name,l=this.#x(o,t,e);void 0!==l?n=!0:!1===o.isOptional&&i.push(o.name),r[c]=l}if(!0===n&&i.length>0)throw new D(i[0]);return n?r:void 0}#P(e,t,s){return void 0===t&&(!0!==e.isOptional&&!0!==s?.isOptional)}#L(e,t,s){return!1!==e.name.startsWith("...")&&(void 0===s&&t instanceof Array==!1||s instanceof P&&t instanceof Array==!1||s instanceof L&&t instanceof Object==!1)}}class B{toStatus(n){return n instanceof e?m:n instanceof t?w:n instanceof s?y:n instanceof r?v:n instanceof i?g:n instanceof a?E:n instanceof o?f:S}fromStatus(c,l){switch(c){case m:return new e(l);case w:return new t(l);case y:return new s(l);case v:return new r(l);case g:return new i(l);case E:return new a(l);case f:return new o(l);default:return new n(l)}}}const H=/^\d+(?:\.\d+){0,2}$/;class U{parse(e){if(0===e.trim().length)return x.DEFAULT;if(!1===H.test(e))throw new b(e);const t=e.split(".");switch(t.length){case 1:return new x(Number.parseInt(t[0]));case 2:return new x(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new x(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class G extends s{#t;#p;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#t=e,this.#p=t}get fqn(){return this.#t}get version(){return this.#p}}class q extends n{constructor(){super("Invalid segment")}}class W extends Error{constructor(e){super("Starting execution manager failed",{cause:e})}}class _ extends Error{constructor(e){super("Stopping execution manager failed",{cause:e})}}class K{#D=new Map;addSegment(e){this.#D.set(e.id,e)}clearSegments(){this.#D.clear()}getClassNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#D.values()){const s=t.getClassByImplementation(e);if(void 0!==s)return s}}getProcedureNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Y{#j;#F;#B=new F;#H=new B;#U=new K;constructor(e,t=[]){this.#j=e,this.#F=t}async start(){try{await this.#G()}catch(e){throw new W(e)}}async stop(){try{return this.#q()}catch(e){throw new _(e)}}async loadSegment(e){const t=await this.#j.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof N==!1)throw new q;this.#U.addSegment(e)}getClassNames(){return this.#U.getClassNames()}hasClass(e){return this.#U.hasClass(e)}getClass(e){return this.#U.getClass(e)}getClassByImplementation(e){return this.#U.getClassByImplementation(e)}getProcedureNames(){return this.#U.getProcedureNames()}hasProcedure(e){return this.#U.hasProcedure(e)}getProcedure(e){return this.#U.getProcedure(e)}async run(e){const t=this.#W(e.fqn,e.version),s=this.#B.extract(t.parameters,e.args);return e.mode===d?new $(p,void 0):this.#_(e,t,s)}async#G(){await Promise.all(this.#F.map(e=>this.loadSegment(e)))}#q(){this.#U.clearSegments()}#W(e,t){const s=this.#U.getProcedure(e);if(void 0===s)throw new O(e);const r=s.getImplementation(t);if(void 0===r)throw new G(s.fqn,t.toString());return r}async#_(e,t,s){try{const r=await t.executable.call(e,...s);return new $(p,r)}catch(e){const t=this.#H.toStatus(e);return new $(t,e)}}}class X extends n{constructor(){super("Request cancelled")}}class J{#K;#Y;#X=[];#J=!1;#Q=0;constructor(e,t=20){this.#K=e,this.#Y=t}start(){this.#J=!0,this.#Z()}stop(){this.#J=!1,this.#ee()}run(e){return new Promise((t,s)=>{this.#X.push({request:e,resolve:t,reject:s}),this.#Z()})}#Z(){if(this.#te())return;const e=this.#X.length,t=this.#Y-this.#Q,s=Math.min(e,t);this.#se(s)}#te(){return this.#re()||this.#ie()||this.#ne()}#re(){return!1===this.#J}#ie(){return 0===this.#X.length}#ne(){return this.#Q>=this.#Y}#se(e){const t=this.#X.splice(0,e);this.#Q+=e,t.forEach(e=>this.#ae(e))}async#ae(e){try{const t=await this.#K.run(e.request);e.resolve(t)}catch(t){e.reject(t)}finally{this.#Q--,this.#Z()}}#ee(){for(;this.#X.length>0;){const e=this.#X.shift();void 0!==e&&this.#oe(e)}}#oe(e){e.reject(new X)}}const Q="starting",Z="available",ee="unavailable",te="stopping",se="stopped";class re{#ce=se;get state(){return this.#ce}set state(e){this.#ce=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.#le(se)}isStopped(){return this.#ue(se)}isAvailable(){return this.#ue(Z)}setStarting(){this.#ce=Q}setAvailable(){this.#ce=Z}setUnavailable(){this.#ce=ee}setAvailability(e){return this.#ce=e?Z:ee,this.#ce}setStopping(){this.#ce=te}setStopped(){this.#ce=se}#ue(...e){return e.includes(this.#ce)}#le(...e){return!1===this.#ue(...e)}}class ie{#he;#de;#pe=new re;constructor(e){this.#he=e.url,this.#de=e.remote}get url(){return this.#he}get state(){return this.#pe.state}get trustKey(){}async start(){return this.#pe.start(async()=>{await this.#de.connect(),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{await this.#de.disconnect()})}isHealthy(){return this.#de.isHealthy()}getHealth(){return this.#de.getHealth()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}getProcedureNames(){throw new r}hasProcedure(e){throw new r}addWorker(e){return this.#de.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#de.reportWorker(e,t)}removeWorker(e){return this.#de.removeWorker(e)}run(e){return this.#de.run(e)}}class ne extends Error{constructor(e){super(`Invalid location '${e}'`)}}class ae extends Error{constructor(e){super(`File could not be found from '${e}'`)}}class oe{#me;#fe;#ge;constructor(e,t,s){this.#me=e,this.#fe=t,this.#ge=s}get location(){return this.#me}get type(){return this.#fe}get content(){return this.#ge}get size(){return this.#ge.length}}class ce{#me;#we;#ye;constructor(e,t){const s=t.resolve(e);this.#me=t.normalize(e),this.#we=t.normalize(s),this.#ye=t}getAbsoluteLocation(e){const t=this.#ye.isAbsolute(e)?e:this.#ye.join(this.#me,e),s=this.#ye.resolve(t),r=this.#ye.normalize(s);return this.#Ee(r,e),r}getRelativeLocation(e){const t=this.#ye.relative(this.#me,e);return this.#ye.normalize(t)}normalizeLocation(e){return this.#ye.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#ye.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#ye.exists(t))throw new ae(e);return this.#ye.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#ye.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#ye.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new oe(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#ye.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#ye.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#ye.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#ye.normalize(e);return(await this.#ye.filter(t,s)).map(e=>this.#ye.normalize(e))}async filterWithIgnores(e,t){const s=await this.filter(e),r=t.map(e=>this.filter(e)),i=await Promise.all(r),n=new Set(i.flat());return s.filter(e=>!1===n.has(e))}#Ee(e,t){if(!1===e.startsWith(this.#we))throw new ne(t)}}class le extends Error{constructor(){super("Remote files are not supported")}}class ue{copy(e,t){throw new le}delete(e){throw new le}exists(e){throw new le}async filter(e,t){return[]}isAbsolute(e){return e.startsWith("/")}isDirectory(e){throw new le}join(...e){throw new le}read(e){throw new le}resolve(e){return e}relative(e,t){throw new le}normalize(e){return e}mimeType(e){throw new le}write(e,t){throw new le}}class he extends ce{constructor(e){super(e,new ue)}}class de extends Error{constructor(e,t){super(`Module could not be loaded from '${e}'`,{cause:t})}}class pe{#Se;constructor(e){this.#Se=e}async import(e){const t=this.#Se.locate(e);try{return await(import(t))}catch(e){throw new de(t,e)}}}class me{constructor(e){}locate(e){throw new de(e,"Remote module loading is not allowed")}}class fe extends pe{constructor(e){super(new me(e))}}class ge{#ve;#be;constructor(e,t){this.#ve=e,this.#be=t}get fileManager(){return this.#ve}get importManager(){return this.#be}async filter(...e){return(await Promise.all(e.map(e=>this.#ve.filter(e)))).flat().map(e=>this.#ve.getRelativeLocation(e))}exists(e){return this.#ve.exists(e)}read(e){return this.#ve.read(e)}import(e){return this.#be.import(e)}}class we extends ge{constructor(e){super(new he(e),new fe(e))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new we(t)}}class ye extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class Ee extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class Se extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class ve extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class be{#Oe=[];addSerializer(e){e.parent=this,this.#Oe.unshift(e)}async serialize(e){const t=this.#Oe.find(t=>t.canSerialize(e));if(void 0===t)throw new ve(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Oe.find(t=>t.canDeserialize(e));if(void 0===t)throw new Se(typeof e);return t.deserialize(e)}}class Oe extends Error{constructor(){super("Parent serializer not set")}}class Ae{#Ae;set parent(e){this.#Ae=e}serializeOther(e){if(void 0===this.#Ae)throw new Oe;return this.#Ae.serialize(e)}deserializeOther(e){if(void 0===this.#Ae)throw new Oe;return this.#Ae.deserialize(e)}}class Ne extends Ae{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const s of e)t.push(await this.serializeOther(s));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Te extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class xe extends Ae{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 Te(e.value)}}}class Ie extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ce extends Ae{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 Ie(e.base64)}}}class Re{}class Me extends Re{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Me(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class ze{}class Pe extends ze{identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class Le extends Pe{parameters;body;isAsync;constructor(e,t,s,r=!1){super(e),this.parameters=t,this.body=s,this.isAsync=r}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new Le(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier?` ${this.identifier}`:"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function${t}(${s.join(",")})${r}`}}class ke extends Le{constructor(e,t,s=!1){super(void 0,e,t,s)}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new ke(e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.parameters.map(e=>e.toString()),s=this.body.toString();return`${e}(${t.join(", ")})=>${s}`}}class $e{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new $e(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class Ve extends ze{code;constructor(e){super(),this.code=e}clone(){return new Ve(this.code)}toString(){return this.code}}class De{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class je extends De{parameters;body;constructor(e,t){super("constructor","public","instance"),this.parameters=e,this.body=t}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new je(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class Fe extends De{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new Fe(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.body.toString();return`${e}get ${t}${this.identifier}()${s}`}}class Be extends De{parameter;body;constructor(e,t,s,r,i){super(e,t,s),this.parameter=r,this.body=i}clone(){const e=this.parameter.clone(),t=this.body.clone();return new Be(this.identifier,this.visibility,this.location,e,t)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.parameter.toString(),r=this.body.toString();return`${e}set ${t}${this.identifier}(${s})${r}`}}class He extends De{parameters;body;isAsync;constructor(e,t,s,r,i,n=!1){super(e,t,s),this.parameters=r,this.body=i,this.isAsync=n}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new He(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.isAsync?"async ":"",r=this.parameters.map(e=>e.toString()),i=this.body.toString();return`${e}${s}${t}${this.identifier}(${r.join(",")})${i}`}}class Ue extends De{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new Ue(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${e}${t}${this.identifier}${s}`}}class Ge extends Pe{parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof je)}get fields(){return this.members.filter(e=>e instanceof Ue)}get getters(){return this.members.filter(e=>e instanceof Fe)}get setters(){return this.members.filter(e=>e instanceof Be)}get methods(){return this.members.filter(e=>e instanceof He)}get publicFields(){return this.fields.filter(e=>"public"===e.visibility)}get publicGetters(){return this.getters.filter(e=>"public"===e.visibility)}get publicSetters(){return this.setters.filter(e=>"public"===e.visibility)}get publicMethods(){return this.methods.filter(e=>"public"===e.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(e){return this.members.find(t=>t.is(e))}hasMember(e){return this.members.some(t=>t.is(e))}getField(e){return this.fields.find(t=>t.is(e))}hasField(e){return this.fields.some(t=>t.is(e))}getGetter(e){return this.getters.find(t=>t.is(e))}hasGetter(e){return this.getters.some(t=>t.is(e))}getSetter(e){return this.setters.find(t=>t.is(e))}hasSetter(e){return this.setters.some(t=>t.is(e))}getMethod(e){return this.methods.find(t=>t.is(e))}hasMethod(e){return this.methods.some(t=>t.is(e))}canRead(e){return this.readable.some(t=>t.is(e))}canWrite(e){return this.writable.some(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Ge(this.identifier,this.parent,e)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(e=>e.toString()).join("")}}`}}class qe extends ze{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new qe(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class We extends ze{code;constructor(e){super(),this.code=e}clone(){return new We(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class _e extends Le{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new _e(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier??"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function* ${t}(${s.join(",")})${r}`}}class Ke extends He{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new Ke(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier,s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}*${t}(${s.join(",")})${r}`}}class Ye extends Re{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new Ye(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Xe extends ze{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Xe(e,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(e=>e.toString()).join(",")}} from '${this.from}';`}}class Je extends Pe{type;binding;initializer;constructor(e,t,s){super(t.toString()),this.type=e,this.binding=t,this.initializer=s}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new Je(this.type,e,t)}toString(){const e=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",t=e.endsWith(";")?"":";";return`${this.type} ${this.identifier}${e}${t}`}}class Qe{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof qe)}get imports(){return this.statements.filter(e=>e instanceof Xe)}get expressions(){return this.statements.filter(e=>e instanceof We)}get declarations(){return this.statements.filter(e=>e instanceof Pe)}get variables(){return this.statements.filter(e=>e instanceof Je)}get functions(){return this.statements.filter(e=>e instanceof Le)}get classes(){return this.statements.filter(e=>e instanceof Ge)}get exported(){const e=[];for(const t of this.exports)for(const s of t.members){const t=this.getDeclaration(s.identifier);void 0!==t&&e.push(t)}return e}get exportedVariables(){return this.exported.filter(e=>e instanceof Je)}get exportedFunctions(){return this.exported.filter(e=>e instanceof Le)}get exportedClasses(){return this.exported.filter(e=>e instanceof Ge)}getExport(e){return this.exports.find(t=>t.hasMember(e))}getImport(e){return this.imports.find(t=>t.hasMember(e))}hasDeclaration(e){return this.declarations.some(t=>t.is(e))}getDeclaration(e){return this.declarations.find(t=>t.is(e))}hasVariable(e){return this.variables.some(t=>t.is(e))}getVariable(e){return this.variables.find(t=>t.is(e))}hasFunction(e){return this.functions.some(t=>t.is(e))}getFunction(e){return this.functions.find(t=>t.is(e))}hasClass(e){return this.classes.some(t=>t.is(e))}getClass(e){return this.classes.find(t=>t.is(e))}clone(){const e=this.statements.map(e=>e.clone());return new Qe(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class Ze{identifier;alias;constructor(e,t){this.identifier=e,this.alias=t}is(e){return this.alias===e||void 0===this.alias&&this.identifier===e}clone(){return new Ze(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class et extends Re{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new et(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const tt={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},st=Object.values(tt);const rt=".",it="(",nt=")",at="[",ot="]",ct="{",lt="}",ut="_",ht={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},dt=Object.values(ht);function pt(e){return dt.includes(e)}const mt={UNDEFINED:void 0,NULL:null,STRING:""},ft=["null","undefined"],gt=Object.values(mt);function wt(e){return gt.includes(e)}const yt={OPEN:it,CLOSE:nt};function Et(e){return e===yt.OPEN||e===yt.CLOSE}const St={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally",TYPEOF:"typeof",INSTANCEOF:"instanceof"},vt=Object.values(St),bt=[St.IMPORT,St.EXPORT,St.VAR,St.LET,St.CONST,St.FUNCTION,St.CLASS,St.ASYNC],Ot=[St.VAR,St.LET,St.CONST,St.FUNCTION,St.CLASS,St.USING],At=[St.AS,St.ASYNC,St.GET,St.SET,St.OF,St.YIELD,St.FROM,St.STATIC];function Nt(e){return bt.includes(e)}function Tt(e){return At.includes(e)}const xt={OPEN:at,CLOSE:ot};function It(e){return e===xt.OPEN||e===xt.CLOSE}const Ct=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Rt(e){return Ct.includes(e)}const Mt={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},zt=Object.values(Mt);function Pt(e){return zt.includes(e)}const Lt={OPEN:ct,CLOSE:lt};function kt(e){return e===Lt.OPEN||e===Lt.CLOSE}const $t={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},Vt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Dt=Object.values(Vt);function jt(e){return Dt.includes(e)}class Ft{#Ne;#Te;constructor(e){this.#Ne=e,this.#Te=0}get items(){return this.#Ne}get position(){return this.#Te}get size(){return this.#Ne.length}get eol(){return this.#Te>=this.#Ne.length}get current(){return this.#Ne[this.#Te]}get next(){return this.#Ne[this.#Te+1]}get previous(){return this.#Ne[this.#Te-1]}notAtEnd(){return!1===this.eol}get(e){return this.#Ne[e]}step(e=1){return this.#Te+=e,this.current}stepBack(e=1){return this.#Te-=e,this.current}hasNext(){return this.#Te+1<this.#Ne.length}insert(...e){this.#Ne.splice(this.#Te,0,...e)}}class Bt extends Ft{constructor(e){super(e.split(""))}}class Ht{#fe;#xe;#Ie;#Ce;constructor(e,t,s,r){this.#fe=e,this.#xe=t,this.#Ie=s,this.#Ce=r}get type(){return this.#fe}get value(){return this.#xe}get start(){return this.#Ie}get end(){return this.#Ce}isType(e){return this.#fe===e}hasValue(e){return this.#xe===e}toString(){return`${this.#xe}`}}class Ut extends Ft{}const Gt=["true","false"];const qt=["0","1","2","3","4","5","6","7","8","9"],Wt=[...qt,"a","b","c","d","e","f","A","B","C","D","E","F"],_t=["0","1"];function Kt(e){return qt.includes(e)}const Yt={GENERATOR:"*",PRIVATE:"#"},Xt=Object.values(Yt);class Jt{tokenize(e){const t=new Bt(e),s=[];let r;for(;t.notAtEnd();){const e=this.#Re(t,r);if(void 0===e)break;e.isType($t.WHITESPACE)||e.isType($t.COMMENT)?t.step():(s.push(e),this.#Me(e)&&(r=e),t.step())}return new Ut(s)}#Me(e){return!1===[$t.WHITESPACE,$t.COMMENT].includes(e.type)}#Re(e,t){const s=e.current,r=e.position;if(jt(s)){const t=e.position;return new Ht($t.WHITESPACE,s,r,t)}if(function(e){return st.includes(e)}(s+e.next)){const t=this.#ze(e),s=e.position;return new Ht($t.COMMENT,t,r,s)}if(this.#Pe(s,t)){const t=this.#Le(e),s=e.position;return new Ht($t.REGEX,t,r,s)}if(this.#ke(e,t)){const t=this.#$e(e),s=e.position;return new Ht($t.NUMBER,t,r,s)}if(Rt(s)){const t=this.#Ve(e),s=e.position;return new Ht($t.LITERAL,t,r,s)}if(Pt(s)){const t=this.#De(e),s=e.position;return new Ht($t.OPERATOR,t,r,s)}if(function(e){return Xt.includes(e)}(s)){const t=this.#De(e),s=e.position;return new Ht($t.INDICATOR,t,r,s)}if(pt(s)){const t=e.position;return new Ht($t.DIVIDER,s,r,t)}if(Et(s)){const t=e.position;return new Ht($t.GROUP,s,r,t)}if(kt(s)){const t=e.position;return new Ht($t.SCOPE,s,r,t)}if(It(s)){const t=e.position;return new Ht($t.LIST,s,r,t)}if(wt(s))return;const i=this.#je(e),n=e.position;return function(e){return vt.includes(e)}(i)?new Ht($t.KEYWORD,i,r,n):function(e){return Gt.includes(e)}(i)?new Ht($t.BOOLEAN,i,r,n):function(e){return ft.includes(e)}(i)?new Ht($t.NOTHING,i,r,n):new Ht($t.IDENTIFIER,i,r,n)}#ze(e){const t=e.current+e.next===tt.MULTI_START,s=t?tt.MULTI_END:Vt.NEWLINE;let r=t?tt.MULTI_START:tt.SINGLE;for(e.step(2);e.notAtEnd();){const i=e.current;if((t?i+e.next:i)===s){e.step(s.length-1);break}r+=i,e.step()}return t?r+tt.MULTI_END:r.trim()}#Pe(e,t){return e===Mt.DIVIDE&&(void 0===t||([$t.OPERATOR,$t.DIVIDER,$t.KEYWORD].includes(t.type)||[yt.OPEN,xt.OPEN].includes(t.value)))}#Fe(e){return jt(e)||e==rt||!1===this.#Be(e)}#Le(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Mt.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#Fe(r)){e.stepBack();break}t+=r,e.step()}return t}#ke(e,t){const s=e.current,r=e.next;return!!Kt(s)||s===Mt.SUBTRACT&&(!t?.isType($t.NUMBER)&&Kt(r))}#He(e,t,s){return t?!1===(r=e,Wt.includes(r))&&e!==ut:s?!1===function(e){return _t.includes(e)}(e)&&e!==ut:!1===Kt(e)&&e!==rt&&e!==ut&&"e"!==e;var r}#$e(e){let t=e.current;t===Mt.SUBTRACT&&(t+=e.step()),e.step();const s="x"===e.current,r="b"===e.current;for((s||r)&&(t+=e.current,e.step());e.notAtEnd();){const i=e.current;if(this.#He(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#Ve(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const i=e.current;if(!1===r){if(i===t){s+=i;break}"\\"===i&&(r=!0)}else r=!1;s+=i,e.step()}return s}#Be(e){return!1===(wt(e)||jt(e)||Pt(e)||Rt(e)||pt(e)||Et(e)||kt(e)||It(e))}#je(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#Be(s)){e.stepBack();break}t+=s,e.step()}return t}#De(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===Pt(s)||!1===Pt(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Qt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Zt extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class es extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class ts extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class ss extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const rs=new Ht($t.NONE,"",-1,0);class is{#Ue;constructor(e=[]){this.#Ue=e}get tokens(){return this.#Ue}append(...e){this.#Ue.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="";for(let t=0;t<this.#Ue.length;t++){const s=this.#Ue[t-1]??rs,r=this.#Ue[t],i=this.#Ue[t+1]??rs,n=this.#Ge(s,r)?" ":"",a=this.#qe(r,i)?" ":"";e+=`${n}${r.value}${a}`}return e}#Ge(e,t){return!(!t.isType($t.KEYWORD)||!this.#We(e))||!(!t.isType($t.OPERATOR)||!e.isType($t.OPERATOR))}#qe(e,t){return e.isType($t.KEYWORD)&&(t.isType($t.KEYWORD)||this.#We(t))}#We(e){return e.isType($t.IDENTIFIER)||e.isType($t.BOOLEAN)||e.isType($t.NOTHING)||e.isType($t.NUMBER)}}const ns="default",as="$_EXPORT";class os{#_e;constructor(e=new Jt){this.#_e=e}parse(e){const t=this.#_e.tokenize(e),s=this.#Ke(t);return new Qe(s)}parseStatement(e){const t=this.#_e.tokenize(e),s=this.#Ye(t);if(void 0===s)throw new ts("a statement");return s}parseImport(e){const t=this.#_e.tokenize(e),s=this.#Xe(t);if(s instanceof Xe==!1)throw new ts("an import definition");return s}parseExport(e){const t=this.#_e.tokenize(e),s=this.#Xe(t);if(s instanceof qe==!1)throw new ts("an export definition");return s}parseVariable(e){const t=this.#_e.tokenize(e),s=this.#Xe(t);if(s instanceof Je==!1)throw new ts("a variable definition");return s}parseFunction(e){const t=this.#_e.tokenize(e),s=this.#Xe(t);if(s instanceof Le==!1)throw new ts("a function definition");return s}parseClass(e){const t=this.#_e.tokenize(e),s=this.#Xe(t);if(s instanceof Ge==!1)throw new ts("a class definition");return s}#Ke(e){const t=[];for(;e.notAtEnd();){const s=this.#Ye(e);void 0!==s&&t.push(s)}return t}#Ye(e,t=!1){const s=e.current;if(this.#Je(s))return this.#Qe(e);if(s.isType($t.IDENTIFIER)){const s=e.next;return s?.hasValue(Mt.ARROW)?this.#Ze(e,t):this.#Qe(e)}if(s.isType($t.KEYWORD)){if(Tt(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(St.FUNCTION)||t.hasValue(yt.OPEN));if(s.hasValue(St.ASYNC)&&r)return e.step(),this.#Ye(e,!0);if(void 0===t||this.#et(t))return this.#Qe(e)}return s.hasValue(St.RETURN)?this.#Qe(e):!1===Nt(s.value)?this.#Qe(e):this.#Xe(e,t)}if(s.isType($t.REGEX))return this.#Qe(e);if(s.hasValue(yt.OPEN)){const s=this.#tt(e,yt.OPEN,yt.CLOSE);return s?.hasValue(Mt.ARROW)?this.#Ze(e,t):this.#Qe(e)}if(s.hasValue(Lt.OPEN))return this.#Qe(e);if(s.hasValue(xt.OPEN))return this.#Qe(e);if(s.hasValue(Mt.NOT)||s.hasValue(Mt.SUBTRACT))return this.#Qe(e);if(!pt(s.value))throw new ss(s.value,s.start);e.step()}#Je(e){return e.isType($t.LITERAL)||e.isType($t.NUMBER)||e.isType($t.BOOLEAN)||e.isType($t.NOTHING)||e.hasValue(St.NEW)}#Xe(e,t=!1){const s=e.current;switch(e.step(),s.value){case St.IMPORT:return this.#st(e);case St.EXPORT:return this.#rt(e);case St.CLASS:return this.#it(e);case St.FUNCTION:return this.#nt(e,t);case St.VAR:return this.#at(e,"var");case St.LET:return this.#at(e,"let");case St.CONST:return this.#at(e,"const");case St.ASYNC:return this.#Ye(e,!0);default:throw new es(s.value,s.start)}}#st(e){const t=[];let s=e.current;if(s.isType($t.LITERAL)){const e=this.#ot(s.value);return new Xe(t,e)}if(s.hasValue(yt.OPEN)){s=e.step();const r=this.#ot(s.value);return e.step(2),new Xe(t,r)}if(!1===s.hasValue(Lt.OPEN)){const r=s.hasValue(Mt.MULTIPLY)?Mt.MULTIPLY:ns;let i=s.value;s=e.step(),s.hasValue(St.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new Ze(r,i))}if(s.hasValue(ht.SEPARATOR)&&(s=e.step()),s.hasValue(Lt.OPEN)){const r=this.#ct(e);t.push(...r),s=e.current}if(!1===s.hasValue(St.FROM))throw new Qt(St.FROM,s.start);s=e.step();const r=this.#ot(s.value);return e.step(),new Xe(t,r)}#rt(e){switch(e.current.value){case St.DEFAULT:return e.step(),this.#lt(e,!0);case Lt.OPEN:return this.#ut(e);default:return this.#lt(e,!1)}}#lt(e,t){let s=e.current,r=0;if(t&&this.#ht(e)){const t=`${as}_${s.start}_${s.end}`;e.insert(new Ht($t.KEYWORD,St.CONST,0,0),new Ht($t.IDENTIFIER,t,0,0),new Ht($t.OPERATOR,Mt.ASSIGN,0,0)),s=e.current}var i;if(s.hasValue(St.ASYNC)&&(s=e.step(),r++),i=s.value,Ot.includes(i)&&(s=e.step(),r++,s.hasValue(Yt.GENERATOR)&&(s=e.step(),r++)),s.hasValue(St.EXTENDS)||s.hasValue(yt.OPEN)||s.hasValue(Lt.OPEN)){const t=`${as}_${s.start}_${s.end}`;e.insert(new Ht($t.IDENTIFIER,t,0,0)),s=e.current}const n=this.#Be(s)?s.value:"",a=t?ns:void 0;let o;s=e.step(),s?.hasValue(St.FROM)&&(s=e.step(),o=this.#ot(s.value)),r>0&&(r++,e.stepBack(r));const c=new Ze(n,a);return new qe([c],o)}#ht(e){const t=e.current;if(this.#Je(t))return!0;const s=e.next;return this.#Be(t)&&s?.hasValue(yt.OPEN)}#ut(e){const t=this.#ct(e);let s,r=e.current;return r?.hasValue(St.FROM)&&(r=e.step(),s=this.#ot(r.value)),e.step(),new qe(t,s)}#ot(e){return e.slice(1,-1)}#ct(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Lt.CLOSE)){e.step();break}if(s.hasValue(ht.SEPARATOR)){s=e.step();continue}const r=this.#dt(e);t.push(r),s=e.step()}return t}#dt(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(St.AS)&&(t=e.step(2),r=t.value),new Ze(s,r)}#at(e,t){const s=this.#pt(e),r=this.#mt(e);return e.notAtEnd()&&e.current.hasValue(ht.SEPARATOR)&&(e.step(),e.insert(new Ht($t.KEYWORD,t,0,0))),new Je(t,s,r)}#pt(e){const t=e.current;return t.hasValue(xt.OPEN)?this.#ft(e):t.hasValue(Lt.OPEN)?this.#gt(e):this.#wt(e)}#ft(e){const t=this.#yt(e,xt.CLOSE);return new Me(t)}#gt(e){const t=this.#yt(e,Lt.CLOSE);return new et(t)}#yt(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(ht.SEPARATOR)){e.step();continue}const i=this.#pt(e),n=this.#mt(e),a=new $e(i,n);s.push(a)}return s}#wt(e){let t=e.current,s=!1;t.hasValue(Mt.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new Ye(r,s)}#mt(e){const t=e.current;if(!1!==t.hasValue(Mt.ASSIGN))return e.step(),this.#Ye(e,!1);t.hasValue(ht.TERMINATOR)&&e.step()}#nt(e,t){let s,r=e.current,i=!1;r.hasValue(Yt.GENERATOR)&&(i=!0,r=e.step()),this.#Be(r)&&(s=r.value,e.step());const n=this.#yt(e,yt.CLOSE);if(r=e.current,!1===r.hasValue(Lt.OPEN))throw new Zt(Lt.OPEN,r.start);const a=this.#Et(e);return i?new _e(s,n,a,t):new Le(s,n,a,t)}#Ze(e,t){let s,r,i=e.current;if(i.hasValue(yt.OPEN))s=this.#yt(e,yt.CLOSE);else{const t=this.#wt(e);s=[new $e(t,void 0)]}if(i=e.current,!1===i.hasValue(Mt.ARROW))throw new Zt(Mt.ARROW,i.start);if(i=e.step(),i.hasValue(Lt.OPEN))r=this.#Et(e);else{const t=this.#Qe(e);r=new Ve(t.code)}return new ke(s,r,t)}#it(e){let t,s,r=e.current;if(this.#Be(r)&&(t=r.value,r=e.step()),r.hasValue(St.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Lt.OPEN))throw new Zt(Lt.OPEN,r.start);const i=this.#St(e);return new Ge(t,s,i)}#St(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Lt.CLOSE)){e.step();break}const r=this.#vt(e);s.push(r),t=e.current}return s}#vt(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(Yt.PRIVATE))s="private";else if(t.hasValue(St.STATIC))r="static";else{if(!t.hasValue(St.ASYNC)){if(t.hasValue(St.CONSTRUCTOR))return this.#bt(e);if(t.hasValue(St.GET))return this.#Ot(e,r);if(t.hasValue(St.SET))return this.#At(e,r);if(t.hasValue(Yt.GENERATOR))return e.step(),this.#Nt(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(yt.OPEN)?this.#Nt(e,s,r,i,!1):this.#Tt(e,s,r)}#bt(e){e.step();const t=this.#yt(e,yt.CLOSE),s=e.current;if(!1===s.hasValue(Lt.OPEN))throw new Zt(Lt.OPEN,s.start);const r=this.#Et(e);return new je(t,r)}#Ot(e,t){let s="public",r=e.step();r.hasValue(Yt.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#yt(e,yt.CLOSE).length)throw new ts("an empty parameter list");if(r=e.current,!1===r.hasValue(Lt.OPEN))throw new Zt(Lt.OPEN,r.start);const n=this.#Et(e);return new Fe(i,s,t,n)}#At(e,t){let s="public",r=e.step();r.hasValue(Yt.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#yt(e,yt.CLOSE);if(r=e.current,1!==n.length)throw new ts("exactly one setter parameter");if(!1===r.hasValue(Lt.OPEN))throw new Zt(Lt.OPEN,r.start);const a=this.#Et(e);return new Be(i,s,t,n[0],a)}#Nt(e,t,s,r,i){let n=e.current;const a=n.value;e.step();const o=this.#yt(e,yt.CLOSE);if(n=e.current,!1===n.hasValue(Lt.OPEN))throw new Zt(Lt.OPEN,n.start);const c=this.#Et(e);return i?new Ke(a,t,s,o,c,r):new He(a,t,s,o,c,r)}#Tt(e,t,s){const r=e.current.value;e.step();const i=this.#mt(e);return new Ue(r,t,s,i)}#Et(e){const t=this.#xt(e,Lt.OPEN,Lt.CLOSE).generate();return new Ve(t)}#Qe(e){const t=new is;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(xt.OPEN)){const r=this.#xt(e,xt.OPEN,xt.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(yt.OPEN)){const r=this.#xt(e,yt.OPEN,yt.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Lt.OPEN)){const r=this.#xt(e,Lt.OPEN,Lt.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#et(s)){s.hasValue(ht.TERMINATOR)&&e.step();break}}const r=t.generate();return new We(r)}#xt(e,t,s){let r=e.current;const i=new is([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#xt(e,t,s);i.merge(n),r=e.current;continue}if(r.hasValue(s))return e.step(),i.append(r),i;i.append(r),r=e.step()}return i}#tt(e,t,s){const r=e.position;this.#xt(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#et(e){return[ht.TERMINATOR,ht.SEPARATOR].includes(e.value)||[xt.CLOSE,yt.CLOSE,Lt.CLOSE].includes(e.value)||Nt(e.value)}#Be(e){return e.isType($t.IDENTIFIER)||e.isType($t.KEYWORD)&&Tt(e.value)}}class cs{merge(e,t){const s=void 0!==e.construct?[e.construct]:[],r=[...this.#It(e.fields,t.fields),...s,...this.#It(e.methods,t.methods),...this.#It(e.getters,t.getters),...this.#It(e.setters,t.setters)];return new Ge(e.identifier,t.identifier,r)}#It(e,t){const s=new Map;return t.forEach(e=>s.set(e.identifier,e)),e.forEach(e=>s.set(e.identifier,e)),[...s.values()]}}class ls{#Ct=new os;#Rt=new cs;fromModule(e,t=!1){const s=Object.entries(e),r=[];for(const[e,i]of s){if("function"!=typeof i.toString)continue;const s=i.toString();if(s.startsWith("class"))r.push(this.fromClass(i,t));else if(s.startsWith("function"))r.push(this.fromFunction(i));else{const t=new Ye(e,!1),i=new We(s);r.push(new Je("var",t,i))}}return new Qe(r)}fromClass(e,t=!1){const s=this.isClass(e)?this.#Mt(e):this.#zt(e);if(!1===t)return s;const r=this.getParentClass(e);if(""===r.name)return s;const i=this.fromClass(r,!0);return this.#Rt.merge(s,i)}fromObject(e,t=!0){const s=this.getClass(e);return this.fromClass(s,t)}fromFunction(e){const t=e.toString();return this.#Ct.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")}#Mt(e){const t=e.toString();return this.#Ct.parseClass(t)}#zt(e){const t=this.createInstance(e),s=this.#Pt(e,t);return new Ge(e.name,void 0,s)}#Pt(e,t){return[...this.#Lt(t),...this.#kt(e)]}#Lt(e){const t=Object.getOwnPropertyNames(e),s=e,r=[];for(const e of t){const t=s[e],i=void 0!==t?new We(String(t)):void 0,n=new Ue(e,"public","instance",i);r.push(n)}return r}#kt(e){const t=Object.getOwnPropertyDescriptors(e.prototype),s=[];for(const e in t){const r=t[e],i=r.value;if(i instanceof Function==!1)continue;const n=this.fromFunction(i);"constructor"===n.identifier?s.push(new je(n.parameters,n.body)):void 0!==r.get?s.push(new Fe(n.identifier,"public","instance",n.body)):void 0!==r.set?s.push(new Be(n.identifier,"public","instance",n.parameters[0],n.body)):s.push(new He(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return s}}const us=new ls;class hs extends Ae{#$t;constructor(e){super(),this.#$t=e}canSerialize(e){return e instanceof Object&&us.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=us.getClass(e),s=us.fromClass(t,!0),r=this.#Vt(s),i=this.#$t.resolveKey(t);if(void 0===i)throw new ye(t.name);return{serialized:!0,key:i,name:"class",args:await this.#Dt(s,r,e),fields:await this.#jt(s,r,e)}}#Vt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#Dt(e,t,s){const r={};for(const[i,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(s[n]):void 0;r[i.toString()]=t}return r}async#jt(e,t,s){const r={};for(const i of e.writable){const n=i.identifier;t.includes(n)||!1===e.canRead(n)||(r[n]=await this.serializeOther(s[n]))}return r}async deserialize(e){const t=await this.#Ft(e);if(void 0===t)throw new ye(e.key);if(t instanceof Function==!1)throw new Ee(e.key);const s=await this.#Bt(t,e.args),r=us.createInstance(t,s);for(const t in e.fields){const s=e.fields[t];r[t]=await this.deserializeOther(s)}return r}async#Bt(e,t){const s=us.fromClass(e,!0).construct,r=(s?.parameters??[]).map((e,s)=>{const r=s.toString(),i=t[r];return this.deserializeOther(i)});return Promise.all(r)}async#Ft(e){return globalThis[e.key]??this.#$t.resolveClass(e.key)}}class ds extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class ps extends Ae{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 ds(e.value);return t}}class ms extends Ae{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 fs extends Ae{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=[],s=[];for(const[r,i]of e)t.push(await this.serializeOther(r)),s.push(await this.serializeOther(i));return{serialized:!0,name:"Map",entries:{keys:t,values:s}}}async deserialize(e){const t=e.entries.keys,s=e.entries.values,r=new Map;for(let e=0;e<t.length;e++){const i=await this.deserializeOther(t[e]),n=await this.deserializeOther(s[e]);r.set(i,n)}return r}}class gs extends Ae{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 s in e){const r=e[s];t[s]=await this.serializeOther(r)}return t}async deserialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.deserializeOther(r)}return t}}class ws extends Ae{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 ys extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Es extends Ae{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 ys(e.source,e.flags)}}}class Ss extends Ae{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 s of e.values())t.push(await this.serializeOther(s));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 vs=new ls;class bs extends Ae{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,s=new DataView(e.buffer),r=[];for(let e=0;e<s.byteLength;e++)r.push(s.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:r}}async deserialize(e){const t=e.type,s=e.bytes,r=new ArrayBuffer(s.length),i=new DataView(r);for(let e=0;e<s.length;e++)i.setUint8(e,s[e]);const n=globalThis[t];return vs.createInstance(n,[r])}}class Os extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class As extends Ae{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 Os(e.value)}}}class Ns{static build(e){const t=new be;return t.addSerializer(new ws),t.addSerializer(new gs),void 0!==e&&t.addSerializer(new hs(e)),t.addSerializer(new ms),t.addSerializer(new Es),t.addSerializer(new xe),t.addSerializer(new As),t.addSerializer(new ps),t.addSerializer(new Ss),t.addSerializer(new fs),t.addSerializer(new Ne),t.addSerializer(new bs),"undefined"!=typeof Buffer&&t.addSerializer(new Ce),t}}class Ts{#Ht;constructor(e){this.#Ht=e}resolveKey(e){const t=this.#Ht.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Ht.getClass(e);return t?.implementation}}class xs extends o{constructor(){super("Request not trusted")}}const Is="X-Jitar-Trust-Key",Cs="X-Jitar-Data-Encoding",Rs="serialized";class Ms{#s;#he;#Ut;#Gt;#qt;#Ht;#Wt;#_t;#Kt;#pe=new re;constructor(e){this.#he=e.url,this.#Ut=e.trustKey,this.#Gt=e.gateway,this.#qt=!0===e.registerAtGateway,this.#Ht=e.executionManager,this.#Wt=e.healthManager;const t=e.scheduleManager;this.#_t=t.create(()=>this.#Yt(),e.reportInterval);const s=new Ts(this.#Ht);this.#Kt=Ns.build(s)}get id(){return this.#s}set id(e){this.#s=e}get state(){return this.#pe.state}get url(){return this.#he}get trustKey(){return this.#Ut}async start(){return this.#pe.start(async()=>{await Promise.all([this.#Ht.start(),this.#Wt.start()]),void 0!==this.#Gt&&(await this.#Gt.start(),this.#qt&&(this.#s=await this.#Gt.addWorker(this),this.#_t.start())),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{void 0!==this.#Gt&&(void 0!==this.#s&&(this.#_t.stop(),await this.#Gt.removeWorker(this.#s)),await this.#Gt.stop()),await Promise.all([this.#Wt.stop(),this.#Ht.stop()])})}getProcedureNames(){return this.#Ht.getProcedureNames()}hasProcedure(e){return this.#Ht.hasProcedure(e)}isHealthy(){return this.#Wt.isHealthy()}getHealth(){return this.#Wt.getHealth()}isAvailable(){return this.#pe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}async reportState(e){if(void 0!==this.#Gt&&void 0!==this.#s)return this.#Gt.reportWorker(this.#s,e)}async run(e){return this.#Xt(e)?this.#Jt(e):this.#Qt(e)}#Xt(e){return void 0===this.#Gt||this.#Ht.hasProcedure(e.fqn)}async#Jt(e){const t=this.#Ht.getProcedure(e.fqn),s=t?.getImplementation(e.version);if(this.#Zt(s))throw new O(e.fqn);if(this.#es(e,s))throw new xs;const r=e.getHeader(Cs);r===Rs&&(e=await this.#ts(e)),e.removeHeader(Cs);const i=await this.#Ht.run(e);return r===Rs?this.#ss(i):i}#Zt(e){return void 0===e||e.private}#es(e,t){if(t.public)return!1;const s=e.getHeader(Is);return this.#Ut!==s}async#Qt(e){(e=await this.#rs(e)).setHeader(Cs,Rs),void 0!==this.#Ut&&e.setHeader(Is,this.#Ut);const t=await this.#Gt.run(e);return this.#is(t)}async#rs(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#Kt.serialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#ts(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#Kt.deserialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#ss(e){const t=await this.#Kt.serialize(e.result);return new $(e.status,t,e.headers)}async#is(e){const t=await this.#Kt.deserialize(e.result);return new $(e.status,t,e.headers)}async#Yt(){const e=await this.updateState();return this.reportState(e)}}class zs extends Error{constructor(e){super("Starting client failed",{cause:e})}}class Ps extends Error{constructor(e){super("Stopping client failed",{cause:e})}}class Ls{#K;constructor(e){this.#K=e}async handle(e,t){return this.#K.run(e)}}class ks{#ns=new U;constructor(){this.#as()}#as(){const e=globalThis;e.__run=this.#os.bind(this),e.ProcedureNotAccessible=A}async#os(e,t,s,r){const i=this.#ns.parse(t),n=new Map(Object.entries(s)),a=r instanceof k?r.headers:new Map,o=new k(e,i,n,a,h),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const l=await this.runInternal(o);if(l.status!==p)throw l.result;return l.result}}class $s extends ks{#cs;#ls;#us=new J(this);constructor(e){super(),this.#cs=new Ms({url:e.remoteUrl,gateway:new ie({url:e.remoteUrl,remote:e.remote}),healthManager:e.healthManager,executionManager:e.executionManager,scheduleManager:e.scheduleManager}),this.#ls=e.middlewareManager}get worker(){return this.#cs}async start(){try{await this.#hs(),this.#us.start()}catch(e){throw new zs(e)}}async stop(){try{this.#us.stop(),await this.#ds()}catch(e){throw new Ps(e)}}getTrustKey(){}run(e){return this.#ls.handle(e)}async runInternal(e){return this.#us.run(e)}async#hs(){await Promise.all([this.#cs.start(),this.#ls.start()]);const e=new Ls(this.#cs);this.#ls.addMiddleware(e)}async#ds(){await Promise.all([this.#ls.stop(),this.#cs.stop()])}}const Vs="starting",Ds="started",js="stopping",Fs="stopped";class Bs extends n{constructor(){super("Invalid health check")}}class Hs extends Error{constructor(e){super("Starting health manager failed",{cause:e})}}class Us extends Error{constructor(e){super("Stopping health manager failed",{cause:e})}}class Gs{#ce=Fs;#ps=new Map;#j;#ms;constructor(e,t=[]){this.#j=e,this.#ms=t}get state(){return this.#ce}async start(){if(this.#ce===Fs)try{this.#ce=Vs,await this.#fs(),this.#ce=Ds}catch(e){throw this.#ce=Fs,new Hs(e)}}async stop(){if(this.#ce===Ds)try{this.#ce=js,this.clearHealthChecks(),this.#ce=Fs}catch(e){throw this.#ce=Ds,new Us(e)}}async loadHealthCheck(e){const t=await this.#gs(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new Bs;this.#ps.set(e.name,e)}clearHealthChecks(){this.#ps.clear()}async isHealthy(){const e=[];for(const t of this.#ps.values()){const s=this.#ws(t);e.push(s)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,s]of this.#ps){const r=this.#ws(s).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(r)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ys(e,t))).then(()=>t)}async#fs(){(await Promise.all(this.#ms.map(e=>this.#gs(e)))).forEach(e=>this.addHealthCheck(e))}async#gs(e){return(await this.#j.import(e)).default}#ys(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#ws(e){const t=e.isHealthy(),s=e.timeout;if(void 0===s)return t;const r=new Promise(e=>{setTimeout(e,s)}).then(()=>!1);return Promise.race([r,t])}}const qs=0,Ws=1,_s=2,Ks=3;class Ys{#Es;#Ss;constructor(e=Ws,t=console){this.#Es=e,this.#Ss=t}debug(...e){if(this.#Es>qs)return;const t=this.#vs("DEBUG",e);this.#Ss.debug(t)}info(...e){if(this.#Es>Ws)return;const t=this.#vs("INFO",e);this.#Ss.info(t)}warn(...e){if(this.#Es>_s)return;const t=this.#vs("WARN",e);this.#Ss.warn(t)}error(...e){if(this.#Es>Ks)return;const t=this.#vs("ERROR",e);this.#Ss.error(t)}fatal(...e){const t=this.#vs("FATAL",e);this.#Ss.error(t)}#vs(e,t){return`[${(new Date).toISOString()}][${e}] ${t.map(e=>this.#bs(e)).join(" ")}`}#bs(e,t=0){let s;switch(typeof e){case"string":s=e;break;case"object":s=this.#Os(e,t+1);break;case"undefined":s="undefined";break;case"function":s="function";break;default:s=String(e)}return`${this.#As(t)}${s}`}#Os(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#bs(e,t)).join(",\n")}\n${this.#As(t-1)}]`}if(e instanceof Error){const s=void 0!==e.cause?this.#bs(e.cause,t+1):void 0,r=void 0!==s?`\n=>${s}`:"";return`${e.message}${r}`}return JSON.stringify(e)}#As(e){return" ".repeat(e)}}const Xs="starting",Js="started",Qs="stopping",Zs="stopped";class er extends n{constructor(){super("Invalid middleware")}}class tr extends Error{constructor(e){super("Starting middleware manager failed",{cause:e})}}class sr extends Error{constructor(e){super("Stopping middleware manager failed",{cause:e})}}class rr{#ce=Zs;#Ns=[];#j;#Ts;constructor(e,t=[]){this.#j=e,this.#Ts=t}get state(){return this.#ce}async start(){if(this.#ce===Zs)try{this.#ce=Xs,await this.#xs(),this.#ce=Js}catch(e){throw this.#ce=Zs,new tr(e)}}async stop(){if(this.#ce===Js)try{this.#ce=Qs,this.clearMiddlewares(),this.#ce=Zs}catch(e){throw this.#ce=Js,new sr(e)}}async loadMiddleware(e){const t=await this.#Is(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new er;this.#Ns.push(e)}getMiddleware(e){return this.#Ns.find(t=>t instanceof e)}clearMiddlewares(){this.#Ns=[]}handle(e){return this.#Cs(e,0)()}async#xs(){(await Promise.all(this.#Ts.map(e=>this.#Is(e)))).forEach(e=>this.addMiddleware(e))}async#Is(e){return(await this.#j.import(e)).default}#Cs(e,t){const s=this.#Ns[t];if(void 0===s)return async()=>new $(p);const r=this.#Cs(e,t+1);return async()=>await s.handle(e,r)}}class ir{#Rs;#Ms;#zs;#Ps=null;constructor(e,t,s=5e3){this.#Rs=e,this.#Ms=t,this.#zs=s}start(){this.#Ls()}stop(){null!==this.#Ps&&(clearTimeout(this.#Ps),this.#Ps=null)}#Ls(){this.#Ps=setTimeout(async()=>{null!==this.#Ps&&(await this.#ks(),this.#Ls())},this.#zs),this.#Ps.unref()}async#ks(){try{await this.#Ms()}catch(e){this.#Rs.warn("Scheduled task failed",e)}}}class nr{#$s=[];#Rs;constructor(e){this.#Rs=e}create(e,t){const s=new ir(this.#Rs,e,t);return this.#$s.push(s),s}remove(e){const t=this.#$s.indexOf(e);t<0||this.#$s.splice(t,1)}startAll(){this.#$s.forEach(e=>e.start())}stopAll(){this.#$s.forEach(e=>e.stop())}}class ar{#Vs;constructor(e){this.#Vs=e}build(e){const t=e.remoteUrl,s=e.middleware,r=e.segments,i=new Ys(e.logLevel??_s),n=this.#Vs.build(t),a=new we(t),o=this.#Ds(a),c=this.#js(a,s),l=this.#Fs(a,r),u=this.#Bs(i);return new $s({remoteUrl:t,remote:n,healthManager:o,middlewareManager:c,executionManager:l,scheduleManager:u})}#Ds(e){return new Gs(e)}#js(e,t=[]){const s=new rr(e);return t.forEach(e=>s.addMiddleware(e)),s}#Fs(e,t=[]){const s=new Y(e);return t.forEach(e=>s.addSegment(e)),s}#Bs(e){return new nr(e)}}class or{#Hs;constructor(e=!0){this.#Hs=e}validate(e,t){const s=[];this.#Us("",e,t,s);return{valid:0===s.length,errors:s}}#Us(e,t,s,r){this.#Hs&&this.#Gs(e,t,s,r),this.#qs(e,t,s,r)}#Gs(e,t,s,r){const i=Object.keys(t),n=Object.keys(s);for(const t of i)if(!1===n.includes(t)){const s=this.#Ws(e,t);r.push(`Unknown field '${s}'`)}}#qs(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#Ws(e,n),a=s[n],o=t[n];this.#_s(i,o,a,r)}}#_s(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#Ks(e,t,s,r);case"integer":return this.#Ys(e,t,s,r);case"real":return this.#Xs(e,t,s,r);case"boolean":return this.#Js(e,t,s,r);case"url":return this.#Qs(e,t,s,r);case"group":return this.#Zs(e,t,s,r);case"list":return this.#er(e,t,s,r);case"enum":return this.#tr(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#Ks(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#Ys(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Xs(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Js(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#Qs(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#Zs(e,t,s,r){"object"==typeof t?this.#Us(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#er(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const i=t;for(const t in i){const n=this.#Ws(e,t),a=i[t];this.#_s(n,a,s.items,r)}}#tr(e,t,s,r){if(!1===s.options.includes(t)){const t=s.options.map(e=>String(e));r.push(`Field '${e}' is not one of: ${t.join(", ")}`)}}#Ws(e,t){return""===e?t:`${e}.${t}`}}const cr="content-type",lr="x-jitar-content-type",ur="x-jitar-procedure-version",hr="application/json",dr="application/octet-stream";class pr extends Error{constructor(){super("Invalid worker id")}}class mr{#he;#sr;#H=new B;#rr=new or;constructor(e,t){this.#he=e,this.#sr=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#he}/${e}`,s=await this.#ir(t,{method:"GET"}),r=s.headers.get(cr)??dr,i=await s.arrayBuffer(),n=Buffer.from(i);return new oe(e,r,n)}async isHealthy(){const e=`${this.#he}/health/status`,t=await this.#ir(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#he}/health`,t=await this.#ir(e,{method:"GET"}),s=await t.json();return new Map(Object.entries(s))}async addWorker(e,t,s){const r=`${this.#he}/workers`,i={url:e,procedureNames:t,trustKey:s},n={method:"POST",headers:{"Content-Type":hr},body:JSON.stringify(i)},a=await this.#ir(r,n),o=a.headers.get(cr);if(null===o||!1===o.includes(hr))throw new pr;const c=await a.json();if(!1===this.#rr.validate(c,{id:{type:"string",required:!0}}).valid)throw new pr;return c.id}async reportWorker(e,t){const s=`${this.#he}/workers/${e}/report`,r={state:t},i={method:"POST",headers:{"Content-Type":hr},body:JSON.stringify(r)};await this.#ir(s,i)}async removeWorker(e){const t=`${this.#he}/workers/${e}`,s={method:"DELETE",headers:{"Content-Type":hr}};await this.#ir(t,s)}async run(e){e.setHeader(cr,hr);const t=Object.fromEntries(e.args),s=Object.fromEntries(e.headers),r=e.version.toString();s[ur]=r;const i=`${this.#he}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:s,body:await this.#nr(t)},a=await this.#ir(i,n,!1),o=a.status,c=await this.#ar(a),l=this.#or(a);return new $(o,c,l)}async#ir(e,t,s=!0){const r=await this.#sr.execute(e,t);if(s&&this.#cr(r)){const e=await this.#ar(r);throw this.#H.fromStatus(r.status,String(e))}return r}#cr(e){return e.status<200||e.status>399}async#nr(e){return JSON.stringify(e)}async#ar(e){const t=e.headers.get(lr)??e.headers.get(cr);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const s=await e.text();return t?.includes("boolean")?"true"===s:t?.includes("number")?Number(s):s}#or(e){const t=new Map;for(const[s,r]of e.headers)t.set(s,r);return t}}class fr{async execute(e,t){return fetch(e,t)}}class gr{#sr;constructor(e=new fr){this.#sr=e}build(e){return new mr(e,this.#sr)}}export{P as ArrayParameter,e as BadRequest,T as Class,ar as ClientBuilder,t as Forbidden,gr as HttpRemoteBuilder,C as Implementation,M as NamedParameter,s as NotFound,r as NotImplemented,L as ObjectParameter,i as PaymentRequired,I as Procedure,k as Request,$ as Response,N as Segment,n as ServerError,a as Teapot,o as Unauthorized,x as Version};
|
package/dist/lib.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ type RuntimeConfiguration = {
|
|
|
3
3
|
target: string;
|
|
4
4
|
segments: string;
|
|
5
5
|
resources: string;
|
|
6
|
+
build: {
|
|
7
|
+
ignore: string[];
|
|
8
|
+
};
|
|
6
9
|
meta: {
|
|
7
10
|
root: string;
|
|
8
11
|
configFile: string;
|
|
@@ -71,6 +74,7 @@ declare class BuildHelper {
|
|
|
71
74
|
constructor(configuration: RuntimeConfiguration);
|
|
72
75
|
readApplication(): Promise<void>;
|
|
73
76
|
generateModuleCode(filename: string, segmentNames?: string[]): string;
|
|
77
|
+
generateSegmentCode(segmentName: string): string;
|
|
74
78
|
}
|
|
75
79
|
|
|
76
80
|
declare class BadRequest extends Error {
|
package/dist/lib.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{x as e,y as t,n as s,q as a,L as i,r as n,s as r,o,p,G as c}from"./ConfigurationManager-DE4YOzeh.js";export{A as ArrayParameter,B as BadRequest,C as ConfigurationManager,F as Forbidden,j as NamedParameter,N as NotFound,k as NotImplemented,O as ObjectParameter,l as PaymentRequired,v as Request,R as Response,m as Segment,S as ServerError,T as Teapot,U as Unauthorized}from"./ConfigurationManager-DE4YOzeh.js";import"node:fs";import"node:path";import"glob";import"mime-types";import"dotenv";class u{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get fqn(){return this.#e}get implementation(){return this.#t}}class h{#e;#s=new Map;#a;constructor(e){this.#e=e}get fqn(){return this.#e}get public(){return[...this.#s.values()].some(e=>e.public)}get protected(){return[...this.#s.values()].some(e=>e.protected)}addImplementation(e){return this.#s.set(e.version,e),this.#i(e)&&(this.#a=e),this}#i(e){return void 0===this.#a||e.version.greater(this.#a.version)}getImplementation(e){const t=this.#n(e);return this.#s.get(t)}#n(t){let s=e.DEFAULT;for(const e of this.#s.keys()){if(e.equals(t))return e;e.greater(t)||s.less(e)&&(s=e)}return s}}class g{#r;#o;#l;#p;constructor(e,t,s,a){this.#r=e,this.#o=t,this.#l=s,this.#p=a}get version(){return this.#r}get public(){return this.#o===t.PUBLIC}get protected(){return this.#o===t.PROTECTED}get private(){return this.#o===t.PRIVATE}get parameters(){return this.#l}get executable(){return this.#p}}class f extends Error{constructor(){super("Application not read")}}class d extends Error{constructor(e){super(`Application module not found '${e}'`)}}class w extends Error{constructor(e){super(`Application segment not found '${e}'`)}}class b{#m=new s;#c;#u;#h;constructor(e){const t=this.#m.makePathAbsolute(e.source,e.meta.root),s=this.#m.makePathAbsolute(e.target,e.meta.root),r=this.#m.makePathAbsolute(e.resources,e.meta.root),o=this.#m.makePathAbsolute(e.segments,e.meta.root);this.#c=new a(new i(t),new i(s),new i(r),new i(o),e.build.ignore),this.#u=new n(this.#c)}async readApplication(){const e=this.#c.source,t=this.#c.resource,s=this.#c.segment,a=await e.filterWithIgnores(r.MODULE_PATTERN,this.#c.sourceIgnores),i=await t.filter(r.RESOURCE_PATTERN),n=await s.filter(r.SEGMENT_PATTERN);this.#h=await this.#u.read(a,i,n)}generateModuleCode(e,t=[]){if(void 0===this.#h)throw new f;const s=this.#h.repository.get(e);if(void 0===s)throw new d(e);const a=this.#h.resources,i=this.#h.segmentation,n=i.getSegments(e);if(0===n.length){return new o(s,a,i).generate()}if(void 0===n.find(e=>t.includes(e.name))){return new p(s,n).generate()}return new o(s,a,i).generate()}generateSegmentCode(e){if(void 0===this.#h)throw new f;const t=this.#h.segmentation.getSegment(e);if(void 0===t)throw new w(e);return new c(t).generate()}}export{b as BuildHelper,u as Class,g as Implementation,h as Procedure,e as Version};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jitar",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.3",
|
|
4
4
|
"description": "Distributed runtime for JavaScript and TypeScript to chop monolithic applications into micros.",
|
|
5
5
|
"author": "Masking Technology <info@masking.tech> (https://jitar.dev)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@rollup/plugin-replace": "6.0.3",
|
|
49
49
|
"@rollup/plugin-terser": "1.0.0",
|
|
50
50
|
"@rollup/plugin-typescript": "12.3.0",
|
|
51
|
-
"rollup": "4.
|
|
51
|
+
"rollup": "4.62.2",
|
|
52
52
|
"rollup-plugin-dts": "6.4.1"
|
|
53
53
|
},
|
|
54
54
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e,{promises as t}from"node:fs";import s from"node:path";import{glob as r}from"glob";import i from"mime-types";import n from"dotenv";const o={MODULE_PATTERN:"**/*.js",RESOURCE_PATTERN:"**/*.json",SEGMENT_PATTERN:"**/*.json"};class a extends Error{#e;constructor(e){super(`Invalid location: ${e}`),this.#e=e}get location(){return this.#e}}class c extends Error{#t;constructor(e){super(`The file '${e}' could not be found`),this.#t=e}get filename(){return this.#t}}class u{#e;#s;#r;constructor(e,t,s){this.#e=e,this.#s=t,this.#r=s}get location(){return this.#e}get type(){return this.#s}get content(){return this.#r}get size(){return this.#r.length}}class l{#e;#i;#n;constructor(e,t){const s=t.resolve(e);this.#e=t.normalize(e),this.#i=t.normalize(s),this.#n=t}getAbsoluteLocation(e){const t=this.#n.isAbsolute(e)?e:this.#n.join(this.#e,e),s=this.#n.resolve(t),r=this.#n.normalize(s);return this.#o(r,e),r}getRelativeLocation(e){const t=this.#n.relative(this.#e,e);return this.#n.normalize(t)}normalizeLocation(e){return this.#n.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#n.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#n.exists(t))throw new c(e);return this.#n.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#n.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#n.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new u(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#n.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#n.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#n.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#n.normalize(e);return(await this.#n.filter(t,s)).map(e=>this.#n.normalize(e))}#o(e,t){if(!1===e.startsWith(this.#i))throw new a(t)}}class h{copy(e,s){return t.cp(e,s,{recursive:!0,force:!0})}delete(e){return t.rm(e,{recursive:!0,force:!0})}async exists(e){try{return await t.stat(e),!0}catch{return!1}}isAbsolute(e){return s.isAbsolute(e)}isDirectory(t){try{return e.statSync(t).isDirectory()}catch{return!1}}filter(e,t){return r(`${e}/${t}`)}join(...e){return s.join(...e)}read(e){return t.readFile(e)}resolve(e){return s.resolve(e)}relative(e,t){return s.relative(e,t)}normalize(e){return e.replaceAll(s.win32.sep,s.posix.sep)}async mimeType(e){const t=i.lookup(e);if(!1!==t)return t}async write(r,i){const n=s.dirname(r);return e.mkdirSync(n,{recursive:!0}),t.writeFile(r,i)}}class p extends l{constructor(e){super(e,new h)}}class d{#a;#c;#u;constructor(e,t,s){this.#a=e,this.#c=t,this.#u=s}get resources(){return this.#c}get repository(){return this.#a}get segmentation(){return this.#u}}class m{#c;constructor(e){this.#c=e}isResourceModule(e){return this.#c.includes(e)}}const f="private",g="0.0.0",E="index.js",y=".json",w="default";class S{#l=0;next(){return"$"+ ++this.#l}}const b="js",A=/\.js$/,T=[".","/","http:","https:"];class I{translatePath(e){const t=e.split("/"),s=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":s.pop();continue}s.push(e)}return s.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const s=e.split("/"),r=t.split("/");for(;s[0]===r[0];)s.shift(),r.shift();const i=r.map(()=>"..").join("/");return`${r.length>0?i:"."}/${s.join("/")}`}makePathAbsolute(e,t,s="/"){const r=""!==t?`${t}/${e}`:e;return`${s}${this.translatePath(r)}`}extractPath(e){return e.split("/").slice(0,-1).join("/")}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${b}`)?e:`${e}.${b}`}addSubExtension(e,t){return e.replace(A,`.${t}.${b}`)}isApplicationModule(e){return T.some(t=>e.startsWith(t))}}let v=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class O{#h;#p;#d=new I;constructor(e,t){this.#h=e,this.#p=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#m(e)));return new m(t.flat())}async#m(e){try{const t=await this.#h.getContent(e);return JSON.parse(t.toString()).map(e=>this.#f(e))}catch(t){const s=t instanceof Error?t.message:String(t);throw new v(e,s)}}#f(e){const t=this.#p.normalizeLocation(e),s=this.#p.isDirectory(t)?`${t}/${E}`:this.#d.assureExtension(t);return s.startsWith("./")?s.substring(2):s.startsWith("/")?s.substring(1):s}}let N=class{#t;#g;constructor(e,t){this.#t=e,this.#g=t}get filename(){return this.#t}get model(){return this.#g}};class R{#E;constructor(e){this.#E=e}get modules(){return this.#E}get(e){return this.#E.find(t=>t.filename===e)}}class x{}class M extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new M(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class C{}class $ extends C{identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class L extends ${parameters;body;isAsync;constructor(e,t,s,r=!1){super(e),this.parameters=t,this.body=s,this.isAsync=r}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new L(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier?` ${this.identifier}`:"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function${t}(${s.join(",")})${r}`}}class P extends L{constructor(e,t,s=!1){super(void 0,e,t,s)}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new P(e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.parameters.map(e=>e.toString()),s=this.body.toString();return`${e}(${t.join(", ")})=>${s}`}}class F{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new F(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class V extends C{code;constructor(e){super(),this.code=e}clone(){return new V(this.code)}toString(){return this.code}}class D{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class k extends D{parameters;body;constructor(e,t){super("constructor","public","instance"),this.parameters=e,this.body=t}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new k(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class B extends D{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new B(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.body.toString();return`${e}get ${t}${this.identifier}()${s}`}}class j extends D{parameter;body;constructor(e,t,s,r,i){super(e,t,s),this.parameter=r,this.body=i}clone(){const e=this.parameter.clone(),t=this.body.clone();return new j(this.identifier,this.visibility,this.location,e,t)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.parameter.toString(),r=this.body.toString();return`${e}set ${t}${this.identifier}(${s})${r}`}}class U extends D{parameters;body;isAsync;constructor(e,t,s,r,i,n=!1){super(e,t,s),this.parameters=r,this.body=i,this.isAsync=n}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new U(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.isAsync?"async ":"",r=this.parameters.map(e=>e.toString()),i=this.body.toString();return`${e}${s}${t}${this.identifier}(${r.join(",")})${i}`}}class q extends D{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new q(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${e}${t}${this.identifier}${s}`}}class G extends ${parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof k)}get fields(){return this.members.filter(e=>e instanceof q)}get getters(){return this.members.filter(e=>e instanceof B)}get setters(){return this.members.filter(e=>e instanceof j)}get methods(){return this.members.filter(e=>e instanceof U)}get publicFields(){return this.fields.filter(e=>"public"===e.visibility)}get publicGetters(){return this.getters.filter(e=>"public"===e.visibility)}get publicSetters(){return this.setters.filter(e=>"public"===e.visibility)}get publicMethods(){return this.methods.filter(e=>"public"===e.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(e){return this.members.find(t=>t.is(e))}hasMember(e){return this.members.some(t=>t.is(e))}getField(e){return this.fields.find(t=>t.is(e))}hasField(e){return this.fields.some(t=>t.is(e))}getGetter(e){return this.getters.find(t=>t.is(e))}hasGetter(e){return this.getters.some(t=>t.is(e))}getSetter(e){return this.setters.find(t=>t.is(e))}hasSetter(e){return this.setters.some(t=>t.is(e))}getMethod(e){return this.methods.find(t=>t.is(e))}hasMethod(e){return this.methods.some(t=>t.is(e))}canRead(e){return this.readable.some(t=>t.is(e))}canWrite(e){return this.writable.some(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new G(this.identifier,this.parent,e)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(e=>e.toString()).join("")}}`}}class H extends C{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new H(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class K extends C{code;constructor(e){super(),this.code=e}clone(){return new K(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class _ extends L{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new _(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier??"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function* ${t}(${s.join(",")})${r}`}}class W extends U{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new W(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier,s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}*${t}(${s.join(",")})${r}`}}class z extends x{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new z(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Y extends C{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Y(e,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(e=>e.toString()).join(",")}} from '${this.from}';`}}class X extends ${type;binding;initializer;constructor(e,t,s){super(t.toString()),this.type=e,this.binding=t,this.initializer=s}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new X(this.type,e,t)}toString(){const e=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",t=e.endsWith(";")?"":";";return`${this.type} ${this.identifier}${e}${t}`}}class Q{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof H)}get imports(){return this.statements.filter(e=>e instanceof Y)}get expressions(){return this.statements.filter(e=>e instanceof K)}get declarations(){return this.statements.filter(e=>e instanceof $)}get variables(){return this.statements.filter(e=>e instanceof X)}get functions(){return this.statements.filter(e=>e instanceof L)}get classes(){return this.statements.filter(e=>e instanceof G)}get exported(){const e=[];for(const t of this.exports)for(const s of t.members){const t=this.getDeclaration(s.identifier);void 0!==t&&e.push(t)}return e}get exportedVariables(){return this.exported.filter(e=>e instanceof X)}get exportedFunctions(){return this.exported.filter(e=>e instanceof L)}get exportedClasses(){return this.exported.filter(e=>e instanceof G)}getExport(e){return this.exports.find(t=>t.hasMember(e))}getImport(e){return this.imports.find(t=>t.hasMember(e))}hasDeclaration(e){return this.declarations.some(t=>t.is(e))}getDeclaration(e){return this.declarations.find(t=>t.is(e))}hasVariable(e){return this.variables.some(t=>t.is(e))}getVariable(e){return this.variables.find(t=>t.is(e))}hasFunction(e){return this.functions.some(t=>t.is(e))}getFunction(e){return this.functions.find(t=>t.is(e))}hasClass(e){return this.classes.some(t=>t.is(e))}getClass(e){return this.classes.find(t=>t.is(e))}clone(){const e=this.statements.map(e=>e.clone());return new Q(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class J{identifier;alias;constructor(e,t){this.identifier=e,this.alias=t}is(e){return this.alias===e||void 0===this.alias&&this.identifier===e}clone(){return new J(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class Z extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Z(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const ee={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},te=Object.values(ee);const se=".",re="(",ie=")",ne="[",oe="]",ae="{",ce="}",ue="_",le={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},he=Object.values(le);function pe(e){return he.includes(e)}const de={UNDEFINED:void 0,NULL:null,STRING:""},me=["null","undefined"],fe=Object.values(de);function ge(e){return fe.includes(e)}const Ee={OPEN:re,CLOSE:ie};function ye(e){return e===Ee.OPEN||e===Ee.CLOSE}const we={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally"},Se=Object.values(we),be=[we.IMPORT,we.EXPORT,we.VAR,we.LET,we.CONST,we.FUNCTION,we.CLASS,we.ASYNC],Ae=[we.VAR,we.LET,we.CONST,we.FUNCTION,we.CLASS,we.USING],Te=[we.AS,we.ASYNC,we.GET,we.SET,we.OF,we.YIELD,we.FROM,we.STATIC];function Ie(e){return be.includes(e)}function ve(e){return Te.includes(e)}const Oe={OPEN:ne,CLOSE:oe};function Ne(e){return e===Oe.OPEN||e===Oe.CLOSE}const Re=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xe(e){return Re.includes(e)}const Me={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},Ce=Object.values(Me);function $e(e){return Ce.includes(e)}const Le={OPEN:ae,CLOSE:ce};function Pe(e){return e===Le.OPEN||e===Le.CLOSE}const Fe={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},Ve={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},De=Object.values(Ve);function ke(e){return De.includes(e)}class Be{#y;#w;constructor(e){this.#y=e,this.#w=0}get items(){return this.#y}get position(){return this.#w}get size(){return this.#y.length}get eol(){return this.#w>=this.#y.length}get current(){return this.#y[this.#w]}get next(){return this.#y[this.#w+1]}get previous(){return this.#y[this.#w-1]}notAtEnd(){return!1===this.eol}get(e){return this.#y[e]}step(e=1){return this.#w+=e,this.current}stepBack(e=1){return this.#w-=e,this.current}hasNext(){return this.#w+1<this.#y.length}insert(...e){this.#y.splice(this.#w,0,...e)}}class je extends Be{constructor(e){super(e.split(""))}}class Ue{#s;#S;#b;#A;constructor(e,t,s,r){this.#s=e,this.#S=t,this.#b=s,this.#A=r}get type(){return this.#s}get value(){return this.#S}get start(){return this.#b}get end(){return this.#A}isType(e){return this.#s===e}hasValue(e){return this.#S===e}toString(){return`${this.#S}`}}class qe extends Be{}const Ge=["true","false"];const He=["0","1","2","3","4","5","6","7","8","9"],Ke=[...He,"a","b","c","d","e","f","A","B","C","D","E","F"],_e=["0","1"];function We(e){return He.includes(e)}const ze={GENERATOR:"*",PRIVATE:"#"},Ye=Object.values(ze);class Xe{tokenize(e){const t=new je(e),s=[];let r;for(;t.notAtEnd();){const e=this.#T(t,r);if(void 0===e)break;e.isType(Fe.WHITESPACE)||e.isType(Fe.COMMENT)?t.step():(s.push(e),this.#I(e)&&(r=e),t.step())}return new qe(s)}#I(e){return!1===[Fe.WHITESPACE,Fe.COMMENT].includes(e.type)}#T(e,t){const s=e.current,r=e.position;if(ke(s)){const t=e.position;return new Ue(Fe.WHITESPACE,s,r,t)}if(function(e){return te.includes(e)}(s+e.next)){const t=this.#v(e),s=e.position;return new Ue(Fe.COMMENT,t,r,s)}if(this.#O(s,t)){const t=this.#N(e),s=e.position;return new Ue(Fe.REGEX,t,r,s)}if(this.#R(e,t)){const t=this.#x(e),s=e.position;return new Ue(Fe.NUMBER,t,r,s)}if(xe(s)){const t=this.#M(e),s=e.position;return new Ue(Fe.LITERAL,t,r,s)}if($e(s)){const t=this.#C(e),s=e.position;return new Ue(Fe.OPERATOR,t,r,s)}if(function(e){return Ye.includes(e)}(s)){const t=this.#C(e),s=e.position;return new Ue(Fe.INDICATOR,t,r,s)}if(pe(s)){const t=e.position;return new Ue(Fe.DIVIDER,s,r,t)}if(ye(s)){const t=e.position;return new Ue(Fe.GROUP,s,r,t)}if(Pe(s)){const t=e.position;return new Ue(Fe.SCOPE,s,r,t)}if(Ne(s)){const t=e.position;return new Ue(Fe.LIST,s,r,t)}if(ge(s))return;const i=this.#$(e),n=e.position;return function(e){return Se.includes(e)}(i)?new Ue(Fe.KEYWORD,i,r,n):function(e){return Ge.includes(e)}(i)?new Ue(Fe.BOOLEAN,i,r,n):function(e){return me.includes(e)}(i)?new Ue(Fe.NOTHING,i,r,n):new Ue(Fe.IDENTIFIER,i,r,n)}#v(e){const t=e.current+e.next===ee.MULTI_START,s=t?ee.MULTI_END:Ve.NEWLINE;let r=t?ee.MULTI_START:ee.SINGLE;for(e.step(2);e.notAtEnd();){const i=e.current;if((t?i+e.next:i)===s){e.step(s.length-1);break}r+=i,e.step()}return t?r+ee.MULTI_END:r.trim()}#O(e,t){return e===Me.DIVIDE&&(void 0===t||([Fe.OPERATOR,Fe.DIVIDER,Fe.KEYWORD].includes(t.type)||[Ee.OPEN,Oe.OPEN].includes(t.value)))}#L(e){return ke(e)||e==se||!1===this.#P(e)}#N(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Me.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#L(r)){e.stepBack();break}t+=r,e.step()}return t}#R(e,t){const s=e.current,r=e.next;return!!We(s)||s===Me.SUBTRACT&&(!t?.isType(Fe.NUMBER)&&We(r))}#F(e,t,s){return t?!1===(r=e,Ke.includes(r))&&e!==ue:s?!1===function(e){return _e.includes(e)}(e)&&e!==ue:!1===We(e)&&e!==se&&e!==ue&&"e"!==e;var r}#x(e){let t=e.current;t===Me.SUBTRACT&&(t+=e.step()),e.step();const s="x"===e.current,r="b"===e.current;for((s||r)&&(t+=e.current,e.step());e.notAtEnd();){const i=e.current;if(this.#F(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#M(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const i=e.current;if(!1===r){if(i===t){s+=i;break}"\\"===i&&(r=!0)}else r=!1;s+=i,e.step()}return s}#P(e){return!1===(ge(e)||ke(e)||$e(e)||xe(e)||pe(e)||ye(e)||Pe(e)||Ne(e))}#$(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#P(s)){e.stepBack();break}t+=s,e.step()}return t}#C(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===$e(s)||!1===$e(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Qe extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Je extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Ze extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class et extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class tt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const st=new Ue(Fe.NONE,"",-1,0);class rt{#V;constructor(e=[]){this.#V=e}get tokens(){return this.#V}append(...e){this.#V.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="";for(let t=0;t<this.#V.length;t++){const s=this.#V[t-1]??st,r=this.#V[t],i=this.#V[t+1]??st,n=this.#D(s,r)?" ":"",o=this.#k(r,i)?" ":"";e+=`${n}${r.value}${o}`}return e}#D(e,t){return!(!t.isType(Fe.KEYWORD)||!this.#B(e))||!(!t.isType(Fe.OPERATOR)||!e.isType(Fe.OPERATOR))}#k(e,t){return e.isType(Fe.KEYWORD)&&(t.isType(Fe.KEYWORD)||this.#B(t))}#B(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.isType(Fe.NUMBER)}}const it="default";class nt{#j;constructor(e=new Xe){this.#j=e}parse(e){const t=this.#j.tokenize(e),s=this.#U(t);return new Q(s)}parseStatement(e){const t=this.#j.tokenize(e),s=this.#q(t);if(void 0===s)throw new et("a statement");return s}parseImport(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof Y==!1)throw new et("an import definition");return s}parseExport(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof H==!1)throw new et("an export definition");return s}parseVariable(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof X==!1)throw new et("a variable definition");return s}parseFunction(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof L==!1)throw new et("a function definition");return s}parseClass(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof G==!1)throw new et("a class definition");return s}#U(e){const t=[];for(;e.notAtEnd();){const s=this.#q(e);void 0!==s&&t.push(s)}return t}#q(e,t=!1){const s=e.current;if(this.#H(s))return this.#K(e);if(s.isType(Fe.IDENTIFIER)){const s=e.next;return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#K(e)}if(s.isType(Fe.KEYWORD)){if(ve(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(we.FUNCTION)||t.hasValue(Ee.OPEN));if(s.hasValue(we.ASYNC)&&r)return e.step(),this.#q(e,!0);if(void 0===t||this.#W(t))return this.#K(e)}return s.hasValue(we.RETURN)?this.#K(e):!1===Ie(s.value)?this.#K(e):this.#G(e,t)}if(s.isType(Fe.REGEX))return this.#K(e);if(s.hasValue(Ee.OPEN)){const s=this.#z(e,Ee.OPEN,Ee.CLOSE);return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#K(e)}if(s.hasValue(Le.OPEN))return this.#K(e);if(s.hasValue(Oe.OPEN))return this.#K(e);if(s.hasValue(Me.NOT)||s.hasValue(Me.SUBTRACT))return this.#K(e);if(!pe(s.value))throw new tt(s.value,s.start);e.step()}#H(e){return e.isType(Fe.LITERAL)||e.isType(Fe.NUMBER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.hasValue(we.NEW)}#G(e,t=!1){const s=e.current;switch(e.step(),s.value){case we.IMPORT:return this.#Y(e);case we.EXPORT:return this.#X(e);case we.CLASS:return this.#Q(e);case we.FUNCTION:return this.#J(e,t);case we.VAR:return this.#Z(e,"var");case we.LET:return this.#Z(e,"let");case we.CONST:return this.#Z(e,"const");case we.ASYNC:return this.#q(e,!0);default:throw new Ze(s.value,s.start)}}#Y(e){const t=[];let s=e.current;if(s.isType(Fe.LITERAL)){const e=this.#ee(s.value);return new Y(t,e)}if(s.hasValue(Ee.OPEN)){s=e.step();const r=this.#ee(s.value);return e.step(2),new Y(t,r)}if(!1===s.hasValue(Le.OPEN)){const r=s.hasValue(Me.MULTIPLY)?Me.MULTIPLY:it;let i=s.value;s=e.step(),s.hasValue(we.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new J(r,i))}if(s.hasValue(le.SEPARATOR)&&(s=e.step()),s.hasValue(Le.OPEN)){const r=this.#te(e);t.push(...r),s=e.current}if(!1===s.hasValue(we.FROM))throw new Qe(we.FROM,s.start);s=e.step();const r=this.#ee(s.value);return e.step(),new Y(t,r)}#X(e){switch(e.current.value){case we.DEFAULT:return e.step(),this.#se(e,!0);case Le.OPEN:return this.#re(e);default:return this.#se(e,!1)}}#se(e,t){let s=e.current,r=0;if(t&&this.#ie(e)){const t=`$_EXPORT_${s.start}_${s.end}`;e.insert(new Ue(Fe.KEYWORD,we.CONST,0,0),new Ue(Fe.IDENTIFIER,t,0,0),new Ue(Fe.OPERATOR,Me.ASSIGN,0,0)),s=e.current}var i;s.hasValue(we.ASYNC)&&(s=e.step(),r++),i=s.value,Ae.includes(i)&&(s=e.step(),r++);const n=this.#P(s)?s.value:"",o=t?it:void 0;let a;s=e.step(),s?.hasValue(we.FROM)&&(s=e.step(),a=this.#ee(s.value)),r>0&&(r++,e.stepBack(r));const c=new J(n,o);return new H([c],a)}#ie(e){const t=e.current;if(this.#H(t))return!0;const s=e.next;return this.#P(t)&&s?.hasValue(Ee.OPEN)}#re(e){const t=this.#te(e);let s,r=e.current;return r?.hasValue(we.FROM)&&(r=e.step(),s=this.#ee(r.value)),e.step(),new H(t,s)}#ee(e){return e.slice(1,-1)}#te(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Le.CLOSE)){e.step();break}if(s.hasValue(le.SEPARATOR)){s=e.step();continue}const r=this.#ne(e);t.push(r),s=e.step()}return t}#ne(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(we.AS)&&(t=e.step(2),r=t.value),new J(s,r)}#Z(e,t){const s=this.#oe(e),r=this.#ae(e);return new X(t,s,r)}#oe(e){const t=e.current;return t.hasValue(Oe.OPEN)?this.#ce(e):t.hasValue(Le.OPEN)?this.#ue(e):this.#le(e)}#ce(e){const t=this.#he(e,Oe.CLOSE);return new M(t)}#ue(e){const t=this.#he(e,Le.CLOSE);return new Z(t)}#he(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(le.SEPARATOR)){e.step();continue}const i=this.#oe(e),n=this.#ae(e),o=new F(i,n);s.push(o)}return s}#le(e){let t=e.current,s=!1;t.hasValue(Me.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new z(r,s)}#ae(e){const t=e.current;if(!1!==t.hasValue(Me.ASSIGN))return e.step(),this.#q(e,!1);t.hasValue(le.TERMINATOR)&&e.step()}#J(e,t){let s,r=e.current,i=!1;r.hasValue(ze.GENERATOR)&&(i=!0,r=e.step()),this.#P(r)&&(s=r.value,e.step());const n=this.#he(e,Ee.CLOSE);if(r=e.current,!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const o=this.#pe(e);return i?new _(s,n,o,t):new L(s,n,o,t)}#_(e,t){let s,r,i=e.current;if(i.hasValue(Ee.OPEN))s=this.#he(e,Ee.CLOSE);else{const t=this.#le(e);s=[new F(t,void 0)]}if(i=e.current,!1===i.hasValue(Me.ARROW))throw new Je(Me.ARROW,i.start);if(i=e.step(),i.hasValue(Le.OPEN))r=this.#pe(e);else{const t=this.#K(e);r=new V(t.code)}return new P(s,r,t)}#Q(e){let t,s,r=e.current;if(this.#P(r)&&(t=r.value,r=e.step()),r.hasValue(we.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const i=this.#de(e);return new G(t,s,i)}#de(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Le.CLOSE)){e.step();break}const r=this.#me(e);s.push(r),t=e.current}return s}#me(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(ze.PRIVATE))s="private";else if(t.hasValue(we.STATIC))r="static";else{if(!t.hasValue(we.ASYNC)){if(t.hasValue(we.CONSTRUCTOR))return this.#fe(e);if(t.hasValue(we.GET))return this.#ge(e,r);if(t.hasValue(we.SET))return this.#Ee(e,r);if(t.hasValue(ze.GENERATOR))return e.step(),this.#ye(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(Ee.OPEN)?this.#ye(e,s,r,i,!1):this.#we(e,s,r)}#fe(e){e.step();const t=this.#he(e,Ee.CLOSE),s=e.current;if(!1===s.hasValue(Le.OPEN))throw new Je(Le.OPEN,s.start);const r=this.#pe(e);return new k(t,r)}#ge(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#he(e,Ee.CLOSE).length)throw new et("an empty parameter list");if(r=e.current,!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const n=this.#pe(e);return new B(i,s,t,n)}#Ee(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#he(e,Ee.CLOSE);if(r=e.current,1!==n.length)throw new et("exactly one setter parameter");if(!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const o=this.#pe(e);return new j(i,s,t,n[0],o)}#ye(e,t,s,r,i){let n=e.current;const o=n.value;e.step();const a=this.#he(e,Ee.CLOSE);if(n=e.current,!1===n.hasValue(Le.OPEN))throw new Je(Le.OPEN,n.start);const c=this.#pe(e);return i?new W(o,t,s,a,c,r):new U(o,t,s,a,c,r)}#we(e,t,s){const r=e.current.value;e.step();const i=this.#ae(e);return new q(r,t,s,i)}#pe(e){const t=this.#Se(e,Le.OPEN,Le.CLOSE).generate();return new V(t)}#K(e){const t=new rt;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Oe.OPEN)){const r=this.#Se(e,Oe.OPEN,Oe.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Ee.OPEN)){const r=this.#Se(e,Ee.OPEN,Ee.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Le.OPEN)){const r=this.#Se(e,Le.OPEN,Le.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#W(s)){s.hasValue(le.TERMINATOR)&&e.step();break}}const r=t.generate();return new K(r)}#Se(e,t,s){let r=e.current;const i=new rt([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#Se(e,t,s);i.merge(n),r=e.current;continue}if(r.hasValue(s))return e.step(),i.append(r),i;i.append(r),r=e.step()}return i}#z(e,t,s){const r=e.position;this.#Se(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#W(e){return[le.TERMINATOR,le.SEPARATOR].includes(e.value)||[Oe.CLOSE,Ee.CLOSE,Le.CLOSE].includes(e.value)||Ie(e.value)}#P(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.KEYWORD)&&ve(e.value)}}let ot=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}};class at{#p;#d=new I;constructor(e){this.#p=e}rewrite(e,t){e.imports.forEach(e=>this.#be(e,t)),e.exports.forEach(e=>this.#Ae(e,t))}#be(e,t){const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Te(t,s))}#Ae(e,t){if(void 0===e.from)return;const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Te(t,s))}#Te(e,t){const s=this.#d.extractPath(e),r=this.#d.makePathAbsolute(t,s,"");return this.#p.isDirectory(r)?`${t}/${E}`:this.#d.assureExtension(t)}}let ct=class{#p;#Ie;#ve;constructor(e,t=new nt){this.#p=e,this.#Ie=t,this.#ve=new at(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new R(t)}async read(e){try{const t=this.#p.getRelativeLocation(e),s=await this.#Oe(e),r=this.#Ie.parse(s);return this.#ve.rewrite(r,t),new N(t,r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new ot(e,s)}}async#Oe(e){return(await this.#p.getContent(e)).toString()}},ut=class{#Ne;#E=new Map;#Re=new Map;#xe=new Map;constructor(e){this.#Ne=e}get name(){return this.#Ne}get modules(){return[...this.#E.values()]}get classes(){return[...this.#Re.values()]}get procedures(){return[...this.#xe.values()]}hasModule(e){return this.#E.has(e)}getModule(e){return this.#E.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#E.set(e.filename,e)}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}setProcedure(e){this.#xe.set(e.fqn,e)}setClass(e){this.#Re.set(e.fqn,e)}};class lt{#l;#Me;#Ce;constructor(e,t,s){this.#l=e,this.#Me=t,this.#Ce=s}get id(){return this.#l}get importKey(){return this.#Me}get fqn(){return this.#Ce}}class ht extends lt{#g;constructor(e,t,s,r){super(e,t,s),this.#g=r}get model(){return this.#g}}class pt extends lt{#$e;#Le;#g;constructor(e,t,s,r,i,n){super(e,t,s),this.#$e=r,this.#Le=i,this.#g=n}get access(){return this.#$e}get version(){return this.#Le}get model(){return this.#g}}class dt{#t;#e;#Pe;#Fe=[];#Ve;constructor(e,t,s,r){this.#t=e,this.#e=t,this.#Pe=s,this.#Ve=r}get filename(){return this.#t}get location(){return this.#e}get imports(){return this.#Pe}get members(){return this.#Fe}get segmented(){return this.#Ve}hasClasses(){return this.#Fe.some(e=>e instanceof ht)}getClasses(){return this.#Fe.filter(e=>e instanceof ht)}hasImplementations(){return this.#Fe.some(e=>e instanceof pt)}getImplementations(){return this.#Fe.filter(e=>e instanceof pt)}addMember(e){this.#Fe.push(e)}addImports(e){const t=Object.keys(e);for(const s of t){const t=s.trim();this.#Pe[t]=e[s]}}}class mt{#Ce;#De=[];constructor(e,t=[]){this.#Ce=e,this.#De=t}get fqn(){return this.#Ce}get implementations(){return this.#De}addImplementation(e){this.#De.push(e)}}class ft{#ke;constructor(e){this.#ke=e}get segments(){return this.#ke}getSegment(e){return this.#ke.find(t=>t.name===e)}isSegmentedModule(e){return this.#ke.some(t=>t.hasModule(e))}getSegments(e){return this.#ke.filter(t=>t.hasModule(e))}}class gt extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class Et extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class yt extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class wt extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class St extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class bt extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class At{#a;#d=new I;constructor(e){this.#a=e}locate(e,t){const s=[];return{trace:s,model:this.#Be(e,t,s)}}#Be(e,t,s){s.push({filename:e,importKey:t});const r=this.#je(e);return this.#Ue(r,t)?this.#qe(r,t,s):this.#Ge(r,t)}#je(e){const t=this.#a.get(e);if(void 0===t)throw new bt(e);return t}#Ue(e,t){const s=e.model.getImport(t),r=e.model.getExport(t);return void 0!==s||void 0!==r?.from}#qe(e,t,s){const r=this.#He(e,t)??this.#Ke(e,t),i=r?.from,n=r?.name,o=this.#d.extractPath(e.filename),a=i,c=this.#d.makePathAbsolute(a,o,"");return this.#Be(c,n,s)}#Ge(e,t){const s=this.#Ke(e,t);if(void 0===s)throw new St(e.filename,t);const r=e.model.getDeclaration(s.name);if(void 0===r)throw new St(e.filename,s.name);return r}#Ke(e,t){const s=e.model.getExport(t),r=s?.getMember(t);if(void 0!==r)return{from:s?.from,name:r.identifier}}#He(e,t){const s=e.model.getImport(t),r=s?.getMember(t);if(void 0!==s&&void 0!==r)return{from:s.from,name:r.identifier}}}class Tt{#_e;#p;#We;#d=new I;constructor(e,t,s){this.#_e=e,this.#p=t,this.#We=new At(s)}async readAll(e){const t=await Promise.all(e.map(e=>this.#ze(e)));return new ft(t)}async#ze(e){const t=await this.#Ye(e),s=this.#Xe(e),r=new ut(s);return this.#Qe(r,t),this.#Je(r),r}#Xe(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new Et(e);return t.replace(y,"")}async#Ye(e){try{const t=await this.#_e.getContent(e);return JSON.parse(t.toString())}catch(t){const s=t instanceof Error?t.message:String(t);throw new yt(e,s)}}#Qe(e,t){for(const[s,r]of Object.entries(t))this.#Ze(e,s,r,!0)}#Ze(e,t,s,r){const i=this.#et(t),n=this.#d.extractPath(i),o=e.hasModule(i)?e.getModule(i):new dt(i,n,{},r);o.addImports(s),e.setModule(o)}#et(e){const t=e.trim(),s=this.#p.normalizeLocation(t),r=this.#p.isDirectory(s)?`${s}/${E}`:this.#d.assureExtension(s);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#Je(e){const t=new S;for(const s of e.modules)for(const r in s.imports)this.#tt(e,s,r,t)}#tt(e,t,s,r){const{model:i,trace:n}=this.#We.locate(t.filename,s),o=this.#st(t,i,s,r);this.#rt(e,t,i,o),n.shift();for(const t of n){const s={[t.importKey]:{access:o.access}};this.#Ze(e,t.filename,s,!1)}}#st(e,t,s,r){const i=e.imports[s],n=r.next(),o=i.as??t.identifier;return{id:n,importKey:s,name:o,access:i.access??f,version:i.version??g,fqn:this.#it(e,o,s)}}#it(e,t,s){return this.#nt(e)?t:this.#ot(e)&&this.#at(s)?e.location:`${e.location}/${t}`}#nt(e){return""===e.location}#ot(e){return e.filename.endsWith(E)}#at(e){return e===w}#rt(e,t,s,r){if(s instanceof G)return this.#ct(e,t,s,r);if(s instanceof L)return this.#ut(e,t,s,r);throw new wt(t.filename,r.importKey)}#ct(e,t,s,r){const i=new ht(r.id,r.importKey,r.fqn,s);t.addMember(i),e.setClass(i)}#ut(e,t,s,r){if(!1===s.isAsync)throw new gt(t.filename,r.name);const i=new pt(r.id,r.importKey,r.fqn,r.access,r.version,s);this.#lt(e,t,i)}#lt(e,t,s){const r=e.hasProcedure(s.fqn)?e.getProcedure(s.fqn):new mt(s.fqn);r.addImplementation(s),t.addMember(s),e.setProcedure(r)}}class It{#ht;constructor(e){this.#ht=e}async read(e,t,s){const r=this.#ht.source,i=this.#ht.resource,n=this.#ht.segment,o=new ct(r),a=await o.readAll(e),c=new O(i,r),u=await c.readAll(t),l=new Tt(n,r,a),h=await l.readAll(s);return new d(a,u,h)}}class vt extends Error{constructor(e){super(`Could not find the rewrite item: ${e}`)}}class Ot{#pt;#c;#u;#dt;#d=new I;constructor(e,t,s,r){this.#pt=e,this.#c=t,this.#u=s,this.#dt=r}generate(){const e=this.#pt.model.clone();return this.#mt(e,e.imports),this.#mt(e,e.exports),e.toString()}#mt(e,t){for(const s of t){const t=this.#ft(s);if(0===t.length)continue;const r=e.statements.indexOf(s);if(-1===r)throw new vt(s.toString());e.statements.splice(r,1,...t)}}#ft(e){if(this.#gt(e))return[];const t=this.#Et(e);return this.#c.isResourceModule(t)?this.#yt(e,t):this.#wt(e,t)}#gt(e){return void 0===e.from||this.#St(e)}#St(e){return!1===this.#d.isApplicationModule(e.from)}#Et(e){const t=e.from,s=this.#d.extractPath(this.#pt.filename);return this.#d.makePathAbsolute(t,s,"")}#yt(e,t){const s=e.clone();return s.from=this.#bt(t),[s]}#wt(e,t){if(0===e.members.length)return[this.#At(t,e,[])];const{segmentKeys:s,remoteKeys:r,commonKeys:i}=this.#Tt(t,e),n=[];return s.length>0&&n.push(this.#It(t,e,s)),r.length>0&&n.push(this.#vt(t,e,r)),i.length>0&&n.push(this.#At(t,e,i)),n}#Tt(e,t){const s=this.#Ot(e,this.#dt),r=this.#Nt(e,s),i=this.#Rt(t,s),n=this.#Rt(t,r);return{segmentKeys:i,remoteKeys:n,commonKeys:this.#xt(t,[...i,...n])}}#Ot(e,t){if(void 0===t)return[];const s=t.getModule(e);return void 0===s?[]:Object.keys(s.imports)}#Nt(e,t){const s=this.#u.getSegments(e).filter(e=>e!==this.#dt).flatMap(t=>this.#Ot(e,t));return[...new Set(s)].filter(e=>!1===t.includes(e))}#Rt(e,t){return e.members.filter(e=>t.includes(e.identifier)).map(e=>e.identifier)}#xt(e,t){return e.members.filter(e=>!1===t.includes(e.identifier)).map(e=>e.identifier)}#It(e,t,s){const r=t.clone();return r.from=this.#bt(e,this.#dt?.name),r.members=this.#Mt(t.members,s),r}#vt(e,t,s){const r=t.clone();return r.from=this.#bt(e,"remote"),r.members=this.#Mt(t.members,s),r}#At(e,t,s){const r=t.clone();return r.from=this.#bt(e),r.members=this.#Mt(t.members,s),r}#Mt(e,t){const s=[];for(const r of t){const t=e.find(e=>e.identifier===r);void 0!==t&&s.push(t)}return s}#bt(e,t){const s=this.#d.extractPath(this.#pt.filename),r=this.#d.makePathRelative(e,s);return void 0!==t?this.#d.addSubExtension(r,t):r}}const Nt={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class Rt extends Error{constructor(e="Invalid request"){super(e)}}class xt extends Error{constructor(e="Forbidden"){super(e)}}class Mt extends Error{constructor(e="Not found"){super(e)}}class Ct extends Error{constructor(e="Not implemented"){super(e)}}class $t extends Error{constructor(e="Payment required"){super(e)}}class Lt extends Error{constructor(e="Server error"){super(e)}}class Pt extends Error{constructor(e="I'm a teapot"){super(e)}}class Ft extends Error{constructor(e="Unauthorized"){super(e)}}class Vt{#l;#Re=new Map;#xe=new Map;constructor(e){this.#l=e}get id(){return this.#l}addClass(e){return this.#Re.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#Re.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#Re.values()]}addProcedure(e){return this.#xe.set(e.fqn,e),this}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}getExposedProcedures(){return[...this.#xe.values()].filter(e=>e.public||e.protected)}}class Dt{static get DEFAULT(){return new Dt(0,0,0)}#Ct;#$t;#Lt;constructor(e=0,t=0,s=0){this.#Ct=e,this.#$t=t,this.#Lt=s}get major(){return this.#Ct}get minor(){return this.#$t}get patch(){return this.#Lt}equals(e){return this.#Ct===e.major&&this.#$t===e.minor&&this.#Lt===e.patch}greater(e){return this.#Ct!==e.major?this.#Ct>e.major:this.#$t!==e.minor?this.#$t>e.minor:this.#Lt!==e.patch&&this.#Lt>e.patch}less(e){return this.#Ct!==e.major?this.#Ct<e.major:this.#$t!==e.minor?this.#$t<e.minor:this.#Lt!==e.patch&&this.#Lt<e.patch}toString(){return`${this.#Ct}.${this.#$t}.${this.#Lt}`}}class kt{#Ne;#Pt;constructor(e,t=!1){this.#Ne=e,this.#Pt=t}get name(){return this.#Ne}get isOptional(){return this.#Pt}}class Bt extends kt{}class jt extends kt{#Ft;constructor(e,t,s){super(t??"(anonymous)",s),this.#Ft=e}get variables(){return this.#Ft}}class Ut extends jt{}class qt extends jt{}class Gt{#Ce;#Le;#Vt;#Dt=new Map;#kt;constructor(e,t,s,r,i){this.#Ce=e,this.#Le=t,this.#Vt=s,this.#Dt=r,this.#kt=i}get fqn(){return this.#Ce}get version(){return this.#Le}get args(){return this.#Vt}get headers(){return this.#Dt}get mode(){return this.#kt}clearArguments(){this.#Vt.clear()}setArgument(e,t){this.#Vt.set(e,t)}getArgument(e){return this.#Vt.get(e)}hasArgument(e){return this.#Vt.has(e)}removeArgument(e){this.#Vt.delete(e)}clearHeaders(){this.#Dt.clear()}setHeader(e,t){this.#Dt.set(e.toLowerCase(),t)}getHeader(e){return this.#Dt.get(e.toLowerCase())}hasHeader(e){return this.#Dt.has(e.toLowerCase())}removeHeader(e){this.#Dt.delete(e.toLowerCase())}}class Ht{#Bt;#jt;#Dt;constructor(e,t=void 0,s=new Map){this.#Bt=e,this.#jt=t,this.#Dt=s}get status(){return this.#Bt}get result(){return this.#jt}set result(e){this.#jt=e}get headers(){return this.#Dt}clearHeaders(){this.#Dt.clear()}setHeader(e,t){this.#Dt.set(e.toLowerCase(),t)}getHeader(e){return this.#Dt.get(e.toLowerCase())}hasHeader(e){return this.#Dt.has(e.toLowerCase())}removeHeader(e){this.#Dt.delete(e.toLowerCase())}}class Kt{#pt;#ke;constructor(e,t){this.#pt=e,this.#ke=t}generate(){const e=[],t=this.#Ut();for(const s of t){const t=s.access===Nt.PRIVATE?this.#qt(s):this.#Gt(s);e.push(...t)}return new Q(e).toString()}#Ut(){const e=this.#ke.map(e=>e.getModule(this.#pt.filename)).flatMap(e=>e.getImplementations()),t=new Map;for(const s of e){const e=`${s.fqn}:${s.version.toString()}`;t.set(e,s)}return[...t.values()]}#qt(e){const t=`throw new ProcedureNotAccessible('${e.fqn}','${e.version}');`;return[this.#Ht(e),this.#Kt(e,t)]}#Gt(e){const t=`return __run('${e.fqn}','${e.version}',{${this.#_t(e.model.parameters)}},this);`;return[this.#Ht(e),this.#Kt(e,t)]}#Ht(e){const t=e.model.identifier,s=e.importKey===w?w:void 0,r=new J(t,s);return new H([r],void 0)}#Kt(e,t){const s=e.model.identifier,r=e.model.parameters,i=new V(`{${t}}`),n=e.model.isAsync;return new L(s,r,i,n)}#_t(e){return this.#Wt(e).join(",")}#Wt(e){const t=[];for(const s of e)if(s.binding instanceof z){const e=this.#zt(s.binding);t.push(e)}else if(s.binding instanceof M){const e=this.#Wt(s.binding.elements);t.push(...e)}else if(s.binding instanceof Z){const e=this.#Wt(s.binding.elements);t.push(...e)}return t}#zt(e){return`'${e.identifier}':${e.toString()}`}}class _t{#Yt;#Xt;#Qt;#dt;constructor(e,t,s,r){this.#Yt=e,this.#Xt=t,this.#Qt=s,this.#dt=r}get source(){return this.#Yt}get target(){return this.#Xt}get resource(){return this.#Qt}get segment(){return this.#dt}}class Wt{#Jt;constructor(e=!0){this.#Jt=e}validate(e,t){const s=[];this.#Zt("",e,t,s);return{valid:0===s.length,errors:s}}#Zt(e,t,s,r){this.#Jt&&this.#es(e,t,s,r),this.#ts(e,t,s,r)}#es(e,t,s,r){const i=Object.keys(t),n=Object.keys(s);for(const t of i)if(!1===n.includes(t)){const s=this.#ss(e,t);r.push(`Unknown field '${s}'`)}}#ts(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#ss(e,n),o=s[n],a=t[n];this.#rs(i,a,o,r)}}#rs(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#is(e,t,s,r);case"integer":return this.#ns(e,t,s,r);case"real":return this.#os(e,t,s,r);case"boolean":return this.#as(e,t,s,r);case"url":return this.#cs(e,t,s,r);case"group":return this.#us(e,t,s,r);case"list":return this.#ls(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#is(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#ns(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#os(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#as(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#cs(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#us(e,t,s,r){"object"==typeof t?this.#Zt(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#ls(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const i=t;for(const t in i){const n=this.#ss(e,t),o=i[t];this.#rs(n,o,s.items,r)}}#ss(e,t){return""===e?t:`${e}.${t}`}}class zt{#hs;constructor(e){this.#hs=e}async configure(e){const t=this.#hs.getAbsoluteLocation(e);n.config({path:t})}}class Yt extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Xt="./jitar.json",Qt="./src",Jt="./dist",Zt="./segments",es="./resources",ts={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let ss=class{#ps;#ds;constructor(e,t){this.#ps=e,this.#ds=t}async build(e=Xt){const t=await this.#ps.read(e),s=this.#ds.validate(t,ts);if(!1===s.valid)throw new Yt(s);return t.source??=Qt,t.target??=Jt,t.segments??=Zt,t.resources??=es,t.meta={root:this.#ps.getRootLocation(),configFile:e},t}};const rs="\n => ";class is extends Error{constructor(e){const t=e.errors.join(rs);super(`Invalid server configuration:${rs}${t}`)}}const ns={indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assetRoot:{type:"string",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}},os={gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}},as={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:ns},standalone:{type:"group",required:!1,fields:{...ns,segments:os.segments}},worker:{type:"group",required:!1,fields:os},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class cs{#ps;#ds;constructor(e,t){this.#ps=e,this.#ds=t}async build(e){const t=await this.#ps.read(e),s=this.#ds.validate(t,as);if(!1===s.valid)throw new is(s);return t.meta={root:this.#ps.getRootLocation(),configFile:e},t}}class us extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const ls=/\${([^}]*)}/g;class hs{#hs;constructor(e){this.#hs=e}getRootLocation(){return this.#hs.getAbsoluteLocation(".")}async read(e){if(!1===await this.#hs.exists(e))return{};const t=await this.#hs.read(e);if(!1===t.type.includes("json"))throw new us(e);const s=t.content.toString(),r=this.#ms(s);return this.#fs(r)}#ms(e){return e.replace(ls,(e,t)=>process.env[t]??"null")}#fs(e){return JSON.parse(e)}}class ps{#gs;#Es;#ys;constructor(e="./"){const t=new p(e),s=new hs(t),r=new Wt;this.#gs=new zt(t),this.#Es=new ss(s,r),this.#ys=new cs(s,r)}configureEnvironment(e=".env"){return this.#gs.configure(e)}getRuntimeConfiguration(e){return this.#Es.build(e)}getServerConfiguration(e){return this.#ys.build(e)}}export{Ut as A,Rt as B,ps as C,c as D,G as E,xt as F,Gt as G,Nt as H,p as L,Mt as N,qt as O,nt as P,Ht as R,Lt as S,Pt as T,Ft as U,Dt as V,z as a,K as b,X as c,Q as d,q as e,k as f,B as g,j as h,U as i,Bt as j,Ct as k,$t as l,Vt as m,I as n,Ot as o,Kt as p,Y as q,J as r,H as s,M as t,Z as u,_t as v,It as w,o as x,Wt as y,u as z};
|