jitar 0.11.3 → 0.12.0
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.
|
@@ -1 +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};
|
|
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={directoryIndex:{type:"string",required:!1},fallback:{type:"string",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)}getServiceConfiguration(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 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}
|
|
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 l,d as u,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 S,l as x,T as k,U as P,S as A,m as z,R,n as E,o as C,p as H,G as T,q as O,r as I,s as N,C as j,V as $,t as L,u as W,v as B,w as q,x as D}from"./ConfigurationManager-CQWv0Wmk.js";import F 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.12.0")}}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.#l(),this.#c=this.#u(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)}#l(){const e=r.dirname(s(import.meta.url));return r.join(e,"templates")}#u(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;#S=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 l("var",t,a))}}return new u(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#x(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.#S.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")}#x(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 le extends Error{constructor(e,t){super(`Failed building module for '${e}'`,{cause:t})}}const ue="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 Se extends f{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class xe 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 xe(e)}return s}#C(e,t){const r=new Map;for(const[s,a]of t){if(this.#T(s)){const t=this.#O(s);!0===this.#I(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#T(e){return e.startsWith("*")}#O(e){return e.substring(1)}#I(e,t){return void 0!==e.find(e=>e.name===t)}#H(e,t,r){return e instanceof v?this.#N(e,t,r):this.#j(e,t)}#N(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.#W(e,t):this.#B(e,t)}#W(e,t){const r=this.#q(e,t);return void 0!==r?Object.values(r):void 0}#B(e,t){return this.#q(e,t)}#q(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,l=this.#H(o,t,e);void 0!==l?n=!0:!1===o.isOptional&&a.push(o.name),s[c]=l}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 S?be:e instanceof x?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 S(t);case me:return new x(t);case ye:return new k(t);case ge:return new P(t);default:return new A(t)}}}class Re extends w{#R;#D;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#R=e,this.#D=t}get fqn(){return this.#R}get version(){return this.#D}}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 Te{#F=new Map;addSegment(e){this.#F.set(e.id,e)}clearSegments(){this.#F.clear()}getClassNames(){const e=new Set;for(const t of this.#F.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.#F.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#F.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#F.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.#F.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Oe{#V;#K;#U=new Ae;#_=new ze;#G=new Te;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 Ie=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 le(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 Ne 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 T(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 Ne(e.name,t)}}};class $e{#oe;#ce;constructor(e,t){const r=e.target;this.#oe=new Ie(r),this.#ce=new je(r,t)}async build(e){await Promise.all([this.#oe.build(e),this.#ce.build(e)])}}const Le=0,We=1,Be=2,qe=3,De=4;class Fe{#le;#ue;constructor(e=We,t=console){this.#le=e,this.#ue=t}debug(...e){if(this.#le>Le)return;const t=this.#he("DEBUG",e);this.#ue.debug(t)}info(...e){if(this.#le>We)return;const t=this.#he("INFO",e);this.#ue.info(t)}warn(...e){if(this.#le>Be)return;const t=this.#he("WARN",e);this.#ue.warn(t)}error(...e){if(this.#le>qe)return;const t=this.#he("ERROR",e);this.#ue.error(t)}fatal(...e){const t=this.#he("FATAL",e);this.#ue.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 We;case"WARN":return Be;case"ERROR":return qe;case"FATAL":return De;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 Fe(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 O(new a(r),new a(s),new a(n),new a(i),e.build.ignore),this.#me=new I(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(N.MODULE_PATTERN,this.#y.sourceIgnores),a=await t.filter(N.RESOURCE_PATTERN),n=await r.filter(N.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.#Se(t)},i=await this.#Me(a,n,!1),o=i.status,c=await this.#xe(i),l=this.#ke(i);return new R(o,c,l)}async#Me(e,t,r=!0){const s=await this.#ve.execute(e,t);if(r&&this.#Pe(s)){const e=await this.#xe(s);throw this.#_.fromStatus(s.status,String(e))}return s}#Pe(e){return e.status<200||e.status>399}async#Se(e){return JSON.stringify(e)}async#xe(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 S}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 S}}class lt{get url(){throw new S}get state(){return ot.AVAILABLE}get trustKey(){throw new S}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 S}hasProcedure(e){throw new S}run(e){throw new S}}class ut{#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;#Te=new ut;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.#Te.state}get trustKey(){return this.#Ee}async start(){return this.#Te.start(async()=>{await this.#Ce.start(),this.#He.start(),await this.updateState()})}async stop(){return this.#Te.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.#Te.setAvailability(e)}async addWorker(e){if(this.#Oe(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)}#Oe(e){return void 0!==this.#Ee&&e!==this.#Ee}}class pt{#ye;#Ie;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ie=e.remote}get url(){return this.#ye}get state(){return this.#Te.state}get trustKey(){}async start(){return this.#Te.start(async()=>{await this.#Ie.connect(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ie.disconnect()})}isHealthy(){return this.#Ie.isHealthy()}getHealth(){return this.#Ie.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}getProcedureNames(){throw new S}hasProcedure(e){throw new S}addWorker(e){return this.#Ie.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Ie.reportWorker(e,t)}removeWorker(e){return this.#Ie.removeWorker(e)}run(e){return this.#Ie.run(e)}}class gt extends A{#Ne;constructor(e){super(`No worker available for procedure '${e}'`),this.#Ne=e}get name(){return this.#Ne}}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 F.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;#We=new Map;#Be=new wt;#qe;constructor(e,t){this.#qe=e.create(()=>this.#De(),t)}get workers(){return[...this.#je.values()]}get balancers(){return this.#We}start(){this.#qe.start()}stop(){this.#qe.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.#Be.generate(),this.#je.set(e.id,e);for(const t of e.getProcedureNames()){this.#Fe(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.#We.get(e)}#Fe(e){let t=this.#Ve(e);return void 0===t&&(t=new mt,this.#We.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#De(){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;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ue=e.provider,this.#_e=e.runner}get url(){return this.#ye}get state(){return this.#Te.state}get trustKey(){return this.#_e.trustKey}get provider(){return this.#Ue}get runner(){return this.#_e}async start(){return this.#Te.start(async()=>{await Promise.all([this.#Ue.start(),this.#_e.start()]),await this.updateState()})}async stop(){return this.#Te.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.#Te.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;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ce=e.healthManager,this.#Ge=e.sourcingManager,this.#Je=e.assets,this.#Xe=e.directoryIndex??"index.html",this.#Qe=e.fallback}get url(){return this.#ye}get state(){return this.#Te.state}async start(){return this.#Te.start(async()=>{await this.#Ce.start(),await this.updateState()})}async stop(){return this.#Te.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.#Te.setAvailability(e)}async provide(e){if(this.#Je.has(e))return this.#Ge.read(e);const t=this.#Ze(e);if(this.#Je.has(t))return this.#Ge.read(t);if(void 0!==this.#Qe&&this.#Je.has(this.#Qe))return this.#Ge.read(this.#Qe);throw new W(e)}#Ze(e){return""===e||"/"===e?this.#Xe:e.endsWith("/")?`${e}${this.#Xe}`:`${e}/${this.#Xe}`}}class Mt{#ye;#Ie;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ie=e.remote}get url(){return this.#ye}get state(){return this.#Te.state}async start(){return this.#Te.start(async()=>{await this.#Ie.connect(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ie.disconnect()})}isHealthy(){return this.#Ie.isHealthy()}getHealth(){return this.#Ie.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}provide(e){return this.#Ie.provide(e)}}class St extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class xt 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 Tt extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ot 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 Tt(e.base64)}}}const It=new ce;class Nt extends Rt{#tt;constructor(e){super(),this.#tt=e}canSerialize(e){return e instanceof Object&&It.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=It.getClass(e),r=It.fromClass(t,!0),s=this.#rt(r),a=this.#tt.resolveKey(t);if(void 0===a)throw new St(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 St(e.key);if(t instanceof Function==!1)throw new xt(e.key);const r=await this.#it(t,e.args),s=It.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=It.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 Wt 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 Bt 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 qt 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 Dt extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Ft 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 Dt(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 qt),t.addSerializer(new Bt),void 0!==e&&t.addSerializer(new Nt(e)),t.addSerializer(new Lt),t.addSerializer(new Ft),t.addSerializer(new Ht),t.addSerializer(new Gt),t.addSerializer(new $t),t.addSerializer(new Vt),t.addSerializer(new Wt),t.addSerializer(new Et),t.addSerializer(new Ut),"undefined"!=typeof Buffer&&t.addSerializer(new Ot),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;#lt;#ot;#Ce;#ut;#ht;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#ct=e.gateway,this.#lt=!0===e.registerAtGateway,this.#ot=e.executionManager,this.#Ce=e.healthManager;const t=e.scheduleManager;this.#ut=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.#Te.state}get url(){return this.#ye}get trustKey(){return this.#Ee}async start(){return this.#Te.start(async()=>{await Promise.all([this.#ot.start(),this.#Ce.start()]),void 0!==this.#ct&&(await this.#ct.start(),this.#lt&&(this.#Le=await this.#ct.addWorker(this),this.#ut.start())),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{void 0!==this.#ct&&(void 0!==this.#Le&&(this.#ut.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.#Te.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Te.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 B(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 B(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 ut{#St;#xt;#kt=Date.now();#Pt=Date.now();constructor(e=6e3,t=18e3){super(),this.#St=e,this.#xt=t}report(e){this.#kt=Date.now(),this.state=e}update(){this.#Pt=Date.now();const e=this.#Pt-this.#kt;return e>=this.#St&&(this.state=e>=this.#xt?ot.STOPPED:ot.UNAVAILABLE),this.state}}class sr{#Le;#ye;#Ee;#At;#Ie;#Te;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#At=e.procedureNames,this.#Ie=e.remote,this.#Te=new rr(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#Le}set id(e){this.#Le=e}get state(){return this.#Te.state}get url(){return this.#ye}get trustKey(){return this.#Ee}async start(){return this.#Te.start(async()=>{await this.#Ie.connect(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ie.disconnect()})}getProcedureNames(){return[...this.#At.values()]}hasProcedure(e){return this.#At.has(e)}isHealthy(){return this.#Ie.isHealthy()}getHealth(){return this.#Ie.getHealth()}isAvailable(){return this.#Te.isAvailable()}async updateState(){return this.#Te.update()}async reportState(e){this.#Te.report(e)}run(e){return this.#Ie.run(e)}}class ar{#zt;#St;#xt;constructor(e,t,r){this.#zt=e,this.#St=t,this.#xt=r}build(e,t,r){const s=this.#zt.build(e),a=new Set(t),n=this.#St,i=this.#xt;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 q;constructor(){this.#Et()}#Et(){const e=globalThis;e.__run=this.#Ct.bind(this),e.ProcedureNotAccessible=Se}async#Ct(e,t,r,s){const a=this.#Rt.parse(t),n=new Map(Object.entries(r)),i=s instanceof B?s.headers:new Map,o=new B(e,a,n,i,ue),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const l=await this.runInternal(o);if(l.status!==de)throw l.result;return l.result}}const or="starting",cr="started",lr="stopping",ur="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=ur;#Ht=new Map;#V;#Tt;constructor(e,t=[]){this.#V=e,this.#Tt=t}get state(){return this.#Ae}async start(){if(this.#Ae===ur)try{this.#Ae=or,await this.#Ot(),this.#Ae=cr}catch(e){throw this.#Ae=ur,new dr(e)}}async stop(){if(this.#Ae===cr)try{this.#Ae=lr,this.clearHealthChecks(),this.#Ae=ur}catch(e){throw this.#Ae=cr,new pr(e)}}async loadHealthCheck(e){const t=await this.#It(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.#Nt(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.#Nt(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#Ot(){(await Promise.all(this.#Tt.map(e=>this.#It(e)))).forEach(e=>this.addHealthCheck(e))}async#It(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#Nt(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 Sr{#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.#Wt(),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.#Bt(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.#qt(e,0)()}async#Wt(){(await Promise.all(this.#Lt.map(e=>this.#Bt(e)))).forEach(e=>this.addMiddleware(e))}async#Bt(e){return(await this.#V.import(e)).default}#qt(e,t){const r=this.#$t[t];if(void 0===r)return async()=>new R(de);const s=this.#qt(e,t+1);return async()=>await r.handle(e,s)}}class xr{#ne;#Dt;#Ft;#Vt=null;constructor(e,t,r=5e3){this.#ne=e,this.#Dt=t,this.#Ft=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.#Ft),this.#Vt.unref()}async#Ut(){try{await this.#Dt()}catch(e){this.#ne.warn("Scheduled task failed",e)}}}class kr{#_t=[];#ne;constructor(e){this.#ne=e}create(e,t){const r=new xr(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,Tr=400,Or=401,Ir=402,Nr=403,jr=404,$r=418,Lr=500,Wr=501;class Br extends Error{constructor(e){super("Starting server failed",{cause:e})}}class qr extends Error{constructor(e){super("Stopping server failed",{cause:e})}}class Dr extends ir{#Gt;#Jt;#Xt;#Qt;#ne;#Rt=new q;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 Br(e)}}async stop(){try{await this.#Yt(),this.#ne.info("Server stopped")}catch(e){throw new qr(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),r=t.location!==e.filename?`${e.filename} => ${t.location}`:e.filename;return this.#ne.info(`Provided file: ${r}`),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.#lr(e.fqn),r=this.#ur(e.version),s=this.#hr(e.args),a=this.#dr(e.headers);return new B(t,r,s,a,e.mode)}#lr(e){if(0===e.length)throw new y("Missing procedure name");if(e.includes(".."))throw new y("Invalid procedure name");return e}#ur(e){return"string"!=typeof e?D.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?Tr:e instanceof f?Nr:e instanceof w?jr:e instanceof S?Wr:e instanceof x?Ir:e instanceof k?$r:e instanceof P?Or:Lr}#ir(){const e=this.#Gt.runner;if(e instanceof dt==!1)throw new y("Cannot remove worker from remote gateway");return e}}class Fr 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 Fe(t),o=this.#Mr(n),c=this.#Sr(i),l=await this.#xr(e,o,c),u=this.#Ge,h=this.#kr(r,s),d=this.#Pr(a),p=this.#Ar(e);return new Dr({proxy:l,sourcingManager:u,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#xr(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 Fr}async#zr(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#Rr(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#Er(e,t,r){const s=await this.#Ir(e,t,r),a=new lt;return new vt({url:e,provider:s,runner:a})}#Tr(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})}#Nr(e){const t=this.#zt.build(e);return new pt({url:e,remote:t})}#Or(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Nr(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#Ir(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.directoryIndex,i=t.fallback;return new bt({url:e,sourcingManager:s,assets:a,directoryIndex:n,fallback: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.#Nr(t.gateway);return new vt({url:e,provider:r,runner:s})}async#Hr(e,t,r,s){const a=await this.#Ir(e,t,r),n=this.#Or(e,t,r,s);return new vt({url:e,provider:a,runner:n})}#kr(e=[],t=[]){const r=e.map(e=>this.#Wr(e)),s=t.map(e=>this.#Wr(e));return new Vr(this.#Ge,r,s)}#Mr(e=[]){const t=e.map(e=>this.#Wr(e));return new gr(this.#Ge,t)}#Pr(e=[]){const t=e.map(e=>this.#Wr(e));return new Sr(this.#Ge,t)}#jr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Oe(this.#Ge,t)}#Sr(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)}#Wr(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{#Br;#qr;#Dr;#Fr;#be=new $;constructor(e,t=Ur,r=_r){this.#Br=e,this.#qr=t,this.#Dr=V(),this.#Vr(r),this.#Kr()}async start(){return await this.#Br.start(),this.#Ur()}async stop(){return await this.#_r(),this.#Br.stop()}#Vr(e){this.#Dr.use(V.json({limit:e})),this.#Dr.use(V.urlencoded({extended:!1})),this.#Dr.use(this.#Gr.bind(this)),this.#Dr.disable(Ye)}#Kr(){this.#Dr.get("/health",(e,t)=>{this.#Jr(e,t)}),this.#Dr.get("/health/status",(e,t)=>{this.#Xr(e,t)}),this.#Dr.get("/rpc/*procedure",(e,t)=>{this.#Qr(e,t)}),this.#Dr.post("/rpc/*procedure",(e,t)=>{this.#Zr(e,t)}),this.#Dr.options("/rpc/*procedure",(e,t)=>{this.#Yr(e,t)}),this.#Dr.post("/workers",(e,t)=>{this.#es(e,t)}),this.#Dr.post("/workers/:id/report",(e,t)=>{this.#ts(e,t)}),this.#Dr.delete("/workers/:id",(e,t)=>{this.#rs(e,t)}),this.#Dr.use((e,t)=>{this.#ss(e,t)})}#Ur(){return void 0!==this.#Fr?Promise.resolve():new Promise((e,t)=>{this.#Fr=this.#Dr.listen(this.#qr,t),e()})}#_r(){return void 0===this.#Fr?Promise.resolve():new Promise(e=>{this.#Fr.close(()=>e())})}#Gr(e,t,r){t.setHeader(Xe,et),r()}async#Jr(e,t){const r=await this.#Br.getHealth();return this.#as(t,r)}async#Xr(e,t){const r=await this.#Br.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=ue,o=await this.#Br.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.#ls(e),n=this.#cs(e),i=ue,o=await this.#Br.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.#ls(e),n=this.#cs(e),i=he,o=await this.#Br.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#es(e,t){const r=this.#ls(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.#Br.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.#Br.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.#Br.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.#Br.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}#ls(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.#us(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)}#us(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 l=await c.getRuntimeConfiguration(r),u=await c.getServiceConfiguration(s),h=await this.#gs(l,u,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 Fe;try{const e=new Yr;await e.start()}catch(t){es.fatal(t),e.exitCode=1}
|
package/dist/lib.d.ts
CHANGED
|
@@ -23,8 +23,8 @@ type ProxyConfiguration = {
|
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
type RepositoryConfiguration = {
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
directoryIndex?: string;
|
|
27
|
+
fallback?: string;
|
|
28
28
|
assetRoot?: string;
|
|
29
29
|
assets?: string[];
|
|
30
30
|
};
|
|
@@ -43,7 +43,7 @@ type RemoteWorkerConfiguration = {
|
|
|
43
43
|
stoppedThreshold?: number;
|
|
44
44
|
};
|
|
45
45
|
|
|
46
|
-
type
|
|
46
|
+
type ServiceConfiguration = {
|
|
47
47
|
url: string;
|
|
48
48
|
setUp?: string[];
|
|
49
49
|
tearDown?: string[];
|
|
@@ -66,13 +66,14 @@ declare class ConfigurationManager {
|
|
|
66
66
|
constructor(rootPath?: string);
|
|
67
67
|
configureEnvironment(filename?: string): Promise<void>;
|
|
68
68
|
getRuntimeConfiguration(filename?: string): Promise<RuntimeConfiguration>;
|
|
69
|
-
|
|
69
|
+
getServiceConfiguration(filename: string): Promise<ServiceConfiguration>;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
declare class BuildHelper {
|
|
73
73
|
#private;
|
|
74
74
|
constructor(configuration: RuntimeConfiguration);
|
|
75
75
|
readApplication(): Promise<void>;
|
|
76
|
+
includesModule(filename: string): boolean;
|
|
76
77
|
generateModuleCode(filename: string, segmentNames?: string[]): string;
|
|
77
78
|
generateSegmentCode(segmentName: string): string;
|
|
78
79
|
}
|
package/dist/lib.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as e,y as t,n as s,q as a,L as
|
|
1
|
+
import{x as e,y as t,n as s,q as a,L as r,r as n,s as i,o,p,G as c}from"./ConfigurationManager-CQWv0Wmk.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-CQWv0Wmk.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 g{#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.#r(e)&&(this.#a=e),this}#r(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 h{#i;#o;#l;#p;constructor(e,t,s,a){this.#i=e,this.#o=t,this.#l=s,this.#p=a}get version(){return this.#i}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 d extends Error{constructor(){super("Application not read")}}class f 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;#g;constructor(e){const t=this.#m.makePathAbsolute(e.source,e.meta.root),s=this.#m.makePathAbsolute(e.target,e.meta.root),i=this.#m.makePathAbsolute(e.resources,e.meta.root),o=this.#m.makePathAbsolute(e.segments,e.meta.root);this.#c=new a(new r(t),new r(s),new r(i),new r(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(i.MODULE_PATTERN,this.#c.sourceIgnores),r=await t.filter(i.RESOURCE_PATTERN),n=await s.filter(i.SEGMENT_PATTERN);this.#g=await this.#u.read(a,r,n)}includesModule(e){return void 0!==this.#h().repository.get(e)}generateModuleCode(e,t=[]){const s=this.#h(),a=s.repository.get(e);if(void 0===a)throw new f(e);const r=s.resources,n=s.segmentation,i=n.getSegments(e);if(0===i.length){return new o(a,r,n).generate()}if(void 0===i.find(e=>t.includes(e.name))){return new p(a,i).generate()}return new o(a,r,n).generate()}generateSegmentCode(e){const t=this.#h().segmentation.getSegment(e);if(void 0===t)throw new w(e);return new c(t).generate()}#h(){if(void 0===this.#g)throw new d;return this.#g}}export{b as BuildHelper,u as Class,h as Implementation,g as Procedure,e as Version};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jitar",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
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",
|