jitar 0.10.7 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ConfigurationManager-D8N-pXTY.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/lib.d.ts +76 -1
- package/dist/lib.js +1 -1
- package/dist/templates/backend/jitar.json +1 -1
- package/dist/templates/backend/{_package.json → package.json} +4 -3
- package/dist/templates/backend/src/tsconfig.json +8 -0
- package/dist/templates/{react/tsconfig.base.json → backend/tsconfig.json} +4 -11
- package/dist/templates/react/jitar.json +1 -1
- package/dist/templates/react/package.json +28 -0
- package/dist/templates/react/services/standalone.json +1 -0
- package/dist/templates/react/src/{webui → app/components}/App.tsx +3 -3
- package/dist/templates/react/{index.html → src/app/index.html} +1 -1
- package/dist/templates/react/src/app/public/vite.svg +1 -0
- package/dist/templates/react/src/app/tsconfig.json +9 -0
- package/dist/templates/react/src/app/vite.config.ts +25 -0
- package/dist/templates/react/src/tsconfig.json +8 -0
- package/dist/templates/react/tsconfig.json +15 -0
- package/dist/templates/vue/jitar.json +1 -1
- package/dist/templates/vue/package.json +27 -0
- package/dist/templates/vue/services/standalone.json +1 -0
- package/dist/templates/vue/src/{webui → app/components}/App.vue +3 -3
- package/dist/templates/vue/{index.html → src/app/index.html} +1 -1
- package/dist/templates/vue/src/app/public/vite.svg +1 -0
- package/dist/templates/vue/src/app/tsconfig.json +7 -0
- package/dist/templates/vue/src/app/vite.config.ts +25 -0
- package/dist/templates/vue/src/domain/sayHello.js +3 -0
- package/dist/templates/vue/src/tsconfig.json +8 -0
- package/dist/templates/vue/tsconfig.json +15 -0
- package/package.json +4 -4
- package/dist/Response-DEjrdAZ9.js +0 -1
- package/dist/templates/backend/_gitignore +0 -25
- package/dist/templates/backend/_tsconfig.json +0 -20
- package/dist/templates/react/_gitignore +0 -25
- package/dist/templates/react/_package.json +0 -28
- package/dist/templates/react/_tsconfig.json +0 -6
- package/dist/templates/react/_vite.config.ts +0 -14
- package/dist/templates/react/public/vite.svg +0 -1
- package/dist/templates/react/src/vite-env.d.ts +0 -1
- package/dist/templates/react/tsconfig.build.json +0 -11
- package/dist/templates/vue/_gitignore +0 -25
- package/dist/templates/vue/_package.json +0 -26
- package/dist/templates/vue/_tsconfig.json +0 -19
- package/dist/templates/vue/_vite.config.ts +0 -14
- package/dist/templates/vue/public/vite.svg +0 -1
- package/dist/templates/vue/src/vite-env.d.ts +0 -1
- package/dist/templates/vue/tsconfig.build.json +0 -10
- /package/dist/templates/react/src/{webui → app}/assets/jitar.svg +0 -0
- /package/dist/templates/react/src/{webui → app}/assets/react.svg +0 -0
- /package/dist/templates/react/src/{webui → app/components}/App.css +0 -0
- /package/dist/templates/react/src/{webui → app/components}/index.css +0 -0
- /package/dist/templates/react/src/{webui → app/components}/main.tsx +0 -0
- /package/dist/templates/vue/src/{webui → app}/assets/jitar.svg +0 -0
- /package/dist/templates/vue/src/{webui → app}/assets/vue.svg +0 -0
- /package/dist/templates/vue/src/{webui → app/components}/main.ts +0 -0
- /package/dist/templates/vue/src/{webui → app/components}/style.css +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e,{promises as t}from"node:fs";import s from"node:path";import{glob as r}from"glob";import i from"mime-types";import n from"dotenv";const o={MODULE_PATTERN:"**/*.js",RESOURCE_PATTERN:"**/*.json",SEGMENT_PATTERN:"**/*.json"};class a extends Error{#e;constructor(e){super(`Invalid location: ${e}`),this.#e=e}get location(){return this.#e}}class c extends Error{#t;constructor(e){super(`The file '${e}' could not be found`),this.#t=e}get filename(){return this.#t}}class u{#e;#s;#r;constructor(e,t,s){this.#e=e,this.#s=t,this.#r=s}get location(){return this.#e}get type(){return this.#s}get content(){return this.#r}get size(){return this.#r.length}}class l{#e;#i;#n;constructor(e,t){const s=t.resolve(e);this.#e=t.normalize(e),this.#i=t.normalize(s),this.#n=t}getAbsoluteLocation(e){const t=this.#n.isAbsolute(e)?e:this.#n.join(this.#e,e),s=this.#n.resolve(t),r=this.#n.normalize(s);return this.#o(r,e),r}getRelativeLocation(e){const t=this.#n.relative(this.#e,e);return this.#n.normalize(t)}normalizeLocation(e){return this.#n.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#n.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#n.exists(t))throw new c(e);return this.#n.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#n.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#n.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new u(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#n.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#n.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#n.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#n.normalize(e);return(await this.#n.filter(t,s)).map(e=>this.#n.normalize(e))}#o(e,t){if(!1===e.startsWith(this.#i))throw new a(t)}}class h{copy(e,s){return t.cp(e,s,{recursive:!0,force:!0})}delete(e){return t.rm(e,{recursive:!0,force:!0})}async exists(e){try{return await t.stat(e),!0}catch{return!1}}isAbsolute(e){return s.isAbsolute(e)}isDirectory(t){try{return e.statSync(t).isDirectory()}catch{return!1}}filter(e,t){return r(`${e}/${t}`)}join(...e){return s.join(...e)}read(e){return t.readFile(e)}resolve(e){return s.resolve(e)}relative(e,t){return s.relative(e,t)}normalize(e){return e.replaceAll(s.win32.sep,s.posix.sep)}async mimeType(e){const t=i.lookup(e);if(!1!==t)return t}async write(r,i){const n=s.dirname(r);return e.mkdirSync(n,{recursive:!0}),t.writeFile(r,i)}}class p extends l{constructor(e){super(e,new h)}}class d{#a;#c;#u;constructor(e,t,s){this.#a=e,this.#c=t,this.#u=s}get resources(){return this.#c}get repository(){return this.#a}get segmentation(){return this.#u}}class m{#c;constructor(e){this.#c=e}isResourceModule(e){return this.#c.includes(e)}}const f="private",g="0.0.0",E="index.js",y=".json",w="default";class S{#l=0;next(){return"$"+ ++this.#l}}const b="js",A=/\.js$/,T=[".","/","http:","https:"];class I{translatePath(e){const t=e.split("/"),s=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":s.pop();continue}s.push(e)}return s.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const s=e.split("/"),r=t.split("/");for(;s[0]===r[0];)s.shift(),r.shift();const i=r.map(()=>"..").join("/");return`${r.length>0?i:"."}/${s.join("/")}`}makePathAbsolute(e,t,s="/"){const r=""!==t?`${t}/${e}`:e;return`${s}${this.translatePath(r)}`}extractPath(e){return e.split("/").slice(0,-1).join("/")}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${b}`)?e:`${e}.${b}`}addSubExtension(e,t){return e.replace(A,`.${t}.${b}`)}isApplicationModule(e){return T.some(t=>e.startsWith(t))}}let v=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class O{#h;#p;#d=new I;constructor(e,t){this.#h=e,this.#p=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#m(e)));return new m(t.flat())}async#m(e){try{const t=await this.#h.getContent(e);return JSON.parse(t.toString()).map(e=>this.#f(e))}catch(t){const s=t instanceof Error?t.message:String(t);throw new v(e,s)}}#f(e){const t=this.#p.normalizeLocation(e),s=this.#p.isDirectory(t)?`${t}/${E}`:this.#d.assureExtension(t);return s.startsWith("./")?s.substring(2):s.startsWith("/")?s.substring(1):s}}let N=class{#t;#g;constructor(e,t){this.#t=e,this.#g=t}get filename(){return this.#t}get model(){return this.#g}};class R{#E;constructor(e){this.#E=e}get modules(){return this.#E}get(e){return this.#E.find(t=>t.filename===e)}}class x{}class M extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new M(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class C{}class $ extends C{identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class L extends ${parameters;body;isAsync;constructor(e,t,s,r=!1){super(e),this.parameters=t,this.body=s,this.isAsync=r}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new L(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier?` ${this.identifier}`:"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function${t}(${s.join(",")})${r}`}}class P extends L{constructor(e,t,s=!1){super(void 0,e,t,s)}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new P(e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.parameters.map(e=>e.toString()),s=this.body.toString();return`${e}(${t.join(", ")})=>${s}`}}class F{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new F(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class V extends C{code;constructor(e){super(),this.code=e}clone(){return new V(this.code)}toString(){return this.code}}class D{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class k extends D{parameters;body;constructor(e,t){super("constructor","public","instance"),this.parameters=e,this.body=t}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new k(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class B extends D{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new B(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.body.toString();return`${e}get ${t}${this.identifier}()${s}`}}class j extends D{parameter;body;constructor(e,t,s,r,i){super(e,t,s),this.parameter=r,this.body=i}clone(){const e=this.parameter.clone(),t=this.body.clone();return new j(this.identifier,this.visibility,this.location,e,t)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.parameter.toString(),r=this.body.toString();return`${e}set ${t}${this.identifier}(${s})${r}`}}class U extends D{parameters;body;isAsync;constructor(e,t,s,r,i,n=!1){super(e,t,s),this.parameters=r,this.body=i,this.isAsync=n}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new U(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.isAsync?"async ":"",r=this.parameters.map(e=>e.toString()),i=this.body.toString();return`${e}${s}${t}${this.identifier}(${r.join(",")})${i}`}}class q extends D{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new q(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${e}${t}${this.identifier}${s}`}}class G extends ${parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof k)}get fields(){return this.members.filter(e=>e instanceof q)}get getters(){return this.members.filter(e=>e instanceof B)}get setters(){return this.members.filter(e=>e instanceof j)}get methods(){return this.members.filter(e=>e instanceof U)}get publicFields(){return this.fields.filter(e=>"public"===e.visibility)}get publicGetters(){return this.getters.filter(e=>"public"===e.visibility)}get publicSetters(){return this.setters.filter(e=>"public"===e.visibility)}get publicMethods(){return this.methods.filter(e=>"public"===e.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(e){return this.members.find(t=>t.is(e))}hasMember(e){return this.members.some(t=>t.is(e))}getField(e){return this.fields.find(t=>t.is(e))}hasField(e){return this.fields.some(t=>t.is(e))}getGetter(e){return this.getters.find(t=>t.is(e))}hasGetter(e){return this.getters.some(t=>t.is(e))}getSetter(e){return this.setters.find(t=>t.is(e))}hasSetter(e){return this.setters.some(t=>t.is(e))}getMethod(e){return this.methods.find(t=>t.is(e))}hasMethod(e){return this.methods.some(t=>t.is(e))}canRead(e){return this.readable.some(t=>t.is(e))}canWrite(e){return this.writable.some(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new G(this.identifier,this.parent,e)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(e=>e.toString()).join("")}}`}}class H extends C{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new H(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class K extends C{code;constructor(e){super(),this.code=e}clone(){return new K(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class _ extends L{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new _(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier??"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function* ${t}(${s.join(",")})${r}`}}class W extends U{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new W(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier,s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}*${t}(${s.join(",")})${r}`}}class z extends x{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new z(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Y extends C{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Y(e,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(e=>e.toString()).join(",")}} from '${this.from}';`}}class X extends ${type;binding;initializer;constructor(e,t,s){super(t.toString()),this.type=e,this.binding=t,this.initializer=s}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new X(this.type,e,t)}toString(){const e=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",t=e.endsWith(";")?"":";";return`${this.type} ${this.identifier}${e}${t}`}}class Q{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof H)}get imports(){return this.statements.filter(e=>e instanceof Y)}get expressions(){return this.statements.filter(e=>e instanceof K)}get declarations(){return this.statements.filter(e=>e instanceof $)}get variables(){return this.statements.filter(e=>e instanceof X)}get functions(){return this.statements.filter(e=>e instanceof L)}get classes(){return this.statements.filter(e=>e instanceof G)}get exported(){const e=[];for(const t of this.exports)for(const s of t.members){const t=this.getDeclaration(s.identifier);void 0!==t&&e.push(t)}return e}get exportedVariables(){return this.exported.filter(e=>e instanceof X)}get exportedFunctions(){return this.exported.filter(e=>e instanceof L)}get exportedClasses(){return this.exported.filter(e=>e instanceof G)}getExport(e){return this.exports.find(t=>t.hasMember(e))}getImport(e){return this.imports.find(t=>t.hasMember(e))}hasDeclaration(e){return this.declarations.some(t=>t.is(e))}getDeclaration(e){return this.declarations.find(t=>t.is(e))}hasVariable(e){return this.variables.some(t=>t.is(e))}getVariable(e){return this.variables.find(t=>t.is(e))}hasFunction(e){return this.functions.some(t=>t.is(e))}getFunction(e){return this.functions.find(t=>t.is(e))}hasClass(e){return this.classes.some(t=>t.is(e))}getClass(e){return this.classes.find(t=>t.is(e))}clone(){const e=this.statements.map(e=>e.clone());return new Q(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class J{identifier;alias;constructor(e,t){this.identifier=e,this.alias=t}is(e){return this.alias===e||void 0===this.alias&&this.identifier===e}clone(){return new J(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class Z extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Z(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const ee={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},te=Object.values(ee);const se=".",re="(",ie=")",ne="[",oe="]",ae="{",ce="}",ue="_",le={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},he=Object.values(le);function pe(e){return he.includes(e)}const de={UNDEFINED:void 0,NULL:null,STRING:""},me=["null","undefined"],fe=Object.values(de);function ge(e){return fe.includes(e)}const Ee={OPEN:re,CLOSE:ie};function ye(e){return e===Ee.OPEN||e===Ee.CLOSE}const we={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally"},Se=Object.values(we),be=[we.IMPORT,we.EXPORT,we.VAR,we.LET,we.CONST,we.FUNCTION,we.CLASS,we.ASYNC],Ae=[we.VAR,we.LET,we.CONST,we.FUNCTION,we.CLASS,we.USING],Te=[we.AS,we.ASYNC,we.GET,we.SET,we.OF,we.YIELD,we.FROM,we.STATIC];function Ie(e){return be.includes(e)}function ve(e){return Te.includes(e)}const Oe={OPEN:ne,CLOSE:oe};function Ne(e){return e===Oe.OPEN||e===Oe.CLOSE}const Re=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xe(e){return Re.includes(e)}const Me={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},Ce=Object.values(Me);function $e(e){return Ce.includes(e)}const Le={OPEN:ae,CLOSE:ce};function Pe(e){return e===Le.OPEN||e===Le.CLOSE}const Fe={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},Ve={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},De=Object.values(Ve);function ke(e){return De.includes(e)}class Be{#y;#w;constructor(e){this.#y=e,this.#w=0}get items(){return this.#y}get position(){return this.#w}get size(){return this.#y.length}get eol(){return this.#w>=this.#y.length}get current(){return this.#y[this.#w]}get next(){return this.#y[this.#w+1]}get previous(){return this.#y[this.#w-1]}notAtEnd(){return!1===this.eol}get(e){return this.#y[e]}step(e=1){return this.#w+=e,this.current}stepBack(e=1){return this.#w-=e,this.current}hasNext(){return this.#w+1<this.#y.length}insert(...e){this.#y.splice(this.#w,0,...e)}}class je extends Be{constructor(e){super(e.split(""))}}class Ue{#s;#S;#b;#A;constructor(e,t,s,r){this.#s=e,this.#S=t,this.#b=s,this.#A=r}get type(){return this.#s}get value(){return this.#S}get start(){return this.#b}get end(){return this.#A}isType(e){return this.#s===e}hasValue(e){return this.#S===e}toString(){return`${this.#S}`}}class qe extends Be{}const Ge=["true","false"];const He=["0","1","2","3","4","5","6","7","8","9"],Ke=[...He,"a","b","c","d","e","f","A","B","C","D","E","F"],_e=["0","1"];function We(e){return He.includes(e)}const ze={GENERATOR:"*",PRIVATE:"#"},Ye=Object.values(ze);class Xe{tokenize(e){const t=new je(e),s=[];let r;for(;t.notAtEnd();){const e=this.#T(t,r);if(void 0===e)break;e.isType(Fe.WHITESPACE)||e.isType(Fe.COMMENT)?t.step():(s.push(e),this.#I(e)&&(r=e),t.step())}return new qe(s)}#I(e){return!1===[Fe.WHITESPACE,Fe.COMMENT].includes(e.type)}#T(e,t){const s=e.current,r=e.position;if(ke(s)){const t=e.position;return new Ue(Fe.WHITESPACE,s,r,t)}if(function(e){return te.includes(e)}(s+e.next)){const t=this.#v(e),s=e.position;return new Ue(Fe.COMMENT,t,r,s)}if(this.#O(s,t)){const t=this.#N(e),s=e.position;return new Ue(Fe.REGEX,t,r,s)}if(this.#R(e,t)){const t=this.#x(e),s=e.position;return new Ue(Fe.NUMBER,t,r,s)}if(xe(s)){const t=this.#M(e),s=e.position;return new Ue(Fe.LITERAL,t,r,s)}if($e(s)){const t=this.#C(e),s=e.position;return new Ue(Fe.OPERATOR,t,r,s)}if(function(e){return Ye.includes(e)}(s)){const t=this.#C(e),s=e.position;return new Ue(Fe.INDICATOR,t,r,s)}if(pe(s)){const t=e.position;return new Ue(Fe.DIVIDER,s,r,t)}if(ye(s)){const t=e.position;return new Ue(Fe.GROUP,s,r,t)}if(Pe(s)){const t=e.position;return new Ue(Fe.SCOPE,s,r,t)}if(Ne(s)){const t=e.position;return new Ue(Fe.LIST,s,r,t)}if(ge(s))return;const i=this.#$(e),n=e.position;return function(e){return Se.includes(e)}(i)?new Ue(Fe.KEYWORD,i,r,n):function(e){return Ge.includes(e)}(i)?new Ue(Fe.BOOLEAN,i,r,n):function(e){return me.includes(e)}(i)?new Ue(Fe.NOTHING,i,r,n):new Ue(Fe.IDENTIFIER,i,r,n)}#v(e){const t=e.current+e.next===ee.MULTI_START,s=t?ee.MULTI_END:Ve.NEWLINE;let r=t?ee.MULTI_START:ee.SINGLE;for(e.step(2);e.notAtEnd();){const i=e.current;if((t?i+e.next:i)===s){e.step(s.length-1);break}r+=i,e.step()}return t?r+ee.MULTI_END:r.trim()}#O(e,t){return e===Me.DIVIDE&&(void 0===t||([Fe.OPERATOR,Fe.DIVIDER,Fe.KEYWORD].includes(t.type)||[Ee.OPEN,Oe.OPEN].includes(t.value)))}#L(e){return ke(e)||e==se||!1===this.#P(e)}#N(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Me.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#L(r)){e.stepBack();break}t+=r,e.step()}return t}#R(e,t){const s=e.current,r=e.next;return!!We(s)||s===Me.SUBTRACT&&(!t?.isType(Fe.NUMBER)&&We(r))}#F(e,t,s){return t?!1===(r=e,Ke.includes(r))&&e!==ue:s?!1===function(e){return _e.includes(e)}(e)&&e!==ue:!1===We(e)&&e!==se&&e!==ue&&"e"!==e;var r}#x(e){let t=e.current;t===Me.SUBTRACT&&(t+=e.step()),e.step();const s="x"===e.current,r="b"===e.current;for((s||r)&&(t+=e.current,e.step());e.notAtEnd();){const i=e.current;if(this.#F(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#M(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const i=e.current;if(!1===r){if(i===t){s+=i;break}"\\"===i&&(r=!0)}else r=!1;s+=i,e.step()}return s}#P(e){return!1===(ge(e)||ke(e)||$e(e)||xe(e)||pe(e)||ye(e)||Pe(e)||Ne(e))}#$(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#P(s)){e.stepBack();break}t+=s,e.step()}return t}#C(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===$e(s)||!1===$e(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Qe extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Je extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Ze extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class et extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class tt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const st=new Ue(Fe.NONE,"",-1,0);class rt{#V;constructor(e=[]){this.#V=e}get tokens(){return this.#V}append(...e){this.#V.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="";for(let t=0;t<this.#V.length;t++){const s=this.#V[t-1]??st,r=this.#V[t],i=this.#V[t+1]??st,n=this.#D(s,r)?" ":"",o=this.#k(r,i)?" ":"";e+=`${n}${r.value}${o}`}return e}#D(e,t){return!(!t.isType(Fe.KEYWORD)||!this.#B(e))||!(!t.isType(Fe.OPERATOR)||!e.isType(Fe.OPERATOR))}#k(e,t){return e.isType(Fe.KEYWORD)&&(t.isType(Fe.KEYWORD)||this.#B(t))}#B(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.isType(Fe.NUMBER)}}const it="default";class nt{#j;constructor(e=new Xe){this.#j=e}parse(e){const t=this.#j.tokenize(e),s=this.#U(t);return new Q(s)}parseStatement(e){const t=this.#j.tokenize(e),s=this.#q(t);if(void 0===s)throw new et("a statement");return s}parseImport(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof Y==!1)throw new et("an import definition");return s}parseExport(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof H==!1)throw new et("an export definition");return s}parseVariable(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof X==!1)throw new et("a variable definition");return s}parseFunction(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof L==!1)throw new et("a function definition");return s}parseClass(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof G==!1)throw new et("a class definition");return s}#U(e){const t=[];for(;e.notAtEnd();){const s=this.#q(e);void 0!==s&&t.push(s)}return t}#q(e,t=!1){const s=e.current;if(this.#H(s))return this.#K(e);if(s.isType(Fe.IDENTIFIER)){const s=e.next;return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#K(e)}if(s.isType(Fe.KEYWORD)){if(ve(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(we.FUNCTION)||t.hasValue(Ee.OPEN));if(s.hasValue(we.ASYNC)&&r)return e.step(),this.#q(e,!0);if(void 0===t||this.#W(t))return this.#K(e)}return s.hasValue(we.RETURN)?this.#K(e):!1===Ie(s.value)?this.#K(e):this.#G(e,t)}if(s.isType(Fe.REGEX))return this.#K(e);if(s.hasValue(Ee.OPEN)){const s=this.#z(e,Ee.OPEN,Ee.CLOSE);return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#K(e)}if(s.hasValue(Le.OPEN))return this.#K(e);if(s.hasValue(Oe.OPEN))return this.#K(e);if(s.hasValue(Me.NOT)||s.hasValue(Me.SUBTRACT))return this.#K(e);if(!pe(s.value))throw new tt(s.value,s.start);e.step()}#H(e){return e.isType(Fe.LITERAL)||e.isType(Fe.NUMBER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.hasValue(we.NEW)}#G(e,t=!1){const s=e.current;switch(e.step(),s.value){case we.IMPORT:return this.#Y(e);case we.EXPORT:return this.#X(e);case we.CLASS:return this.#Q(e);case we.FUNCTION:return this.#J(e,t);case we.VAR:return this.#Z(e,"var");case we.LET:return this.#Z(e,"let");case we.CONST:return this.#Z(e,"const");case we.ASYNC:return this.#q(e,!0);default:throw new Ze(s.value,s.start)}}#Y(e){const t=[];let s=e.current;if(s.isType(Fe.LITERAL)){const e=this.#ee(s.value);return new Y(t,e)}if(s.hasValue(Ee.OPEN)){s=e.step();const r=this.#ee(s.value);return e.step(2),new Y(t,r)}if(!1===s.hasValue(Le.OPEN)){const r=s.hasValue(Me.MULTIPLY)?Me.MULTIPLY:it;let i=s.value;s=e.step(),s.hasValue(we.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new J(r,i))}if(s.hasValue(le.SEPARATOR)&&(s=e.step()),s.hasValue(Le.OPEN)){const r=this.#te(e);t.push(...r),s=e.current}if(!1===s.hasValue(we.FROM))throw new Qe(we.FROM,s.start);s=e.step();const r=this.#ee(s.value);return e.step(),new Y(t,r)}#X(e){switch(e.current.value){case we.DEFAULT:return e.step(),this.#se(e,!0);case Le.OPEN:return this.#re(e);default:return this.#se(e,!1)}}#se(e,t){let s=e.current,r=0;if(t&&this.#ie(e)){const t=`$_EXPORT_${s.start}_${s.end}`;e.insert(new Ue(Fe.KEYWORD,we.CONST,0,0),new Ue(Fe.IDENTIFIER,t,0,0),new Ue(Fe.OPERATOR,Me.ASSIGN,0,0)),s=e.current}var i;s.hasValue(we.ASYNC)&&(s=e.step(),r++),i=s.value,Ae.includes(i)&&(s=e.step(),r++);const n=this.#P(s)?s.value:"",o=t?it:void 0;let a;s=e.step(),s?.hasValue(we.FROM)&&(s=e.step(),a=this.#ee(s.value)),r>0&&(r++,e.stepBack(r));const c=new J(n,o);return new H([c],a)}#ie(e){const t=e.current;if(this.#H(t))return!0;const s=e.next;return this.#P(t)&&s?.hasValue(Ee.OPEN)}#re(e){const t=this.#te(e);let s,r=e.current;return r?.hasValue(we.FROM)&&(r=e.step(),s=this.#ee(r.value)),e.step(),new H(t,s)}#ee(e){return e.slice(1,-1)}#te(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Le.CLOSE)){e.step();break}if(s.hasValue(le.SEPARATOR)){s=e.step();continue}const r=this.#ne(e);t.push(r),s=e.step()}return t}#ne(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(we.AS)&&(t=e.step(2),r=t.value),new J(s,r)}#Z(e,t){const s=this.#oe(e),r=this.#ae(e);return new X(t,s,r)}#oe(e){const t=e.current;return t.hasValue(Oe.OPEN)?this.#ce(e):t.hasValue(Le.OPEN)?this.#ue(e):this.#le(e)}#ce(e){const t=this.#he(e,Oe.CLOSE);return new M(t)}#ue(e){const t=this.#he(e,Le.CLOSE);return new Z(t)}#he(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(le.SEPARATOR)){e.step();continue}const i=this.#oe(e),n=this.#ae(e),o=new F(i,n);s.push(o)}return s}#le(e){let t=e.current,s=!1;t.hasValue(Me.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new z(r,s)}#ae(e){const t=e.current;if(!1!==t.hasValue(Me.ASSIGN))return e.step(),this.#q(e,!1);t.hasValue(le.TERMINATOR)&&e.step()}#J(e,t){let s,r=e.current,i=!1;r.hasValue(ze.GENERATOR)&&(i=!0,r=e.step()),this.#P(r)&&(s=r.value,e.step());const n=this.#he(e,Ee.CLOSE);if(r=e.current,!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const o=this.#pe(e);return i?new _(s,n,o,t):new L(s,n,o,t)}#_(e,t){let s,r,i=e.current;if(i.hasValue(Ee.OPEN))s=this.#he(e,Ee.CLOSE);else{const t=this.#le(e);s=[new F(t,void 0)]}if(i=e.current,!1===i.hasValue(Me.ARROW))throw new Je(Me.ARROW,i.start);if(i=e.step(),i.hasValue(Le.OPEN))r=this.#pe(e);else{const t=this.#K(e);r=new V(t.code)}return new P(s,r,t)}#Q(e){let t,s,r=e.current;if(this.#P(r)&&(t=r.value,r=e.step()),r.hasValue(we.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const i=this.#de(e);return new G(t,s,i)}#de(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Le.CLOSE)){e.step();break}const r=this.#me(e);s.push(r),t=e.current}return s}#me(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(ze.PRIVATE))s="private";else if(t.hasValue(we.STATIC))r="static";else{if(!t.hasValue(we.ASYNC)){if(t.hasValue(we.CONSTRUCTOR))return this.#fe(e);if(t.hasValue(we.GET))return this.#ge(e,r);if(t.hasValue(we.SET))return this.#Ee(e,r);if(t.hasValue(ze.GENERATOR))return e.step(),this.#ye(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(Ee.OPEN)?this.#ye(e,s,r,i,!1):this.#we(e,s,r)}#fe(e){e.step();const t=this.#he(e,Ee.CLOSE),s=e.current;if(!1===s.hasValue(Le.OPEN))throw new Je(Le.OPEN,s.start);const r=this.#pe(e);return new k(t,r)}#ge(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#he(e,Ee.CLOSE).length)throw new et("an empty parameter list");if(r=e.current,!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const n=this.#pe(e);return new B(i,s,t,n)}#Ee(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#he(e,Ee.CLOSE);if(r=e.current,1!==n.length)throw new et("exactly one setter parameter");if(!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const o=this.#pe(e);return new j(i,s,t,n[0],o)}#ye(e,t,s,r,i){let n=e.current;const o=n.value;e.step();const a=this.#he(e,Ee.CLOSE);if(n=e.current,!1===n.hasValue(Le.OPEN))throw new Je(Le.OPEN,n.start);const c=this.#pe(e);return i?new W(o,t,s,a,c,r):new U(o,t,s,a,c,r)}#we(e,t,s){const r=e.current.value;e.step();const i=this.#ae(e);return new q(r,t,s,i)}#pe(e){const t=this.#Se(e,Le.OPEN,Le.CLOSE).generate();return new V(t)}#K(e){const t=new rt;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Oe.OPEN)){const r=this.#Se(e,Oe.OPEN,Oe.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Ee.OPEN)){const r=this.#Se(e,Ee.OPEN,Ee.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Le.OPEN)){const r=this.#Se(e,Le.OPEN,Le.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#W(s)){s.hasValue(le.TERMINATOR)&&e.step();break}}const r=t.generate();return new K(r)}#Se(e,t,s){let r=e.current;const i=new rt([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#Se(e,t,s);i.merge(n),r=e.current;continue}if(r.hasValue(s))return e.step(),i.append(r),i;i.append(r),r=e.step()}return i}#z(e,t,s){const r=e.position;this.#Se(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#W(e){return[le.TERMINATOR,le.SEPARATOR].includes(e.value)||[Oe.CLOSE,Ee.CLOSE,Le.CLOSE].includes(e.value)||Ie(e.value)}#P(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.KEYWORD)&&ve(e.value)}}let ot=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}};class at{#p;#d=new I;constructor(e){this.#p=e}rewrite(e,t){e.imports.forEach(e=>this.#be(e,t)),e.exports.forEach(e=>this.#Ae(e,t))}#be(e,t){const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Te(t,s))}#Ae(e,t){if(void 0===e.from)return;const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Te(t,s))}#Te(e,t){const s=this.#d.extractPath(e),r=this.#d.makePathAbsolute(t,s,"");return this.#p.isDirectory(r)?`${t}/${E}`:this.#d.assureExtension(t)}}let ct=class{#p;#Ie;#ve;constructor(e,t=new nt){this.#p=e,this.#Ie=t,this.#ve=new at(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new R(t)}async read(e){try{const t=this.#p.getRelativeLocation(e),s=await this.#Oe(e),r=this.#Ie.parse(s);return this.#ve.rewrite(r,t),new N(t,r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new ot(e,s)}}async#Oe(e){return(await this.#p.getContent(e)).toString()}},ut=class{#Ne;#E=new Map;#Re=new Map;#xe=new Map;constructor(e){this.#Ne=e}get name(){return this.#Ne}get modules(){return[...this.#E.values()]}get classes(){return[...this.#Re.values()]}get procedures(){return[...this.#xe.values()]}hasModule(e){return this.#E.has(e)}getModule(e){return this.#E.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#E.set(e.filename,e)}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}setProcedure(e){this.#xe.set(e.fqn,e)}setClass(e){this.#Re.set(e.fqn,e)}};class lt{#l;#Me;#Ce;constructor(e,t,s){this.#l=e,this.#Me=t,this.#Ce=s}get id(){return this.#l}get importKey(){return this.#Me}get fqn(){return this.#Ce}}class ht extends lt{#g;constructor(e,t,s,r){super(e,t,s),this.#g=r}get model(){return this.#g}}class pt extends lt{#$e;#Le;#g;constructor(e,t,s,r,i,n){super(e,t,s),this.#$e=r,this.#Le=i,this.#g=n}get access(){return this.#$e}get version(){return this.#Le}get model(){return this.#g}}class dt{#t;#e;#Pe;#Fe=[];#Ve;constructor(e,t,s,r){this.#t=e,this.#e=t,this.#Pe=s,this.#Ve=r}get filename(){return this.#t}get location(){return this.#e}get imports(){return this.#Pe}get members(){return this.#Fe}get segmented(){return this.#Ve}hasClasses(){return this.#Fe.some(e=>e instanceof ht)}getClasses(){return this.#Fe.filter(e=>e instanceof ht)}hasImplementations(){return this.#Fe.some(e=>e instanceof pt)}getImplementations(){return this.#Fe.filter(e=>e instanceof pt)}addMember(e){this.#Fe.push(e)}addImports(e){const t=Object.keys(e);for(const s of t){const t=s.trim();this.#Pe[t]=e[s]}}}class mt{#Ce;#De=[];constructor(e,t=[]){this.#Ce=e,this.#De=t}get fqn(){return this.#Ce}get implementations(){return this.#De}addImplementation(e){this.#De.push(e)}}class ft{#ke;constructor(e){this.#ke=e}get segments(){return this.#ke}getSegment(e){return this.#ke.find(t=>t.name===e)}isSegmentedModule(e){return this.#ke.some(t=>t.hasModule(e))}getSegments(e){return this.#ke.filter(t=>t.hasModule(e))}}class gt extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class Et extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class yt extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class wt extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class St extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class bt extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class At{#a;#d=new I;constructor(e){this.#a=e}locate(e,t){const s=[];return{trace:s,model:this.#Be(e,t,s)}}#Be(e,t,s){s.push({filename:e,importKey:t});const r=this.#je(e);return this.#Ue(r,t)?this.#qe(r,t,s):this.#Ge(r,t)}#je(e){const t=this.#a.get(e);if(void 0===t)throw new bt(e);return t}#Ue(e,t){const s=e.model.getImport(t),r=e.model.getExport(t);return void 0!==s||void 0!==r?.from}#qe(e,t,s){const r=this.#He(e,t)??this.#Ke(e,t),i=r?.from,n=r?.name,o=this.#d.extractPath(e.filename),a=i,c=this.#d.makePathAbsolute(a,o,"");return this.#Be(c,n,s)}#Ge(e,t){const s=this.#Ke(e,t);if(void 0===s)throw new St(e.filename,t);const r=e.model.getDeclaration(s.name);if(void 0===r)throw new St(e.filename,s.name);return r}#Ke(e,t){const s=e.model.getExport(t),r=s?.getMember(t);if(void 0!==r)return{from:s?.from,name:r.identifier}}#He(e,t){const s=e.model.getImport(t),r=s?.getMember(t);if(void 0!==s&&void 0!==r)return{from:s.from,name:r.identifier}}}class Tt{#_e;#p;#We;#d=new I;constructor(e,t,s){this.#_e=e,this.#p=t,this.#We=new At(s)}async readAll(e){const t=await Promise.all(e.map(e=>this.#ze(e)));return new ft(t)}async#ze(e){const t=await this.#Ye(e),s=this.#Xe(e),r=new ut(s);return this.#Qe(r,t),this.#Je(r),r}#Xe(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new Et(e);return t.replace(y,"")}async#Ye(e){try{const t=await this.#_e.getContent(e);return JSON.parse(t.toString())}catch(t){const s=t instanceof Error?t.message:String(t);throw new yt(e,s)}}#Qe(e,t){for(const[s,r]of Object.entries(t))this.#Ze(e,s,r,!0)}#Ze(e,t,s,r){const i=this.#et(t),n=this.#d.extractPath(i),o=e.hasModule(i)?e.getModule(i):new dt(i,n,{},r);o.addImports(s),e.setModule(o)}#et(e){const t=e.trim(),s=this.#p.normalizeLocation(t),r=this.#p.isDirectory(s)?`${s}/${E}`:this.#d.assureExtension(s);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#Je(e){const t=new S;for(const s of e.modules)for(const r in s.imports)this.#tt(e,s,r,t)}#tt(e,t,s,r){const{model:i,trace:n}=this.#We.locate(t.filename,s),o=this.#st(t,i,s,r);this.#rt(e,t,i,o),n.shift();for(const t of n){const s={[t.importKey]:{access:o.access}};this.#Ze(e,t.filename,s,!1)}}#st(e,t,s,r){const i=e.imports[s],n=r.next(),o=i.as??t.identifier;return{id:n,importKey:s,name:o,access:i.access??f,version:i.version??g,fqn:this.#it(e,o,s)}}#it(e,t,s){return this.#nt(e)?t:this.#ot(e)&&this.#at(s)?e.location:`${e.location}/${t}`}#nt(e){return""===e.location}#ot(e){return e.filename.endsWith(E)}#at(e){return e===w}#rt(e,t,s,r){if(s instanceof G)return this.#ct(e,t,s,r);if(s instanceof L)return this.#ut(e,t,s,r);throw new wt(t.filename,r.importKey)}#ct(e,t,s,r){const i=new ht(r.id,r.importKey,r.fqn,s);t.addMember(i),e.setClass(i)}#ut(e,t,s,r){if(!1===s.isAsync)throw new gt(t.filename,r.name);const i=new pt(r.id,r.importKey,r.fqn,r.access,r.version,s);this.#lt(e,t,i)}#lt(e,t,s){const r=e.hasProcedure(s.fqn)?e.getProcedure(s.fqn):new mt(s.fqn);r.addImplementation(s),t.addMember(s),e.setProcedure(r)}}class It{#ht;constructor(e){this.#ht=e}async read(e,t,s){const r=this.#ht.source,i=this.#ht.resource,n=this.#ht.segment,o=new ct(r),a=await o.readAll(e),c=new O(i,r),u=await c.readAll(t),l=new Tt(n,r,a),h=await l.readAll(s);return new d(a,u,h)}}class vt extends Error{constructor(e){super(`Could not find the rewrite item: ${e}`)}}class Ot{#pt;#c;#u;#dt;#d=new I;constructor(e,t,s,r){this.#pt=e,this.#c=t,this.#u=s,this.#dt=r}generate(){const e=this.#pt.model.clone();return this.#mt(e,e.imports),this.#mt(e,e.exports),e.toString()}#mt(e,t){for(const s of t){const t=this.#ft(s);if(0===t.length)continue;const r=e.statements.indexOf(s);if(-1===r)throw new vt(s.toString());e.statements.splice(r,1,...t)}}#ft(e){if(this.#gt(e))return[];const t=this.#Et(e);return this.#c.isResourceModule(t)?this.#yt(e,t):this.#wt(e,t)}#gt(e){return void 0===e.from||this.#St(e)}#St(e){return!1===this.#d.isApplicationModule(e.from)}#Et(e){const t=e.from,s=this.#d.extractPath(this.#pt.filename);return this.#d.makePathAbsolute(t,s,"")}#yt(e,t){const s=e.clone();return s.from=this.#bt(t),[s]}#wt(e,t){if(0===e.members.length)return[this.#At(t,e,[])];const{segmentKeys:s,remoteKeys:r,commonKeys:i}=this.#Tt(t,e),n=[];return s.length>0&&n.push(this.#It(t,e,s)),r.length>0&&n.push(this.#vt(t,e,r)),i.length>0&&n.push(this.#At(t,e,i)),n}#Tt(e,t){const s=this.#Ot(e,this.#dt),r=this.#Nt(e,s),i=this.#Rt(t,s),n=this.#Rt(t,r);return{segmentKeys:i,remoteKeys:n,commonKeys:this.#xt(t,[...i,...n])}}#Ot(e,t){if(void 0===t)return[];const s=t.getModule(e);return void 0===s?[]:Object.keys(s.imports)}#Nt(e,t){const s=this.#u.getSegments(e).filter(e=>e!==this.#dt).flatMap(t=>this.#Ot(e,t));return[...new Set(s)].filter(e=>!1===t.includes(e))}#Rt(e,t){return e.members.filter(e=>t.includes(e.identifier)).map(e=>e.identifier)}#xt(e,t){return e.members.filter(e=>!1===t.includes(e.identifier)).map(e=>e.identifier)}#It(e,t,s){const r=t.clone();return r.from=this.#bt(e,this.#dt?.name),r.members=this.#Mt(t.members,s),r}#vt(e,t,s){const r=t.clone();return r.from=this.#bt(e,"remote"),r.members=this.#Mt(t.members,s),r}#At(e,t,s){const r=t.clone();return r.from=this.#bt(e),r.members=this.#Mt(t.members,s),r}#Mt(e,t){const s=[];for(const r of t){const t=e.find(e=>e.identifier===r);void 0!==t&&s.push(t)}return s}#bt(e,t){const s=this.#d.extractPath(this.#pt.filename),r=this.#d.makePathRelative(e,s);return void 0!==t?this.#d.addSubExtension(r,t):r}}const Nt={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class Rt extends Error{constructor(e="Invalid request"){super(e)}}class xt extends Error{constructor(e="Forbidden"){super(e)}}class Mt extends Error{constructor(e="Not found"){super(e)}}class Ct extends Error{constructor(e="Not implemented"){super(e)}}class $t extends Error{constructor(e="Payment required"){super(e)}}class Lt extends Error{constructor(e="Server error"){super(e)}}class Pt extends Error{constructor(e="I'm a teapot"){super(e)}}class Ft extends Error{constructor(e="Unauthorized"){super(e)}}class Vt{#l;#Re=new Map;#xe=new Map;constructor(e){this.#l=e}get id(){return this.#l}addClass(e){return this.#Re.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#Re.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#Re.values()]}addProcedure(e){return this.#xe.set(e.fqn,e),this}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}getExposedProcedures(){return[...this.#xe.values()].filter(e=>e.public||e.protected)}}class Dt{static get DEFAULT(){return new Dt(0,0,0)}#Ct;#$t;#Lt;constructor(e=0,t=0,s=0){this.#Ct=e,this.#$t=t,this.#Lt=s}get major(){return this.#Ct}get minor(){return this.#$t}get patch(){return this.#Lt}equals(e){return this.#Ct===e.major&&this.#$t===e.minor&&this.#Lt===e.patch}greater(e){return this.#Ct!==e.major?this.#Ct>e.major:this.#$t!==e.minor?this.#$t>e.minor:this.#Lt!==e.patch&&this.#Lt>e.patch}less(e){return this.#Ct!==e.major?this.#Ct<e.major:this.#$t!==e.minor?this.#$t<e.minor:this.#Lt!==e.patch&&this.#Lt<e.patch}toString(){return`${this.#Ct}.${this.#$t}.${this.#Lt}`}}class kt{#Ne;#Pt;constructor(e,t=!1){this.#Ne=e,this.#Pt=t}get name(){return this.#Ne}get isOptional(){return this.#Pt}}class Bt extends kt{}class jt extends kt{#Ft;constructor(e,t,s){super(t??"(anonymous)",s),this.#Ft=e}get variables(){return this.#Ft}}class Ut extends jt{}class qt extends jt{}class Gt{#Ce;#Le;#Vt;#Dt=new Map;#kt;constructor(e,t,s,r,i){this.#Ce=e,this.#Le=t,this.#Vt=s,this.#Dt=r,this.#kt=i}get fqn(){return this.#Ce}get version(){return this.#Le}get args(){return this.#Vt}get headers(){return this.#Dt}get mode(){return this.#kt}clearArguments(){this.#Vt.clear()}setArgument(e,t){this.#Vt.set(e,t)}getArgument(e){return this.#Vt.get(e)}hasArgument(e){return this.#Vt.has(e)}removeArgument(e){this.#Vt.delete(e)}clearHeaders(){this.#Dt.clear()}setHeader(e,t){this.#Dt.set(e.toLowerCase(),t)}getHeader(e){return this.#Dt.get(e.toLowerCase())}hasHeader(e){return this.#Dt.has(e.toLowerCase())}removeHeader(e){this.#Dt.delete(e.toLowerCase())}}class Ht{#Bt;#jt;#Dt;constructor(e,t=void 0,s=new Map){this.#Bt=e,this.#jt=t,this.#Dt=s}get status(){return this.#Bt}get result(){return this.#jt}set result(e){this.#jt=e}get headers(){return this.#Dt}clearHeaders(){this.#Dt.clear()}setHeader(e,t){this.#Dt.set(e.toLowerCase(),t)}getHeader(e){return this.#Dt.get(e.toLowerCase())}hasHeader(e){return this.#Dt.has(e.toLowerCase())}removeHeader(e){this.#Dt.delete(e.toLowerCase())}}class Kt{#pt;#ke;constructor(e,t){this.#pt=e,this.#ke=t}generate(){const e=[],t=this.#Ut();for(const s of t){const t=s.access===Nt.PRIVATE?this.#qt(s):this.#Gt(s);e.push(...t)}return new Q(e).toString()}#Ut(){const e=this.#ke.map(e=>e.getModule(this.#pt.filename)).flatMap(e=>e.getImplementations()),t=new Map;for(const s of e){const e=`${s.fqn}:${s.version.toString()}`;t.set(e,s)}return[...t.values()]}#qt(e){const t=`throw new ProcedureNotAccessible('${e.fqn}','${e.version}');`;return[this.#Ht(e),this.#Kt(e,t)]}#Gt(e){const t=`return __run('${e.fqn}','${e.version}',{${this.#_t(e.model.parameters)}},this);`;return[this.#Ht(e),this.#Kt(e,t)]}#Ht(e){const t=e.model.identifier,s=e.importKey===w?w:void 0,r=new J(t,s);return new H([r],void 0)}#Kt(e,t){const s=e.model.identifier,r=e.model.parameters,i=new V(`{${t}}`),n=e.model.isAsync;return new L(s,r,i,n)}#_t(e){return this.#Wt(e).join(",")}#Wt(e){const t=[];for(const s of e)if(s.binding instanceof z){const e=this.#zt(s.binding);t.push(e)}else if(s.binding instanceof M){const e=this.#Wt(s.binding.elements);t.push(...e)}else if(s.binding instanceof Z){const e=this.#Wt(s.binding.elements);t.push(...e)}return t}#zt(e){return`'${e.identifier}':${e.toString()}`}}class _t{#Yt;#Xt;#Qt;#dt;constructor(e,t,s,r){this.#Yt=e,this.#Xt=t,this.#Qt=s,this.#dt=r}get source(){return this.#Yt}get target(){return this.#Xt}get resource(){return this.#Qt}get segment(){return this.#dt}}class Wt{#Jt;constructor(e=!0){this.#Jt=e}validate(e,t){const s=[];this.#Zt("",e,t,s);return{valid:0===s.length,errors:s}}#Zt(e,t,s,r){this.#Jt&&this.#es(e,t,s,r),this.#ts(e,t,s,r)}#es(e,t,s,r){const i=Object.keys(t),n=Object.keys(s);for(const t of i)if(!1===n.includes(t)){const s=this.#ss(e,t);r.push(`Unknown field '${s}'`)}}#ts(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#ss(e,n),o=s[n],a=t[n];this.#rs(i,a,o,r)}}#rs(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#is(e,t,s,r);case"integer":return this.#ns(e,t,s,r);case"real":return this.#os(e,t,s,r);case"boolean":return this.#as(e,t,s,r);case"url":return this.#cs(e,t,s,r);case"group":return this.#us(e,t,s,r);case"list":return this.#ls(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#is(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#ns(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#os(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#as(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#cs(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#us(e,t,s,r){"object"==typeof t?this.#Zt(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#ls(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const i=t;for(const t in i){const n=this.#ss(e,t),o=i[t];this.#rs(n,o,s.items,r)}}#ss(e,t){return""===e?t:`${e}.${t}`}}class zt{#hs;constructor(e){this.#hs=e}async configure(e){const t=this.#hs.getAbsoluteLocation(e);n.config({path:t})}}class Yt extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Xt="./jitar.json",Qt="./src",Jt="./dist",Zt="./segments",es="./resources",ts={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let ss=class{#ps;#ds;constructor(e,t){this.#ps=e,this.#ds=t}async build(e=Xt){const t=await this.#ps.read(e),s=this.#ds.validate(t,ts);if(!1===s.valid)throw new Yt(s);return t.source??=Qt,t.target??=Jt,t.segments??=Zt,t.resources??=es,t.meta={root:this.#ps.getRootLocation(),configFile:e},t}};const rs="\n => ";class is extends Error{constructor(e){const t=e.errors.join(rs);super(`Invalid server configuration:${rs}${t}`)}}const ns={indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assetRoot:{type:"string",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}},os={gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}},as={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:ns},standalone:{type:"group",required:!1,fields:{...ns,segments:os.segments}},worker:{type:"group",required:!1,fields:os},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class cs{#ps;#ds;constructor(e,t){this.#ps=e,this.#ds=t}async build(e){const t=await this.#ps.read(e),s=this.#ds.validate(t,as);if(!1===s.valid)throw new is(s);return t.meta={root:this.#ps.getRootLocation(),configFile:e},t}}class us extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const ls=/\${([^}]*)}/g;class hs{#hs;constructor(e){this.#hs=e}getRootLocation(){return this.#hs.getAbsoluteLocation(".")}async read(e){if(!1===await this.#hs.exists(e))return{};const t=await this.#hs.read(e);if(!1===t.type.includes("json"))throw new us(e);const s=t.content.toString(),r=this.#ms(s);return this.#fs(r)}#ms(e){return e.replace(ls,(e,t)=>process.env[t]??"null")}#fs(e){return JSON.parse(e)}}class ps{#gs;#Es;#ys;constructor(e="./"){const t=new p(e),s=new hs(t),r=new Wt;this.#gs=new zt(t),this.#Es=new ss(s,r),this.#ys=new cs(s,r)}configureEnvironment(e=".env"){return this.#gs.configure(e)}getRuntimeConfiguration(e){return this.#Es.build(e)}getServerConfiguration(e){return this.#ys.build(e)}}export{Ut as A,Rt as B,ps as C,c as D,G as E,xt as F,Gt as G,Nt as H,p as L,Mt as N,qt as O,nt as P,Ht as R,Lt as S,Pt as T,Ft as U,Dt as V,z as a,K as b,X as c,Q as d,q as e,k as f,B as g,j as h,U as i,Bt as j,Ct as k,$t as l,Vt as m,I as n,Ot as o,Kt as p,Y as q,J as r,H as s,M as t,Z as u,_t as v,It as w,o as x,Wt as y,u as z};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e,{promises as t,existsSync as r}from"node:fs";import s from"node:path";import{fileURLToPath as n}from"node:url";import{glob as a}from"glob";import i from"mime-types";import o from"dotenv";import{B as c,N as u,F as l,a as h,A as d,O as m,b as p,P as g,T as f,U as w,S as y,V as v,c as b,R as S,d as M,e as x}from"./Response-DEjrdAZ9.js";import E from"node:crypto";import A from"express";class P extends Error{constructor(e){super(`Missing argument '${e}'`)}}class I{#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 P(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 O{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.#n(t);this.#a()}#a(){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")}#n(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,n=e.defaultValue?`default: ${e.defaultValue}`:"no default value",a=e.required?"required":`optional - ${n}`;console.log(` ${t} ${r} (${a})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class R{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 k{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class T extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class N extends Error{constructor(e){super(`Unknown template: ${e}`)}}const C=/^[a-zA-Z.\-_]+$/,$={_gitignore:".gitignore","_package.json":"package.json","_tsconfig.json":"tsconfig.json","_vite.config.ts":"vite.config.ts"};class F{#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 N(t);await this.#m(e,t),this.#p(e)}#u(){const e=s.dirname(n(import.meta.url));return s.join(e,"templates")}#l(e){return s.resolve(e)}#h(e,t){if(!1===C.test(e))throw new T(e,t)}async#d(e){try{const r=s.join(this.#o,e);return(await t.stat(r)).isDirectory()}catch{return!1}}#m(e,r){const n=s.join(this.#o,r),a=s.join(this.#c,e);return t.cp(n,a,{recursive:!0,force:!0})}async#p(e){const n=s.join(this.#c,e),a=Object.entries($),i=[];for(const[e,o]of a){const a=s.join(n,e),c=s.join(n,o);r(a)&&i.push(t.rename(a,c))}await Promise.all(i)}}class L{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.#f(t,r,s),this.#w(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#f(e,t,r){return new F(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`)}}const j=0,z=1,H=2,D=3,q=4;class V{#y;#v;constructor(e=z,t=console){this.#y=e,this.#v=t}debug(...e){if(this.#y>j)return;const t=this.#b("DEBUG",e);this.#v.debug(t)}info(...e){if(this.#y>z)return;const t=this.#b("INFO",e);this.#v.info(t)}warn(...e){if(this.#y>H)return;const t=this.#b("WARN",e);this.#v.warn(t)}error(...e){if(this.#y>D)return;const t=this.#b("ERROR",e);this.#v.error(t)}fatal(...e){const t=this.#b("FATAL",e);this.#v.error(t)}#b(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#S(e)).join(" ")}`}#S(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#M(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#x(t)}${r}`}#M(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#S(e,t)).join(",\n")}\n${this.#x(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#x(e){return" ".repeat(e)}}class B extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class W{parse(e){switch(e.toUpperCase()){case"DEBUG":return j;case"INFO":return z;case"WARN":return H;case"ERROR":return D;case"FATAL":return q;default:throw new B(e)}}}const K="**/*.js",G="**/*.json",U="**/*.json";class _ extends Error{#E;constructor(e){super(`Invalid location: ${e}`),this.#E=e}get location(){return this.#E}}class J extends Error{#A;constructor(e){super(`The file '${e}' could not be found`),this.#A=e}get filename(){return this.#A}}class Y{#E;#P;#I;constructor(e,t,r){this.#E=e,this.#P=t,this.#I=r}get location(){return this.#E}get type(){return this.#P}get content(){return this.#I}get size(){return this.#I.length}}class X{#E;#O;#R;constructor(e,t){const r=t.resolve(e);this.#E=t.normalize(e),this.#O=t.normalize(r),this.#R=t}getAbsoluteLocation(e){const t=this.#R.isAbsolute(e)?e:this.#R.join(this.#E,e),r=this.#R.resolve(t),s=this.#R.normalize(r);return this.#k(s,e),s}getRelativeLocation(e){const t=this.#R.relative(this.#E,e);return this.#R.normalize(t)}normalizeLocation(e){return this.#R.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#R.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#R.exists(t))throw new J(e);return this.#R.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#R.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#R.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),r=await this.getType(t),s=await this.getContent(t);return new Y(e,r,s)}async write(e,t){const r=this.getAbsoluteLocation(e);return this.#R.write(r,t)}async copy(e,t){const r=this.getAbsoluteLocation(e),s=this.getAbsoluteLocation(t);return this.#R.copy(r,s)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#R.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),r=this.#R.normalize(e);return(await this.#R.filter(t,r)).map(e=>this.#R.normalize(e))}#k(e,t){if(!1===e.startsWith(this.#O))throw new _(t)}}class Q{copy(e,r){return t.cp(e,r,{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 a(`${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,n){const a=s.dirname(r);return e.mkdirSync(a,{recursive:!0}),t.writeFile(r,n)}}class Z extends X{constructor(e){super(e,new Q)}}let ee=class extends Error{#T;#N;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#T=e,this.#N=t}get url(){return this.#T}get reason(){return this.#N}};class te{#C;constructor(e){this.#C=e}async import(e){const t=this.#C.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new ee(t,r)}}}class re{#$;constructor(e){this.#$=e}locate(e){return`file://${e.startsWith("/")?this.#$.getAbsoluteLocation(`.${e}`):this.#$.getAbsoluteLocation(e)}`}}class se extends te{constructor(e){super(new re(e))}}class ne{#$;#F;constructor(e,t){this.#$=e,this.#F=t}async filter(...e){return(await Promise.all(e.map(e=>this.#$.filter(e)))).flat().map(e=>this.#$.getRelativeLocation(e))}exists(e){return this.#$.exists(e)}read(e){return this.#$.read(e)}import(e){return this.#F.import(e)}}class ae extends ne{constructor(e){const t=new Z(e);super(t,new se(t))}}let ie=class{#L;#j;#z;constructor(e,t,r){this.#L=e,this.#j=t,this.#z=r}get resources(){return this.#j}get repository(){return this.#L}get segmentation(){return this.#z}};class oe{#j;constructor(e){this.#j=e}isResourceModule(e){return this.#j.includes(e)}}const ce="private",ue="0.0.0",le="index.js",he=".json",de="default",me=/import\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,pe=/export\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,ge="*";let fe=class{#H=0;next(){return"$"+ ++this.#H}};const we="js",ye=/\.js$/,ve=[".","/","http:","https:"];class be{translatePath(e){const t=e.split("/"),r=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":r.pop();continue}r.push(e)}return r.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const r=e.split("/"),s=t.split("/");for(;r[0]===s[0];)r.shift(),s.shift();const n=s.map(()=>"..").join("/");return`${s.length>0?n:"."}/${r.join("/")}`}makePathAbsolute(e,t){const r=""!==t?`${t}/${e}`:e;return this.translatePath(r)}extractPath(e){return e.split("/").slice(0,-1).join("/")}stripPath(e){return e.substring(1,e.length-1)}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${we}`)?e:`${e}.${we}`}addSubExtension(e,t){return e.replace(ye,`.${t}.${we}`)}isApplicationModule(e){return ve.some(t=>e.startsWith(t))}}let Se=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class Me{#D;#q;#V=new be;constructor(e,t){this.#D=e,this.#q=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#B(e)));return new oe(t.flat())}async#B(e){try{const t=await this.#D.getContent(e);return JSON.parse(t.toString()).map(e=>this.#W(e))}catch(t){const r=t instanceof Error?t.message:String(t);throw new Se(e,r)}}#W(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${le}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}}let xe=class{#A;#K;#G;constructor(e,t,r){this.#K=t,this.#A=e,this.#G=r}get filename(){return this.#A}get code(){return this.#K}get model(){return this.#G}};class Ee{#U;constructor(e){this.#U=e}get modules(){return this.#U}get(e){return this.#U.find(t=>t.filename===e)}}class Ae{#_;#J;constructor(e,t){this.#_=e,this.#J=t}get name(){return this.#_}get as(){return this.#J}toString(){return`${this.#_} as ${this.#J}`}}class Pe{#Y;constructor(e){this.#Y=e}get definition(){return this.#Y}toString(){return this.#Y}}class Ie extends Pe{}class Oe{#_;#X;#Q;constructor(e,t=!1,r=!1){this.#_=e,this.#X=t,this.#Q=r}get name(){return this.#_}get isStatic(){return this.#X}get isPrivate(){return this.#Q}get isPublic(){return!1===this.#Q}}class Re extends Oe{#Z;#ee;constructor(e,t,r){super(e),this.#Z=t,this.#ee=r}get parentName(){return this.#Z}get scope(){return this.#ee}get members(){return this.#ee.members}get declarations(){return this.#ee.declarations}get functions(){return this.#ee.functions}get getters(){return this.#ee.getters}get setters(){return this.#ee.setters}get generators(){return this.#ee.generators}get readable(){const e=new Map;return this.getters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get writable(){const e=new Map;return this.setters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get callable(){return this.functions.filter(e=>e.isPublic)}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGetter(e){return this.#ee.getGetter(e)}getSetter(e){return this.#ee.getSetter(e)}getGenerator(e){return this.#ee.getGenerator(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGetter(e){return this.#ee.hasGetter(e)}hasSetter(e){return this.#ee.hasSetter(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}canRead(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasGetter(e)}canWrite(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasSetter(e)}canCall(e){const t=this.getFunction(e);return t?.isPublic??!1}toString(){const e=void 0!==this.#Z?` extends ${this.#Z}`:"";return`class ${this.name}${e} { ${this.#ee.toString()} }`}}class ke extends Oe{#te;#re;constructor(e,t,r=!1,s=!1){super(e.toString(),r,s),this.#te=e,this.#re=t}get identifier(){return this.#te}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Te{#se;constructor(e){this.#se=e}get members(){return this.#se}toString(){return this.#se.map(e=>e.toString()).join(" , ")}}class Ne extends Te{toString(){return`[ ${super.toString()} ]`}}class Ce extends Te{toString(){return`{ ${super.toString()} }`}}class $e extends Oe{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){const e=this.#ne?` from '${this.#ne}'`:"";return`export { ${this.#se.join(", ")} }${e}`}}class Fe extends Pe{}class Le{#_;#re;constructor(e,t){this.#_=e,this.#re=t}get name(){return this.#_}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class je extends Oe{#ae;#ie;#oe;constructor(e,t,r,s=!1,n=!1,a=!1){super(e,s,a),this.#ae=t,this.#ie=r,this.#oe=n}get parameters(){return this.#ae}get body(){return this.#ie}get isAsync(){return this.#oe}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class ze extends je{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class He extends je{toString(){return`get ${super.toString()}`}}class De extends Oe{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){return`import { ${this.#se.map(e=>e.toString()).join(", ")} } from '${this.#ne}';`}}class qe{#ee;constructor(e){this.#ee=e}get scope(){return this.#ee}get members(){return this.#ee.members}get exportedMembers(){return this.#ce(this.#ee.members)}get imports(){return this.#ee.imports}get exports(){return this.#ee.exports}get declarations(){return this.#ee.declarations}get exportedDeclarations(){return this.#ce(this.#ee.declarations)}get functions(){return this.#ee.functions}get exportedFunctions(){return this.#ce(this.#ee.functions)}get generators(){return this.#ee.generators}get exportedGenerators(){return this.#ce(this.#ee.generators)}get classes(){return this.#ee.classes}get exportedClasses(){return this.#ce(this.#ee.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const r of t.members){const t=this.getMember(r.name);void 0!==t&&e.set(r.as,t)}return e}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGenerator(e){return this.#ee.getGenerator(e)}getClass(e){return this.#ee.getClass(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}hasClass(e){return this.#ee.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}isExported(e){for(const t of this.exports)for(const r of t.members)if(r.name===e.name)return!0;return!1}getExport(e){return this.exports.find(t=>t.hasMember(e))}getExported(e){for(const t of this.exports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}#ce(e){return e.filter(e=>this.isExported(e))}}class Ve extends Pe{}class Be extends je{toString(){return`set ${super.toString()}`}}const We=De.name,Ke=$e.name,Ge=ke.name,Ue=je.name,_e=He.name,Je=Be.name,Ye=ze.name,Xe=Re.name;class Qe{#se;constructor(e){this.#se=e}get members(){return this.#se}get imports(){return this.#se.filter(e=>e.constructor.name===We)}get exports(){return this.#se.filter(e=>e.constructor.name===Ke)}get declarations(){return this.#se.filter(e=>e.constructor.name===Ge)}get functions(){return this.#se.filter(e=>e.constructor.name===Ue)}get getters(){return this.#se.filter(e=>e.constructor.name===_e)}get setters(){return this.#se.filter(e=>e.constructor.name===Je)}get generators(){return this.#se.filter(e=>e.constructor.name===Ye)}get classes(){return this.#se.filter(e=>e.constructor.name===Xe)}getMember(e){return this.#se.find(t=>t.name===e)}getDeclaration(e){return this.declarations.find(t=>t.name===e)}getFunction(e){return this.functions.find(t=>t.name===e)}getGetter(e){return this.getters.find(t=>t.name===e)}getSetter(e){return this.setters.find(t=>t.name===e)}getGenerator(e){return this.generators.find(t=>t.name===e)}getClass(e){return this.classes.find(t=>t.name===e)}hasMember(e){return void 0!==this.getMember(e)}hasDeclaration(e){return void 0!==this.getDeclaration(e)}hasFunction(e){return void 0!==this.getFunction(e)}hasGetter(e){return void 0!==this.getGetter(e)}hasSetter(e){return void 0!==this.getSetter(e)}hasGenerator(e){return void 0!==this.getGenerator(e)}hasClass(e){return void 0!==this.getClass(e)}toString(){return this.#se.map(e=>e.toString()).join("\n")}}const Ze={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},et=Object.values(Ze);const tt=".",rt="(",st=")",nt="[",at="]",it="{",ot="}",ct={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},ut=Object.values(ct);function lt(e){return ut.includes(e)}const ht={UNDEFINED:void 0,NULL:null,STRING:""},dt=Object.values(ht);function mt(e){return dt.includes(e)}const pt={OPEN:rt,CLOSE:st};function gt(e){return e===pt.OPEN||e===pt.CLOSE}const ft={EXPORT:"export",DEFAULT:"default",CLASS:"class",FUNCTION:"function",CONST:"const",LET:"let",VAR:"var",AS:"as",FROM:"from",IMPORT:"import",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",ASYNC:"async",RETURN:"return"},wt=Object.values(ft);function yt(e){return wt.includes(e)}function vt(e){return e===ft.AS||e===ft.ASYNC||e===ft.FROM||e===ft.GET||e===ft.SET}const bt={OPEN:nt,CLOSE:at};function St(e){return e===bt.OPEN||e===bt.CLOSE}const Mt=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xt(e){return Mt.includes(e)}const Et={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_DIVIDE:"/=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_MODULO:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",ASSIGN_XOR:"^=",BITWISE_AND:"&",BITWISE_OR:"|",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",MODULO:"%",MULTIPLY:"*",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",XOR:"^"},At=Object.values(Et);function Pt(e){return At.includes(e)}const It={OPEN:it,CLOSE:ot};function Ot(e){return e===It.OPEN||e===It.CLOSE}const Rt={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},kt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Tt=Object.values(kt);function Nt(e){return Tt.includes(e)}class Ct{#ue;#le;constructor(e){this.#ue=e,this.#le=0}get items(){return this.#ue}get position(){return this.#le}get size(){return this.#ue.length}get eol(){return this.#le>=this.#ue.length}get current(){return this.#ue[this.#le]}get next(){return this.#ue[this.#le+1]}get previous(){return this.#ue[this.#le-1]}notAtEnd(){return!1===this.eol}get(e){return this.#ue[e]}step(e=1){return this.#le+=e,this.current}stepBack(e=1){return this.#le-=e,this.current}hasNext(){return this.#le+1<this.#ue.length}}class $t extends Ct{constructor(e){super(e.split(""))}}class Ft{#P;#re;#he;#de;constructor(e,t,r,s){this.#P=e,this.#re=t,this.#he=r,this.#de=s}get type(){return this.#P}get value(){return this.#re}get start(){return this.#he}get end(){return this.#de}isType(e){return this.#P===e}hasValue(e){return this.#re===e}toString(){return`${this.#re}`}}class Lt extends Ct{}class jt{tokenize(e){const t=new $t(e),r=[];let s;for(;t.notAtEnd();){const e=this.#me(t,s);if(void 0===e)break;e.isType(Rt.WHITESPACE)||e.isType(Rt.COMMENT)?t.step():(r.push(e),this.#pe(e)&&(s=e),t.step())}return new Lt(r)}#pe(e){return!1===[Rt.WHITESPACE,Rt.COMMENT].includes(e.type)}#me(e,t){const r=e.current,s=e.position;if(Nt(r)){const t=e.position;return new Ft(Rt.WHITESPACE,r,s,t)}if(function(e){return et.includes(e)}(r+e.next)){const t=this.#ge(e),r=e.position;return new Ft(Rt.COMMENT,t,s,r)}if(this.#fe(r,t)){const t=this.#we(e),r=e.position;return new Ft(Rt.REGEX,t,s,r)}if(xt(r)){const t=this.#ye(e),r=e.position;return new Ft(Rt.LITERAL,t,s,r)}if(Pt(r)){const t=this.#ve(e),r=e.position;return new Ft(Rt.OPERATOR,t,s,r)}if(lt(r)){const t=e.position;return new Ft(Rt.DIVIDER,r,s,t)}if(gt(r)){const t=e.position;return new Ft(Rt.GROUP,r,s,t)}if(Ot(r)){const t=e.position;return new Ft(Rt.SCOPE,r,s,t)}if(St(r)){const t=e.position;return new Ft(Rt.LIST,r,s,t)}if(mt(r))return;const n=this.#be(e),a=yt(n)?Rt.KEYWORD:Rt.IDENTIFIER,i=e.position;return new Ft(a,n,s,i)}#ge(e){const t=e.current+e.next===Ze.MULTI_START,r=t?Ze.MULTI_END:kt.NEWLINE;let s=t?Ze.MULTI_START:Ze.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===r){e.step(r.length-1);break}s+=n,e.step()}return t?s+Ze.MULTI_END:s.trim()}#fe(e,t){return e===Et.DIVIDE&&(void 0===t||([Rt.OPERATOR,Rt.DIVIDER,Rt.KEYWORD].includes(t.type)||[pt.OPEN,bt.OPEN].includes(t.value)))}#Se(e){return Nt(e)||e==tt||!1===this.#Me(e)}#we(e){let t=e.current,r=!1;for(e.step();e.notAtEnd();){const s=e.current,n=e.previous;if(s===Et.DIVIDE&&"\\"!==n)r=!0;else if(!0===r&&this.#Se(s)){e.stepBack();break}t+=s,e.step()}return t}#ye(e){const t=e.current;let r=t,s=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===s){if(n===t){r+=n;break}"\\"===n&&(s=!0)}else s=!1;r+=n,e.step()}return r}#Me(e){return!1===(mt(e)||Nt(e)||Pt(e)||xt(e)||lt(e)||gt(e)||Ot(e)||St(e))}#be(e){let t="";for(;e.notAtEnd();){const r=e.current;if(!1===this.#Me(r)){e.stepBack();break}t+=r,e.step()}return t}#ve(e){let t=e.current;for(e.step();e.notAtEnd();){const r=e.current;if(!1===Pt(r)||!1===Pt(t+r)){e.stepBack();break}t+=r,e.step()}return t}}class zt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ht extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Dt extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class qt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class Vt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Bt="default",Wt=" ";class Kt{#xe;constructor(e=new jt){this.#xe=e}parse(e){const t=this.#xe.tokenize(e),r=this.#Ee(t);return new qe(r)}parseFirst(e){const t=this.#xe.tokenize(e);return this.#Ae(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Pe==!1)throw new qt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof De==!1)throw new qt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof $e==!1)throw new qt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof ke==!1)throw new qt("a declaration definition");return t}parseFunction(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof je==!1)throw new qt("a function definition");return r}parseClass(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof Re==!1)throw new qt("a class definition");return r}#Ee(e){const t=[];for(;e.notAtEnd();){const r=this.#Ae(e);r instanceof Oe&&t.push(r)}return new Qe(t)}#Ae(e,t=!1){const r=e.current;if(r.isType(Rt.LITERAL))return this.#Ie(e);if(r.isType(Rt.IDENTIFIER)){const r=e.next;return r?.hasValue(Et.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.isType(Rt.KEYWORD)){if(vt(r.value)){const t=e.next,s=void 0!==t&&(t.hasValue(ft.FUNCTION)||t.hasValue(pt.OPEN));if(r.hasValue(ft.ASYNC)&&s)return e.step(),this.#Ae(e,!0);if(void 0===t||this.#Re(t))return this.#Ie(e)}return r.hasValue(ft.RETURN)?this.#Ie(e):this.#Pe(e,t)}if(r.isType(Rt.REGEX))return this.#Ie(e);if(r.hasValue(pt.OPEN)){const r=this.#ke(e,pt.OPEN,pt.CLOSE);return r?.hasValue(Et.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.hasValue(It.OPEN))return this.#Te(e);if(r.hasValue(bt.OPEN))return this.#Ne(e);if(r.hasValue(Et.NOT)||r.hasValue(Et.SUBTRACT))return this.#Ie(e);if(!lt(r.value))throw new Vt(r.value,r.start);e.step()}#Pe(e,t=!1){const r=e.current;switch(e.step(),r.value){case ft.IMPORT:return this.#Ce(e);case ft.EXPORT:return this.#$e(e);case ft.CLASS:return this.#Fe(e);case ft.FUNCTION:return this.#Le(e,t);case ft.VAR:case ft.LET:case ft.CONST:return this.#je(e,!1,!0);case ft.ASYNC:return this.#Pe(e,!0);default:throw new Dt(r.value,r.start)}}#Ce(e){const t=[];let r=e.current;if(r.isType(Rt.LITERAL))return new De(t,r.value);if(r.hasValue(pt.OPEN)){r=e.step();const s=r.value;return e.step(2),new De(t,s)}if(!1===r.hasValue(It.OPEN)){const s=r.hasValue(Et.MULTIPLY)?Et.MULTIPLY:Bt;let n=r.value;r=e.step(),r.hasValue(ft.AS)&&(r=e.step(),n=r.value,r=e.step()),t.push(new Ae(s,n))}if(r.hasValue(ct.SEPARATOR)&&(r=e.step()),r.hasValue(It.OPEN)){const s=this.#ze(e);t.push(...s),r=e.current}if(!1===r.hasValue(ft.FROM))throw new zt(ft.FROM,r.start);r=e.step();const s=r.value;return e.step(),new De(t,s)}#$e(e){switch(e.current.value){case ft.DEFAULT:return e.step(),this.#He(e,!0);case It.OPEN:return this.#De(e);default:return this.#He(e,!1)}}#He(e,t){let r=e.current,s=0;var n;r.hasValue(ft.ASYNC)&&(r=e.step(),s++),((n=r.value)===ft.CLASS||n===ft.FUNCTION||n===ft.CONST||n===ft.LET||n===ft.VAR)&&(r=e.step(),s++);const a=this.#Me(r)?r.value:"",i=t?Bt:a;let o;r=e.step(),r?.hasValue(ft.FROM)&&(r=e.step(),o=r.value),s>0&&(s++,e.stepBack(s));const c=new Ae(a,i);return new $e([c],o)}#De(e){const t=this.#ze(e);let r,s=e.current;return s?.hasValue(ft.FROM)&&(s=e.step(),r=s.value),e.step(),new $e(t,r)}#ze(e){const t=[];let r=e.step();for(;e.notAtEnd();){if(r.hasValue(It.CLOSE)){e.step();break}if(r.hasValue(ct.SEPARATOR)){r=e.step();continue}const s=this.#qe(e);t.push(s),r=e.step()}return t}#qe(e){let t=e.current;const r=t.value;let s=r;return e.next.hasValue(ft.AS)&&(t=e.step(2),s=t.value),new Ae(r,s)}#je(e,t,r=!1){let s,n,a=e.current,i=!1;return a.hasValue(bt.OPEN)?(s=this.#Ve(e),a=e.current):a.hasValue(It.OPEN)?(s=this.#Be(e),a=e.current):(i=a.value.startsWith("#"),s=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(Et.ASSIGN)&&(e.step(),n=this.#Ae(e,!1),a=e.current),void 0!==a&&(a.hasValue(ct.TERMINATOR)?e.step():!0===r&&a.hasValue(ct.SEPARATOR)&&(e.step(),this.#je(e,t,!0))),n instanceof ze?new ze(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof je?new je(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof Re?new Re(s.toString(),n.parentName,n.scope):new ke(s,n,t,i)}#Le(e,t,r=!1,s=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(Et.MULTIPLY)&&(o=!0,a=e.step()),this.#Me(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,e.step());const u=this.#We(e,pt.CLOSE);if(a=e.current,!1===a.hasValue(It.OPEN))throw new Ht(It.OPEN,a.start);const l=this.#Ke(e,It.OPEN,It.CLOSE);return o?new ze(i,u,l,r,t,c):s?new He(i,u,l,r,t,c):n?new Be(i,u,l,r,t,c):new je(i,u,l,r,t,c)}#Oe(e,t){let r,s=e.current;if(s.hasValue(pt.OPEN)?(r=this.#We(e,pt.CLOSE),s=e.current):(r=[new Le(s.value,void 0)],s=e.step()),!1===s.hasValue(Et.ARROW))throw new Ht(Et.ARROW,s.start);s=e.step();const n=s.hasValue(It.OPEN)?this.#Ke(e,It.OPEN,It.CLOSE):this.#Ie(e).definition;return new je("",r,n,!1,t,!1)}#We(e,t){const r=[];for(e.step();e.notAtEnd();){const s=e.current;if(s.hasValue(t)){e.step();break}if(s.hasValue(ct.SEPARATOR)){e.step();continue}let n;n=s.hasValue(It.OPEN)?this.#Be(e):s.hasValue(bt.OPEN)?this.#Ve(e):this.#Ge(e),r.push(n)}return r}#Fe(e){let t,r=e.current,s="";if(this.#Me(r)&&(s=r.value,r=e.step()),r.hasValue(ft.EXTENDS)&&(r=e.step(),t=r.value,r=e.step()),!1===r.hasValue(It.OPEN))throw new Ht(It.OPEN,r.start);const n=this.#Ue(e);return new Re(s,t,n)}#Ue(e){let t=e.step();const r=[];for(;e.notAtEnd();){if(t.hasValue(It.CLOSE)){e.step();break}const s=this.#_e(e);r.push(s),t=e.current}return new Qe(r)}#_e(e){let t=e.current,r=!1,s=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(ft.STATIC))s=!0;else if(t.hasValue(ft.ASYNC))r=!0;else if(t.hasValue(ft.GET))n=!0;else{if(!t.hasValue(ft.SET)){if(t.hasValue(Et.MULTIPLY))return this.#Le(e,r,s,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(pt.OPEN)?this.#Le(e,r,s,n,a):this.#je(e,s)}#Ne(e){const t=this.#Ke(e,bt.OPEN,bt.CLOSE);return new Ie(t)}#Ve(e){const t=this.#We(e,bt.CLOSE);return new Ne(t)}#Te(e){const t=this.#Ke(e,It.OPEN,It.CLOSE);return new Ve(t)}#Be(e){const t=this.#We(e,It.CLOSE);return new Ce(t)}#Ge(e){let t=e.current;const r=t.value;let s;return t=e.step(),t.hasValue(Et.ASSIGN)&&(e.step(),s=this.#Ae(e,!1)),new Le(r,s)}#Ie(e){let t=e.current,r="";for(;e.notAtEnd();){if(t.hasValue(bt.OPEN)){r+=this.#Ke(e,bt.OPEN,bt.CLOSE)+Wt,t=e.current}else if(t.hasValue(pt.OPEN)){r+=this.#Ke(e,pt.OPEN,pt.CLOSE)+Wt,t=e.current}else if(t.hasValue(It.OPEN)){r+=this.#Ke(e,It.OPEN,It.CLOSE)+Wt,t=e.current}else r+=t.toString()+Wt,t=e.step();if(void 0===t||this.#Re(t))break}return new Fe(r.trim())}#Ke(e,t,r){let s=e.step(),n=t+Wt;for(;e.notAtEnd();)if(s.hasValue(t))n+=this.#Ke(e,t,r)+Wt,s=e.current;else{if(s.hasValue(r))return e.step(),n+=r,n;n+=s.toString()+Wt,s=e.step()}return n}#ke(e,t,r){const s=e.position;this.#Ke(e,t,r);const n=e.current,a=e.position;return e.stepBack(a-s),n}#Re(e){return[ct.TERMINATOR,ct.SEPARATOR].includes(e.value)||[bt.CLOSE,pt.CLOSE,It.CLOSE].includes(e.value)||yt(e.value)}#Me(e){return e.isType(Rt.IDENTIFIER)||e.isType(Rt.KEYWORD)&&vt(e.value)}}class Gt{merge(e,t){const r=this.#Je(e.declarations,t.declarations),s=this.#Ye(e.functions,t.functions),n=this.#Ye(e.getters,t.getters),a=this.#Ye(e.setters,t.setters),i=[...r.values(),...s.values(),...n.values(),...a.values()];return new Re(e.name,t.name,new Qe(i))}#Je(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}#Ye(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}}class Ut{#Xe=new Kt;#Qe=new Gt;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,n]of r){if("function"!=typeof n.toString)continue;const r=n.toString();if(r.startsWith("class"))s.push(this.fromClass(n,t));else if(r.startsWith("function"))s.push(this.fromFunction(n));else{const t=new Fe(r);s.push(new ke(e,t))}}return new qe(new Qe(s))}fromClass(e,t=!1){const r=this.isClass(e)?this.#Ze(e):this.#et(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const n=this.fromClass(s,!0);return this.#Qe.merge(r,n)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#Xe.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")}#Ze(e){const t=e.toString();return this.#Xe.parseClass(t)}#et(e){const t=this.createInstance(e),r=this.#tt(e,t),s=new Qe(r);return new Re(e.name,void 0,s)}#tt(e,t){return[...this.#rt(t),...this.#st(e)]}#rt(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],n=void 0!==t?new Pe(String(t)):void 0,a=new ke(e,n);s.push(a)}return s}#st(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],n=s.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==s.get?r.push(new He(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==s.set?r.push(new Be(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):r.push(a)}return r}}let _t=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}},Jt=class{#q;#Xe=new Kt;#V=new be;constructor(e){this.#q=e}rewrite(e,t){const r=this.#nt(e,t);return this.#at(e,r)}#nt(e,t){return t.replaceAll(me,t=>this.#it(e,t))}#at(e,t){return t.replaceAll(pe,t=>this.#ot(e,t))}#it(e,t){const r=this.#Xe.parseImport(t),s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ot(e,t){const r=this.#Xe.parseExport(t);if(void 0===r.from)return t;const s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ct(e,t){const r=this.#V.extractPath(e),s=this.#V.makePathAbsolute(t,r);return this.#q.isDirectory(s)?`${t}/${le}`:this.#V.assureExtension(t)}},Yt=class{#q;#Xe;#ut;constructor(e,t=new Kt){this.#q=e,this.#Xe=t,this.#ut=new Jt(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new Ee(t)}async read(e){const t=this.#q.getRelativeLocation(e),r=await this.#lt(e),s=this.#ut.rewrite(t,r),n=this.#Xe.parse(s);return new xe(t,s,n)}async#lt(e){try{return(await this.#q.getContent(e)).toString()}catch(t){const r=t instanceof Error?t.message:String(t);throw new _t(e,r)}}};class Xt{#_;#U=new Map;#ht=new Map;#dt=new Map;constructor(e){this.#_=e}get name(){return this.#_}get modules(){return[...this.#U.values()]}get classes(){return[...this.#ht.values()]}get procedures(){return[...this.#dt.values()]}hasModule(e){return this.#U.has(e)}getModule(e){return this.#U.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#U.set(e.filename,e)}hasProcedure(e){return this.#dt.has(e)}getProcedure(e){return this.#dt.get(e)}setProcedure(e){this.#dt.set(e.fqn,e)}setClass(e){this.#ht.set(e.fqn,e)}}class Qt{#H;#mt;#pt;constructor(e,t,r){this.#H=e,this.#mt=t,this.#pt=r}get id(){return this.#H}get importKey(){return this.#mt}get fqn(){return this.#pt}}class Zt extends Qt{#G;constructor(e,t,r,s){super(e,t,r),this.#G=s}get model(){return this.#G}}class er extends Qt{#gt;#ft;#G;constructor(e,t,r,s,n,a){super(e,t,r),this.#gt=s,this.#ft=n,this.#G=a}get access(){return this.#gt}get version(){return this.#ft}get model(){return this.#G}}class tr{#A;#E;#wt;#se=[];#yt;constructor(e,t,r,s){this.#A=e,this.#E=t,this.#wt=r,this.#yt=s}get filename(){return this.#A}get location(){return this.#E}get imports(){return this.#wt}get members(){return this.#se}get segmented(){return this.#yt}hasClasses(){return this.#se.some(e=>e instanceof Zt)}getClasses(){return this.#se.filter(e=>e instanceof Zt)}hasImplementations(){return this.#se.some(e=>e instanceof er)}getImplementations(){return this.#se.filter(e=>e instanceof er)}addMember(e){this.#se.push(e)}addImports(e){const t=Object.keys(e);for(const r of t)this.#wt[r]=e[r]}}class rr{#pt;#vt=[];constructor(e,t=[]){this.#pt=e,this.#vt=t}get fqn(){return this.#pt}get implementations(){return this.#vt}addImplementation(e){this.#vt.push(e)}}class sr{#bt;constructor(e){this.#bt=e}get segments(){return this.#bt}getSegment(e){return this.#bt.find(t=>t.name===e)}isSegmentedModule(e){return this.#bt.some(t=>t.hasModule(e))}getSegments(e){return this.#bt.filter(t=>t.hasModule(e))}}class nr extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class ar extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class ir extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class or extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class cr extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class ur extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class lr{#L;#V=new be;constructor(e){this.#L=e}locate(e,t){const r=[];return{trace:r,model:this.#St(e,t,r)}}#St(e,t,r){r.push({filename:e,importKey:t});const s=this.#Mt(e);return this.#xt(s,t)?this.#Et(s,t,r):this.#At(s,t)}#Mt(e){const t=this.#L.get(e);if(void 0===t)throw new ur(e);return t}#xt(e,t){const r=e.model.getImport(t),s=e.model.getExport(t);return void 0!==r||void 0!==s?.from}#Et(e,t,r){const s=this.#Pt(e,t)??this.#It(e,t),n=s?.from,a=s?.name,i=this.#V.extractPath(e.filename),o=this.#V.stripPath(n),c=this.#V.makePathAbsolute(o,i);return this.#St(c,a,r)}#At(e,t){const r=this.#It(e,t);if(void 0===r)throw new cr(e.filename,t);const s=e.model.getMember(r.name);if(void 0===s)throw new cr(e.filename,r.name);return s}#It(e,t){const r=e.model.getExport(t),s=r?.getMember(t);if(void 0!==s)return{from:r?.from,name:s.name}}#Pt(e,t){const r=e.model.getImport(t),s=r?.getMember(t);if(void 0!==r&&void 0!==s)return{from:r.from,name:s.name}}}class hr{#Ot;#q;#Rt;#V=new be;constructor(e,t,r){this.#Ot=e,this.#q=t,this.#Rt=new lr(r)}async readAll(e){const t=await Promise.all(e.map(e=>this.#kt(e)));return new sr(t)}async#kt(e){const t=await this.#Tt(e),r=this.#Nt(e),s=new Xt(r);return this.#Ct(s,t),this.#$t(s),s}#Nt(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new ar(e);return t.replace(he,"")}async#Tt(e){try{const t=await this.#Ot.getContent(e);return JSON.parse(t.toString())}catch(t){const r=t instanceof Error?t.message:String(t);throw new ir(e,r)}}#Ct(e,t){for(const[r,s]of Object.entries(t))this.#Ft(e,r,s,!0)}#Ft(e,t,r,s){const n=this.#Lt(t),a=this.#V.extractPath(n),i=e.hasModule(n)?e.getModule(n):new tr(n,a,{},s);i.addImports(r),e.setModule(i)}#Lt(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${le}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#$t(e){const t=new fe;for(const r of e.modules)for(const s in r.imports)this.#jt(e,r,s,t)}#jt(e,t,r,s){const{model:n,trace:a}=this.#Rt.locate(t.filename,r),i=this.#zt(t,n,r,s);this.#Ht(e,t,n,i),a.shift();for(const t of a){const r={[t.importKey]:{access:i.access}};this.#Ft(e,t.filename,r,!1)}}#zt(e,t,r,s){const n=e.imports[r],a=s.next(),i=n.as??t.name;return{id:a,importKey:r,name:i,access:n.access??ce,version:n.version??ue,fqn:this.#Dt(e,i,r)}}#Dt(e,t,r){return this.#qt(e)?t:this.#Vt(e)&&this.#Bt(r)?e.location:`${e.location}/${t}`}#qt(e){return""===e.location}#Vt(e){return e.filename.endsWith(le)}#Bt(e){return e===de}#Ht(e,t,r,s){if(r instanceof Re)return this.#Wt(e,t,r,s);if(r instanceof je)return this.#Kt(e,t,r,s);throw new or(t.filename,s.importKey)}#Wt(e,t,r,s){const n=new Zt(s.id,s.importKey,s.fqn,r);t.addMember(n),e.setClass(n)}#Kt(e,t,r,s){if(!1===r.isAsync)throw new nr(t.filename,s.name);const n=new er(s.id,s.importKey,s.fqn,s.access,s.version,r);this.#Gt(e,t,n)}#Gt(e,t,r){const s=e.hasProcedure(r.fqn)?e.getProcedure(r.fqn):new rr(r.fqn);s.addImplementation(r),t.addMember(r),e.setProcedure(s)}}class dr{#Ut;constructor(e){this.#Ut=e}async read(e,t,r){const s=this.#Ut.source,n=this.#Ut.resource,a=this.#Ut.segment,i=new Yt(s),o=await i.readAll(e),c=new Me(n,s),u=await c.readAll(t),l=new hr(a,s,o),h=await l.readAll(r);return new ie(o,u,h)}}class mr{#_t;#j;#z;#Jt;#Xe=new Kt;#V=new be;constructor(e,t,r,s){this.#_t=e,this.#j=t,this.#z=r,this.#Jt=s}get parser(){return this.#Xe}rewrite(e){return e.replaceAll(this.replacementPattern,e=>this.replaceStatement(e))}replaceStatement(e){const t=this.parseStatement(e);return void 0===t.from?e:this.#Yt(t)?this.#Xt(t):this.#Qt(t)}#Xt(e){const t=this.#Zt(e);return this.#j.isResourceModule(t)?this.#er(t,e):this.#tr(t,e)}#Qt(e){const t=this.#rr(e),r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#tr(e,t){if(0===t.members.length)return this.#sr(e,t,[]);const{segmentKeys:r,remoteKeys:s,commonKeys:n}=this.#nr(e,t),a=[];return r.length>0&&a.push(this.#ar(e,t,r)),s.length>0&&a.push(this.#ir(e,t,s)),n.length>0&&a.push(this.#sr(e,t,n)),a.filter(e=>e.length>0).join("\n")}#er(e,t){const r=this.#or(e);return this.excludeFromBundle(t,r)}#ar(e,t,r){const s=this.#or(e,this.#Jt?.name);return this.includeInBundle(t,s,r)}#ir(e,t,r){const s=this.#or(e,"remote");return this.includeInBundle(t,s,r)}#sr(e,t,r){const s=this.#or(e);return this.includeInBundle(t,s,r)}#Yt(e){const t=this.#V.stripPath(e.from);return this.#V.isApplicationModule(t)}#Zt(e){const t=this.#V.stripPath(e.from),r=this.#V.extractPath(this.#_t.filename);return this.#V.makePathAbsolute(t,r)}#nr(e,t){const r=this.#cr(e,this.#Jt),s=this.#ur(e,r),n=this.#lr(t,r),a=this.#lr(t,s);return{segmentKeys:n,remoteKeys:a,commonKeys:this.#hr(t,[...n,...a])}}#cr(e,t){if(void 0===t)return[];const r=t.getModule(e);return void 0!==r?Object.keys(r.imports):[]}#ur(e,t){const r=this.#z.getSegments(e).filter(e=>e!==this.#Jt).map(t=>this.#cr(e,t)).flat();return[...new Set(r)].filter(e=>!1===t.includes(e))}#lr(e,t){return e.members.filter(e=>t.includes(e.name)).map(e=>e.name)}#hr(e,t){return e.members.filter(e=>!1===t.includes(e.name)).map(e=>e.name)}#or(e,t){const r=this.#V.extractPath(this.#_t.filename),s=this.#V.makePathRelative(e,r);return void 0!==t?this.#V.addSubExtension(s,t):s}#rr(e){return this.#V.stripPath(e.from)}}class pr extends mr{get replacementPattern(){return me}parseStatement(e){return this.parser.parseImport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`import "${t}";`;return`import ${this.#dr(e,r)} from "${t}";`}excludeFromBundle(e,t){if(0===e.members.length)return`await import("${t}");`;return`const ${this.#mr(e)} = await import("${t}");`}#dr(e,t){const r=e.members.filter(e=>t.includes(e.name)),s=r.find(e=>e.name===de),n=void 0!==s,a=n?s.as:"",i=r.filter(e=>e.name!==de).map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name),o=i.length>0;return`${a}${n&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#mr(e){if(this.#pr(e))return e.members[0].as;return`{ ${e.members.map(e=>e.name!==e.as?`${e.name} : ${e.as}`:e.name).join(", ")} }`}#pr(e){return 1===e.members.length&&e.members[0].name===ge}}class gr extends mr{get replacementPattern(){return pe}parseStatement(e){return this.parser.parseExport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`export "${t}";`;return`export ${this.#gr(e,r)} from "${t}";`}excludeFromBundle(e,t){const r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#gr(e,t){const r=e.members.filter(e=>t.includes(e.name));if(1===r.length&&""===r[0].name){const e=r[0];return e.name!==e.as?`${ge} as ${e.as}`:ge}return`{ ${r.map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name).join(", ")} }`}}class fr{build(e,t,r,s){const n=new pr(e,t,r,s),a=new gr(e,t,r,s),i=n.rewrite(e.code);return a.rewrite(i)}}const wr="normal",yr="dry",vr=200,br=400,Sr=401,Mr=402,xr=403,Er=404,Ar=418,Pr=500,Ir=501;class Or extends c{#fr;constructor(e){super(`Invalid version number '${e}'`),this.#fr=e}get number(){return this.#fr}}class Rr extends u{#pt;constructor(e){super(`Procedure '${e}' not found`),this.#pt=e}get fqn(){return this.#pt}}class kr extends l{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Tr extends c{#wr;constructor(e){super(`Unknown parameter ${e}`),this.#wr=e}get parameterName(){return this.#wr}}class Nr extends c{#wr;constructor(e){super(`Missing value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class Cr extends c{#wr;constructor(e){super(`Invalid value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class $r{extract(e,t){const r=this.#yr(e,t),s=[];for(const t of e){const e=this.#vr(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Tr(e)}return s}#yr(e,t){const r=new Map;for(const[s,n]of t){if(this.#br(s)){const t=this.#Sr(s);!0===this.#Mr(e,t)&&r.set(t,n);continue}r.set(s,n)}return r}#br(e){return e.startsWith("*")}#Sr(e){return e.substring(1)}#Mr(e,t){return void 0!==e.find(e=>e.name===t)}#vr(e,t,r){return e instanceof h?this.#xr(e,t,r):this.#Er(e,t)}#xr(e,t,r){const s=t.get(e.name);if(this.#Ar(e,s,r))throw new Nr(e.name);if(this.#Pr(e,s,r))throw new Cr(e.name);return t.delete(e.name),s}#Er(e,t){return e instanceof d?this.#Ir(e,t):this.#Or(e,t)}#Ir(e,t){const r=this.#Rr(e,t);return void 0!==r?Object.values(r):void 0}#Or(e,t){return this.#Rr(e,t)}#Rr(e,t){const r=e instanceof d,s={},n=[];let a=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#vr(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),s[c]=u}if(!0===a&&n.length>0)throw new Nr(n[0]);return a?s:void 0}#Ar(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#Pr(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof d&&t instanceof Array==!1||r instanceof m&&t instanceof Object==!1)}}class Fr{toStatus(e){return e instanceof c?br:e instanceof l?xr:e instanceof u?Er:e instanceof p?Ir:e instanceof g?Mr:e instanceof f?Ar:e instanceof w?Sr:Pr}fromStatus(e,t){switch(e){case br:return new c(t);case xr:return new l(t);case Er:return new u(t);case Ir:return new p(t);case Mr:return new g(t);case Ar:return new f(t);case Sr:return new w(t);default:return new y(t)}}}const Lr=/^\d+(?:\.\d+){0,2}$/;class jr{parse(e){if(0===e.trim().length)return v.DEFAULT;if(!1===Lr.test(e))throw new Or(e);const t=e.split(".");switch(t.length){case 1:return new v(Number.parseInt(t[0]));case 2:return new v(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new v(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class zr extends u{#pt;#ft;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#pt=e,this.#ft=t}get fqn(){return this.#pt}get version(){return this.#ft}}class Hr extends y{constructor(){super("Invalid segment")}}class Dr{#bt=new Map;addSegment(e){this.#bt.set(e.id,e)}clearSegments(){this.#bt.clear()}getClassNames(){const e=new Set;for(const t of this.#bt.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.#bt.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#bt.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#bt.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.#bt.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class qr{#kr;#Tr;#Nr=new $r;#Cr=new Fr;#$r=new Dr;constructor(e,t=[]){this.#kr=e,this.#Tr=t}async start(){return this.#Fr()}async stop(){return this.#Lr()}async loadSegment(e){const t=await this.#kr.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof b==!1)throw new Hr;this.#$r.addSegment(e)}getClassNames(){return this.#$r.getClassNames()}hasClass(e){return this.#$r.hasClass(e)}getClass(e){return this.#$r.getClass(e)}getClassByImplementation(e){return this.#$r.getClassByImplementation(e)}getProcedureNames(){return this.#$r.getProcedureNames()}hasProcedure(e){return this.#$r.hasProcedure(e)}getProcedure(e){return this.#$r.getProcedure(e)}async run(e){const t=this.#jr(e.fqn,e.version),r=this.#Nr.extract(t.parameters,e.args);return e.mode===yr?new S(vr,void 0):this.#zr(e,t,r)}async#Fr(){await Promise.all(this.#Tr.map(e=>this.loadSegment(e)))}#Lr(){this.#$r.clearSegments()}#jr(e,t){const r=this.#$r.getProcedure(e);if(void 0===r)throw new Rr(e);const s=r.getImplementation(t);if(void 0===s)throw new zr(r.fqn,t.toString());return s}async#zr(e,t,r){try{const s=await t.executable.call(e,...r);return new S(vr,s)}catch(e){const t=this.#Cr.toStatus(e);return new S(t,e)}}}class Vr{build(e){let t="";for(const r of e)t+=r.access===M.PRIVATE?this.#Hr(r):this.#Dr(r);return t.trim()}#Hr(e){const t=e.fqn,r=e.version,s=this.#qr(e),n=`throw new ProcedureNotAccessible('${t}', '${r}');`;return this.#Vr(s,n)}#Dr(e){const t=e.fqn,r=e.version,s=this.#Br(e.model.parameters),n=this.#qr(e),a=`return __run('${t}', '${r}', { ${s} }, this);`;return this.#Vr(n,a)}#Wr(e){const t=[];for(const r of e)r instanceof Le?t.push(r.name):(r instanceof Ne||r instanceof Ce)&&t.push(r.toString());return t.join(", ")}#Br(e){return this.#Kr(e).join(", ")}#Kr(e){const t=[];for(const r of e)if(r instanceof Te){const e=this.#Kr(r.members);t.push(...e)}else if(r instanceof Le){const e=this.#Gr(r);t.push(e)}return t}#Gr(e){const t=e.name,r=t.startsWith("...")?t.substring(3):t;return`'${t}': ${r}`}#qr(e){const t=e.model.name,r=this.#Wr(e.model.parameters);return`\nexport ${e.importKey===de?`${de} `:""}async function ${t}(${r})`}#Vr(e,t){return`${e} {\n\t${t}\n}\n`}}let Br=class{#Ur;#_r=new fr;#Jr=new Vr;#V=new be;constructor(e){this.#Ur=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,n=t.modules.map(e=>this.#Yr(e,s,r));await Promise.all(n)}async#Yr(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#Xr(e,t,r);const n=s.map(s=>this.#Qr(e,t,s,r)),a=s[0].getModule(e.filename),i=a?.hasImplementations()?this.#Zr(e,s):Promise.resolve();await Promise.all([...n,i]),this.#Ur.delete(e.filename)}async#Xr(e,t,r){const s=e.filename,n=this.#_r.build(e,t,r);return this.#Ur.write(s,n)}async#Qr(e,t,r,s){const n=this.#V.addSubExtension(e.filename,r.name),a=this.#_r.build(e,t,s,r);return this.#Ur.write(n,a)}async#Zr(e,t){const r=this.#es(e,t),s=this.#V.addSubExtension(e.filename,"remote"),n=this.#Jr.build(r);return this.#Ur.write(s,n)}#es(e,t){const r=t.map(t=>t.getModule(e.filename)).flatMap(e=>e.getImplementations()),s=new Map;for(const e of r){const t=`${e.fqn}:${e.version.toString()}`;s.set(t,e)}return[...s.values()]}};let Wr=class{#Ur;#ts;#V=new be;#rs=new jr;constructor(e,t){this.#Ur=e,this.#ts=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ss(e));await Promise.all(t)}async#ss(e){const t=`${e.name}.segment.js`,r=this.#ns(e);await this.#Ur.write(t,r),this.#ts.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}#ns(e){return`${this.#as(e)}\n${this.#is(e)}`}#as(e){return`import { Segment, Class, Procedure, Implementation, Version, NamedParameter, ArrayParameter, ObjectParameter } from "jitar";\n${this.#os(e)}`}#os(e){const t=[];for(const r of e.getSegmentedModules()){if(0===r.members.length)continue;const s=this.#V.addSubExtension(r.filename,e.name),n=`import ${this.#cs(r)} from "./${s}";`;t.push(n)}return t.join("\n")}#cs(e){const t=e.members,r=t.find(e=>e.importKey===de),s=void 0!==r,n=s?r.id:"",a=t.filter(e=>e.importKey!==de),i=a.map(e=>`${e.importKey} as ${e.id}`),o=a.length>0;return`${n}${s&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#is(e){const t=[];t.push(`export default new Segment("${e.name}")`);for(const r of e.classes)t.push(`\t.addClass(new Class("${r.fqn}", ${r.id}))`);for(const r of e.procedures){t.push(`\t.addProcedure(new Procedure("${r.fqn}")`);for(const e of r.implementations){const r=this.#us(e.version),s=this.#ls(e.model);t.push(`\t\t.addImplementation(new Implementation(${r}, "${e.access}", ${s}, ${e.id}))`)}t.push("\t)")}return t.join("\n")}#us(e){const t=this.#rs.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#ls(e){return`[${this.#hs(e.parameters).join(", ")}]`}#hs(e){const t=[];for(const r of e)t.push(this.#ds(r));return t}#ds(e){return e instanceof Ne?this.#ms(e):e instanceof Ce?this.#ps(e):this.#gs(e)}#gs(e){return`new NamedParameter("${e.name}", ${void 0!==e.value})`}#ms(e){return`new ArrayParameter([${this.#hs(e.members).join(", ")}])`}#ps(e){return`new ObjectParameter([${this.#hs(e.members).join(", ")}])`}};class Kr{#fs;#ws;constructor(e,t){const r=e.target;this.#fs=new Br(r),this.#ws=new Wr(r,t)}async build(e){await Promise.all([this.#fs.build(e),this.#ws.build(e)])}}class Gr{#ys;#vs;#bs;#Jt;constructor(e,t,r,s){this.#ys=e,this.#vs=t,this.#bs=r,this.#Jt=s}get source(){return this.#ys}get target(){return this.#vs}get resource(){return this.#bs}get segment(){return this.#Jt}}class Ur{#ts;#$;#Ss;#Ms;constructor(e,t){this.#ts=new V(t);const r=new Z(e.source),s=new Z(e.target),n=new Z(e.resources),a=new Z(e.segments);this.#$=new Gr(r,s,n,a),this.#Ss=new dr(this.#$),this.#Ms=new Kr(this.#$,this.#ts)}async build(){const e=this.#$.source,t=this.#$.resource,r=this.#$.segment,s=await e.filter(K),n=await t.filter(G),a=await r.filter(U),i=await this.#Ss.read(s,n,a);return this.#Ms.build(i)}}class _r{#xs;constructor(e=!0){this.#xs=e}validate(e,t){const r=[];this.#Es("",e,t,r);return{valid:0===r.length,errors:r}}#Es(e,t,r,s){this.#xs&&this.#As(e,t,r,s),this.#Ps(e,t,r,s)}#As(e,t,r,s){const n=Object.keys(t),a=Object.keys(r);for(const t of n)if(!1===a.includes(t)){const r=this.#Is(e,t);s.push(`Unknown field '${r}'`)}}#Ps(e,t,r,s){const n=Object.keys(r);for(const a of n){const n=this.#Is(e,a),i=r[a],o=t[a];this.#Os(n,o,i,s)}}#Os(e,t,r,s){if(void 0!==t)switch(r.type){case"string":return this.#Rs(e,t,r,s);case"integer":return this.#ks(e,t,r,s);case"real":return this.#Ts(e,t,r,s);case"boolean":return this.#Ns(e,t,r,s);case"url":return this.#Cs(e,t,r,s);case"group":return this.#$s(e,t,r,s);case"list":return this.#Fs(e,t,r,s)}else!0===r.required&&s.push(`Field '${e}' is required`)}#Rs(e,t,r,s){"string"!=typeof t&&s.push(`Field '${e}' is not a string`)}#ks(e,t,r,s){"number"==typeof t&&!1!==Number.isInteger(t)||s.push(`Field '${e}' is not an integer`)}#Ts(e,t,r,s){"number"!=typeof t&&s.push(`Field '${e}' is not a real number`)}#Ns(e,t,r,s){"boolean"!=typeof t&&s.push(`Field '${e}' is not a boolean`)}#Cs(e,t,r,s){"string"==typeof t&&!1!==t.startsWith("http")||s.push(`Field '${e}' is not a valid URL`)}#$s(e,t,r,s){"object"==typeof t?this.#Es(e,t,r.fields,s):s.push(`Field '${e}' is not an object`)}#Fs(e,t,r,s){if(!Array.isArray(t))return void s.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Is(e,t),i=n[t];this.#Os(a,i,r.items,s)}}#Is(e,t){return""===e?t:`${e}.${t}`}}class Jr{async configure(e){o.config({path:e})}}class Yr extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Xr="./jitar.json",Qr="./src",Zr="./dist",es="./segments",ts="./resources",rs={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let ss=class{#Ls;#js;constructor(e,t){this.#Ls=e,this.#js=t}async build(e=Xr){const t=await this.#Ls.read(e),r=this.#js.validate(t,rs);if(!1===r.valid)throw new Yr(r);return t.source??=Qr,t.target??=Zr,t.segments??=es,t.resources??=ts,t}};const ns="\n => ";class as extends Error{constructor(e){const t=e.errors.join(ns);super(`Invalid server configuration:${ns}${t}`)}}const is={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:{indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},standalone:{type:"group",required:!1,fields:{segments:{type:"list",required:!0,items:{type:"string"}},indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},worker:{type:"group",required:!1,fields:{gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}}},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class os{#Ls;#js;constructor(e,t){this.#Ls=e,this.#js=t}async build(e){const t=await this.#Ls.read(e),r=this.#js.validate(t,is);if(!1===r.valid)throw new as(r);return t}}class cs extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const us=/\${([^}]*)}/g;class ls{#$;constructor(e){this.#$=e}async read(e){if(!1===await this.#$.exists(e))return{};const t=await this.#$.read(e);if(!1===t.type.includes("json"))throw new cs(e);const r=t.content.toString(),s=this.#zs(r);return this.#Hs(s)}#zs(e){return e.replace(us,(e,t)=>process.env[t]??"null")}#Hs(e){return JSON.parse(e)}}class hs{#Ds;#qs;#Vs;constructor(e="./"){const t=new Z(e),r=new ls(t),s=new _r;this.#Ds=new Jr,this.#qs=new ss(r,s),this.#Vs=new os(r,s)}configureEnvironment(e=".env"){return this.#Ds.configure(e)}getRuntimeConfiguration(e){return this.#qs.build(e)}getServerConfiguration(e){return this.#Vs.build(e)}}class ds{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),n=this.#Bs(s),a=new hs;await a.configureEnvironment(t);const i=await a.getRuntimeConfiguration(r);return new Ur(i,n).build()}#Bs(e){if(void 0===e)return;return(new W).parse(e)}}const ms="content-type",ps="x-content-type-options",gs="x-jitar-content-type",fs="x-jitar-procedure-version",ws="x-powered-by",ys="nosniff",vs="application/json",bs="application/octet-stream";class Ss extends Error{constructor(){super("Invalid worker id")}}class Ms{#T;#Ws;#Cr=new Fr;#js=new _r;constructor(e,t){this.#T=e,this.#Ws=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#T}/${e}`,r=await this.#Ks(t,{method:"GET"}),s=r.headers.get(ms)??bs,n=await r.arrayBuffer(),a=Buffer.from(n);return new Y(e,s,a)}async isHealthy(){const e=`${this.#T}/health/status`,t=await this.#Ks(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#T}/health`,t=await this.#Ks(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#T}/workers`,n={url:e,procedureNames:t,trustKey:r},a={method:"POST",headers:{"Content-Type":vs},body:JSON.stringify(n)},i=await this.#Ks(s,a),o=i.headers.get(ms);if(null===o||!1===o.includes(vs))throw new Ss;const c=await i.json();if(!1===this.#js.validate(c,{id:{type:"string",required:!0}}).valid)throw new Ss;return c.id}async reportWorker(e,t){const r=`${this.#T}/workers/${e}/report`,s={state:t},n={method:"POST",headers:{"Content-Type":vs},body:JSON.stringify(s)};await this.#Ks(r,n)}async removeWorker(e){const t=`${this.#T}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":vs}};await this.#Ks(t,r)}async run(e){e.setHeader(ms,vs);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[fs]=s;const n=`${this.#T}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:r,body:await this.#Gs(t)},i=await this.#Ks(n,a,!1),o=i.status,c=await this.#Us(i),u=this.#_s(i);return new S(o,c,u)}async#Ks(e,t,r=!0){const s=await this.#Ws.execute(e,t);if(r&&this.#Js(s)){const e=await this.#Us(s);throw this.#Cr.fromStatus(s.status,String(e))}return s}#Js(e){return e.status<200||e.status>399}async#Gs(e){return JSON.stringify(e)}async#Us(e){const t=e.headers.get(gs)??e.headers.get(ms);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}#_s(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class xs{async execute(e,t){return fetch(e,t)}}class Es{#Ws;constructor(e=new xs){this.#Ws=e}build(e){return new Ms(e,this.#Ws)}}const As={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class Ps{get url(){throw new p}get state(){return As.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return As.AVAILABLE}provide(e){throw new p}}class Is{get url(){throw new p}get state(){return As.AVAILABLE}get trustKey(){throw new p}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return As.AVAILABLE}getProcedureNames(){throw new p}hasProcedure(e){throw new p}run(e){throw new p}}class Os{#Ys=As.STOPPED;get state(){return this.#Ys}set state(e){this.#Ys=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.#Xs(As.STOPPED)}isStopped(){return this.#Qs(As.STOPPED)}isAvailable(){return this.#Qs(As.AVAILABLE)}setStarting(){this.#Ys=As.STARTING}setAvailable(){this.#Ys=As.AVAILABLE}setUnavailable(){this.#Ys=As.UNAVAILABLE}setAvailability(e){return this.#Ys=e?As.AVAILABLE:As.UNAVAILABLE,this.#Ys}setStopping(){this.#Ys=As.STOPPING}setStopped(){this.#Ys=As.STOPPED}#Qs(...e){return e.includes(this.#Ys)}#Xs(...e){return!1===this.#Qs(...e)}}class Rs extends w{constructor(){super("Invalid trust key")}}class ks{#T;#Zs;#en;#tn;#rn=new Os;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#en=e.healthManager,this.#tn=e.workerManager}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await this.#en.start(),this.#tn.start(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{this.#tn.stop(),await this.#en.stop()})}async isHealthy(){return this.#en.isHealthy()}async getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async addWorker(e){if(this.#sn(e.trustKey))throw new Rs;return await e.start(),this.#tn.addWorker(e)}getWorker(e){return this.#tn.getWorker(e)}async reportWorker(e,t){return this.#tn.reportWorker(e,t)}async removeWorker(e){return this.#tn.removeWorker(e).stop()}getProcedureNames(){return this.#tn.getProcedureNames()}hasProcedure(e){return this.#tn.hasProcedure(e)}async run(e){return this.#tn.run(e)}#sn(e){return void 0!==this.#Zs&&e!==this.#Zs}}class Ts{#T;#nn;#rn=new Os;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}getProcedureNames(){throw new p}hasProcedure(e){throw new p}addWorker(e){return this.#nn.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#nn.reportWorker(e,t)}removeWorker(e){return this.#nn.removeWorker(e)}run(e){return this.#nn.run(e)}}class Ns extends y{#_;constructor(e){super(`No worker available for procedure '${e}'`),this.#_=e}get name(){return this.#_}}class Cs{#an=[];#in=0;get workers(){return this.#an}addWorker(e){this.#an.includes(e)||this.#an.push(e)}removeWorker(e){const t=this.#an.indexOf(e);-1!==t&&this.#an.splice(t,1)}getNextWorker(){const e=this.#an.filter(e=>e.isAvailable());if(0!==e.length)return this.#in>=e.length&&(this.#in=0),e[this.#in++];this.#in=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new Ns(e.fqn);return t.run(e)}}class $s{generate(){return E.randomUUID()}}class Fs extends y{#H;constructor(e){super(`Unknown worker id '${e}'`),this.#H=e}get id(){return this.#H}}class Ls{#an=new Map;#on=new Map;#cn=new $s;#un;constructor(e,t){this.#un=e.create(()=>this.#ln(),t)}get workers(){return[...this.#an.values()]}get balancers(){return this.#on}start(){this.#un.start()}stop(){this.#un.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.#cn.generate(),this.#an.set(e.id,e);for(const t of e.getProcedureNames()){this.#hn(t).addWorker(e)}return e.id}getWorker(e){const t=this.#an.get(e);if(void 0===t)throw new Fs(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#an.delete(e);for(const e of t.getProcedureNames()){const r=this.#dn(e);void 0!==r&&r.removeWorker(t)}return t}#dn(e){return this.#on.get(e)}#hn(e){let t=this.#dn(e);return void 0===t&&(t=new Cs,this.#on.set(e,t)),t}async run(e){const t=this.#dn(e.fqn);if(void 0===t)throw new Rr(e.fqn);return t.run(e)}async#ln(){const e=this.workers.map(e=>this.#mn(e));await Promise.allSettled(e)}async#mn(e){await e.updateState()===As.STOPPED&&this.removeWorker(e.id)}}class js{#T;#pn;#gn;#rn=new Os;constructor(e){this.#T=e.url,this.#pn=e.provider,this.#gn=e.runner}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#gn.trustKey}get provider(){return this.#pn}get runner(){return this.#gn}async start(){return this.#rn.start(async()=>{await Promise.all([this.#pn.start(),this.#gn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.allSettled([this.#gn.stop(),this.#pn.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#pn.isHealthy(),this.#gn.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#pn.getHealth(),this.#gn.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#pn.provide(e)}getProcedureNames(){return this.#gn.getProcedureNames()}hasProcedure(e){return this.#gn.hasProcedure(e)}run(e){return this.#gn.run(e)}}class zs{#T;#en;#fn;#wn;#yn;#vn;#rn=new Os;constructor(e){this.#T=e.url,this.#en=e.healthManager,this.#fn=e.sourcingManager,this.#wn=e.assets,this.#yn=e.indexFilename??"index.html",this.#vn=e.serveIndexOnNotFound??false}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#en.start(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#en.stop()})}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async provide(e){if(this.#bn(e))return this.provide(this.#yn);if(!1===this.#wn.has(e))throw new J(e);return this.#fn.read(e)}#bn(e){return""===e||e!==this.#yn&&(this.#vn&&!1===this.#wn.has(e))}}class Hs{#T;#nn;#rn=new Os;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#nn.provide(e)}}class Ds extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class qs extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class Vs extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Bs extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Ws{#Sn=[];addSerializer(e){e.parent=this,this.#Sn.unshift(e)}async serialize(e){const t=this.#Sn.find(t=>t.canSerialize(e));if(void 0===t)throw new Bs(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Sn.find(t=>t.canDeserialize(e));if(void 0===t)throw new Vs(typeof e);return t.deserialize(e)}}class Ks extends Error{constructor(){super("Parent serializer not set")}}class Gs{#Mn;set parent(e){this.#Mn=e}serializeOther(e){if(void 0===this.#Mn)throw new Ks;return this.#Mn.serialize(e)}deserializeOther(e){if(void 0===this.#Mn)throw new Ks;return this.#Mn.deserialize(e)}}class Us extends Gs{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 _s extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Js extends Gs{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 _s(e.value)}}}class Ys extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Xs extends Gs{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 Ys(e.base64)}}}const Qs=new Ut;class Zs extends Gs{#xn;constructor(e){super(),this.#xn=e}canSerialize(e){return e instanceof Object&&Qs.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=Qs.getClass(e),r=Qs.fromClass(t,!0),s=this.#En(r),n=this.#xn.resolveKey(t);if(void 0===n)throw new Ds(t.name);return{serialized:!0,key:n,name:"class",args:await this.#An(r,s,e),fields:await this.#Pn(r,s,e)}}#En(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#An(e,t,r){const s={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(r[a]):void 0;s[n.toString()]=t}return s}async#Pn(e,t,r){const s={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(s[a]=await this.serializeOther(r[a]))}return s}async deserialize(e){const t=await this.#In(e);if(void 0===t)throw new Ds(e.key);if(t instanceof Function==!1)throw new qs(e.key);const r=await this.#On(t,e.args),s=Qs.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#On(e,t){const r=Qs.fromClass(e,!0).getFunction("constructor"),s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),n=t[s];return this.deserializeOther(n)});return Promise.all(s)}async#In(e){return globalThis[e.key]??this.#xn.resolveClass(e.key)}}class en extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class tn extends Gs{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 en(e.value);return t}}class rn extends Gs{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 sn extends Gs{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,n]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(n));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 n=await this.deserializeOther(t[e]),a=await this.deserializeOther(r[e]);s.set(n,a)}return s}}class nn extends Gs{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 an extends Gs{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 on extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class cn extends Gs{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 on(e.source,e.flags)}}}class un extends Gs{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 ln=new Ut;class hn extends Gs{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),n=new DataView(s);for(let e=0;e<r.length;e++)n.setUint8(e,r[e]);const a=globalThis[t];return ln.createInstance(a,[s])}}class dn extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class mn extends Gs{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 dn(e.value)}}}class pn{static build(e){const t=new Ws;return t.addSerializer(new an),t.addSerializer(new nn),void 0!==e&&t.addSerializer(new Zs(e)),t.addSerializer(new rn),t.addSerializer(new cn),t.addSerializer(new Js),t.addSerializer(new mn),t.addSerializer(new tn),t.addSerializer(new un),t.addSerializer(new sn),t.addSerializer(new Us),t.addSerializer(new hn),"undefined"!=typeof Buffer&&t.addSerializer(new Xs),t}}class gn{#Rn;constructor(e){this.#Rn=e}resolveKey(e){const t=this.#Rn.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Rn.getClass(e);return t?.implementation}}class fn extends w{constructor(){super("Request not trusted")}}const wn="X-Jitar-Trust-Key",yn="X-Jitar-Data-Encoding",vn="serialized";class bn{#H;#T;#Zs;#kn;#Tn;#Rn;#en;#Nn;#Cn;#rn=new Os;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#kn=e.gateway,this.#Tn=!0===e.registerAtGateway,this.#Rn=e.executionManager,this.#en=e.healthManager;const t=e.scheduleManager;this.#Nn=t.create(()=>this.#$n(),e.reportInterval);const r=new gn(this.#Rn);this.#Cn=pn.build(r)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#Rn.start(),this.#en.start()]),void 0!==this.#kn&&(await this.#kn.start(),this.#Tn&&(this.#H=await this.#kn.addWorker(this),this.#Nn.start())),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{void 0!==this.#kn&&(void 0!==this.#H&&(this.#Nn.stop(),await this.#kn.removeWorker(this.#H)),await this.#kn.stop()),await Promise.all([this.#en.stop(),this.#Rn.stop()])})}getProcedureNames(){return this.#Rn.getProcedureNames()}hasProcedure(e){return this.#Rn.hasProcedure(e)}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async reportState(e){if(void 0!==this.#kn&&void 0!==this.#H)return this.#kn.reportWorker(this.#H,e)}async run(e){return this.#Fn(e)?this.#Ln(e):this.#jn(e)}#Fn(e){return void 0===this.#kn||this.#Rn.hasProcedure(e.fqn)}async#Ln(e){const t=this.#Rn.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#zn(r))throw new Rr(e.fqn);if(this.#Hn(e,r))throw new fn;const s=e.getHeader(yn);s===vn&&(e=await this.#Dn(e)),e.removeHeader(yn);const n=await this.#Rn.run(e);return s===vn?this.#qn(n):n}#zn(e){return void 0===e||e.private}#Hn(e,t){if(t.public)return!1;const r=e.getHeader(wn);return this.#Zs!==r}async#jn(e){(e=await this.#Vn(e)).setHeader(yn,vn),void 0!==this.#Zs&&e.setHeader(wn,this.#Zs);const t=await this.#kn.run(e);return this.#Bn(t)}async#Vn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.serialize(s);t.set(r,e)}return new x(e.fqn,e.version,t,e.headers,e.mode)}async#Dn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.deserialize(s);t.set(r,e)}return new x(e.fqn,e.version,t,e.headers,e.mode)}async#qn(e){const t=await this.#Cn.serialize(e.result);return new S(e.status,t,e.headers)}async#Bn(e){const t=await this.#Cn.deserialize(e.result);return new S(e.status,t,e.headers)}async#$n(){const e=await this.updateState();return this.reportState(e)}}class Sn extends Os{#Wn;#Kn;#Gn=Date.now();#Un=Date.now();constructor(e=6e3,t=18e3){super(),this.#Wn=e,this.#Kn=t}report(e){this.#Gn=Date.now(),this.state=e}update(){this.#Un=Date.now();const e=this.#Un-this.#Gn;return e>=this.#Wn&&(this.state=e>=this.#Kn?As.STOPPED:As.UNAVAILABLE),this.state}}class Mn{#H;#T;#Zs;#_n;#nn;#rn;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#_n=e.procedureNames,this.#nn=e.remote,this.#rn=new Sn(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}getProcedureNames(){return[...this.#_n.values()]}hasProcedure(e){return this.#_n.has(e)}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){return this.#rn.update()}async reportState(e){this.#rn.report(e)}run(e){return this.#nn.run(e)}}class xn{#Jr;#Wn;#Kn;constructor(e,t,r){this.#Jr=e,this.#Wn=t,this.#Kn=r}build(e,t,r){const s=this.#Jr.build(e),n=new Set(t),a=this.#Wn,i=this.#Kn;return new Mn({url:e,trustKey:r,remote:s,procedureNames:n,unavailableThreshold:a,stoppedThreshold:i})}}class En{#gn;constructor(e){this.#gn=e}async handle(e,t){return this.#gn.run(e)}}class An{#rs=new jr;constructor(){this.#Jn()}#Jn(){const e=globalThis;e.__run=this.#Yn.bind(this),e.ProcedureNotAccessible=kr}async#Yn(e,t,r,s){const n=this.#rs.parse(t),a=new Map(Object.entries(r)),i=s instanceof x?s.headers:new Map,o=new x(e,n,a,i,wr),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==vr)throw u.result;return u.result}}const Pn="starting",In="started",On="stopping",Rn="stopped";class kn extends y{constructor(){super("Invalid health check")}}class Tn{#Ys=Rn;#Xn=new Map;#kr;#Qn;constructor(e,t=[]){this.#kr=e,this.#Qn=t}get state(){return this.#Ys}async start(){if(this.#Ys===Rn)try{this.#Ys=Pn,await this.#Zn(),this.#Ys=In}catch(e){throw this.#Ys=Rn,e}}async stop(){if(this.#Ys===In)try{this.#Ys=On,this.clearHealthChecks(),this.#Ys=Rn}catch(e){throw this.#Ys=In,e}}async loadHealthCheck(e){const t=await this.#ea(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new kn;this.#Xn.set(e.name,e)}clearHealthChecks(){this.#Xn.clear()}async isHealthy(){const e=[];for(const t of this.#Xn.values()){const r=this.#ta(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.#Xn){const s=this.#ta(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.#ra(e,t))).then(()=>t)}async#Zn(){(await Promise.all(this.#Qn.map(e=>this.#ea(e)))).forEach(e=>this.addHealthCheck(e))}async#ea(e){return(await this.#kr.import(e)).default}#ra(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#ta(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 Nn="starting",Cn="started",$n="stopping",Fn="stopped";class Ln extends y{constructor(){super("Invalid middleware")}}class jn{#Ys=Fn;#sa=[];#kr;#na;constructor(e,t=[]){this.#kr=e,this.#na=t}get state(){return this.#Ys}async start(){if(this.#Ys===Fn)try{this.#Ys=Nn,await this.#aa(),this.#Ys=Cn}catch(e){throw this.#Ys=Fn,e}}async stop(){if(this.#Ys===Cn)try{this.#Ys=$n,this.clearMiddlewares(),this.#Ys=Fn}catch(e){throw this.#Ys=Cn,e}}async loadMiddleware(e){const t=await this.#ia(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Ln;this.#sa.push(e)}getMiddleware(e){return this.#sa.find(t=>t instanceof e)}clearMiddlewares(){this.#sa=[]}handle(e){return this.#oa(e,0)()}async#aa(){(await Promise.all(this.#na.map(e=>this.#ia(e)))).forEach(e=>this.addMiddleware(e))}async#ia(e){return(await this.#kr.import(e)).default}#oa(e,t){const r=this.#sa[t];if(void 0===r)return async()=>new S(vr);const s=this.#oa(e,t+1);return async()=>await r.handle(e,s)}}class zn{#ts;#ca;#ua;#la=null;constructor(e,t,r=5e3){this.#ts=e,this.#ca=t,this.#ua=r}start(){this.#ha()}stop(){null!==this.#la&&(clearTimeout(this.#la),this.#la=null)}#ha(){this.#la=setTimeout(async()=>{null!==this.#la&&(await this.#da(),this.#ha())},this.#ua),this.#la.unref()}async#da(){try{await this.#ca()}catch(e){this.#ts.warn("Scheduled task failed",e)}}}class Hn{#ma=[];#ts;constructor(e){this.#ts=e}create(e,t){const r=new zn(this.#ts,e,t);return this.#ma.push(r),r}remove(e){const t=this.#ma.indexOf(e);t<0||this.#ma.splice(t,1)}startAll(){this.#ma.forEach(e=>e.start())}stopAll(){this.#ma.forEach(e=>e.stop())}}const Dn="application/null",qn="application/undefined",Vn="application/boolean",Bn="application/number",Wn="application/json",Kn="text/plain",Gn=200,Un=400,_n=401,Jn=402,Yn=403,Xn=404,Qn=418,Zn=500,ea=501;class ta extends An{#pa;#ga;#fa;#wa;#ts;#rs=new jr;constructor(e){super(),this.#pa=e.proxy,this.#ga=e.remoteWorkerBuilder,this.#fa=e.resourceManager,this.#wa=e.middlewareManager,this.#ts=e.logger}get proxy(){return this.#pa}getTrustKey(){return this.#pa.trustKey}async start(){await this.#ya(),this.#ts.info(`Server started at ${this.#pa.url}`),this.#pa.runner instanceof bn&&this.#ts.info("RPC procedures:",this.#pa.runner.getProcedureNames())}async stop(){await this.#va(),this.#ts.info("Server stopped")}async getHealth(){try{const e=await this.#pa.getHealth();return this.#ts.debug("Got health"),this.#ba(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health:",t),this.#Sa(e)}}async isHealthy(){try{const e=await this.#pa.isHealthy();return this.#ts.debug("Got health status"),this.#Ma(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health status:",t),this.#Sa(e)}}async provide(e){try{const t=await this.#pa.provide(e.filename);return this.#ts.info("Provided file:",e.filename),this.#xa(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.warn("Failed to provide file:",t),this.#Sa(e)}}async run(e){try{const t=this.#Ea(e),r=await this.#wa.handle(t);return this.#ts.info("Ran request:",t.fqn),this.#Aa(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed run request:",t),this.#Sa(e)}}async runInternal(e){return this.#pa.run(e)}async addWorker(e){try{const t=this.#Pa(),r=this.#ga.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#ts.info("Added worker:",r.url),this.#Ia({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to add worker:",t),this.#Sa(e)}}async reportWorker(e){try{const t=this.#Oa(e.state),r=this.#Pa();return await r.reportWorker(e.id,t),this.#ts.debug("Reported worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to report worker:",t),this.#Sa(e)}}async removeWorker(e){try{const t=this.#Pa();return await t.removeWorker(e.id),this.#ts.info("Removed worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to remove worker:",t),this.#Sa(e)}}async#ya(){await this.#fa.start(),await Promise.all([this.#pa.start(),this.#wa.start()]);const e=new En(this.#pa);this.#wa.addMiddleware(e)}async#va(){await Promise.all([this.#wa.stop(),this.#pa.stop()]),await this.#fa.stop()}#Ea(e){const t=this.#Ra(e.fqn),r=this.#ka(e.version),s=this.#Ta(e.args),n=this.#Na(e.headers);return new x(t,r,s,n,e.mode)}#Ra(e){if(0===e.length)throw new c("Missing procedure name");if(e.includes(".."))throw new c("Invalid procedure name");return e}#ka(e){return"string"!=typeof e?v.DEFAULT:this.#rs.parse(e)}#Ta(e){return new Map(Object.entries(e))}#Na(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();t.set(e,n)}return t}#Oa(e){if(!1===Object.values(As).includes(e))throw new c("Invalid state value");return e}#ba(e){return{result:Object.fromEntries(e),contentType:Wn,headers:{},status:Gn}}#Ma(e){return{result:e,contentType:Vn,headers:{},status:Gn}}#xa(e){return{result:e.content,contentType:e.type,headers:{},status:Gn}}#Aa(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Ca(t),headers:this.#$a(e.headers),status:e.status}}#Sa(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Ca(t),headers:{},status:this.#Fa(e)}}#Ia(e){return{result:e,contentType:this.#Ca(e),headers:{},status:Gn}}#Ca(e){if(void 0===e)return qn;if(null===e)return Dn;switch(typeof e){case"boolean":return Vn;case"number":return Bn;case"object":return Wn;default:return Kn}}#$a(e){return Object.fromEntries(e)}#Fa(e){return e instanceof c?Un:e instanceof l?Yn:e instanceof u?Xn:e instanceof p?ea:e instanceof g?Jn:e instanceof f?Qn:e instanceof w?_n:Zn}#Pa(){const e=this.#pa.runner;if(e instanceof ks==!1)throw new c("Cannot remove worker from remote gateway");return e}}class ra extends Error{constructor(){super("Unknown service configured")}}class sa{#fn;#La;#ja;constructor(e,t=[],r=[]){this.#fn=e,this.#La=t,this.#ja=r}async start(){return this.#za()}async stop(){return this.#Ha()}#za(){return this.#Da(this.#La)}#Ha(){return this.#Da(this.#ja)}async#Da(e){await Promise.all(e.map(e=>this.#fn.import(e)))}}class na{#fn;#Jr;constructor(e,t){this.#fn=e,this.#Jr=t}async build(e,t){const r=e.setUp,s=e.tearDown,n=e.middleware,a=e.healthChecks,i=new V(t),o=this.#qa(a),c=this.#Va(i),u=await this.#Ba(e,o,c),l=this.#fn,h=this.#Wa(r,s),d=this.#Ka(n),m=this.#Ga(e);return new ta({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:m,logger:i})}#Ba(e,t,r){if(void 0!==e.gateway)return this.#Ua(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#_a(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Ja(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Ya(e.url,e.proxy);if(void 0!==e.standalone)return this.#Xa(e.url,e.standalone,t,r);throw new ra}async#Ua(e,t,r,s){const n=new Ps,a=this.#Qa(e,t,r,s);return new js({url:e,provider:n,runner:a})}async#_a(e,t,r,s){const n=new Ps,a=this.#Za(e,t,r,s);return new js({url:e,provider:n,runner:a})}async#Ja(e,t,r){const s=await this.#ei(e,t,r),n=new Is;return new js({url:e,provider:s,runner:n})}#Qa(e,t,r,s){const n=t.trustKey,a=t.monitorInterval,i=new Ls(s,a);return new ks({url:e,trustKey:n,healthManager:r,workerManager:i})}#ti(e){const t=this.#Jr.build(e);return new Ts({url:e,remote:t})}#Za(e,t,r,s){const n=t.trustKey,a=t.gateway?this.#ti(t.gateway):void 0,i=t.reportInterval,o=void 0!==a,c=this.#ri(t.segments);return new bn({url:e,trustKey:n,reportInterval:i,gateway:a,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#ei(e,t,r){const s=this.#fn,n=await this.#si(t.assets),a=t.indexFilename,i=t.serveIndexOnNotFound;return new zs({url:e,sourcingManager:s,assets:n,indexFilename:a,serveIndexOnNotFound:i,healthManager:r})}#ni(e){const t=this.#Jr.build(e);return new Hs({url:e,remote:t})}async#Ya(e,t){const r=this.#ni(t.repository),s=this.#ti(t.gateway);return new js({url:e,provider:r,runner:s})}async#Xa(e,t,r,s){const n=await this.#ei(e,t,r),a=this.#Za(e,t,r,s);return new js({url:e,provider:n,runner:a})}#Wa(e=[],t=[]){const r=e.map(e=>this.#ai(e)),s=t.map(e=>this.#ai(e));return new sa(this.#fn,r,s)}#qa(e=[]){const t=e.map(e=>this.#ai(e));return new Tn(this.#fn,t)}#Ka(e=[]){const t=e.map(e=>this.#ai(e));return new jn(this.#fn,t)}#ri(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new qr(this.#fn,t)}#Va(e){return new Hn(e)}#Ga(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new xn(this.#Jr,t,r)}async#si(e){if(void 0===e)return new Set;const t=await this.#fn.filter(...e);return new Set(t)}#ai(e){return e.endsWith(".js")?e:e+".js"}}const aa="3000",ia=204800,oa=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class ca{#ii;#oi;#ci;#ui;#js=new _r;constructor(e,t=aa,r=ia){this.#ii=e,this.#oi=t,this.#ci=A(),this.#li(r),this.#hi()}async start(){return await this.#ii.start(),this.#di()}async stop(){return await this.#mi(),this.#ii.stop()}#li(e){this.#ci.use(A.json({limit:e})),this.#ci.use(A.urlencoded({extended:!0})),this.#ci.use(this.#pi.bind(this)),this.#ci.disable(ws)}#hi(){this.#ci.get("/health",(e,t)=>{this.#gi(e,t)}),this.#ci.get("/health/status",(e,t)=>{this.#fi(e,t)}),this.#ci.get("/rpc/*procedure",(e,t)=>{this.#wi(e,t)}),this.#ci.post("/rpc/*procedure",(e,t)=>{this.#yi(e,t)}),this.#ci.options("/rpc/*procedure",(e,t)=>{this.#vi(e,t)}),this.#ci.post("/workers",(e,t)=>{this.#bi(e,t)}),this.#ci.post("/workers/:id/report",(e,t)=>{this.#Si(e,t)}),this.#ci.delete("/workers/:id",(e,t)=>{this.#Mi(e,t)}),this.#ci.use((e,t)=>{this.#xi(e,t)})}#di(){return void 0!==this.#ui?Promise.resolve():new Promise((e,t)=>{this.#ui=this.#ci.listen(this.#oi,t),e()})}#mi(){return void 0===this.#ui?Promise.resolve():new Promise(e=>{this.#ui.close(()=>e())})}#pi(e,t,r){t.setHeader(ps,ys),r()}async#gi(e,t){const r=await this.#ii.getHealth();return this.#Ei(t,r)}async#fi(e,t){const r=await this.#ii.isHealthy();return this.#Ei(t,r)}async#wi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ii(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#yi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#vi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=yr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#bi(e,t){const r=this.#Ri(e),s=this.#js.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 n=r.url,a=r.procedureNames,i=r.trustKey;try{const e=await this.#ii.addWorker({url:n,procedureNames:a,trustKey:i});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Si(e,t){const r={id:e.params.id,state:e.body.state},s=this.#js.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 n=r.id,a=r.state;try{const e=await this.#ii.reportWorker({id:n,state:a});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Mi(e,t){const r={id:e.params.id},s=this.#js.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id;try{const e=await this.#ii.removeWorker({id:n});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#xi(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),n=await this.#ii.provide({filename:s});return this.#Ei(t,n)}#Ai(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Pi(e){const t=e.headers[fs];return Array.isArray(t)?t[0]:t}#Ii(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#Ri(e){return e.body}#Oi(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();oa.includes(e)||(t[e]=n)}return t}#Ei(e,t){const r=this.#ki(t),s=this.#Ti(t);e.status(r),e.setHeader(ms,s),e.setHeader(gs,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const n=this.#Ni(t);return e.send(n)}#ki(e){return void 0!==e.headers.location?302:e.status}#Ti(e){const t=e.contentType.toLowerCase();switch(t){case Vn:case Bn:case qn:case Dn:return Kn}return t}#Ni(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class ua{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"),n=e.getOptionalArgument("--log-level",void 0),a=this.#Bs(n),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Ci(i),c=new hs;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#$i(u,l,o,a);return this.#Fi(h)}async#$i(e,t,r,s){const[,,n]=t.url.split(":"),a=new ae(e.target),i=new Es,o=new na(a,i),c=await o.build(t,s);return new ca(c,n,r)}#Fi(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()}#Bs(e){if(void 0===e)return;return(new W).parse(e)}#Ci(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class la extends Error{constructor(e){super(`Command ${e} not found`)}}class ha{#s=new Set;constructor(){this.#s.add(new O(this.#s)),this.#s.add(new R),this.#s.add(new k),this.#s.add(new L),this.#s.add(new ds),this.#s.add(new ua)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new la(e)}}class da{#Li;#ji;constructor(){this.#Li=new I(process.argv),this.#ji=new ha}start(){const e=this.#Li.getCommand()??"help";return this.#ji.run(e,this.#Li)}}try{const e=new da;await e.start()}catch(e){const t=new V,r=e instanceof Error?e.message:String(e);t.fatal(r)}
|
|
2
|
+
import{promises as e}from"node:fs";import t from"node:path";import{fileURLToPath as r}from"node:url";import{L as s,E as a,P as n,a as i,b as o,c,d as u,e as l,f as h,g as d,h as p,i as m,B as g,N as w,F as f,j as y,A as v,O as b,k as M,l as x,T as S,U as k,S as P,V as A,m as z,R,n as C,o as E,p as H,q as O,r as N,s as T,t as I,u as j,v as $,w as L,x as q,C as B,y as F,z as W,D,G as V}from"./ConfigurationManager-D8N-pXTY.js";import K from"node:crypto";import U from"express";import"glob";import"mime-types";import"dotenv";class _ extends Error{constructor(e){super(`Missing argument '${e}'`)}}class G{#e;#t;constructor(e){this.#e=e[2],this.#t=this.#r(e)}getCommand(){return this.#e}containsKey(e){return this.#t.has(e)}getRequiredArgument(e){const t=this.#t.get(e);if(void 0===t)throw new _(e);return t}getOptionalArgument(e,t){return this.#t.get(e)??t}#r(e){const t=e.slice(3),r=new Map;return t.forEach(e=>{const[t,s]=e.split("=");r.set(t.trim(),s?.trim())}),r}}class J{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#s;constructor(e){this.#s=e}async execute(e){for(const t of this.#s.values())if(e.containsKey(t.name))return this.#a(t);this.#n()}#n(){console.log("\njitar <command>\n"),console.log("Available commands:");const e=[...this.#s.values()],t=e.map(e=>e.name),r=this.#i(t);for(const t of e){const e=t.name.padEnd(r," "),s=t.description;console.log(` ${e} ${s}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#a(e){console.log(`\n${e.description}\n`);const t=e.options;if(0===t.length)return void console.log("No options available.\n");console.log("Options:");const r=t.map(e=>e.key),s=this.#i(r);for(const e of t){const t=e.key.padEnd(s," "),r=e.description,a=e.defaultValue?`default: ${e.defaultValue}`:"no default value",n=e.required?"required":`optional - ${a}`;console.log(` ${t} ${r} (${n})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class X{name="about";description="Shows information about Jitar.";options=[];async execute(e){console.log("\nJitar is a JavaScript Distributed Runtime created and maintained by Masking Technology.\n\nMore information can be found at:\n- https://jitar.dev\n- https://masking.tech\n")}}class Q{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class Z extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class Y extends Error{constructor(e){super(`Unknown template: ${e}`)}}const ee=/^[a-zA-Z.\-_]+$/;class te{#o;#c;constructor(e="./"){this.#o=this.#u(),this.#c=this.#l(e)}async init(e,t){this.#h(e,"project"),this.#h(t,"template");if(!1===await this.#d(t))throw new Y(t);await this.#p(e,t)}#u(){const e=t.dirname(r(import.meta.url));return t.join(e,"templates")}#l(e){return t.resolve(e)}#h(e,t){if(!1===ee.test(e))throw new Z(e,t)}async#d(r){try{const s=t.join(this.#o,r);return(await e.stat(s)).isDirectory()}catch{return!1}}#p(r,s){const a=t.join(this.#o,s),n=t.join(this.#c,r);return e.cp(a,n,{recursive:!0,force:!0})}}class re{name="init";description="Initializes a new Jitar project from a template.";options=[{key:"--name",required:!0,description:"Project name used for creating the project folder"},{key:"--template",required:!0,description:"Template to use [react, vue, backend]"},{key:"--location",required:!1,description:"The root location of the project",defaultValue:"./"}];async execute(e){const t=e.getRequiredArgument("--name"),r=e.getRequiredArgument("--template"),s=e.getOptionalArgument("--location",void 0);this.#m(t,r),await this.#g(t,r,s),this.#w(t)}#m(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#g(e,t,r){return new te(r).init(e,t)}#w(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}class se extends Error{#f;#y;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#f=e,this.#y=t}get url(){return this.#f}get reason(){return this.#y}}class ae{#v;constructor(e){this.#v=e}async import(e){const t=this.#v.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new se(t,r)}}}class ne{#b;constructor(e){this.#b=e}locate(e){return`file://${e.startsWith("/")?this.#b.getAbsoluteLocation(`.${e}`):this.#b.getAbsoluteLocation(e)}`}}class ie extends ae{constructor(e){super(new ne(e))}}class oe{#b;#M;constructor(e,t){this.#b=e,this.#M=t}get fileManager(){return this.#b}get importManager(){return this.#M}async filter(...e){return(await Promise.all(e.map(e=>this.#b.filter(e)))).flat().map(e=>this.#b.getRelativeLocation(e))}exists(e){return this.#b.exists(e)}read(e){return this.#b.read(e)}import(e){return this.#M.import(e)}}class ce extends oe{constructor(e){const t=new s(e);super(t,new ie(t))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new ce(t)}}class ue{merge(e,t){const r=void 0!==e.construct?[e.construct]:[],s=[...this.#x(e.fields,t.fields),...r,...this.#x(e.methods,t.methods),...this.#x(e.getters,t.getters),...this.#x(e.setters,t.setters)];return new a(e.identifier,t.identifier,s)}#x(e,t){const r=new Map;return t.forEach(e=>r.set(e.identifier,e)),e.forEach(e=>r.set(e.identifier,e)),[...r.values()]}}class le{#S=new n;#k=new ue;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,a]of r){if("function"!=typeof a.toString)continue;const r=a.toString();if(r.startsWith("class"))s.push(this.fromClass(a,t));else if(r.startsWith("function"))s.push(this.fromFunction(a));else{const t=new i(e,!1),a=new o(r);s.push(new c("var",t,a))}}return new u(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#P(e):this.#A(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const a=this.fromClass(s,!0);return this.#k.merge(r,a)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#S.parseFunction(t)}createInstance(e,t=[]){return new e(...t)}getClass(e){return e.constructor}getParentClass(e){return Object.getPrototypeOf(e)}isClassObject(e){return this.isClass(e.constructor)}isFunctionObject(e){return this.isFunction(e.constructor)}isClass(e){return e.toString().startsWith("class")}isFunction(e){return e.toString().startsWith("function")||e.toString().startsWith("async function")}#P(e){const t=e.toString();return this.#S.parseClass(t)}#A(e){const t=this.createInstance(e),r=this.#z(e,t);return new a(e.name,void 0,r)}#z(e,t){return[...this.#R(t),...this.#C(e)]}#R(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],a=void 0!==t?new o(String(t)):void 0,n=new l(e,"public","instance",a);s.push(n)}return s}#C(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],a=s.value;if(a instanceof Function==!1)continue;const n=this.fromFunction(a);"constructor"===n.identifier?r.push(new h(n.parameters,n.body)):void 0!==s.get?r.push(new d(n.identifier,"public","instance",n.body)):void 0!==s.set?r.push(new p(n.identifier,"public","instance",n.parameters[0],n.body)):r.push(new m(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return r}}const he="normal",de="dry",pe=200,me=400,ge=401,we=402,fe=403,ye=404,ve=418,be=500,Me=501;class xe extends g{#E;constructor(e){super(`Invalid version number '${e}'`),this.#E=e}get number(){return this.#E}}class Se extends w{#H;constructor(e){super(`Procedure '${e}' not found`),this.#H=e}get fqn(){return this.#H}}class ke extends f{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Pe extends g{#O;constructor(e){super(`Unknown parameter ${e}`),this.#O=e}get parameterName(){return this.#O}}class Ae extends g{#O;constructor(e){super(`Missing value for parameter '${e}'`),this.#O=e}get parameterName(){return this.#O}}class ze extends g{#O;constructor(e){super(`Invalid value for parameter '${e}'`),this.#O=e}get parameterName(){return this.#O}}class Re{extract(e,t){const r=this.#N(e,t),s=[];for(const t of e){const e=this.#T(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Pe(e)}return s}#N(e,t){const r=new Map;for(const[s,a]of t){if(this.#I(s)){const t=this.#j(s);!0===this.#$(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#I(e){return e.startsWith("*")}#j(e){return e.substring(1)}#$(e,t){return void 0!==e.find(e=>e.name===t)}#T(e,t,r){return e instanceof y?this.#L(e,t,r):this.#q(e,t)}#L(e,t,r){const s=t.get(e.name);if(this.#B(e,s,r))throw new Ae(e.name);if(this.#F(e,s,r))throw new ze(e.name);return t.delete(e.name),s}#q(e,t){return e instanceof v?this.#W(e,t):this.#D(e,t)}#W(e,t){const r=this.#V(e,t);return void 0!==r?Object.values(r):void 0}#D(e,t){return this.#V(e,t)}#V(e,t){const r=e instanceof v,s={},a=[];let n=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#T(o,t,e);void 0!==u?n=!0:!1===o.isOptional&&a.push(o.name),s[c]=u}if(!0===n&&a.length>0)throw new Ae(a[0]);return n?s:void 0}#B(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#F(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof v&&t instanceof Array==!1||r instanceof b&&t instanceof Object==!1)}}class Ce{toStatus(e){return e instanceof g?me:e instanceof f?fe:e instanceof w?ye:e instanceof M?Me:e instanceof x?we:e instanceof S?ve:e instanceof k?ge:be}fromStatus(e,t){switch(e){case me:return new g(t);case fe:return new f(t);case ye:return new w(t);case Me:return new M(t);case we:return new x(t);case ve:return new S(t);case ge:return new k(t);default:return new P(t)}}}const Ee=/^\d+(?:\.\d+){0,2}$/;class He{parse(e){if(0===e.trim().length)return A.DEFAULT;if(!1===Ee.test(e))throw new xe(e);const t=e.split(".");switch(t.length){case 1:return new A(Number.parseInt(t[0]));case 2:return new A(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new A(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class Oe extends w{#H;#K;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#H=e,this.#K=t}get fqn(){return this.#H}get version(){return this.#K}}class Ne extends P{constructor(){super("Invalid segment")}}class Te{#U=new Map;addSegment(e){this.#U.set(e.id,e)}clearSegments(){this.#U.clear()}getClassNames(){const e=new Set;for(const t of this.#U.values()){t.getClasses().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasClass(e){return this.getClassNames().includes(e)}getClass(e){for(const t of this.#U.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#U.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#U.values()){t.getExposedProcedures().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}getProcedure(e){for(const t of this.#U.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Ie{#_;#G;#J=new Re;#X=new Ce;#Q=new Te;constructor(e,t=[]){this.#_=e,this.#G=t}async start(){return this.#Z()}async stop(){return this.#Y()}async loadSegment(e){const t=await this.#_.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof z==!1)throw new Ne;this.#Q.addSegment(e)}getClassNames(){return this.#Q.getClassNames()}hasClass(e){return this.#Q.hasClass(e)}getClass(e){return this.#Q.getClass(e)}getClassByImplementation(e){return this.#Q.getClassByImplementation(e)}getProcedureNames(){return this.#Q.getProcedureNames()}hasProcedure(e){return this.#Q.hasProcedure(e)}getProcedure(e){return this.#Q.getProcedure(e)}async run(e){const t=this.#ee(e.fqn,e.version),r=this.#J.extract(t.parameters,e.args);return e.mode===de?new R(pe,void 0):this.#te(e,t,r)}async#Z(){await Promise.all(this.#G.map(e=>this.loadSegment(e)))}#Y(){this.#Q.clearSegments()}#ee(e,t){const r=this.#Q.getProcedure(e);if(void 0===r)throw new Se(e);const s=r.getImplementation(t);if(void 0===s)throw new Oe(r.fqn,t.toString());return s}async#te(e,t,r){try{const s=await t.executable.call(e,...r);return new R(pe,s)}catch(e){const t=this.#X.toStatus(e);return new R(t,e)}}}let je=class{#re;#se=new C;constructor(e){this.#re=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,a=t.modules.map(e=>this.#ae(e,s,r));await Promise.all(a)}async#ae(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#ne(e,t,r);const a=s.map(s=>this.#ie(e,t,s,r)),n=s[0].getModule(e.filename),i=n?.hasImplementations()?this.#oe(e,s):Promise.resolve();await Promise.all([...a,i]),this.#re.delete(e.filename)}async#ne(e,t,r){const s=e.filename,a=new E(e,t,r).generate();return this.#re.write(s,a)}async#ie(e,t,r,s){const a=this.#se.addSubExtension(e.filename,r.name),n=new E(e,t,s,r).generate();return this.#re.write(a,n)}async#oe(e,t){const r=this.#se.addSubExtension(e.filename,"remote"),s=new H(e,t).generate();return this.#re.write(r,s)}};const $e=["Segment","Class","Procedure","Implementation","Version","NamedParameter","ArrayParameter","ObjectParameter"];class Le{#ce;#se=new C;#ue=new He;constructor(e){this.#ce=e}generate(){const e=this.#le(),t=this.#he(),r=this.#de();return new u([...e,t,r]).toString()}#le(){return[this.#pe(),...this.#me()]}#pe(){const e=$e.map(e=>new N(e));return new O(e,"jitar")}#me(){const e=[],t=this.#ce.name,r=this.#ce.getSegmentedModules();for(const s of r){const r=`./${this.#se.addSubExtension(s.filename,t)}`;if(0===s.members.length){const t=new O([],r);e.push(t);continue}const a=s.members.map(e=>new N(e.importKey,e.id)),n=new O(a,r);e.push(n)}return e}#he(){const e=new N("segment","default");return new T([e],void 0)}#de(){const e=[],t=this.#ce.name,r=this.#ce.classes,s=this.#ce.procedures;e.push(`new Segment("${t}")`);for(const t of r)e.push(`\t.addClass(new Class("${t.fqn}", ${t.id}))`);for(const t of s){e.push(`\t.addProcedure(new Procedure("${t.fqn}")`);for(const r of t.implementations){const t=this.#ge(r.version),s=this.#we(r.model);e.push(`\t\t.addImplementation(new Implementation(${t}, "${r.access}", ${s}, ${r.id}))`)}e.push("\t)")}const a=e.join("\n"),n=new o(a),u=new i("segment");return new c("const",u,n)}#ge(e){const t=this.#ue.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#we(e){return`[${this.#fe(e.parameters).join(", ")}]`}#fe(e){const t=[];for(const r of e)t.push(this.#ye(r));return t}#ye(e){return e.binding instanceof I?this.#ve(e):e.binding instanceof j?this.#be(e):this.#Me(e)}#Me(e){return`new NamedParameter("${e.binding}", ${void 0!==e.initializer})`}#ve(e){const t=e.binding;return`new ArrayParameter([${this.#fe(t.elements).join(", ")}])`}#be(e){const t=e.binding;return`new ObjectParameter([${this.#fe(t.elements).join(", ")}])`}}let qe=class{#re;#xe;constructor(e,t){this.#re=e,this.#xe=t}async build(e){const t=e.segmentation.segments.map(e=>this.#Se(e));await Promise.all(t)}async#Se(e){const t=`${e.name}.segment.js`,r=new Le(e).generate();await this.#re.write(t,r),this.#xe.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}};class Be{#ke;#Pe;constructor(e,t){const r=e.target;this.#ke=new je(r),this.#Pe=new qe(r,t)}async build(e){await Promise.all([this.#ke.build(e),this.#Pe.build(e)])}}const Fe=0,We=1,De=2,Ve=3,Ke=4;class Ue{#Ae;#ze;constructor(e=We,t=console){this.#Ae=e,this.#ze=t}debug(...e){if(this.#Ae>Fe)return;const t=this.#Re("DEBUG",e);this.#ze.debug(t)}info(...e){if(this.#Ae>We)return;const t=this.#Re("INFO",e);this.#ze.info(t)}warn(...e){if(this.#Ae>De)return;const t=this.#Re("WARN",e);this.#ze.warn(t)}error(...e){if(this.#Ae>Ve)return;const t=this.#Re("ERROR",e);this.#ze.error(t)}fatal(...e){const t=this.#Re("FATAL",e);this.#ze.error(t)}#Re(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Ce(e)).join(" ")}`}#Ce(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#Ee(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#He(t)}${r}`}#Ee(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Ce(e,t)).join(",\n")}\n${this.#He(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#He(e){return" ".repeat(e)}}class _e extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class Ge{parse(e){switch(e.toUpperCase()){case"DEBUG":return Fe;case"INFO":return We;case"WARN":return De;case"ERROR":return Ve;case"FATAL":return Ke;default:throw new _e(e)}}}class Je{#xe;#se;#b;#Oe;#Ne;constructor(e,t){this.#xe=new Ue(t),this.#se=new C;const r=this.#se.makePathAbsolute(e.source,e.meta.root),a=this.#se.makePathAbsolute(e.target,e.meta.root),n=this.#se.makePathAbsolute(e.resources,e.meta.root),i=this.#se.makePathAbsolute(e.segments,e.meta.root),o=new s(r),c=new s(a),u=new s(n),l=new s(i);this.#b=new $(o,c,u,l),this.#Oe=new L(this.#b),this.#Ne=new Be(this.#b,this.#xe)}async build(){const e=this.#b.source,t=this.#b.resource,r=this.#b.segment,s=await e.filter(q.MODULE_PATTERN),a=await t.filter(q.RESOURCE_PATTERN),n=await r.filter(q.SEGMENT_PATTERN),i=await this.#Oe.read(s,a,n);return this.#Ne.build(i)}}class Xe{name="build";description="Builds the application (creates segment bundles).";options=[{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getOptionalArgument("--log-level",void 0),a=this.#Te(s),n=new B;await n.configureEnvironment(t);const i=await n.getRuntimeConfiguration(r);return new Je(i,a).build()}#Te(e){if(void 0===e)return;return(new Ge).parse(e)}}const Qe="content-type",Ze="x-content-type-options",Ye="x-jitar-content-type",et="x-jitar-procedure-version",tt="x-powered-by",rt="nosniff",st="application/json",at="application/octet-stream";class nt extends Error{constructor(){super("Invalid worker id")}}class it{#f;#Ie;#X=new Ce;#je=new F;constructor(e,t){this.#f=e,this.#Ie=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#f}/${e}`,r=await this.#$e(t,{method:"GET"}),s=r.headers.get(Qe)??at,a=await r.arrayBuffer(),n=Buffer.from(a);return new W(e,s,n)}async isHealthy(){const e=`${this.#f}/health/status`,t=await this.#$e(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#f}/health`,t=await this.#$e(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#f}/workers`,a={url:e,procedureNames:t,trustKey:r},n={method:"POST",headers:{"Content-Type":st},body:JSON.stringify(a)},i=await this.#$e(s,n),o=i.headers.get(Qe);if(null===o||!1===o.includes(st))throw new nt;const c=await i.json();if(!1===this.#je.validate(c,{id:{type:"string",required:!0}}).valid)throw new nt;return c.id}async reportWorker(e,t){const r=`${this.#f}/workers/${e}/report`,s={state:t},a={method:"POST",headers:{"Content-Type":st},body:JSON.stringify(s)};await this.#$e(r,a)}async removeWorker(e){const t=`${this.#f}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":st}};await this.#$e(t,r)}async run(e){e.setHeader(Qe,st);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[et]=s;const a=`${this.#f}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:r,body:await this.#Le(t)},i=await this.#$e(a,n,!1),o=i.status,c=await this.#qe(i),u=this.#Be(i);return new R(o,c,u)}async#$e(e,t,r=!0){const s=await this.#Ie.execute(e,t);if(r&&this.#Fe(s)){const e=await this.#qe(s);throw this.#X.fromStatus(s.status,String(e))}return s}#Fe(e){return e.status<200||e.status>399}async#Le(e){return JSON.stringify(e)}async#qe(e){const t=e.headers.get(Ye)??e.headers.get(Qe);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const r=await e.text();return t?.includes("boolean")?"true"===r:t?.includes("number")?Number(r):r}#Be(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class ot{async execute(e,t){return fetch(e,t)}}class ct{#Ie;constructor(e=new ot){this.#Ie=e}build(e){return new it(e,this.#Ie)}}const ut={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class lt{get url(){throw new M}get state(){return ut.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ut.AVAILABLE}provide(e){throw new M}}class ht{get url(){throw new M}get state(){return ut.AVAILABLE}get trustKey(){throw new M}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ut.AVAILABLE}getProcedureNames(){throw new M}hasProcedure(e){throw new M}run(e){throw new M}}class dt{#We=ut.STOPPED;get state(){return this.#We}set state(e){this.#We=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#De(ut.STOPPED)}isStopped(){return this.#Ve(ut.STOPPED)}isAvailable(){return this.#Ve(ut.AVAILABLE)}setStarting(){this.#We=ut.STARTING}setAvailable(){this.#We=ut.AVAILABLE}setUnavailable(){this.#We=ut.UNAVAILABLE}setAvailability(e){return this.#We=e?ut.AVAILABLE:ut.UNAVAILABLE,this.#We}setStopping(){this.#We=ut.STOPPING}setStopped(){this.#We=ut.STOPPED}#Ve(...e){return e.includes(this.#We)}#De(...e){return!1===this.#Ve(...e)}}class pt extends k{constructor(){super("Invalid trust key")}}class mt{#f;#Ke;#Ue;#_e;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Ue=e.healthManager,this.#_e=e.workerManager}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await this.#Ue.start(),this.#_e.start(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{this.#_e.stop(),await this.#Ue.stop()})}async isHealthy(){return this.#Ue.isHealthy()}async getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async addWorker(e){if(this.#Je(e.trustKey))throw new pt;return await e.start(),this.#_e.addWorker(e)}getWorker(e){return this.#_e.getWorker(e)}async reportWorker(e,t){return this.#_e.reportWorker(e,t)}async removeWorker(e){return this.#_e.removeWorker(e).stop()}getProcedureNames(){return this.#_e.getProcedureNames()}hasProcedure(e){return this.#_e.hasProcedure(e)}async run(e){return this.#_e.run(e)}#Je(e){return void 0!==this.#Ke&&e!==this.#Ke}}class gt{#f;#Xe;#Ge=new dt;constructor(e){this.#f=e.url,this.#Xe=e.remote}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}getProcedureNames(){throw new M}hasProcedure(e){throw new M}addWorker(e){return this.#Xe.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Xe.reportWorker(e,t)}removeWorker(e){return this.#Xe.removeWorker(e)}run(e){return this.#Xe.run(e)}}class wt extends P{#Qe;constructor(e){super(`No worker available for procedure '${e}'`),this.#Qe=e}get name(){return this.#Qe}}class ft{#Ze=[];#Ye=0;get workers(){return this.#Ze}addWorker(e){this.#Ze.includes(e)||this.#Ze.push(e)}removeWorker(e){const t=this.#Ze.indexOf(e);-1!==t&&this.#Ze.splice(t,1)}getNextWorker(){const e=this.#Ze.filter(e=>e.isAvailable());if(0!==e.length)return this.#Ye>=e.length&&(this.#Ye=0),e[this.#Ye++];this.#Ye=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new wt(e.fqn);return t.run(e)}}class yt{generate(){return K.randomUUID()}}class vt extends P{#et;constructor(e){super(`Unknown worker id '${e}'`),this.#et=e}get id(){return this.#et}}class bt{#Ze=new Map;#tt=new Map;#rt=new yt;#st;constructor(e,t){this.#st=e.create(()=>this.#at(),t)}get workers(){return[...this.#Ze.values()]}get balancers(){return this.#tt}start(){this.#st.start()}stop(){this.#st.stop()}getProcedureNames(){const e=this.workers.map(e=>e.getProcedureNames());return[...new Set(e.flat()).values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}addWorker(e){e.id=this.#rt.generate(),this.#Ze.set(e.id,e);for(const t of e.getProcedureNames()){this.#nt(t).addWorker(e)}return e.id}getWorker(e){const t=this.#Ze.get(e);if(void 0===t)throw new vt(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#Ze.delete(e);for(const e of t.getProcedureNames()){const r=this.#it(e);void 0!==r&&r.removeWorker(t)}return t}#it(e){return this.#tt.get(e)}#nt(e){let t=this.#it(e);return void 0===t&&(t=new ft,this.#tt.set(e,t)),t}async run(e){const t=this.#it(e.fqn);if(void 0===t)throw new Se(e.fqn);return t.run(e)}async#at(){const e=this.workers.map(e=>this.#ot(e));await Promise.allSettled(e)}async#ot(e){await e.updateState()===ut.STOPPED&&this.removeWorker(e.id)}}class Mt{#f;#ct;#ut;#Ge=new dt;constructor(e){this.#f=e.url,this.#ct=e.provider,this.#ut=e.runner}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){return this.#ut.trustKey}get provider(){return this.#ct}get runner(){return this.#ut}async start(){return this.#Ge.start(async()=>{await Promise.all([this.#ct.start(),this.#ut.start()]),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await Promise.allSettled([this.#ut.stop(),this.#ct.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#ct.isHealthy(),this.#ut.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#ct.getHealth(),this.#ut.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}provide(e){return this.#ct.provide(e)}getProcedureNames(){return this.#ut.getProcedureNames()}hasProcedure(e){return this.#ut.hasProcedure(e)}run(e){return this.#ut.run(e)}}class xt{#f;#Ue;#lt;#ht;#dt;#pt;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ue=e.healthManager,this.#lt=e.sourcingManager,this.#ht=e.assets,this.#dt=e.indexFilename??"index.html",this.#pt=e.serveIndexOnNotFound??false}get url(){return this.#f}get state(){return this.#Ge.state}async start(){return this.#Ge.start(async()=>{await this.#Ue.start(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Ue.stop()})}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async provide(e){if(this.#mt(e))return this.provide(this.#dt);if(!1===this.#ht.has(e))throw new D(e);return this.#lt.read(e)}#mt(e){return""===e||e!==this.#dt&&(this.#pt&&!1===this.#ht.has(e))}}class St{#f;#Xe;#Ge=new dt;constructor(e){this.#f=e.url,this.#Xe=e.remote}get url(){return this.#f}get state(){return this.#Ge.state}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}provide(e){return this.#Xe.provide(e)}}class kt extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class Pt extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class At extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class zt extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Rt{#gt=[];addSerializer(e){e.parent=this,this.#gt.unshift(e)}async serialize(e){const t=this.#gt.find(t=>t.canSerialize(e));if(void 0===t)throw new zt(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#gt.find(t=>t.canDeserialize(e));if(void 0===t)throw new At(typeof e);return t.deserialize(e)}}class Ct extends Error{constructor(){super("Parent serializer not set")}}class Et{#wt;set parent(e){this.#wt=e}serializeOther(e){if(void 0===this.#wt)throw new Ct;return this.#wt.serialize(e)}deserializeOther(e){if(void 0===this.#wt)throw new Ct;return this.#wt.deserialize(e)}}class Ht extends Et{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const r of e)t.push(await this.serializeOther(r));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Ot extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Nt extends Et{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new Ot(e.value)}}}class Tt extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class It extends Et{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Tt(e.base64)}}}const jt=new le;class $t extends Et{#ft;constructor(e){super(),this.#ft=e}canSerialize(e){return e instanceof Object&&jt.isClassObject(e)}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"class"===t.name&&"string"==typeof t.key&&t.args instanceof Object&&t.args.constructor===Object&&t.fields instanceof Object&&t.fields.constructor===Object}async serialize(e){const t=jt.getClass(e),r=jt.fromClass(t,!0),s=this.#yt(r),a=this.#ft.resolveKey(t);if(void 0===a)throw new kt(t.name);return{serialized:!0,key:a,name:"class",args:await this.#vt(r,s,e),fields:await this.#bt(r,s,e)}}#yt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#vt(e,t,r){const s={};for(const[a,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(r[n]):void 0;s[a.toString()]=t}return s}async#bt(e,t,r){const s={};for(const a of e.writable){const n=a.identifier;t.includes(n)||!1===e.canRead(n)||(s[n]=await this.serializeOther(r[n]))}return s}async deserialize(e){const t=await this.#Mt(e);if(void 0===t)throw new kt(e.key);if(t instanceof Function==!1)throw new Pt(e.key);const r=await this.#xt(t,e.args),s=jt.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#xt(e,t){const r=jt.fromClass(e,!0).construct,s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),a=t[s];return this.deserializeOther(a)});return Promise.all(s)}async#Mt(e){return globalThis[e.key]??this.#ft.resolveClass(e.key)}}class Lt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class qt extends Et{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new Lt(e.value);return t}}class Bt extends Et{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class Ft extends Et{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],r=[];for(const[s,a]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(a));return{serialized:!0,name:"Map",entries:{keys:t,values:r}}}async deserialize(e){const t=e.entries.keys,r=e.entries.values,s=new Map;for(let e=0;e<t.length;e++){const a=await this.deserializeOther(t[e]),n=await this.deserializeOther(r[e]);s.set(a,n)}return s}}class Wt extends Et{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.serializeOther(s)}return t}async deserialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.deserializeOther(s)}return t}}class Dt extends Et{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class Vt extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Kt extends Et{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new Vt(e.source,e.flags)}}}class Ut extends Et{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const r of e.values())t.push(await this.serializeOther(r));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const _t=new le;class Gt extends Et{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,r=new DataView(e.buffer),s=[];for(let e=0;e<r.byteLength;e++)s.push(r.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:s}}async deserialize(e){const t=e.type,r=e.bytes,s=new ArrayBuffer(r.length),a=new DataView(s);for(let e=0;e<r.length;e++)a.setUint8(e,r[e]);const n=globalThis[t];return _t.createInstance(n,[s])}}class Jt extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class Xt extends Et{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new Jt(e.value)}}}class Qt{static build(e){const t=new Rt;return t.addSerializer(new Dt),t.addSerializer(new Wt),void 0!==e&&t.addSerializer(new $t(e)),t.addSerializer(new Bt),t.addSerializer(new Kt),t.addSerializer(new Nt),t.addSerializer(new Xt),t.addSerializer(new qt),t.addSerializer(new Ut),t.addSerializer(new Ft),t.addSerializer(new Ht),t.addSerializer(new Gt),"undefined"!=typeof Buffer&&t.addSerializer(new It),t}}class Zt{#St;constructor(e){this.#St=e}resolveKey(e){const t=this.#St.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#St.getClass(e);return t?.implementation}}class Yt extends k{constructor(){super("Request not trusted")}}const er="X-Jitar-Trust-Key",tr="X-Jitar-Data-Encoding",rr="serialized";class sr{#et;#f;#Ke;#kt;#Pt;#St;#Ue;#At;#zt;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#kt=e.gateway,this.#Pt=!0===e.registerAtGateway,this.#St=e.executionManager,this.#Ue=e.healthManager;const t=e.scheduleManager;this.#At=t.create(()=>this.#Rt(),e.reportInterval);const r=new Zt(this.#St);this.#zt=Qt.build(r)}get id(){return this.#et}set id(e){this.#et=e}get state(){return this.#Ge.state}get url(){return this.#f}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await Promise.all([this.#St.start(),this.#Ue.start()]),void 0!==this.#kt&&(await this.#kt.start(),this.#Pt&&(this.#et=await this.#kt.addWorker(this),this.#At.start())),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{void 0!==this.#kt&&(void 0!==this.#et&&(this.#At.stop(),await this.#kt.removeWorker(this.#et)),await this.#kt.stop()),await Promise.all([this.#Ue.stop(),this.#St.stop()])})}getProcedureNames(){return this.#St.getProcedureNames()}hasProcedure(e){return this.#St.hasProcedure(e)}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}isAvailable(){return this.#Ge.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async reportState(e){if(void 0!==this.#kt&&void 0!==this.#et)return this.#kt.reportWorker(this.#et,e)}async run(e){return this.#Ct(e)?this.#Et(e):this.#Ht(e)}#Ct(e){return void 0===this.#kt||this.#St.hasProcedure(e.fqn)}async#Et(e){const t=this.#St.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#Ot(r))throw new Se(e.fqn);if(this.#Nt(e,r))throw new Yt;const s=e.getHeader(tr);s===rr&&(e=await this.#Tt(e)),e.removeHeader(tr);const a=await this.#St.run(e);return s===rr?this.#It(a):a}#Ot(e){return void 0===e||e.private}#Nt(e,t){if(t.public)return!1;const r=e.getHeader(er);return this.#Ke!==r}async#Ht(e){(e=await this.#jt(e)).setHeader(tr,rr),void 0!==this.#Ke&&e.setHeader(er,this.#Ke);const t=await this.#kt.run(e);return this.#$t(t)}async#jt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#zt.serialize(s);t.set(r,e)}return new V(e.fqn,e.version,t,e.headers,e.mode)}async#Tt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#zt.deserialize(s);t.set(r,e)}return new V(e.fqn,e.version,t,e.headers,e.mode)}async#It(e){const t=await this.#zt.serialize(e.result);return new R(e.status,t,e.headers)}async#$t(e){const t=await this.#zt.deserialize(e.result);return new R(e.status,t,e.headers)}async#Rt(){const e=await this.updateState();return this.reportState(e)}}class ar extends dt{#Lt;#qt;#Bt=Date.now();#Ft=Date.now();constructor(e=6e3,t=18e3){super(),this.#Lt=e,this.#qt=t}report(e){this.#Bt=Date.now(),this.state=e}update(){this.#Ft=Date.now();const e=this.#Ft-this.#Bt;return e>=this.#Lt&&(this.state=e>=this.#qt?ut.STOPPED:ut.UNAVAILABLE),this.state}}class nr{#et;#f;#Ke;#Wt;#Xe;#Ge;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Wt=e.procedureNames,this.#Xe=e.remote,this.#Ge=new ar(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#et}set id(e){this.#et=e}get state(){return this.#Ge.state}get url(){return this.#f}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}getProcedureNames(){return[...this.#Wt.values()]}hasProcedure(e){return this.#Wt.has(e)}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}isAvailable(){return this.#Ge.isAvailable()}async updateState(){return this.#Ge.update()}async reportState(e){this.#Ge.report(e)}run(e){return this.#Xe.run(e)}}class ir{#Dt;#Lt;#qt;constructor(e,t,r){this.#Dt=e,this.#Lt=t,this.#qt=r}build(e,t,r){const s=this.#Dt.build(e),a=new Set(t),n=this.#Lt,i=this.#qt;return new nr({url:e,trustKey:r,remote:s,procedureNames:a,unavailableThreshold:n,stoppedThreshold:i})}}class or{#ut;constructor(e){this.#ut=e}async handle(e,t){return this.#ut.run(e)}}class cr{#ue=new He;constructor(){this.#Vt()}#Vt(){const e=globalThis;e.__run=this.#Kt.bind(this),e.ProcedureNotAccessible=ke}async#Kt(e,t,r,s){const a=this.#ue.parse(t),n=new Map(Object.entries(r)),i=s instanceof V?s.headers:new Map,o=new V(e,a,n,i,he),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==pe)throw u.result;return u.result}}const ur="starting",lr="started",hr="stopping",dr="stopped";class pr extends P{constructor(){super("Invalid health check")}}class mr{#We=dr;#Ut=new Map;#_;#_t;constructor(e,t=[]){this.#_=e,this.#_t=t}get state(){return this.#We}async start(){if(this.#We===dr)try{this.#We=ur,await this.#Gt(),this.#We=lr}catch(e){throw this.#We=dr,e}}async stop(){if(this.#We===lr)try{this.#We=hr,this.clearHealthChecks(),this.#We=dr}catch(e){throw this.#We=lr,e}}async loadHealthCheck(e){const t=await this.#Jt(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new pr;this.#Ut.set(e.name,e)}clearHealthChecks(){this.#Ut.clear()}async isHealthy(){const e=[];for(const t of this.#Ut.values()){const r=this.#Xt(t);e.push(r)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,r]of this.#Ut){const s=this.#Xt(r).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(s)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#Qt(e,t))).then(()=>t)}async#Gt(){(await Promise.all(this.#_t.map(e=>this.#Jt(e)))).forEach(e=>this.addHealthCheck(e))}async#Jt(e){return(await this.#_.import(e)).default}#Qt(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#Xt(e){const t=e.isHealthy(),r=e.timeout;if(void 0===r)return t;const s=new Promise(e=>{setTimeout(e,r)}).then(()=>!1);return Promise.race([s,t])}}const gr="starting",wr="started",fr="stopping",yr="stopped";class vr extends P{constructor(){super("Invalid middleware")}}class br{#We=yr;#Zt=[];#_;#Yt;constructor(e,t=[]){this.#_=e,this.#Yt=t}get state(){return this.#We}async start(){if(this.#We===yr)try{this.#We=gr,await this.#er(),this.#We=wr}catch(e){throw this.#We=yr,e}}async stop(){if(this.#We===wr)try{this.#We=fr,this.clearMiddlewares(),this.#We=yr}catch(e){throw this.#We=wr,e}}async loadMiddleware(e){const t=await this.#tr(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new vr;this.#Zt.push(e)}getMiddleware(e){return this.#Zt.find(t=>t instanceof e)}clearMiddlewares(){this.#Zt=[]}handle(e){return this.#rr(e,0)()}async#er(){(await Promise.all(this.#Yt.map(e=>this.#tr(e)))).forEach(e=>this.addMiddleware(e))}async#tr(e){return(await this.#_.import(e)).default}#rr(e,t){const r=this.#Zt[t];if(void 0===r)return async()=>new R(pe);const s=this.#rr(e,t+1);return async()=>await r.handle(e,s)}}class Mr{#xe;#sr;#ar;#nr=null;constructor(e,t,r=5e3){this.#xe=e,this.#sr=t,this.#ar=r}start(){this.#ir()}stop(){null!==this.#nr&&(clearTimeout(this.#nr),this.#nr=null)}#ir(){this.#nr=setTimeout(async()=>{null!==this.#nr&&(await this.#or(),this.#ir())},this.#ar),this.#nr.unref()}async#or(){try{await this.#sr()}catch(e){this.#xe.warn("Scheduled task failed",e)}}}class xr{#cr=[];#xe;constructor(e){this.#xe=e}create(e,t){const r=new Mr(this.#xe,e,t);return this.#cr.push(r),r}remove(e){const t=this.#cr.indexOf(e);t<0||this.#cr.splice(t,1)}startAll(){this.#cr.forEach(e=>e.start())}stopAll(){this.#cr.forEach(e=>e.stop())}}const Sr="application/null",kr="application/undefined",Pr="application/boolean",Ar="application/number",zr="application/json",Rr="text/plain",Cr=200,Er=400,Hr=401,Or=402,Nr=403,Tr=404,Ir=418,jr=500,$r=501;class Lr extends cr{#ur;#lr;#hr;#dr;#xe;#ue=new He;constructor(e){super(),this.#ur=e.proxy,this.#lr=e.remoteWorkerBuilder,this.#hr=e.resourceManager,this.#dr=e.middlewareManager,this.#xe=e.logger}get proxy(){return this.#ur}getTrustKey(){return this.#ur.trustKey}async start(){await this.#pr(),this.#xe.info(`Server started at ${this.#ur.url}`),this.#ur.runner instanceof sr&&this.#xe.info("RPC procedures:",this.#ur.runner.getProcedureNames())}async stop(){await this.#mr(),this.#xe.info("Server stopped")}async getHealth(){try{const e=await this.#ur.getHealth();return this.#xe.debug("Got health"),this.#gr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to get health:",t),this.#wr(e)}}async isHealthy(){try{const e=await this.#ur.isHealthy();return this.#xe.debug("Got health status"),this.#fr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to get health status:",t),this.#wr(e)}}async provide(e){try{const t=await this.#ur.provide(e.filename);return this.#xe.info("Provided file:",e.filename),this.#yr(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.warn("Failed to provide file:",t),this.#wr(e)}}async run(e){try{const t=this.#vr(e),r=await this.#dr.handle(t);return this.#xe.info("Ran request:",t.fqn),this.#br(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed run request:",t),this.#wr(e)}}async runInternal(e){return this.#ur.run(e)}async addWorker(e){try{const t=this.#Mr(),r=this.#lr.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#xe.info("Added worker:",r.url),this.#xr({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to add worker:",t),this.#wr(e)}}async reportWorker(e){try{const t=this.#Sr(e.state),r=this.#Mr();return await r.reportWorker(e.id,t),this.#xe.debug("Reported worker:",e.id),this.#xr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to report worker:",t),this.#wr(e)}}async removeWorker(e){try{const t=this.#Mr();return await t.removeWorker(e.id),this.#xe.info("Removed worker:",e.id),this.#xr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to remove worker:",t),this.#wr(e)}}async#pr(){await this.#hr.start(),await Promise.all([this.#ur.start(),this.#dr.start()]);const e=new or(this.#ur);this.#dr.addMiddleware(e)}async#mr(){await Promise.all([this.#dr.stop(),this.#ur.stop()]),await this.#hr.stop()}#vr(e){const t=this.#kr(e.fqn),r=this.#Pr(e.version),s=this.#Ar(e.args),a=this.#zr(e.headers);return new V(t,r,s,a,e.mode)}#kr(e){if(0===e.length)throw new g("Missing procedure name");if(e.includes(".."))throw new g("Invalid procedure name");return e}#Pr(e){return"string"!=typeof e?A.DEFAULT:this.#ue.parse(e)}#Ar(e){return new Map(Object.entries(e))}#zr(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();t.set(e,a)}return t}#Sr(e){if(!1===Object.values(ut).includes(e))throw new g("Invalid state value");return e}#gr(e){return{result:Object.fromEntries(e),contentType:zr,headers:{},status:Cr}}#fr(e){return{result:e,contentType:Pr,headers:{},status:Cr}}#yr(e){return{result:e.content,contentType:e.type,headers:{},status:Cr}}#br(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Rr(t),headers:this.#Cr(e.headers),status:e.status}}#wr(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Rr(t),headers:{},status:this.#Er(e)}}#xr(e){return{result:e,contentType:this.#Rr(e),headers:{},status:Cr}}#Rr(e){if(void 0===e)return kr;if(null===e)return Sr;switch(typeof e){case"boolean":return Pr;case"number":return Ar;case"object":return zr;default:return Rr}}#Cr(e){return Object.fromEntries(e)}#Er(e){return e instanceof g?Er:e instanceof f?Nr:e instanceof w?Tr:e instanceof M?$r:e instanceof x?Or:e instanceof S?Ir:e instanceof k?Hr:jr}#Mr(){const e=this.#ur.runner;if(e instanceof mt==!1)throw new g("Cannot remove worker from remote gateway");return e}}class qr extends Error{constructor(){super("Unknown service configured")}}class Br{#lt;#Hr;#Or;constructor(e,t=[],r=[]){this.#lt=e,this.#Hr=t,this.#Or=r}async start(){return this.#Nr()}async stop(){return this.#Tr()}#Nr(){return this.#Ir(this.#Hr)}#Tr(){return this.#Ir(this.#Or)}async#Ir(e){await Promise.all(e.map(e=>this.#lt.import(e)))}}class Fr{#lt;#Dt;constructor(e,t){this.#lt=e,this.#Dt=t}async build(e,t){const r=e.setUp,s=e.tearDown,a=e.middleware,n=e.healthChecks,i=new Ue(t),o=this.#jr(n),c=this.#$r(i),u=await this.#Lr(e,o,c),l=this.#lt,h=this.#qr(r,s),d=this.#Br(a),p=this.#Fr(e);return new Lr({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#Lr(e,t,r){if(void 0!==e.gateway)return this.#Wr(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#Dr(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Vr(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Kr(e.url,e.proxy);if(void 0!==e.standalone)return this.#Ur(e.url,e.standalone,t,r);throw new qr}async#Wr(e,t,r,s){const a=new lt,n=this.#_r(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}async#Dr(e,t,r,s){const a=new lt,n=this.#Gr(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}async#Vr(e,t,r){const s=await this.#Jr(e,t,r),a=new ht;return new Mt({url:e,provider:s,runner:a})}#_r(e,t,r,s){const a=t.trustKey,n=t.monitorInterval,i=new bt(s,n);return new mt({url:e,trustKey:a,healthManager:r,workerManager:i})}#Xr(e){const t=this.#Dt.build(e);return new gt({url:e,remote:t})}#Gr(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Xr(t.gateway):void 0,i=t.reportInterval,o=void 0!==n,c=this.#Qr(t.segments);return new sr({url:e,trustKey:a,reportInterval:i,gateway:n,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#Jr(e,t,r){const s=void 0!==t.assetRoot?this.#lt.fork(t.assetRoot):this.#lt,a=await this.#Zr(s,t.assets),n=t.indexFilename,i=t.serveIndexOnNotFound;return new xt({url:e,sourcingManager:s,assets:a,indexFilename:n,serveIndexOnNotFound:i,healthManager:r})}#Yr(e){const t=this.#Dt.build(e);return new St({url:e,remote:t})}async#Kr(e,t){const r=this.#Yr(t.repository),s=this.#Xr(t.gateway);return new Mt({url:e,provider:r,runner:s})}async#Ur(e,t,r,s){const a=await this.#Jr(e,t,r),n=this.#Gr(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}#qr(e=[],t=[]){const r=e.map(e=>this.#es(e)),s=t.map(e=>this.#es(e));return new Br(this.#lt,r,s)}#jr(e=[]){const t=e.map(e=>this.#es(e));return new mr(this.#lt,t)}#Br(e=[]){const t=e.map(e=>this.#es(e));return new br(this.#lt,t)}#Qr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Ie(this.#lt,t)}#$r(e){return new xr(e)}#Fr(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new ir(this.#Dt,t,r)}async#Zr(e,t){if(void 0===t)return new Set;const r=await e.filter(...t);return new Set(r)}#es(e){return e.endsWith(".js")?e:e+".js"}}const Wr="3000",Dr=204800,Vr=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class Kr{#ts;#rs;#ss;#as;#je=new F;constructor(e,t=Wr,r=Dr){this.#ts=e,this.#rs=t,this.#ss=U(),this.#ns(r),this.#is()}async start(){return await this.#ts.start(),this.#os()}async stop(){return await this.#cs(),this.#ts.stop()}#ns(e){this.#ss.use(U.json({limit:e})),this.#ss.use(U.urlencoded({extended:!0})),this.#ss.use(this.#us.bind(this)),this.#ss.disable(tt)}#is(){this.#ss.get("/health",(e,t)=>{this.#ls(e,t)}),this.#ss.get("/health/status",(e,t)=>{this.#hs(e,t)}),this.#ss.get("/rpc/*procedure",(e,t)=>{this.#ds(e,t)}),this.#ss.post("/rpc/*procedure",(e,t)=>{this.#ps(e,t)}),this.#ss.options("/rpc/*procedure",(e,t)=>{this.#ms(e,t)}),this.#ss.post("/workers",(e,t)=>{this.#gs(e,t)}),this.#ss.post("/workers/:id/report",(e,t)=>{this.#ws(e,t)}),this.#ss.delete("/workers/:id",(e,t)=>{this.#fs(e,t)}),this.#ss.use((e,t)=>{this.#ys(e,t)})}#os(){return void 0!==this.#as?Promise.resolve():new Promise((e,t)=>{this.#as=this.#ss.listen(this.#rs,t),e()})}#cs(){return void 0===this.#as?Promise.resolve():new Promise(e=>{this.#as.close(()=>e())})}#us(e,t,r){t.setHeader(Ze,rt),r()}async#ls(e,t){const r=await this.#ts.getHealth();return this.#vs(t,r)}async#hs(e,t){const r=await this.#ts.isHealthy();return this.#vs(t,r)}async#ds(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#xs(e),n=this.#Ss(e),i=he,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#ps(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#ks(e),n=this.#Ss(e),i=he,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#ms(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#ks(e),n=this.#Ss(e),i=de,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#gs(e,t){const r=this.#ks(e),s=this.#je.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.url,n=r.procedureNames,i=r.trustKey;try{const e=await this.#ts.addWorker({url:a,procedureNames:n,trustKey:i});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ws(e,t){const r={id:e.params.id,state:e.body.state},s=this.#je.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id,n=r.state;try{const e=await this.#ts.reportWorker({id:a,state:n});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#fs(e,t){const r={id:e.params.id},s=this.#je.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id;try{const e=await this.#ts.removeWorker({id:a});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ys(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),a=await this.#ts.provide({filename:s});return this.#vs(t,a)}#bs(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Ms(e){const t=e.headers[et];return Array.isArray(t)?t[0]:t}#xs(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#ks(e){return e.body}#Ss(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();Vr.includes(e)||(t[e]=a)}return t}#vs(e,t){const r=this.#Ps(t),s=this.#As(t);e.status(r),e.setHeader(Qe,s),e.setHeader(Ye,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const a=this.#zs(t);return e.send(a)}#Ps(e){return void 0!==e.headers.location?302:e.status}#As(e){const t=e.contentType.toLowerCase();switch(t){case Pr:case Ar:case kr:case Sr:return Rr}return t}#zs(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class Ur{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),a=e.getOptionalArgument("--log-level",void 0),n=this.#Te(a),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Rs(i),c=new B;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#Cs(u,l,o,n);return this.#Es(h)}async#Cs(e,t,r,s){const[,,a]=t.url.split(":"),n=new ce(e.target),i=new ct,o=new Fr(n,i),c=await o.build(t,s);return new Kr(c,a,r)}#Es(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#Te(e){if(void 0===e)return;return(new Ge).parse(e)}#Rs(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class _r extends Error{constructor(e){super(`Command ${e} not found`)}}class Gr{#s=new Set;constructor(){this.#s.add(new J(this.#s)),this.#s.add(new X),this.#s.add(new Q),this.#s.add(new re),this.#s.add(new Xe),this.#s.add(new Ur)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new _r(e)}}class Jr{#Hs;#Os;constructor(){this.#Hs=new G(process.argv),this.#Os=new Gr}start(){const e=this.#Hs.getCommand()??"help";return this.#Os.run(e,this.#Hs)}}try{const e=new Jr;await e.start()}catch(e){const t=new Ue,r=e instanceof Error?e.message:String(e);t.fatal(r)}
|