jitar 0.10.5 → 0.10.6
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/cli.js +1 -1
- package/dist/client.js +1 -1
- package/package.json +4 -4
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"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,a=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 Promise.all([this.#en.start(),this.#tn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.all([this.#tn.stop(),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)}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 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"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,a=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 Promise.all([this.#en.start(),this.#tn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.all([this.#tn.stop(),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)}
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{constructor(e="Invalid request"){super(e)}}class t extends Error{constructor(e="Forbidden"){super(e)}}class s extends Error{constructor(e="Not found"){super(e)}}class r extends Error{constructor(e="Not implemented"){super(e)}}class n extends Error{constructor(e="Payment required"){super(e)}}class a extends Error{constructor(e="Server error"){super(e)}}class i extends Error{constructor(e="I'm a teapot"){super(e)}}class o extends Error{constructor(e="Unauthorized"){super(e)}}const c="private",u="protected",l="public",h="normal",d="dry",p=200,m=400,g=401,f=402,w=403,y=404,v=418,S=500,E=501;class b extends e{#e;constructor(e){super(`Invalid version number '${e}'`),this.#e=e}get number(){return this.#e}}class x extends s{#t;constructor(e){super(`Procedure '${e}' not found`),this.#t=e}get fqn(){return this.#t}}class O extends t{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class A{#s;#r=new Map;#n=new Map;constructor(e){this.#s=e}get id(){return this.#s}addClass(e){return this.#r.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#r.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#r.values()]}addProcedure(e){return this.#n.set(e.fqn,e),this}hasProcedure(e){return this.#n.has(e)}getProcedure(e){return this.#n.get(e)}getExposedProcedures(){return[...this.#n.values()].filter(e=>e.public||e.protected)}}class C{#t;#a;constructor(e,t){this.#t=e,this.#a=t}get fqn(){return this.#t}get implementation(){return this.#a}}class I{static get DEFAULT(){return new I(0,0,0)}#i;#o;#c;constructor(e=0,t=0,s=0){this.#i=e,this.#o=t,this.#c=s}get major(){return this.#i}get minor(){return this.#o}get patch(){return this.#c}equals(e){return this.#i===e.major&&this.#o===e.minor&&this.#c===e.patch}greater(e){return this.#i!==e.major?this.#i>e.major:this.#o!==e.minor?this.#o>e.minor:this.#c!==e.patch&&this.#c>e.patch}less(e){return this.#i!==e.major?this.#i<e.major:this.#o!==e.minor?this.#o<e.minor:this.#c!==e.patch&&this.#c<e.patch}toString(){return`${this.#i}.${this.#o}.${this.#c}`}}class N{#t;#u=new Map;#l;constructor(e){this.#t=e}get fqn(){return this.#t}get public(){return[...this.#u.values()].some(e=>e.public)}get protected(){return[...this.#u.values()].some(e=>e.protected)}addImplementation(e){return this.#u.set(e.version,e),this.#h(e)&&(this.#l=e),this}#h(e){return void 0===this.#l||e.version.greater(this.#l.version)}getImplementation(e){const t=this.#d(e);return this.#u.get(t)}#d(e){let t=I.DEFAULT;for(const s of this.#u.keys()){if(s.equals(e))return s;s.greater(e)||t.less(s)&&(t=s)}return t}}class M{#p;#m;#g;#f;constructor(e,t,s,r){this.#p=e,this.#m=t,this.#g=s,this.#f=r}get version(){return this.#p}get public(){return this.#m===l}get protected(){return this.#m===u}get private(){return this.#m===c}get parameters(){return this.#g}get executable(){return this.#f}}class T{#w;#y;constructor(e,t=!1){this.#w=e,this.#y=t}get name(){return this.#w}get isOptional(){return this.#y}}class R extends T{}class z extends T{#v;constructor(e,t,s){super(t??"(anonymous)",s),this.#v=e}get variables(){return this.#v}}class P extends z{}class L extends z{}class k{#t;#p;#S;#E=new Map;#b;constructor(e,t,s,r,n){this.#t=e,this.#p=t,this.#S=s,this.#E=r,this.#b=n}get fqn(){return this.#t}get version(){return this.#p}get args(){return this.#S}get headers(){return this.#E}get mode(){return this.#b}clearArguments(){this.#S.clear()}setArgument(e,t){this.#S.set(e,t)}getArgument(e){return this.#S.get(e)}hasArgument(e){return this.#S.has(e)}removeArgument(e){this.#S.delete(e)}clearHeaders(){this.#E.clear()}setHeader(e,t){this.#E.set(e.toLowerCase(),t)}getHeader(e){return this.#E.get(e.toLowerCase())}hasHeader(e){return this.#E.has(e.toLowerCase())}removeHeader(e){this.#E.delete(e.toLowerCase())}}class D{#x;#O;#E;constructor(e,t=void 0,s=new Map){this.#x=e,this.#O=t,this.#E=s}get status(){return this.#x}get result(){return this.#O}set result(e){this.#O=e}get headers(){return this.#E}clearHeaders(){this.#E.clear()}setHeader(e,t){this.#E.set(e.toLowerCase(),t)}getHeader(e){return this.#E.get(e.toLowerCase())}hasHeader(e){return this.#E.has(e.toLowerCase())}removeHeader(e){this.#E.delete(e.toLowerCase())}}class F extends e{#A;constructor(e){super(`Unknown parameter ${e}`),this.#A=e}get parameterName(){return this.#A}}class V extends e{#A;constructor(e){super(`Missing value for parameter '${e}'`),this.#A=e}get parameterName(){return this.#A}}class j extends e{#A;constructor(e){super(`Invalid value for parameter '${e}'`),this.#A=e}get parameterName(){return this.#A}}class ${extract(e,t){const s=this.#C(e,t),r=[];for(const t of e){const e=this.#I(t,s);r.push(e)}if(s.size>0){const e=s.keys().next().value;throw new F(e)}return r}#C(e,t){const s=new Map;for(const[r,n]of t){if(this.#N(r)){const t=this.#M(r);!0===this.#T(e,t)&&s.set(t,n);continue}s.set(r,n)}return s}#N(e){return e.startsWith("*")}#M(e){return e.substring(1)}#T(e,t){return void 0!==e.find(e=>e.name===t)}#I(e,t,s){return e instanceof R?this.#R(e,t,s):this.#z(e,t)}#R(e,t,s){const r=t.get(e.name);if(this.#P(e,r,s))throw new V(e.name);if(this.#L(e,r,s))throw new j(e.name);return t.delete(e.name),r}#z(e,t){return e instanceof P?this.#k(e,t):this.#D(e,t)}#k(e,t){const s=this.#F(e,t);return void 0!==s?Object.values(s):void 0}#D(e,t){return this.#F(e,t)}#F(e,t){const s=e instanceof P,r={},n=[];let a=!1,i=0;for(const o of e.variables){const c=s?i++:o.name,u=this.#I(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),r[c]=u}if(!0===a&&n.length>0)throw new V(n[0]);return a?r:void 0}#P(e,t,s){return void 0===t&&(!0!==e.isOptional&&!0!==s?.isOptional)}#L(e,t,s){return!1!==e.name.startsWith("...")&&(void 0===s&&t instanceof Array==!1||s instanceof P&&t instanceof Array==!1||s instanceof L&&t instanceof Object==!1)}}class H{toStatus(a){return a instanceof e?m:a instanceof t?w:a instanceof s?y:a instanceof r?E:a instanceof n?f:a instanceof i?v:a instanceof o?g:S}fromStatus(c,u){switch(c){case m:return new e(u);case w:return new t(u);case y:return new s(u);case E:return new r(u);case f:return new n(u);case v:return new i(u);case g:return new o(u);default:return new a(u)}}}const U=/^\d+(?:\.\d+){0,2}$/;class G{parse(e){if(0===e.trim().length)return I.DEFAULT;if(!1===U.test(e))throw new b(e);const t=e.split(".");switch(t.length){case 1:return new I(Number.parseInt(t[0]));case 2:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class q extends s{#t;#p;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#t=e,this.#p=t}get fqn(){return this.#t}get version(){return this.#p}}class B extends a{constructor(){super("Invalid segment")}}class W{#V=new Map;addSegment(e){this.#V.set(e.id,e)}clearSegments(){this.#V.clear()}getClassNames(){const e=new Set;for(const t of this.#V.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.#V.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#V.values()){const s=t.getClassByImplementation(e);if(void 0!==s)return s}}getProcedureNames(){const e=new Set;for(const t of this.#V.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.#V.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class _{#j;#$;#H=new $;#U=new H;#G=new W;constructor(e,t=[]){this.#j=e,this.#$=t}async start(){return this.#q()}async stop(){return this.#B()}async loadSegment(e){const t=await this.#j.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof A==!1)throw new B;this.#G.addSegment(e)}getClassNames(){return this.#G.getClassNames()}hasClass(e){return this.#G.hasClass(e)}getClass(e){return this.#G.getClass(e)}getClassByImplementation(e){return this.#G.getClassByImplementation(e)}getProcedureNames(){return this.#G.getProcedureNames()}hasProcedure(e){return this.#G.hasProcedure(e)}getProcedure(e){return this.#G.getProcedure(e)}async run(e){const t=this.#W(e.fqn,e.version),s=this.#H.extract(t.parameters,e.args);return e.mode===d?new D(p,void 0):this.#_(e,t,s)}async#q(){await Promise.all(this.#$.map(e=>this.loadSegment(e)))}#B(){this.#G.clearSegments()}#W(e,t){const s=this.#G.getProcedure(e);if(void 0===s)throw new x(e);const r=s.getImplementation(t);if(void 0===r)throw new q(s.fqn,t.toString());return r}async#_(e,t,s){try{const r=await t.executable.call(e,...s);return new D(p,r)}catch(e){const t=this.#U.toStatus(e);return new D(t,e)}}}class K extends a{constructor(){super("Request cancelled")}}class Y{#K;#Y;#X=[];#J=!1;#Q=0;constructor(e,t=20){this.#K=e,this.#Y=t}start(){this.#J=!0,this.#Z()}stop(){this.#J=!1,this.#ee()}run(e){return new Promise((t,s)=>{this.#X.push({request:e,resolve:t,reject:s}),this.#Z()})}#Z(){if(this.#te())return;const e=this.#X.length,t=this.#Y-this.#Q,s=Math.min(e,t);this.#se(s)}#te(){return this.#re()||this.#ne()||this.#ae()}#re(){return!1===this.#J}#ne(){return 0===this.#X.length}#ae(){return this.#Q>=this.#Y}#se(e){const t=this.#X.splice(0,e);this.#Q+=e,t.forEach(e=>this.#ie(e))}async#ie(e){try{const t=await this.#K.run(e.request);e.resolve(t)}catch(t){e.reject(t)}finally{this.#Q--,this.#Z()}}#ee(){for(;this.#X.length>0;){const e=this.#X.shift();void 0!==e&&this.#oe(e)}}#oe(e){e.reject(new K)}}const X="starting",J="available",Q="unavailable",Z="stopping",ee="stopped";class te{#ce=ee;get state(){return this.#ce}set state(e){this.#ce=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#ue(ee)}isStopped(){return this.#le(ee)}isAvailable(){return this.#le(J)}setStarting(){this.#ce=X}setAvailable(){this.#ce=J}setUnavailable(){this.#ce=Q}setAvailability(e){return this.#ce=e?J:Q,this.#ce}setStopping(){this.#ce=Z}setStopped(){this.#ce=ee}#le(...e){return e.includes(this.#ce)}#ue(...e){return!1===this.#le(...e)}}class se{#he;#de;#pe=new te;constructor(e){this.#he=e.url,this.#de=e.remote}get url(){return this.#he}get state(){return this.#pe.state}get trustKey(){}async start(){return this.#pe.start(async()=>{await this.#de.connect(),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{await this.#de.disconnect()})}isHealthy(){return this.#de.isHealthy()}getHealth(){return this.#de.getHealth()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}getProcedureNames(){throw new r}hasProcedure(e){throw new r}addWorker(e){return this.#de.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#de.reportWorker(e,t)}removeWorker(e){return this.#de.removeWorker(e)}run(e){return this.#de.run(e)}}class re extends Error{#me;constructor(e){super(`Invalid location: ${e}`),this.#me=e}get location(){return this.#me}}class ne extends Error{#ge;constructor(e){super(`The file '${e}' could not be found`),this.#ge=e}get filename(){return this.#ge}}class ae{#me;#fe;#we;constructor(e,t,s){this.#me=e,this.#fe=t,this.#we=s}get location(){return this.#me}get type(){return this.#fe}get content(){return this.#we}get size(){return this.#we.length}}class ie{#me;#ye;#ve;constructor(e,t){const s=t.resolve(e);this.#me=t.normalize(e),this.#ye=t.normalize(s),this.#ve=t}getAbsoluteLocation(e){const t=this.#ve.isAbsolute(e)?e:this.#ve.join(this.#me,e),s=this.#ve.resolve(t),r=this.#ve.normalize(s);return this.#Se(r,e),r}getRelativeLocation(e){const t=this.#ve.relative(this.#me,e);return this.#ve.normalize(t)}normalizeLocation(e){return this.#ve.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#ve.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#ve.exists(t))throw new ne(e);return this.#ve.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#ve.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#ve.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new ae(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#ve.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#ve.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#ve.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#ve.normalize(e);return(await this.#ve.filter(t,s)).map(e=>this.#ve.normalize(e))}#Se(e,t){if(!1===e.startsWith(this.#ye))throw new re(t)}}class oe extends Error{constructor(){super("Remote files are not supported")}}class ce{copy(e,t){throw new oe}delete(e){throw new oe}exists(e){throw new oe}async filter(e,t){return[]}isAbsolute(e){return e.startsWith("/")}isDirectory(e){throw new oe}join(...e){throw new oe}read(e){throw new oe}resolve(e){return e}relative(e,t){throw new oe}normalize(e){return e}mimeType(e){throw new oe}write(e,t){throw new oe}}class ue extends ie{constructor(e){super(e,new ce)}}class le extends Error{#he;#Ee;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#he=e,this.#Ee=t}get url(){return this.#he}get reason(){return this.#Ee}}class he{#be;constructor(e){this.#be=e}async import(e){const t=this.#be.locate(e);try{return await import(t)}catch(e){const s=e instanceof Error?e.message:String(e);throw new le(t,s)}}}class de{constructor(e){}locate(e){throw new le(e,"Remote module loading is not allowed")}}class pe extends he{constructor(e){super(new de(e))}}class me{#xe;#Oe;constructor(e,t){this.#xe=e,this.#Oe=t}async filter(...e){return(await Promise.all(e.map(e=>this.#xe.filter(e)))).flat().map(e=>this.#xe.getRelativeLocation(e))}exists(e){return this.#xe.exists(e)}read(e){return this.#xe.read(e)}import(e){return this.#Oe.import(e)}}class ge extends me{constructor(e){super(new ue(e),new pe(e))}}class fe extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class we extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class ye extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class ve extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Se{#Ae=[];addSerializer(e){e.parent=this,this.#Ae.unshift(e)}async serialize(e){const t=this.#Ae.find(t=>t.canSerialize(e));if(void 0===t)throw new ve(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Ae.find(t=>t.canDeserialize(e));if(void 0===t)throw new ye(typeof e);return t.deserialize(e)}}class Ee extends Error{constructor(){super("Parent serializer not set")}}class be{#Ce;set parent(e){this.#Ce=e}serializeOther(e){if(void 0===this.#Ce)throw new Ee;return this.#Ce.serialize(e)}deserializeOther(e){if(void 0===this.#Ce)throw new Ee;return this.#Ce.deserialize(e)}}class xe extends be{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const s of e)t.push(await this.serializeOther(s));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Oe extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Ae extends be{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new Oe(e.value)}}}class Ce extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ie extends be{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Ce(e.base64)}}}class Ne{#w;#Ie;constructor(e,t){this.#w=e,this.#Ie=t}get name(){return this.#w}get as(){return this.#Ie}toString(){return`${this.#w} as ${this.#Ie}`}}class Me{#Ne;constructor(e){this.#Ne=e}get definition(){return this.#Ne}toString(){return this.#Ne}}class Te extends Me{}class Re{#w;#Me;#Te;constructor(e,t=!1,s=!1){this.#w=e,this.#Me=t,this.#Te=s}get name(){return this.#w}get isStatic(){return this.#Me}get isPrivate(){return this.#Te}get isPublic(){return!1===this.#Te}}class ze extends Re{#Re;#ze;constructor(e,t,s){super(e),this.#Re=t,this.#ze=s}get parentName(){return this.#Re}get scope(){return this.#ze}get members(){return this.#ze.members}get declarations(){return this.#ze.declarations}get functions(){return this.#ze.functions}get getters(){return this.#ze.getters}get setters(){return this.#ze.setters}get generators(){return this.#ze.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.#ze.getMember(e)}getDeclaration(e){return this.#ze.getDeclaration(e)}getFunction(e){return this.#ze.getFunction(e)}getGetter(e){return this.#ze.getGetter(e)}getSetter(e){return this.#ze.getSetter(e)}getGenerator(e){return this.#ze.getGenerator(e)}hasMember(e){return this.#ze.hasMember(e)}hasDeclaration(e){return this.#ze.hasDeclaration(e)}hasFunction(e){return this.#ze.hasFunction(e)}hasGetter(e){return this.#ze.hasGetter(e)}hasSetter(e){return this.#ze.hasSetter(e)}hasGenerator(e){return this.#ze.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.#Re?` extends ${this.#Re}`:"";return`class ${this.name}${e} { ${this.#ze.toString()} }`}}class Pe extends Re{#Pe;#Le;constructor(e,t,s=!1,r=!1){super(e.toString(),s,r),this.#Pe=e,this.#Le=t}get identifier(){return this.#Pe}get value(){return this.#Le}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Le{#ke;constructor(e){this.#ke=e}get members(){return this.#ke}toString(){return this.#ke.map(e=>e.toString()).join(" , ")}}class ke extends Le{toString(){return`[ ${super.toString()} ]`}}class De extends Le{toString(){return`{ ${super.toString()} }`}}class Fe extends Re{#ke;#De;constructor(e,t){super(""),this.#ke=e,this.#De=t}get members(){return this.#ke}get from(){return this.#De}hasMember(e){return this.#ke.some(t=>t.as===e)}getMember(e){return this.#ke.find(t=>t.as===e)}toString(){const e=this.#De?` from '${this.#De}'`:"";return`export { ${this.#ke.join(", ")} }${e}`}}class Ve extends Me{}class je{#w;#Le;constructor(e,t){this.#w=e,this.#Le=t}get name(){return this.#w}get value(){return this.#Le}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class $e extends Re{#g;#Fe;#Ve;constructor(e,t,s,r=!1,n=!1,a=!1){super(e,r,a),this.#g=t,this.#Fe=s,this.#Ve=n}get parameters(){return this.#g}get body(){return this.#Fe}get isAsync(){return this.#Ve}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class He extends $e{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class Ue extends $e{toString(){return`get ${super.toString()}`}}class Ge extends Re{#ke;#De;constructor(e,t){super(""),this.#ke=e,this.#De=t}get members(){return this.#ke}get from(){return this.#De}hasMember(e){return this.#ke.some(t=>t.as===e)}getMember(e){return this.#ke.find(t=>t.as===e)}toString(){return`import { ${this.#ke.map(e=>e.toString()).join(", ")} } from '${this.#De}';`}}class qe{#ze;constructor(e){this.#ze=e}get scope(){return this.#ze}get members(){return this.#ze.members}get exportedMembers(){return this.#je(this.#ze.members)}get imports(){return this.#ze.imports}get exports(){return this.#ze.exports}get declarations(){return this.#ze.declarations}get exportedDeclarations(){return this.#je(this.#ze.declarations)}get functions(){return this.#ze.functions}get exportedFunctions(){return this.#je(this.#ze.functions)}get generators(){return this.#ze.generators}get exportedGenerators(){return this.#je(this.#ze.generators)}get classes(){return this.#ze.classes}get exportedClasses(){return this.#je(this.#ze.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const s of t.members){const t=this.getMember(s.name);void 0!==t&&e.set(s.as,t)}return e}getMember(e){return this.#ze.getMember(e)}getDeclaration(e){return this.#ze.getDeclaration(e)}getFunction(e){return this.#ze.getFunction(e)}getGenerator(e){return this.#ze.getGenerator(e)}getClass(e){return this.#ze.getClass(e)}hasMember(e){return this.#ze.hasMember(e)}hasDeclaration(e){return this.#ze.hasDeclaration(e)}hasFunction(e){return this.#ze.hasFunction(e)}hasGenerator(e){return this.#ze.hasGenerator(e)}hasClass(e){return this.#ze.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const s of t.members)if(s.as===e)return this.getMember(s.name)}isExported(e){for(const t of this.exports)for(const s of t.members)if(s.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 s of t.members)if(s.as===e)return this.getMember(s.name)}#je(e){return e.filter(e=>this.isExported(e))}}class Be extends Me{}class We extends $e{toString(){return`set ${super.toString()}`}}const _e=Ge.name,Ke=Fe.name,Ye=Pe.name,Xe=$e.name,Je=Ue.name,Qe=We.name,Ze=He.name,et=ze.name;class tt{#ke;constructor(e){this.#ke=e}get members(){return this.#ke}get imports(){return this.#ke.filter(e=>e.constructor.name===_e)}get exports(){return this.#ke.filter(e=>e.constructor.name===Ke)}get declarations(){return this.#ke.filter(e=>e.constructor.name===Ye)}get functions(){return this.#ke.filter(e=>e.constructor.name===Xe)}get getters(){return this.#ke.filter(e=>e.constructor.name===Je)}get setters(){return this.#ke.filter(e=>e.constructor.name===Qe)}get generators(){return this.#ke.filter(e=>e.constructor.name===Ze)}get classes(){return this.#ke.filter(e=>e.constructor.name===et)}getMember(e){return this.#ke.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.#ke.map(e=>e.toString()).join("\n")}}const st={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},rt=Object.values(st);const nt=".",at="(",it=")",ot="[",ct="]",ut="{",lt="}",ht={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},dt=Object.values(ht);function pt(e){return dt.includes(e)}const mt={UNDEFINED:void 0,NULL:null,STRING:""},gt=Object.values(mt);function ft(e){return gt.includes(e)}const wt={OPEN:at,CLOSE:it};function yt(e){return e===wt.OPEN||e===wt.CLOSE}const vt={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"},St=Object.values(vt);function Et(e){return St.includes(e)}function bt(e){return e===vt.AS||e===vt.ASYNC||e===vt.FROM||e===vt.GET||e===vt.SET}const xt={OPEN:ot,CLOSE:ct};function Ot(e){return e===xt.OPEN||e===xt.CLOSE}const At=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Ct(e){return At.includes(e)}const It={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:"^"},Nt=Object.values(It);function Mt(e){return Nt.includes(e)}const Tt={OPEN:ut,CLOSE:lt};function Rt(e){return e===Tt.OPEN||e===Tt.CLOSE}const zt={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},Pt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Lt=Object.values(Pt);function kt(e){return Lt.includes(e)}class Dt{#$e;#He;constructor(e){this.#$e=e,this.#He=0}get items(){return this.#$e}get position(){return this.#He}get size(){return this.#$e.length}get eol(){return this.#He>=this.#$e.length}get current(){return this.#$e[this.#He]}get next(){return this.#$e[this.#He+1]}get previous(){return this.#$e[this.#He-1]}notAtEnd(){return!1===this.eol}get(e){return this.#$e[e]}step(e=1){return this.#He+=e,this.current}stepBack(e=1){return this.#He-=e,this.current}hasNext(){return this.#He+1<this.#$e.length}}class Ft extends Dt{constructor(e){super(e.split(""))}}class Vt{#fe;#Le;#Ue;#Ge;constructor(e,t,s,r){this.#fe=e,this.#Le=t,this.#Ue=s,this.#Ge=r}get type(){return this.#fe}get value(){return this.#Le}get start(){return this.#Ue}get end(){return this.#Ge}isType(e){return this.#fe===e}hasValue(e){return this.#Le===e}toString(){return`${this.#Le}`}}class jt extends Dt{}class $t{tokenize(e){const t=new Ft(e),s=[];let r;for(;t.notAtEnd();){const e=this.#qe(t,r);if(void 0===e)break;e.isType(zt.WHITESPACE)||e.isType(zt.COMMENT)?t.step():(s.push(e),this.#Be(e)&&(r=e),t.step())}return new jt(s)}#Be(e){return!1===[zt.WHITESPACE,zt.COMMENT].includes(e.type)}#qe(e,t){const s=e.current,r=e.position;if(kt(s)){const t=e.position;return new Vt(zt.WHITESPACE,s,r,t)}if(function(e){return rt.includes(e)}(s+e.next)){const t=this.#We(e),s=e.position;return new Vt(zt.COMMENT,t,r,s)}if(this.#_e(s,t)){const t=this.#Ke(e),s=e.position;return new Vt(zt.REGEX,t,r,s)}if(Ct(s)){const t=this.#Ye(e),s=e.position;return new Vt(zt.LITERAL,t,r,s)}if(Mt(s)){const t=this.#Xe(e),s=e.position;return new Vt(zt.OPERATOR,t,r,s)}if(pt(s)){const t=e.position;return new Vt(zt.DIVIDER,s,r,t)}if(yt(s)){const t=e.position;return new Vt(zt.GROUP,s,r,t)}if(Rt(s)){const t=e.position;return new Vt(zt.SCOPE,s,r,t)}if(Ot(s)){const t=e.position;return new Vt(zt.LIST,s,r,t)}if(ft(s))return;const n=this.#Je(e),a=Et(n)?zt.KEYWORD:zt.IDENTIFIER,i=e.position;return new Vt(a,n,r,i)}#We(e){const t=e.current+e.next===st.MULTI_START,s=t?st.MULTI_END:Pt.NEWLINE;let r=t?st.MULTI_START:st.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===s){e.step(s.length-1);break}r+=n,e.step()}return t?r+st.MULTI_END:r.trim()}#_e(e,t){return e===It.DIVIDE&&(void 0===t||([zt.OPERATOR,zt.DIVIDER,zt.KEYWORD].includes(t.type)||[wt.OPEN,xt.OPEN].includes(t.value)))}#Qe(e){return kt(e)||e==nt||!1===this.#Ze(e)}#Ke(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,n=e.previous;if(r===It.DIVIDE&&"\\"!==n)s=!0;else if(!0===s&&this.#Qe(r)){e.stepBack();break}t+=r,e.step()}return t}#Ye(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===r){if(n===t){s+=n;break}"\\"===n&&(r=!0)}else r=!1;s+=n,e.step()}return s}#Ze(e){return!1===(ft(e)||kt(e)||Mt(e)||Ct(e)||pt(e)||yt(e)||Rt(e)||Ot(e))}#Je(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#Ze(s)){e.stepBack();break}t+=s,e.step()}return t}#Xe(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===Mt(s)||!1===Mt(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Ht extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ut extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Gt 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 Bt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Wt="default",_t=" ";class Kt{#et;constructor(e=new $t){this.#et=e}parse(e){const t=this.#et.tokenize(e),s=this.#tt(t);return new qe(s)}parseFirst(e){const t=this.#et.tokenize(e);return this.#st(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Me==!1)throw new qt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof Ge==!1)throw new qt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof Fe==!1)throw new qt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof Pe==!1)throw new qt("a declaration definition");return t}parseFunction(e){const t=this.#et.tokenize(e),s=this.#rt(t);if(s instanceof $e==!1)throw new qt("a function definition");return s}parseClass(e){const t=this.#et.tokenize(e),s=this.#rt(t);if(s instanceof ze==!1)throw new qt("a class definition");return s}#tt(e){const t=[];for(;e.notAtEnd();){const s=this.#st(e);s instanceof Re&&t.push(s)}return new tt(t)}#st(e,t=!1){const s=e.current;if(s.isType(zt.LITERAL))return this.#nt(e);if(s.isType(zt.IDENTIFIER)){const s=e.next;return s?.hasValue(It.ARROW)?this.#at(e,t):this.#nt(e)}if(s.isType(zt.KEYWORD)){if(bt(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(vt.FUNCTION)||t.hasValue(wt.OPEN));if(s.hasValue(vt.ASYNC)&&r)return e.step(),this.#st(e,!0);if(void 0===t||this.#it(t))return this.#nt(e)}return s.hasValue(vt.RETURN)?this.#nt(e):this.#rt(e,t)}if(s.isType(zt.REGEX))return this.#nt(e);if(s.hasValue(wt.OPEN)){const s=this.#ot(e,wt.OPEN,wt.CLOSE);return s?.hasValue(It.ARROW)?this.#at(e,t):this.#nt(e)}if(s.hasValue(Tt.OPEN))return this.#ct(e);if(s.hasValue(xt.OPEN))return this.#ut(e);if(s.hasValue(It.NOT)||s.hasValue(It.SUBTRACT))return this.#nt(e);if(!pt(s.value))throw new Bt(s.value,s.start);e.step()}#rt(e,t=!1){const s=e.current;switch(e.step(),s.value){case vt.IMPORT:return this.#lt(e);case vt.EXPORT:return this.#ht(e);case vt.CLASS:return this.#dt(e);case vt.FUNCTION:return this.#pt(e,t);case vt.VAR:case vt.LET:case vt.CONST:return this.#mt(e,!1,!0);case vt.ASYNC:return this.#rt(e,!0);default:throw new Gt(s.value,s.start)}}#lt(e){const t=[];let s=e.current;if(s.isType(zt.LITERAL))return new Ge(t,s.value);if(s.hasValue(wt.OPEN)){s=e.step();const r=s.value;return e.step(2),new Ge(t,r)}if(!1===s.hasValue(Tt.OPEN)){const r=s.hasValue(It.MULTIPLY)?It.MULTIPLY:Wt;let n=s.value;s=e.step(),s.hasValue(vt.AS)&&(s=e.step(),n=s.value,s=e.step()),t.push(new Ne(r,n))}if(s.hasValue(ht.SEPARATOR)&&(s=e.step()),s.hasValue(Tt.OPEN)){const r=this.#gt(e);t.push(...r),s=e.current}if(!1===s.hasValue(vt.FROM))throw new Ht(vt.FROM,s.start);s=e.step();const r=s.value;return e.step(),new Ge(t,r)}#ht(e){switch(e.current.value){case vt.DEFAULT:return e.step(),this.#ft(e,!0);case Tt.OPEN:return this.#wt(e);default:return this.#ft(e,!1)}}#ft(e,t){let s=e.current,r=0;var n;s.hasValue(vt.ASYNC)&&(s=e.step(),r++),((n=s.value)===vt.CLASS||n===vt.FUNCTION||n===vt.CONST||n===vt.LET||n===vt.VAR)&&(s=e.step(),r++);const a=this.#Ze(s)?s.value:"",i=t?Wt:a;let o;s=e.step(),s?.hasValue(vt.FROM)&&(s=e.step(),o=s.value),r>0&&(r++,e.stepBack(r));const c=new Ne(a,i);return new Fe([c],o)}#wt(e){const t=this.#gt(e);let s,r=e.current;return r?.hasValue(vt.FROM)&&(r=e.step(),s=r.value),e.step(),new Fe(t,s)}#gt(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Tt.CLOSE)){e.step();break}if(s.hasValue(ht.SEPARATOR)){s=e.step();continue}const r=this.#yt(e);t.push(r),s=e.step()}return t}#yt(e){let t=e.current;const s=t.value;let r=s;return e.next.hasValue(vt.AS)&&(t=e.step(2),r=t.value),new Ne(s,r)}#mt(e,t,s=!1){let r,n,a=e.current,i=!1;return a.hasValue(xt.OPEN)?(r=this.#vt(e),a=e.current):a.hasValue(Tt.OPEN)?(r=this.#St(e),a=e.current):(i=a.value.startsWith("#"),r=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(It.ASSIGN)&&(e.step(),n=this.#st(e,!1),a=e.current),void 0!==a&&(a.hasValue(ht.TERMINATOR)?e.step():!0===s&&a.hasValue(ht.SEPARATOR)&&(e.step(),this.#mt(e,t,!0))),n instanceof He?new He(r.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof $e?new $e(r.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof ze?new ze(r.toString(),n.parentName,n.scope):new Pe(r,n,t,i)}#pt(e,t,s=!1,r=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(It.MULTIPLY)&&(o=!0,a=e.step()),this.#Ze(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,a=e.step());const u=this.#Et(e,wt.CLOSE);if(a=e.current,!1===a.hasValue(Tt.OPEN))throw new Ut(Tt.OPEN,a.start);const l=this.#bt(e,Tt.OPEN,Tt.CLOSE);return o?new He(i,u,l,s,t,c):r?new Ue(i,u,l,s,t,c):n?new We(i,u,l,s,t,c):new $e(i,u,l,s,t,c)}#at(e,t){let s,r=e.current;if(r.hasValue(wt.OPEN)?(s=this.#Et(e,wt.CLOSE),r=e.current):(s=[new je(r.value,void 0)],r=e.step()),!1===r.hasValue(It.ARROW))throw new Ut(It.ARROW,r.start);r=e.step();const n=r.hasValue(Tt.OPEN)?this.#bt(e,Tt.OPEN,Tt.CLOSE):this.#nt(e).definition;return new $e("",s,n,!1,t,!1)}#Et(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(ht.SEPARATOR)){e.step();continue}let n;n=r.hasValue(Tt.OPEN)?this.#St(e):r.hasValue(xt.OPEN)?this.#vt(e):this.#xt(e),s.push(n)}return s}#dt(e){let t,s=e.current,r="";if(this.#Ze(s)&&(r=s.value,s=e.step()),s.hasValue(vt.EXTENDS)&&(s=e.step(),t=s.value,s=e.step()),!1===s.hasValue(Tt.OPEN))throw new Ut(Tt.OPEN,s.start);const n=this.#Ot(e);return new ze(r,t,n)}#Ot(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Tt.CLOSE)){e.step();break}const r=this.#At(e);s.push(r),t=e.current}return new tt(s)}#At(e){let t=e.current,s=!1,r=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(vt.STATIC))r=!0;else if(t.hasValue(vt.ASYNC))s=!0;else if(t.hasValue(vt.GET))n=!0;else{if(!t.hasValue(vt.SET)){if(t.hasValue(It.MULTIPLY))return this.#pt(e,s,r,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(wt.OPEN)?this.#pt(e,s,r,n,a):this.#mt(e,r)}#ut(e){const t=this.#bt(e,xt.OPEN,xt.CLOSE);return new Te(t)}#vt(e){const t=this.#Et(e,xt.CLOSE);return new ke(t)}#ct(e){const t=this.#bt(e,Tt.OPEN,Tt.CLOSE);return new Be(t)}#St(e){const t=this.#Et(e,Tt.CLOSE);return new De(t)}#xt(e){let t=e.current;const s=t.value;let r;return t=e.step(),t.hasValue(It.ASSIGN)&&(e.step(),r=this.#st(e,!1)),new je(s,r)}#nt(e){let t=e.current,s="";for(;e.notAtEnd();){if(t.hasValue(xt.OPEN)){s+=this.#bt(e,xt.OPEN,xt.CLOSE)+_t,t=e.current}else if(t.hasValue(wt.OPEN)){s+=this.#bt(e,wt.OPEN,wt.CLOSE)+_t,t=e.current}else if(t.hasValue(Tt.OPEN)){s+=this.#bt(e,Tt.OPEN,Tt.CLOSE)+_t,t=e.current}else s+=t.toString()+_t,t=e.step();if(void 0===t||this.#it(t))break}return new Ve(s.trim())}#bt(e,t,s){let r=e.step(),n=t+_t;for(;e.notAtEnd();)if(r.hasValue(t))n+=this.#bt(e,t,s)+_t,r=e.current;else{if(r.hasValue(s))return e.step(),n+=s,n;n+=r.toString()+_t,r=e.step()}return n}#ot(e,t,s){const r=e.position;this.#bt(e,t,s);const n=e.current,a=e.position;return e.stepBack(a-r),n}#it(e){return[ht.TERMINATOR,ht.SEPARATOR].includes(e.value)||[xt.CLOSE,wt.CLOSE,Tt.CLOSE].includes(e.value)||Et(e.value)}#Ze(e){return e.isType(zt.IDENTIFIER)||e.isType(zt.KEYWORD)&&bt(e.value)}}class Yt{merge(e,t){const s=this.#Ct(e.declarations,t.declarations),r=this.#It(e.functions,t.functions),n=this.#It(e.getters,t.getters),a=this.#It(e.setters,t.setters),i=[...s.values(),...r.values(),...n.values(),...a.values()];return new ze(e.name,t.name,new tt(i))}#Ct(e,t){const s=new Map;return t.forEach(e=>s.set(e.name,e)),e.forEach(e=>s.set(e.name,e)),[...s.values()]}#It(e,t){const s=new Map;return t.forEach(e=>s.set(e.name,e)),e.forEach(e=>s.set(e.name,e)),[...s.values()]}}class Xt{#Nt=new Kt;#Mt=new Yt;fromModule(e,t=!1){const s=Object.entries(e),r=[];for(const[e,n]of s){if("function"!=typeof n.toString)continue;const s=n.toString();if(s.startsWith("class"))r.push(this.fromClass(n,t));else if(s.startsWith("function"))r.push(this.fromFunction(n));else{const t=new Ve(s);r.push(new Pe(e,t))}}return new qe(new tt(r))}fromClass(e,t=!1){const s=this.isClass(e)?this.#Tt(e):this.#Rt(e);if(!1===t)return s;const r=this.getParentClass(e);if(""===r.name)return s;const n=this.fromClass(r,!0);return this.#Mt.merge(s,n)}fromObject(e,t=!0){const s=this.getClass(e);return this.fromClass(s,t)}fromFunction(e){const t=e.toString();return this.#Nt.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")}#Tt(e){const t=e.toString();return this.#Nt.parseClass(t)}#Rt(e){const t=this.createInstance(e),s=this.#zt(e,t),r=new tt(s);return new ze(e.name,void 0,r)}#zt(e,t){return[...this.#Pt(t),...this.#Lt(e)]}#Pt(e){const t=Object.getOwnPropertyNames(e),s=e,r=[];for(const e of t){const t=s[e],n=void 0!==t?new Me(String(t)):void 0,a=new Pe(e,n);r.push(a)}return r}#Lt(e){const t=Object.getOwnPropertyDescriptors(e.prototype),s=[];for(const e in t){const r=t[e],n=r.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==r.get?s.push(new Ue(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==r.set?s.push(new We(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):s.push(a)}return s}}const Jt=new Xt;class Qt extends be{#kt;constructor(e){super(),this.#kt=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),s=Jt.fromClass(t,!0),r=this.#Dt(s),n=this.#kt.resolveKey(t);if(void 0===n)throw new fe(t.name);return{serialized:!0,key:n,name:"class",args:await this.#Ft(s,r,e),fields:await this.#Vt(s,r,e)}}#Dt(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#Ft(e,t,s){const r={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(s[a]):void 0;r[n.toString()]=t}return r}async#Vt(e,t,s){const r={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(r[a]=await this.serializeOther(s[a]))}return r}async deserialize(e){const t=await this.#jt(e);if(void 0===t)throw new fe(e.key);if(t instanceof Function==!1)throw new we(e.key);const s=await this.#$t(t,e.args),r=Jt.createInstance(t,s);for(const t in e.fields){const s=e.fields[t];r[t]=await this.deserializeOther(s)}return r}async#$t(e,t){const s=Jt.fromClass(e,!0).getFunction("constructor"),r=(s?.parameters??[]).map((e,s)=>{const r=s.toString(),n=t[r];return this.deserializeOther(n)});return Promise.all(r)}async#jt(e){return globalThis[e.key]??this.#kt.resolveClass(e.key)}}class Zt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class es extends be{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new Zt(e.value);return t}}class ts extends be{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class ss extends be{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],s=[];for(const[r,n]of e)t.push(await this.serializeOther(r)),s.push(await this.serializeOther(n));return{serialized:!0,name:"Map",entries:{keys:t,values:s}}}async deserialize(e){const t=e.entries.keys,s=e.entries.values,r=new Map;for(let e=0;e<t.length;e++){const n=await this.deserializeOther(t[e]),a=await this.deserializeOther(s[e]);r.set(n,a)}return r}}class rs extends be{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.serializeOther(r)}return t}async deserialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.deserializeOther(r)}return t}}class ns extends be{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class as extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class is extends be{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new as(e.source,e.flags)}}}class os extends be{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const s of e.values())t.push(await this.serializeOther(s));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const cs=new Xt;class us extends be{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,s=new DataView(e.buffer),r=[];for(let e=0;e<s.byteLength;e++)r.push(s.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:r}}async deserialize(e){const t=e.type,s=e.bytes,r=new ArrayBuffer(s.length),n=new DataView(r);for(let e=0;e<s.length;e++)n.setUint8(e,s[e]);const a=globalThis[t];return cs.createInstance(a,[r])}}class ls extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class hs extends be{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new ls(e.value)}}}class ds{static build(e){const t=new Se;return t.addSerializer(new ns),t.addSerializer(new rs),void 0!==e&&t.addSerializer(new Qt(e)),t.addSerializer(new ts),t.addSerializer(new is),t.addSerializer(new Ae),t.addSerializer(new hs),t.addSerializer(new es),t.addSerializer(new os),t.addSerializer(new ss),t.addSerializer(new xe),t.addSerializer(new us),"undefined"!=typeof Buffer&&t.addSerializer(new Ie),t}}class ps{#Ht;constructor(e){this.#Ht=e}resolveKey(e){const t=this.#Ht.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Ht.getClass(e);return t?.implementation}}class ms extends o{constructor(){super("Request not trusted")}}const gs="X-Jitar-Trust-Key",fs="X-Jitar-Data-Encoding",ws="serialized";class ys{#s;#he;#Ut;#Gt;#qt;#Ht;#Bt;#Wt;#_t;#pe=new te;constructor(e){this.#he=e.url,this.#Ut=e.trustKey,this.#Gt=e.gateway,this.#qt=!0===e.registerAtGateway,this.#Ht=e.executionManager,this.#Bt=e.healthManager;const t=e.scheduleManager;this.#Wt=t.create(()=>this.#Kt(),e.reportInterval);const s=new ps(this.#Ht);this.#_t=ds.build(s)}get id(){return this.#s}set id(e){this.#s=e}get state(){return this.#pe.state}get url(){return this.#he}get trustKey(){return this.#Ut}async start(){return this.#pe.start(async()=>{await Promise.all([this.#Ht.start(),this.#Bt.start()]),void 0!==this.#Gt&&(await this.#Gt.start(),this.#qt&&(this.#s=await this.#Gt.addWorker(this),this.#Wt.start())),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{void 0!==this.#Gt&&(void 0!==this.#s&&(this.#Wt.stop(),await this.#Gt.removeWorker(this.#s)),await this.#Gt.stop()),await Promise.all([this.#Bt.stop(),this.#Ht.stop()])})}getProcedureNames(){return this.#Ht.getProcedureNames()}hasProcedure(e){return this.#Ht.hasProcedure(e)}isHealthy(){return this.#Bt.isHealthy()}getHealth(){return this.#Bt.getHealth()}isAvailable(){return this.#pe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}async reportState(e){if(void 0!==this.#Gt&&void 0!==this.#s)return this.#Gt.reportWorker(this.#s,e)}async run(e){return this.#Yt(e)?this.#Xt(e):this.#Jt(e)}#Yt(e){return void 0===this.#Gt||this.#Ht.hasProcedure(e.fqn)}async#Xt(e){const t=this.#Ht.getProcedure(e.fqn),s=t?.getImplementation(e.version);if(this.#Qt(s))throw new x(e.fqn);if(this.#Zt(e,s))throw new ms;const r=e.getHeader(fs);r===ws&&(e=await this.#es(e)),e.removeHeader(fs);const n=await this.#Ht.run(e);return r===ws?this.#ts(n):n}#Qt(e){return void 0===e||e.private}#Zt(e,t){if(t.public)return!1;const s=e.getHeader(gs);return this.#Ut!==s}async#Jt(e){(e=await this.#ss(e)).setHeader(fs,ws),void 0!==this.#Ut&&e.setHeader(gs,this.#Ut);const t=await this.#Gt.run(e);return this.#rs(t)}async#ss(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#_t.serialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#es(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#_t.deserialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#ts(e){const t=await this.#_t.serialize(e.result);return new D(e.status,t,e.headers)}async#rs(e){const t=await this.#_t.deserialize(e.result);return new D(e.status,t,e.headers)}async#Kt(){const e=await this.updateState();return this.reportState(e)}}class vs{#K;constructor(e){this.#K=e}async handle(e,t){return this.#K.run(e)}}class Ss{#ns=new G;constructor(){this.#as()}#as(){const e=globalThis;e.__run=this.#is.bind(this),e.ProcedureNotAccessible=O}async#is(e,t,s,r){const n=this.#ns.parse(t),a=new Map(Object.entries(s)),i=r instanceof k?r.headers:new Map,o=new k(e,n,a,i,h),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==p)throw u.result;return u.result}}class Es extends Ss{#os;#cs;#us=new Y(this);constructor(e){super(),this.#os=new ys({url:e.remoteUrl,gateway:new se({url:e.remoteUrl,remote:e.remote}),healthManager:e.healthManager,executionManager:e.executionManager,scheduleManager:e.scheduleManager}),this.#cs=e.middlewareManager}get worker(){return this.#os}async start(){await this.#ls(),this.#us.start()}async stop(){this.#us.stop(),await this.#hs()}getTrustKey(){}run(e){return this.#cs.handle(e)}async runInternal(e){return this.#us.run(e)}async#ls(){await Promise.all([this.#os.start(),this.#cs.start()]);const e=new vs(this.#os);this.#cs.addMiddleware(e)}async#hs(){await Promise.all([this.#cs.stop(),this.#os.stop()])}}const bs="starting",xs="started",Os="stopping",As="stopped";class Cs extends a{constructor(){super("Invalid health check")}}class Is{#ce=As;#ds=new Map;#j;#ps;constructor(e,t=[]){this.#j=e,this.#ps=t}get state(){return this.#ce}async start(){if(this.#ce===As)try{this.#ce=bs,await this.#ms(),this.#ce=xs}catch(e){throw this.#ce=As,e}}async stop(){if(this.#ce===xs)try{this.#ce=Os,this.clearHealthChecks(),this.#ce=As}catch(e){throw this.#ce=xs,e}}async loadHealthCheck(e){const t=await this.#gs(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new Cs;this.#ds.set(e.name,e)}clearHealthChecks(){this.#ds.clear()}async isHealthy(){const e=[];for(const t of this.#ds.values()){const s=this.#fs(t);e.push(s)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,s]of this.#ds){const r=this.#fs(s).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(r)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ws(e,t))).then(()=>t)}async#ms(){(await Promise.all(this.#ps.map(e=>this.#gs(e)))).forEach(e=>this.addHealthCheck(e))}async#gs(e){return(await this.#j.import(e)).default}#ws(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#fs(e){const t=e.isHealthy(),s=e.timeout;if(void 0===s)return t;const r=new Promise(e=>{setTimeout(e,s)}).then(()=>!1);return Promise.race([r,t])}}const Ns=0,Ms=1,Ts=2,Rs=3;class zs{#ys;#vs;constructor(e=Ms,t=console){this.#ys=e,this.#vs=t}debug(...e){if(this.#ys>Ns)return;const t=this.#Ss("DEBUG",e);this.#vs.debug(t)}info(...e){if(this.#ys>Ms)return;const t=this.#Ss("INFO",e);this.#vs.info(t)}warn(...e){if(this.#ys>Ts)return;const t=this.#Ss("WARN",e);this.#vs.warn(t)}error(...e){if(this.#ys>Rs)return;const t=this.#Ss("ERROR",e);this.#vs.error(t)}fatal(...e){const t=this.#Ss("FATAL",e);this.#vs.error(t)}#Ss(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Es(e)).join(" ")}`}#Es(e,t=0){let s;switch(typeof e){case"string":s=e;break;case"object":s=this.#bs(e,t+1);break;case"undefined":s="undefined";break;case"function":s="function";break;default:s=String(e)}return`${this.#xs(t)}${s}`}#bs(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Es(e,t)).join(",\n")}\n${this.#xs(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#xs(e){return" ".repeat(e)}}const Ps="starting",Ls="started",ks="stopping",Ds="stopped";class Fs extends a{constructor(){super("Invalid middleware")}}class Vs{#ce=Ds;#Os=[];#j;#As;constructor(e,t=[]){this.#j=e,this.#As=t}get state(){return this.#ce}async start(){if(this.#ce===Ds)try{this.#ce=Ps,await this.#Cs(),this.#ce=Ls}catch(e){throw this.#ce=Ds,e}}async stop(){if(this.#ce===Ls)try{this.#ce=ks,this.clearMiddlewares(),this.#ce=Ds}catch(e){throw this.#ce=Ls,e}}async loadMiddleware(e){const t=await this.#Is(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Fs;this.#Os.push(e)}getMiddleware(e){return this.#Os.find(t=>t instanceof e)}clearMiddlewares(){this.#Os=[]}handle(e){return this.#Ns(e,0)()}async#Cs(){(await Promise.all(this.#As.map(e=>this.#Is(e)))).forEach(e=>this.addMiddleware(e))}async#Is(e){return(await this.#j.import(e)).default}#Ns(e,t){const s=this.#Os[t];if(void 0===s)return async()=>new D(p);const r=this.#Ns(e,t+1);return async()=>await s.handle(e,r)}}class js{#Ms;#Ts;#Rs;#zs=null;constructor(e,t,s=5e3){this.#Ms=e,this.#Ts=t,this.#Rs=s}start(){this.#Ps()}stop(){null!==this.#zs&&(clearTimeout(this.#zs),this.#zs=null)}#Ps(){this.#zs=setTimeout(async()=>{null!==this.#zs&&(await this.#Ls(),this.#Ps())},this.#Rs)}async#Ls(){try{await this.#Ts()}catch(e){this.#Ms.warn("Scheduled task failed",e)}}}class $s{#ks=[];#Ms;constructor(e){this.#Ms=e}create(e,t){const s=new js(this.#Ms,e,t);return this.#ks.push(s),s}remove(e){const t=this.#ks.indexOf(e);t<0||this.#ks.splice(t,1)}startAll(){this.#ks.forEach(e=>e.start())}stopAll(){this.#ks.forEach(e=>e.stop())}}class Hs{#Ds;constructor(e){this.#Ds=e}build(e){const t=e.remoteUrl,s=e.middleware,r=e.segments,n=new zs(e.logLevel??Ts),a=this.#Ds.build(t),i=new ge(t),o=this.#Fs(i),c=this.#Vs(i,s),u=this.#js(i,r),l=this.#$s(n);return new Es({remoteUrl:t,remote:a,healthManager:o,middlewareManager:c,executionManager:u,scheduleManager:l})}#Fs(e){return new Is(e)}#Vs(e,t=[]){const s=new Vs(e);return t.forEach(e=>s.addMiddleware(e)),s}#js(e,t=[]){const s=new _(e);return t.forEach(e=>s.addSegment(e)),s}#$s(e){return new $s(e)}}class Us{#Hs;constructor(e=!0){this.#Hs=e}validate(e,t){const s=[];this.#Us("",e,t,s);return{valid:0===s.length,errors:s}}#Us(e,t,s,r){this.#Hs&&this.#Gs(e,t,s,r),this.#qs(e,t,s,r)}#Gs(e,t,s,r){const n=Object.keys(t),a=Object.keys(s);for(const t of n)if(!1===a.includes(t)){const s=this.#Bs(e,t);r.push(`Unknown field '${s}'`)}}#qs(e,t,s,r){const n=Object.keys(s);for(const a of n){const n=this.#Bs(e,a),i=s[a],o=t[a];this.#Ws(n,o,i,r)}}#Ws(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#_s(e,t,s,r);case"integer":return this.#Ks(e,t,s,r);case"real":return this.#Ys(e,t,s,r);case"boolean":return this.#Xs(e,t,s,r);case"url":return this.#Js(e,t,s,r);case"group":return this.#Qs(e,t,s,r);case"list":return this.#Zs(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#_s(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#Ks(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Ys(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Xs(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#Js(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#Qs(e,t,s,r){"object"==typeof t?this.#Us(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#Zs(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Bs(e,t),i=n[t];this.#Ws(a,i,s.items,r)}}#Bs(e,t){return""===e?t:`${e}.${t}`}}const Gs="content-type",qs="x-jitar-content-type",Bs="x-jitar-procedure-version",Ws="application/json",_s="application/octet-stream";class Ks extends Error{constructor(){super("Invalid worker id")}}class Ys{#he;#er;#U=new H;#tr=new Us;constructor(e,t){this.#he=e,this.#er=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#he}/${e}`,s=await this.#sr(t,{method:"GET"}),r=s.headers.get(Gs)??_s,n=await s.arrayBuffer(),a=Buffer.from(n);return new ae(e,r,a)}async isHealthy(){const e=`${this.#he}/health/status`,t=await this.#sr(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#he}/health`,t=await this.#sr(e,{method:"GET"}),s=await t.json();return new Map(Object.entries(s))}async addWorker(e,t,s){const r=`${this.#he}/workers`,n={url:e,procedureNames:t,trustKey:s},a={method:"POST",headers:{"Content-Type":Ws},body:JSON.stringify(n)},i=await this.#sr(r,a),o=i.headers.get(Gs);if(null===o||!1===o.includes(Ws))throw new Ks;const c=await i.json();if(!1===this.#tr.validate(c,{id:{type:"string",required:!0}}).valid)throw new Ks;return c.id}async reportWorker(e,t){const s=`${this.#he}/workers/${e}/report`,r={state:t},n={method:"POST",headers:{"Content-Type":Ws},body:JSON.stringify(r)};await this.#sr(s,n)}async removeWorker(e){const t=`${this.#he}/workers/${e}`,s={method:"DELETE",headers:{"Content-Type":Ws}};await this.#sr(t,s)}async run(e){e.setHeader(Gs,Ws);const t=Object.fromEntries(e.args),s=Object.fromEntries(e.headers),r=e.version.toString();s[Bs]=r;const n=`${this.#he}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:s,body:await this.#rr(t)},i=await this.#sr(n,a,!1),o=i.status,c=await this.#nr(i),u=this.#ar(i);return new D(o,c,u)}async#sr(e,t,s=!0){const r=await this.#er.execute(e,t);if(s&&this.#ir(r)){const e=await this.#nr(r);throw this.#U.fromStatus(r.status,String(e))}return r}#ir(e){return e.status<200||e.status>399}async#rr(e){return JSON.stringify(e)}async#nr(e){const t=e.headers.get(qs)??e.headers.get(Gs);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const s=await e.text();return t?.includes("boolean")?"true"===s:t?.includes("number")?Number(s):s}#ar(e){const t=new Map;for(const[s,r]of e.headers)t.set(s,r);return t}}class Xs{async execute(e,t){return fetch(e,t)}}class Js{#er;constructor(e=new Xs){this.#er=e}build(e){return new Ys(e,this.#er)}}export{P as ArrayParameter,e as BadRequest,C as Class,Hs as ClientBuilder,t as Forbidden,Js as HttpRemoteBuilder,M as Implementation,R as NamedParameter,s as NotFound,r as NotImplemented,L as ObjectParameter,n as PaymentRequired,N as Procedure,k as Request,D as Response,A as Segment,a as ServerError,i as Teapot,o as Unauthorized,I as Version};
|
|
1
|
+
class e extends Error{constructor(e="Invalid request"){super(e)}}class t extends Error{constructor(e="Forbidden"){super(e)}}class s extends Error{constructor(e="Not found"){super(e)}}class r extends Error{constructor(e="Not implemented"){super(e)}}class n extends Error{constructor(e="Payment required"){super(e)}}class a extends Error{constructor(e="Server error"){super(e)}}class i extends Error{constructor(e="I'm a teapot"){super(e)}}class o extends Error{constructor(e="Unauthorized"){super(e)}}const c="private",u="protected",l="public",h="normal",d="dry",p=200,m=400,g=401,f=402,w=403,y=404,v=418,S=500,E=501;class b extends e{#e;constructor(e){super(`Invalid version number '${e}'`),this.#e=e}get number(){return this.#e}}class x extends s{#t;constructor(e){super(`Procedure '${e}' not found`),this.#t=e}get fqn(){return this.#t}}class O extends t{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class A{#s;#r=new Map;#n=new Map;constructor(e){this.#s=e}get id(){return this.#s}addClass(e){return this.#r.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#r.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#r.values()]}addProcedure(e){return this.#n.set(e.fqn,e),this}hasProcedure(e){return this.#n.has(e)}getProcedure(e){return this.#n.get(e)}getExposedProcedures(){return[...this.#n.values()].filter(e=>e.public||e.protected)}}class C{#t;#a;constructor(e,t){this.#t=e,this.#a=t}get fqn(){return this.#t}get implementation(){return this.#a}}class I{static get DEFAULT(){return new I(0,0,0)}#i;#o;#c;constructor(e=0,t=0,s=0){this.#i=e,this.#o=t,this.#c=s}get major(){return this.#i}get minor(){return this.#o}get patch(){return this.#c}equals(e){return this.#i===e.major&&this.#o===e.minor&&this.#c===e.patch}greater(e){return this.#i!==e.major?this.#i>e.major:this.#o!==e.minor?this.#o>e.minor:this.#c!==e.patch&&this.#c>e.patch}less(e){return this.#i!==e.major?this.#i<e.major:this.#o!==e.minor?this.#o<e.minor:this.#c!==e.patch&&this.#c<e.patch}toString(){return`${this.#i}.${this.#o}.${this.#c}`}}class N{#t;#u=new Map;#l;constructor(e){this.#t=e}get fqn(){return this.#t}get public(){return[...this.#u.values()].some(e=>e.public)}get protected(){return[...this.#u.values()].some(e=>e.protected)}addImplementation(e){return this.#u.set(e.version,e),this.#h(e)&&(this.#l=e),this}#h(e){return void 0===this.#l||e.version.greater(this.#l.version)}getImplementation(e){const t=this.#d(e);return this.#u.get(t)}#d(e){let t=I.DEFAULT;for(const s of this.#u.keys()){if(s.equals(e))return s;s.greater(e)||t.less(s)&&(t=s)}return t}}class M{#p;#m;#g;#f;constructor(e,t,s,r){this.#p=e,this.#m=t,this.#g=s,this.#f=r}get version(){return this.#p}get public(){return this.#m===l}get protected(){return this.#m===u}get private(){return this.#m===c}get parameters(){return this.#g}get executable(){return this.#f}}class T{#w;#y;constructor(e,t=!1){this.#w=e,this.#y=t}get name(){return this.#w}get isOptional(){return this.#y}}class R extends T{}class z extends T{#v;constructor(e,t,s){super(t??"(anonymous)",s),this.#v=e}get variables(){return this.#v}}class P extends z{}class L extends z{}class k{#t;#p;#S;#E=new Map;#b;constructor(e,t,s,r,n){this.#t=e,this.#p=t,this.#S=s,this.#E=r,this.#b=n}get fqn(){return this.#t}get version(){return this.#p}get args(){return this.#S}get headers(){return this.#E}get mode(){return this.#b}clearArguments(){this.#S.clear()}setArgument(e,t){this.#S.set(e,t)}getArgument(e){return this.#S.get(e)}hasArgument(e){return this.#S.has(e)}removeArgument(e){this.#S.delete(e)}clearHeaders(){this.#E.clear()}setHeader(e,t){this.#E.set(e.toLowerCase(),t)}getHeader(e){return this.#E.get(e.toLowerCase())}hasHeader(e){return this.#E.has(e.toLowerCase())}removeHeader(e){this.#E.delete(e.toLowerCase())}}class D{#x;#O;#E;constructor(e,t=void 0,s=new Map){this.#x=e,this.#O=t,this.#E=s}get status(){return this.#x}get result(){return this.#O}set result(e){this.#O=e}get headers(){return this.#E}clearHeaders(){this.#E.clear()}setHeader(e,t){this.#E.set(e.toLowerCase(),t)}getHeader(e){return this.#E.get(e.toLowerCase())}hasHeader(e){return this.#E.has(e.toLowerCase())}removeHeader(e){this.#E.delete(e.toLowerCase())}}class F extends e{#A;constructor(e){super(`Unknown parameter ${e}`),this.#A=e}get parameterName(){return this.#A}}class V extends e{#A;constructor(e){super(`Missing value for parameter '${e}'`),this.#A=e}get parameterName(){return this.#A}}class j extends e{#A;constructor(e){super(`Invalid value for parameter '${e}'`),this.#A=e}get parameterName(){return this.#A}}class ${extract(e,t){const s=this.#C(e,t),r=[];for(const t of e){const e=this.#I(t,s);r.push(e)}if(s.size>0){const e=s.keys().next().value;throw new F(e)}return r}#C(e,t){const s=new Map;for(const[r,n]of t){if(this.#N(r)){const t=this.#M(r);!0===this.#T(e,t)&&s.set(t,n);continue}s.set(r,n)}return s}#N(e){return e.startsWith("*")}#M(e){return e.substring(1)}#T(e,t){return void 0!==e.find(e=>e.name===t)}#I(e,t,s){return e instanceof R?this.#R(e,t,s):this.#z(e,t)}#R(e,t,s){const r=t.get(e.name);if(this.#P(e,r,s))throw new V(e.name);if(this.#L(e,r,s))throw new j(e.name);return t.delete(e.name),r}#z(e,t){return e instanceof P?this.#k(e,t):this.#D(e,t)}#k(e,t){const s=this.#F(e,t);return void 0!==s?Object.values(s):void 0}#D(e,t){return this.#F(e,t)}#F(e,t){const s=e instanceof P,r={},n=[];let a=!1,i=0;for(const o of e.variables){const c=s?i++:o.name,u=this.#I(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),r[c]=u}if(!0===a&&n.length>0)throw new V(n[0]);return a?r:void 0}#P(e,t,s){return void 0===t&&(!0!==e.isOptional&&!0!==s?.isOptional)}#L(e,t,s){return!1!==e.name.startsWith("...")&&(void 0===s&&t instanceof Array==!1||s instanceof P&&t instanceof Array==!1||s instanceof L&&t instanceof Object==!1)}}class H{toStatus(a){return a instanceof e?m:a instanceof t?w:a instanceof s?y:a instanceof r?E:a instanceof n?f:a instanceof i?v:a instanceof o?g:S}fromStatus(c,u){switch(c){case m:return new e(u);case w:return new t(u);case y:return new s(u);case E:return new r(u);case f:return new n(u);case v:return new i(u);case g:return new o(u);default:return new a(u)}}}const U=/^\d+(?:\.\d+){0,2}$/;class G{parse(e){if(0===e.trim().length)return I.DEFAULT;if(!1===U.test(e))throw new b(e);const t=e.split(".");switch(t.length){case 1:return new I(Number.parseInt(t[0]));case 2:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class q extends s{#t;#p;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#t=e,this.#p=t}get fqn(){return this.#t}get version(){return this.#p}}class B extends a{constructor(){super("Invalid segment")}}class W{#V=new Map;addSegment(e){this.#V.set(e.id,e)}clearSegments(){this.#V.clear()}getClassNames(){const e=new Set;for(const t of this.#V.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.#V.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#V.values()){const s=t.getClassByImplementation(e);if(void 0!==s)return s}}getProcedureNames(){const e=new Set;for(const t of this.#V.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.#V.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class _{#j;#$;#H=new $;#U=new H;#G=new W;constructor(e,t=[]){this.#j=e,this.#$=t}async start(){return this.#q()}async stop(){return this.#B()}async loadSegment(e){const t=await this.#j.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof A==!1)throw new B;this.#G.addSegment(e)}getClassNames(){return this.#G.getClassNames()}hasClass(e){return this.#G.hasClass(e)}getClass(e){return this.#G.getClass(e)}getClassByImplementation(e){return this.#G.getClassByImplementation(e)}getProcedureNames(){return this.#G.getProcedureNames()}hasProcedure(e){return this.#G.hasProcedure(e)}getProcedure(e){return this.#G.getProcedure(e)}async run(e){const t=this.#W(e.fqn,e.version),s=this.#H.extract(t.parameters,e.args);return e.mode===d?new D(p,void 0):this.#_(e,t,s)}async#q(){await Promise.all(this.#$.map(e=>this.loadSegment(e)))}#B(){this.#G.clearSegments()}#W(e,t){const s=this.#G.getProcedure(e);if(void 0===s)throw new x(e);const r=s.getImplementation(t);if(void 0===r)throw new q(s.fqn,t.toString());return r}async#_(e,t,s){try{const r=await t.executable.call(e,...s);return new D(p,r)}catch(e){const t=this.#U.toStatus(e);return new D(t,e)}}}class K extends a{constructor(){super("Request cancelled")}}class Y{#K;#Y;#X=[];#J=!1;#Q=0;constructor(e,t=20){this.#K=e,this.#Y=t}start(){this.#J=!0,this.#Z()}stop(){this.#J=!1,this.#ee()}run(e){return new Promise((t,s)=>{this.#X.push({request:e,resolve:t,reject:s}),this.#Z()})}#Z(){if(this.#te())return;const e=this.#X.length,t=this.#Y-this.#Q,s=Math.min(e,t);this.#se(s)}#te(){return this.#re()||this.#ne()||this.#ae()}#re(){return!1===this.#J}#ne(){return 0===this.#X.length}#ae(){return this.#Q>=this.#Y}#se(e){const t=this.#X.splice(0,e);this.#Q+=e,t.forEach(e=>this.#ie(e))}async#ie(e){try{const t=await this.#K.run(e.request);e.resolve(t)}catch(t){e.reject(t)}finally{this.#Q--,this.#Z()}}#ee(){for(;this.#X.length>0;){const e=this.#X.shift();void 0!==e&&this.#oe(e)}}#oe(e){e.reject(new K)}}const X="starting",J="available",Q="unavailable",Z="stopping",ee="stopped";class te{#ce=ee;get state(){return this.#ce}set state(e){this.#ce=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#ue(ee)}isStopped(){return this.#le(ee)}isAvailable(){return this.#le(J)}setStarting(){this.#ce=X}setAvailable(){this.#ce=J}setUnavailable(){this.#ce=Q}setAvailability(e){return this.#ce=e?J:Q,this.#ce}setStopping(){this.#ce=Z}setStopped(){this.#ce=ee}#le(...e){return e.includes(this.#ce)}#ue(...e){return!1===this.#le(...e)}}class se{#he;#de;#pe=new te;constructor(e){this.#he=e.url,this.#de=e.remote}get url(){return this.#he}get state(){return this.#pe.state}get trustKey(){}async start(){return this.#pe.start(async()=>{await this.#de.connect(),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{await this.#de.disconnect()})}isHealthy(){return this.#de.isHealthy()}getHealth(){return this.#de.getHealth()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}getProcedureNames(){throw new r}hasProcedure(e){throw new r}addWorker(e){return this.#de.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#de.reportWorker(e,t)}removeWorker(e){return this.#de.removeWorker(e)}run(e){return this.#de.run(e)}}class re extends Error{#me;constructor(e){super(`Invalid location: ${e}`),this.#me=e}get location(){return this.#me}}class ne extends Error{#ge;constructor(e){super(`The file '${e}' could not be found`),this.#ge=e}get filename(){return this.#ge}}class ae{#me;#fe;#we;constructor(e,t,s){this.#me=e,this.#fe=t,this.#we=s}get location(){return this.#me}get type(){return this.#fe}get content(){return this.#we}get size(){return this.#we.length}}class ie{#me;#ye;#ve;constructor(e,t){const s=t.resolve(e);this.#me=t.normalize(e),this.#ye=t.normalize(s),this.#ve=t}getAbsoluteLocation(e){const t=this.#ve.isAbsolute(e)?e:this.#ve.join(this.#me,e),s=this.#ve.resolve(t),r=this.#ve.normalize(s);return this.#Se(r,e),r}getRelativeLocation(e){const t=this.#ve.relative(this.#me,e);return this.#ve.normalize(t)}normalizeLocation(e){return this.#ve.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#ve.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#ve.exists(t))throw new ne(e);return this.#ve.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#ve.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#ve.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new ae(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#ve.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#ve.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#ve.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#ve.normalize(e);return(await this.#ve.filter(t,s)).map(e=>this.#ve.normalize(e))}#Se(e,t){if(!1===e.startsWith(this.#ye))throw new re(t)}}class oe extends Error{constructor(){super("Remote files are not supported")}}class ce{copy(e,t){throw new oe}delete(e){throw new oe}exists(e){throw new oe}async filter(e,t){return[]}isAbsolute(e){return e.startsWith("/")}isDirectory(e){throw new oe}join(...e){throw new oe}read(e){throw new oe}resolve(e){return e}relative(e,t){throw new oe}normalize(e){return e}mimeType(e){throw new oe}write(e,t){throw new oe}}class ue extends ie{constructor(e){super(e,new ce)}}class le extends Error{#he;#Ee;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#he=e,this.#Ee=t}get url(){return this.#he}get reason(){return this.#Ee}}class he{#be;constructor(e){this.#be=e}async import(e){const t=this.#be.locate(e);try{return await import(t)}catch(e){const s=e instanceof Error?e.message:String(e);throw new le(t,s)}}}class de{constructor(e){}locate(e){throw new le(e,"Remote module loading is not allowed")}}class pe extends he{constructor(e){super(new de(e))}}class me{#xe;#Oe;constructor(e,t){this.#xe=e,this.#Oe=t}async filter(...e){return(await Promise.all(e.map(e=>this.#xe.filter(e)))).flat().map(e=>this.#xe.getRelativeLocation(e))}exists(e){return this.#xe.exists(e)}read(e){return this.#xe.read(e)}import(e){return this.#Oe.import(e)}}class ge extends me{constructor(e){super(new ue(e),new pe(e))}}class fe extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class we extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class ye extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class ve extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Se{#Ae=[];addSerializer(e){e.parent=this,this.#Ae.unshift(e)}async serialize(e){const t=this.#Ae.find(t=>t.canSerialize(e));if(void 0===t)throw new ve(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Ae.find(t=>t.canDeserialize(e));if(void 0===t)throw new ye(typeof e);return t.deserialize(e)}}class Ee extends Error{constructor(){super("Parent serializer not set")}}class be{#Ce;set parent(e){this.#Ce=e}serializeOther(e){if(void 0===this.#Ce)throw new Ee;return this.#Ce.serialize(e)}deserializeOther(e){if(void 0===this.#Ce)throw new Ee;return this.#Ce.deserialize(e)}}class xe extends be{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const s of e)t.push(await this.serializeOther(s));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Oe extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Ae extends be{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new Oe(e.value)}}}class Ce extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ie extends be{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Ce(e.base64)}}}class Ne{#w;#Ie;constructor(e,t){this.#w=e,this.#Ie=t}get name(){return this.#w}get as(){return this.#Ie}toString(){return`${this.#w} as ${this.#Ie}`}}class Me{#Ne;constructor(e){this.#Ne=e}get definition(){return this.#Ne}toString(){return this.#Ne}}class Te extends Me{}class Re{#w;#Me;#Te;constructor(e,t=!1,s=!1){this.#w=e,this.#Me=t,this.#Te=s}get name(){return this.#w}get isStatic(){return this.#Me}get isPrivate(){return this.#Te}get isPublic(){return!1===this.#Te}}class ze extends Re{#Re;#ze;constructor(e,t,s){super(e),this.#Re=t,this.#ze=s}get parentName(){return this.#Re}get scope(){return this.#ze}get members(){return this.#ze.members}get declarations(){return this.#ze.declarations}get functions(){return this.#ze.functions}get getters(){return this.#ze.getters}get setters(){return this.#ze.setters}get generators(){return this.#ze.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.#ze.getMember(e)}getDeclaration(e){return this.#ze.getDeclaration(e)}getFunction(e){return this.#ze.getFunction(e)}getGetter(e){return this.#ze.getGetter(e)}getSetter(e){return this.#ze.getSetter(e)}getGenerator(e){return this.#ze.getGenerator(e)}hasMember(e){return this.#ze.hasMember(e)}hasDeclaration(e){return this.#ze.hasDeclaration(e)}hasFunction(e){return this.#ze.hasFunction(e)}hasGetter(e){return this.#ze.hasGetter(e)}hasSetter(e){return this.#ze.hasSetter(e)}hasGenerator(e){return this.#ze.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.#Re?` extends ${this.#Re}`:"";return`class ${this.name}${e} { ${this.#ze.toString()} }`}}class Pe extends Re{#Pe;#Le;constructor(e,t,s=!1,r=!1){super(e.toString(),s,r),this.#Pe=e,this.#Le=t}get identifier(){return this.#Pe}get value(){return this.#Le}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Le{#ke;constructor(e){this.#ke=e}get members(){return this.#ke}toString(){return this.#ke.map(e=>e.toString()).join(" , ")}}class ke extends Le{toString(){return`[ ${super.toString()} ]`}}class De extends Le{toString(){return`{ ${super.toString()} }`}}class Fe extends Re{#ke;#De;constructor(e,t){super(""),this.#ke=e,this.#De=t}get members(){return this.#ke}get from(){return this.#De}hasMember(e){return this.#ke.some(t=>t.as===e)}getMember(e){return this.#ke.find(t=>t.as===e)}toString(){const e=this.#De?` from '${this.#De}'`:"";return`export { ${this.#ke.join(", ")} }${e}`}}class Ve extends Me{}class je{#w;#Le;constructor(e,t){this.#w=e,this.#Le=t}get name(){return this.#w}get value(){return this.#Le}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class $e extends Re{#g;#Fe;#Ve;constructor(e,t,s,r=!1,n=!1,a=!1){super(e,r,a),this.#g=t,this.#Fe=s,this.#Ve=n}get parameters(){return this.#g}get body(){return this.#Fe}get isAsync(){return this.#Ve}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class He extends $e{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class Ue extends $e{toString(){return`get ${super.toString()}`}}class Ge extends Re{#ke;#De;constructor(e,t){super(""),this.#ke=e,this.#De=t}get members(){return this.#ke}get from(){return this.#De}hasMember(e){return this.#ke.some(t=>t.as===e)}getMember(e){return this.#ke.find(t=>t.as===e)}toString(){return`import { ${this.#ke.map(e=>e.toString()).join(", ")} } from '${this.#De}';`}}class qe{#ze;constructor(e){this.#ze=e}get scope(){return this.#ze}get members(){return this.#ze.members}get exportedMembers(){return this.#je(this.#ze.members)}get imports(){return this.#ze.imports}get exports(){return this.#ze.exports}get declarations(){return this.#ze.declarations}get exportedDeclarations(){return this.#je(this.#ze.declarations)}get functions(){return this.#ze.functions}get exportedFunctions(){return this.#je(this.#ze.functions)}get generators(){return this.#ze.generators}get exportedGenerators(){return this.#je(this.#ze.generators)}get classes(){return this.#ze.classes}get exportedClasses(){return this.#je(this.#ze.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const s of t.members){const t=this.getMember(s.name);void 0!==t&&e.set(s.as,t)}return e}getMember(e){return this.#ze.getMember(e)}getDeclaration(e){return this.#ze.getDeclaration(e)}getFunction(e){return this.#ze.getFunction(e)}getGenerator(e){return this.#ze.getGenerator(e)}getClass(e){return this.#ze.getClass(e)}hasMember(e){return this.#ze.hasMember(e)}hasDeclaration(e){return this.#ze.hasDeclaration(e)}hasFunction(e){return this.#ze.hasFunction(e)}hasGenerator(e){return this.#ze.hasGenerator(e)}hasClass(e){return this.#ze.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const s of t.members)if(s.as===e)return this.getMember(s.name)}isExported(e){for(const t of this.exports)for(const s of t.members)if(s.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 s of t.members)if(s.as===e)return this.getMember(s.name)}#je(e){return e.filter(e=>this.isExported(e))}}class Be extends Me{}class We extends $e{toString(){return`set ${super.toString()}`}}const _e=Ge.name,Ke=Fe.name,Ye=Pe.name,Xe=$e.name,Je=Ue.name,Qe=We.name,Ze=He.name,et=ze.name;class tt{#ke;constructor(e){this.#ke=e}get members(){return this.#ke}get imports(){return this.#ke.filter(e=>e.constructor.name===_e)}get exports(){return this.#ke.filter(e=>e.constructor.name===Ke)}get declarations(){return this.#ke.filter(e=>e.constructor.name===Ye)}get functions(){return this.#ke.filter(e=>e.constructor.name===Xe)}get getters(){return this.#ke.filter(e=>e.constructor.name===Je)}get setters(){return this.#ke.filter(e=>e.constructor.name===Qe)}get generators(){return this.#ke.filter(e=>e.constructor.name===Ze)}get classes(){return this.#ke.filter(e=>e.constructor.name===et)}getMember(e){return this.#ke.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.#ke.map(e=>e.toString()).join("\n")}}const st={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},rt=Object.values(st);const nt=".",at="(",it=")",ot="[",ct="]",ut="{",lt="}",ht={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},dt=Object.values(ht);function pt(e){return dt.includes(e)}const mt={UNDEFINED:void 0,NULL:null,STRING:""},gt=Object.values(mt);function ft(e){return gt.includes(e)}const wt={OPEN:at,CLOSE:it};function yt(e){return e===wt.OPEN||e===wt.CLOSE}const vt={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"},St=Object.values(vt);function Et(e){return St.includes(e)}function bt(e){return e===vt.AS||e===vt.ASYNC||e===vt.FROM||e===vt.GET||e===vt.SET}const xt={OPEN:ot,CLOSE:ct};function Ot(e){return e===xt.OPEN||e===xt.CLOSE}const At=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Ct(e){return At.includes(e)}const It={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:"^"},Nt=Object.values(It);function Mt(e){return Nt.includes(e)}const Tt={OPEN:ut,CLOSE:lt};function Rt(e){return e===Tt.OPEN||e===Tt.CLOSE}const zt={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},Pt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Lt=Object.values(Pt);function kt(e){return Lt.includes(e)}class Dt{#$e;#He;constructor(e){this.#$e=e,this.#He=0}get items(){return this.#$e}get position(){return this.#He}get size(){return this.#$e.length}get eol(){return this.#He>=this.#$e.length}get current(){return this.#$e[this.#He]}get next(){return this.#$e[this.#He+1]}get previous(){return this.#$e[this.#He-1]}notAtEnd(){return!1===this.eol}get(e){return this.#$e[e]}step(e=1){return this.#He+=e,this.current}stepBack(e=1){return this.#He-=e,this.current}hasNext(){return this.#He+1<this.#$e.length}}class Ft extends Dt{constructor(e){super(e.split(""))}}class Vt{#fe;#Le;#Ue;#Ge;constructor(e,t,s,r){this.#fe=e,this.#Le=t,this.#Ue=s,this.#Ge=r}get type(){return this.#fe}get value(){return this.#Le}get start(){return this.#Ue}get end(){return this.#Ge}isType(e){return this.#fe===e}hasValue(e){return this.#Le===e}toString(){return`${this.#Le}`}}class jt extends Dt{}class $t{tokenize(e){const t=new Ft(e),s=[];let r;for(;t.notAtEnd();){const e=this.#qe(t,r);if(void 0===e)break;e.isType(zt.WHITESPACE)||e.isType(zt.COMMENT)?t.step():(s.push(e),this.#Be(e)&&(r=e),t.step())}return new jt(s)}#Be(e){return!1===[zt.WHITESPACE,zt.COMMENT].includes(e.type)}#qe(e,t){const s=e.current,r=e.position;if(kt(s)){const t=e.position;return new Vt(zt.WHITESPACE,s,r,t)}if(function(e){return rt.includes(e)}(s+e.next)){const t=this.#We(e),s=e.position;return new Vt(zt.COMMENT,t,r,s)}if(this.#_e(s,t)){const t=this.#Ke(e),s=e.position;return new Vt(zt.REGEX,t,r,s)}if(Ct(s)){const t=this.#Ye(e),s=e.position;return new Vt(zt.LITERAL,t,r,s)}if(Mt(s)){const t=this.#Xe(e),s=e.position;return new Vt(zt.OPERATOR,t,r,s)}if(pt(s)){const t=e.position;return new Vt(zt.DIVIDER,s,r,t)}if(yt(s)){const t=e.position;return new Vt(zt.GROUP,s,r,t)}if(Rt(s)){const t=e.position;return new Vt(zt.SCOPE,s,r,t)}if(Ot(s)){const t=e.position;return new Vt(zt.LIST,s,r,t)}if(ft(s))return;const n=this.#Je(e),a=Et(n)?zt.KEYWORD:zt.IDENTIFIER,i=e.position;return new Vt(a,n,r,i)}#We(e){const t=e.current+e.next===st.MULTI_START,s=t?st.MULTI_END:Pt.NEWLINE;let r=t?st.MULTI_START:st.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===s){e.step(s.length-1);break}r+=n,e.step()}return t?r+st.MULTI_END:r.trim()}#_e(e,t){return e===It.DIVIDE&&(void 0===t||([zt.OPERATOR,zt.DIVIDER,zt.KEYWORD].includes(t.type)||[wt.OPEN,xt.OPEN].includes(t.value)))}#Qe(e){return kt(e)||e==nt||!1===this.#Ze(e)}#Ke(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,n=e.previous;if(r===It.DIVIDE&&"\\"!==n)s=!0;else if(!0===s&&this.#Qe(r)){e.stepBack();break}t+=r,e.step()}return t}#Ye(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===r){if(n===t){s+=n;break}"\\"===n&&(r=!0)}else r=!1;s+=n,e.step()}return s}#Ze(e){return!1===(ft(e)||kt(e)||Mt(e)||Ct(e)||pt(e)||yt(e)||Rt(e)||Ot(e))}#Je(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#Ze(s)){e.stepBack();break}t+=s,e.step()}return t}#Xe(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===Mt(s)||!1===Mt(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Ht extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ut extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Gt 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 Bt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Wt="default",_t=" ";class Kt{#et;constructor(e=new $t){this.#et=e}parse(e){const t=this.#et.tokenize(e),s=this.#tt(t);return new qe(s)}parseFirst(e){const t=this.#et.tokenize(e);return this.#st(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Me==!1)throw new qt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof Ge==!1)throw new qt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof Fe==!1)throw new qt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof Pe==!1)throw new qt("a declaration definition");return t}parseFunction(e){const t=this.#et.tokenize(e),s=this.#rt(t);if(s instanceof $e==!1)throw new qt("a function definition");return s}parseClass(e){const t=this.#et.tokenize(e),s=this.#rt(t);if(s instanceof ze==!1)throw new qt("a class definition");return s}#tt(e){const t=[];for(;e.notAtEnd();){const s=this.#st(e);s instanceof Re&&t.push(s)}return new tt(t)}#st(e,t=!1){const s=e.current;if(s.isType(zt.LITERAL))return this.#nt(e);if(s.isType(zt.IDENTIFIER)){const s=e.next;return s?.hasValue(It.ARROW)?this.#at(e,t):this.#nt(e)}if(s.isType(zt.KEYWORD)){if(bt(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(vt.FUNCTION)||t.hasValue(wt.OPEN));if(s.hasValue(vt.ASYNC)&&r)return e.step(),this.#st(e,!0);if(void 0===t||this.#it(t))return this.#nt(e)}return s.hasValue(vt.RETURN)?this.#nt(e):this.#rt(e,t)}if(s.isType(zt.REGEX))return this.#nt(e);if(s.hasValue(wt.OPEN)){const s=this.#ot(e,wt.OPEN,wt.CLOSE);return s?.hasValue(It.ARROW)?this.#at(e,t):this.#nt(e)}if(s.hasValue(Tt.OPEN))return this.#ct(e);if(s.hasValue(xt.OPEN))return this.#ut(e);if(s.hasValue(It.NOT)||s.hasValue(It.SUBTRACT))return this.#nt(e);if(!pt(s.value))throw new Bt(s.value,s.start);e.step()}#rt(e,t=!1){const s=e.current;switch(e.step(),s.value){case vt.IMPORT:return this.#lt(e);case vt.EXPORT:return this.#ht(e);case vt.CLASS:return this.#dt(e);case vt.FUNCTION:return this.#pt(e,t);case vt.VAR:case vt.LET:case vt.CONST:return this.#mt(e,!1,!0);case vt.ASYNC:return this.#rt(e,!0);default:throw new Gt(s.value,s.start)}}#lt(e){const t=[];let s=e.current;if(s.isType(zt.LITERAL))return new Ge(t,s.value);if(s.hasValue(wt.OPEN)){s=e.step();const r=s.value;return e.step(2),new Ge(t,r)}if(!1===s.hasValue(Tt.OPEN)){const r=s.hasValue(It.MULTIPLY)?It.MULTIPLY:Wt;let n=s.value;s=e.step(),s.hasValue(vt.AS)&&(s=e.step(),n=s.value,s=e.step()),t.push(new Ne(r,n))}if(s.hasValue(ht.SEPARATOR)&&(s=e.step()),s.hasValue(Tt.OPEN)){const r=this.#gt(e);t.push(...r),s=e.current}if(!1===s.hasValue(vt.FROM))throw new Ht(vt.FROM,s.start);s=e.step();const r=s.value;return e.step(),new Ge(t,r)}#ht(e){switch(e.current.value){case vt.DEFAULT:return e.step(),this.#ft(e,!0);case Tt.OPEN:return this.#wt(e);default:return this.#ft(e,!1)}}#ft(e,t){let s=e.current,r=0;var n;s.hasValue(vt.ASYNC)&&(s=e.step(),r++),((n=s.value)===vt.CLASS||n===vt.FUNCTION||n===vt.CONST||n===vt.LET||n===vt.VAR)&&(s=e.step(),r++);const a=this.#Ze(s)?s.value:"",i=t?Wt:a;let o;s=e.step(),s?.hasValue(vt.FROM)&&(s=e.step(),o=s.value),r>0&&(r++,e.stepBack(r));const c=new Ne(a,i);return new Fe([c],o)}#wt(e){const t=this.#gt(e);let s,r=e.current;return r?.hasValue(vt.FROM)&&(r=e.step(),s=r.value),e.step(),new Fe(t,s)}#gt(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Tt.CLOSE)){e.step();break}if(s.hasValue(ht.SEPARATOR)){s=e.step();continue}const r=this.#yt(e);t.push(r),s=e.step()}return t}#yt(e){let t=e.current;const s=t.value;let r=s;return e.next.hasValue(vt.AS)&&(t=e.step(2),r=t.value),new Ne(s,r)}#mt(e,t,s=!1){let r,n,a=e.current,i=!1;return a.hasValue(xt.OPEN)?(r=this.#vt(e),a=e.current):a.hasValue(Tt.OPEN)?(r=this.#St(e),a=e.current):(i=a.value.startsWith("#"),r=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(It.ASSIGN)&&(e.step(),n=this.#st(e,!1),a=e.current),void 0!==a&&(a.hasValue(ht.TERMINATOR)?e.step():!0===s&&a.hasValue(ht.SEPARATOR)&&(e.step(),this.#mt(e,t,!0))),n instanceof He?new He(r.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof $e?new $e(r.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof ze?new ze(r.toString(),n.parentName,n.scope):new Pe(r,n,t,i)}#pt(e,t,s=!1,r=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(It.MULTIPLY)&&(o=!0,a=e.step()),this.#Ze(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,a=e.step());const u=this.#Et(e,wt.CLOSE);if(a=e.current,!1===a.hasValue(Tt.OPEN))throw new Ut(Tt.OPEN,a.start);const l=this.#bt(e,Tt.OPEN,Tt.CLOSE);return o?new He(i,u,l,s,t,c):r?new Ue(i,u,l,s,t,c):n?new We(i,u,l,s,t,c):new $e(i,u,l,s,t,c)}#at(e,t){let s,r=e.current;if(r.hasValue(wt.OPEN)?(s=this.#Et(e,wt.CLOSE),r=e.current):(s=[new je(r.value,void 0)],r=e.step()),!1===r.hasValue(It.ARROW))throw new Ut(It.ARROW,r.start);r=e.step();const n=r.hasValue(Tt.OPEN)?this.#bt(e,Tt.OPEN,Tt.CLOSE):this.#nt(e).definition;return new $e("",s,n,!1,t,!1)}#Et(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(ht.SEPARATOR)){e.step();continue}let n;n=r.hasValue(Tt.OPEN)?this.#St(e):r.hasValue(xt.OPEN)?this.#vt(e):this.#xt(e),s.push(n)}return s}#dt(e){let t,s=e.current,r="";if(this.#Ze(s)&&(r=s.value,s=e.step()),s.hasValue(vt.EXTENDS)&&(s=e.step(),t=s.value,s=e.step()),!1===s.hasValue(Tt.OPEN))throw new Ut(Tt.OPEN,s.start);const n=this.#Ot(e);return new ze(r,t,n)}#Ot(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Tt.CLOSE)){e.step();break}const r=this.#At(e);s.push(r),t=e.current}return new tt(s)}#At(e){let t=e.current,s=!1,r=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(vt.STATIC))r=!0;else if(t.hasValue(vt.ASYNC))s=!0;else if(t.hasValue(vt.GET))n=!0;else{if(!t.hasValue(vt.SET)){if(t.hasValue(It.MULTIPLY))return this.#pt(e,s,r,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(wt.OPEN)?this.#pt(e,s,r,n,a):this.#mt(e,r)}#ut(e){const t=this.#bt(e,xt.OPEN,xt.CLOSE);return new Te(t)}#vt(e){const t=this.#Et(e,xt.CLOSE);return new ke(t)}#ct(e){const t=this.#bt(e,Tt.OPEN,Tt.CLOSE);return new Be(t)}#St(e){const t=this.#Et(e,Tt.CLOSE);return new De(t)}#xt(e){let t=e.current;const s=t.value;let r;return t=e.step(),t.hasValue(It.ASSIGN)&&(e.step(),r=this.#st(e,!1)),new je(s,r)}#nt(e){let t=e.current,s="";for(;e.notAtEnd();){if(t.hasValue(xt.OPEN)){s+=this.#bt(e,xt.OPEN,xt.CLOSE)+_t,t=e.current}else if(t.hasValue(wt.OPEN)){s+=this.#bt(e,wt.OPEN,wt.CLOSE)+_t,t=e.current}else if(t.hasValue(Tt.OPEN)){s+=this.#bt(e,Tt.OPEN,Tt.CLOSE)+_t,t=e.current}else s+=t.toString()+_t,t=e.step();if(void 0===t||this.#it(t))break}return new Ve(s.trim())}#bt(e,t,s){let r=e.step(),n=t+_t;for(;e.notAtEnd();)if(r.hasValue(t))n+=this.#bt(e,t,s)+_t,r=e.current;else{if(r.hasValue(s))return e.step(),n+=s,n;n+=r.toString()+_t,r=e.step()}return n}#ot(e,t,s){const r=e.position;this.#bt(e,t,s);const n=e.current,a=e.position;return e.stepBack(a-r),n}#it(e){return[ht.TERMINATOR,ht.SEPARATOR].includes(e.value)||[xt.CLOSE,wt.CLOSE,Tt.CLOSE].includes(e.value)||Et(e.value)}#Ze(e){return e.isType(zt.IDENTIFIER)||e.isType(zt.KEYWORD)&&bt(e.value)}}class Yt{merge(e,t){const s=this.#Ct(e.declarations,t.declarations),r=this.#It(e.functions,t.functions),n=this.#It(e.getters,t.getters),a=this.#It(e.setters,t.setters),i=[...s.values(),...r.values(),...n.values(),...a.values()];return new ze(e.name,t.name,new tt(i))}#Ct(e,t){const s=new Map;return t.forEach(e=>s.set(e.name,e)),e.forEach(e=>s.set(e.name,e)),[...s.values()]}#It(e,t){const s=new Map;return t.forEach(e=>s.set(e.name,e)),e.forEach(e=>s.set(e.name,e)),[...s.values()]}}class Xt{#Nt=new Kt;#Mt=new Yt;fromModule(e,t=!1){const s=Object.entries(e),r=[];for(const[e,n]of s){if("function"!=typeof n.toString)continue;const s=n.toString();if(s.startsWith("class"))r.push(this.fromClass(n,t));else if(s.startsWith("function"))r.push(this.fromFunction(n));else{const t=new Ve(s);r.push(new Pe(e,t))}}return new qe(new tt(r))}fromClass(e,t=!1){const s=this.isClass(e)?this.#Tt(e):this.#Rt(e);if(!1===t)return s;const r=this.getParentClass(e);if(""===r.name)return s;const n=this.fromClass(r,!0);return this.#Mt.merge(s,n)}fromObject(e,t=!0){const s=this.getClass(e);return this.fromClass(s,t)}fromFunction(e){const t=e.toString();return this.#Nt.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")}#Tt(e){const t=e.toString();return this.#Nt.parseClass(t)}#Rt(e){const t=this.createInstance(e),s=this.#zt(e,t),r=new tt(s);return new ze(e.name,void 0,r)}#zt(e,t){return[...this.#Pt(t),...this.#Lt(e)]}#Pt(e){const t=Object.getOwnPropertyNames(e),s=e,r=[];for(const e of t){const t=s[e],n=void 0!==t?new Me(String(t)):void 0,a=new Pe(e,n);r.push(a)}return r}#Lt(e){const t=Object.getOwnPropertyDescriptors(e.prototype),s=[];for(const e in t){const r=t[e],n=r.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==r.get?s.push(new Ue(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==r.set?s.push(new We(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):s.push(a)}return s}}const Jt=new Xt;class Qt extends be{#kt;constructor(e){super(),this.#kt=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),s=Jt.fromClass(t,!0),r=this.#Dt(s),n=this.#kt.resolveKey(t);if(void 0===n)throw new fe(t.name);return{serialized:!0,key:n,name:"class",args:await this.#Ft(s,r,e),fields:await this.#Vt(s,r,e)}}#Dt(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#Ft(e,t,s){const r={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(s[a]):void 0;r[n.toString()]=t}return r}async#Vt(e,t,s){const r={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(r[a]=await this.serializeOther(s[a]))}return r}async deserialize(e){const t=await this.#jt(e);if(void 0===t)throw new fe(e.key);if(t instanceof Function==!1)throw new we(e.key);const s=await this.#$t(t,e.args),r=Jt.createInstance(t,s);for(const t in e.fields){const s=e.fields[t];r[t]=await this.deserializeOther(s)}return r}async#$t(e,t){const s=Jt.fromClass(e,!0).getFunction("constructor"),r=(s?.parameters??[]).map((e,s)=>{const r=s.toString(),n=t[r];return this.deserializeOther(n)});return Promise.all(r)}async#jt(e){return globalThis[e.key]??this.#kt.resolveClass(e.key)}}class Zt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class es extends be{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new Zt(e.value);return t}}class ts extends be{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class ss extends be{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],s=[];for(const[r,n]of e)t.push(await this.serializeOther(r)),s.push(await this.serializeOther(n));return{serialized:!0,name:"Map",entries:{keys:t,values:s}}}async deserialize(e){const t=e.entries.keys,s=e.entries.values,r=new Map;for(let e=0;e<t.length;e++){const n=await this.deserializeOther(t[e]),a=await this.deserializeOther(s[e]);r.set(n,a)}return r}}class rs extends be{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.serializeOther(r)}return t}async deserialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.deserializeOther(r)}return t}}class ns extends be{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class as extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class is extends be{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new as(e.source,e.flags)}}}class os extends be{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const s of e.values())t.push(await this.serializeOther(s));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const cs=new Xt;class us extends be{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,s=new DataView(e.buffer),r=[];for(let e=0;e<s.byteLength;e++)r.push(s.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:r}}async deserialize(e){const t=e.type,s=e.bytes,r=new ArrayBuffer(s.length),n=new DataView(r);for(let e=0;e<s.length;e++)n.setUint8(e,s[e]);const a=globalThis[t];return cs.createInstance(a,[r])}}class ls extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class hs extends be{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new ls(e.value)}}}class ds{static build(e){const t=new Se;return t.addSerializer(new ns),t.addSerializer(new rs),void 0!==e&&t.addSerializer(new Qt(e)),t.addSerializer(new ts),t.addSerializer(new is),t.addSerializer(new Ae),t.addSerializer(new hs),t.addSerializer(new es),t.addSerializer(new os),t.addSerializer(new ss),t.addSerializer(new xe),t.addSerializer(new us),"undefined"!=typeof Buffer&&t.addSerializer(new Ie),t}}class ps{#Ht;constructor(e){this.#Ht=e}resolveKey(e){const t=this.#Ht.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Ht.getClass(e);return t?.implementation}}class ms extends o{constructor(){super("Request not trusted")}}const gs="X-Jitar-Trust-Key",fs="X-Jitar-Data-Encoding",ws="serialized";class ys{#s;#he;#Ut;#Gt;#qt;#Ht;#Bt;#Wt;#_t;#pe=new te;constructor(e){this.#he=e.url,this.#Ut=e.trustKey,this.#Gt=e.gateway,this.#qt=!0===e.registerAtGateway,this.#Ht=e.executionManager,this.#Bt=e.healthManager;const t=e.scheduleManager;this.#Wt=t.create(()=>this.#Kt(),e.reportInterval);const s=new ps(this.#Ht);this.#_t=ds.build(s)}get id(){return this.#s}set id(e){this.#s=e}get state(){return this.#pe.state}get url(){return this.#he}get trustKey(){return this.#Ut}async start(){return this.#pe.start(async()=>{await Promise.all([this.#Ht.start(),this.#Bt.start()]),void 0!==this.#Gt&&(await this.#Gt.start(),this.#qt&&(this.#s=await this.#Gt.addWorker(this),this.#Wt.start())),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{void 0!==this.#Gt&&(void 0!==this.#s&&(this.#Wt.stop(),await this.#Gt.removeWorker(this.#s)),await this.#Gt.stop()),await Promise.all([this.#Bt.stop(),this.#Ht.stop()])})}getProcedureNames(){return this.#Ht.getProcedureNames()}hasProcedure(e){return this.#Ht.hasProcedure(e)}isHealthy(){return this.#Bt.isHealthy()}getHealth(){return this.#Bt.getHealth()}isAvailable(){return this.#pe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}async reportState(e){if(void 0!==this.#Gt&&void 0!==this.#s)return this.#Gt.reportWorker(this.#s,e)}async run(e){return this.#Yt(e)?this.#Xt(e):this.#Jt(e)}#Yt(e){return void 0===this.#Gt||this.#Ht.hasProcedure(e.fqn)}async#Xt(e){const t=this.#Ht.getProcedure(e.fqn),s=t?.getImplementation(e.version);if(this.#Qt(s))throw new x(e.fqn);if(this.#Zt(e,s))throw new ms;const r=e.getHeader(fs);r===ws&&(e=await this.#es(e)),e.removeHeader(fs);const n=await this.#Ht.run(e);return r===ws?this.#ts(n):n}#Qt(e){return void 0===e||e.private}#Zt(e,t){if(t.public)return!1;const s=e.getHeader(gs);return this.#Ut!==s}async#Jt(e){(e=await this.#ss(e)).setHeader(fs,ws),void 0!==this.#Ut&&e.setHeader(gs,this.#Ut);const t=await this.#Gt.run(e);return this.#rs(t)}async#ss(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#_t.serialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#es(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#_t.deserialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#ts(e){const t=await this.#_t.serialize(e.result);return new D(e.status,t,e.headers)}async#rs(e){const t=await this.#_t.deserialize(e.result);return new D(e.status,t,e.headers)}async#Kt(){const e=await this.updateState();return this.reportState(e)}}class vs{#K;constructor(e){this.#K=e}async handle(e,t){return this.#K.run(e)}}class Ss{#ns=new G;constructor(){this.#as()}#as(){const e=globalThis;e.__run=this.#is.bind(this),e.ProcedureNotAccessible=O}async#is(e,t,s,r){const n=this.#ns.parse(t),a=new Map(Object.entries(s)),i=r instanceof k?r.headers:new Map,o=new k(e,n,a,i,h),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==p)throw u.result;return u.result}}class Es extends Ss{#os;#cs;#us=new Y(this);constructor(e){super(),this.#os=new ys({url:e.remoteUrl,gateway:new se({url:e.remoteUrl,remote:e.remote}),healthManager:e.healthManager,executionManager:e.executionManager,scheduleManager:e.scheduleManager}),this.#cs=e.middlewareManager}get worker(){return this.#os}async start(){await this.#ls(),this.#us.start()}async stop(){this.#us.stop(),await this.#hs()}getTrustKey(){}run(e){return this.#cs.handle(e)}async runInternal(e){return this.#us.run(e)}async#ls(){await Promise.all([this.#os.start(),this.#cs.start()]);const e=new vs(this.#os);this.#cs.addMiddleware(e)}async#hs(){await Promise.all([this.#cs.stop(),this.#os.stop()])}}const bs="starting",xs="started",Os="stopping",As="stopped";class Cs extends a{constructor(){super("Invalid health check")}}class Is{#ce=As;#ds=new Map;#j;#ps;constructor(e,t=[]){this.#j=e,this.#ps=t}get state(){return this.#ce}async start(){if(this.#ce===As)try{this.#ce=bs,await this.#ms(),this.#ce=xs}catch(e){throw this.#ce=As,e}}async stop(){if(this.#ce===xs)try{this.#ce=Os,this.clearHealthChecks(),this.#ce=As}catch(e){throw this.#ce=xs,e}}async loadHealthCheck(e){const t=await this.#gs(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new Cs;this.#ds.set(e.name,e)}clearHealthChecks(){this.#ds.clear()}async isHealthy(){const e=[];for(const t of this.#ds.values()){const s=this.#fs(t);e.push(s)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,s]of this.#ds){const r=this.#fs(s).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(r)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ws(e,t))).then(()=>t)}async#ms(){(await Promise.all(this.#ps.map(e=>this.#gs(e)))).forEach(e=>this.addHealthCheck(e))}async#gs(e){return(await this.#j.import(e)).default}#ws(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#fs(e){const t=e.isHealthy(),s=e.timeout;if(void 0===s)return t;const r=new Promise(e=>{setTimeout(e,s)}).then(()=>!1);return Promise.race([r,t])}}const Ns=0,Ms=1,Ts=2,Rs=3;class zs{#ys;#vs;constructor(e=Ms,t=console){this.#ys=e,this.#vs=t}debug(...e){if(this.#ys>Ns)return;const t=this.#Ss("DEBUG",e);this.#vs.debug(t)}info(...e){if(this.#ys>Ms)return;const t=this.#Ss("INFO",e);this.#vs.info(t)}warn(...e){if(this.#ys>Ts)return;const t=this.#Ss("WARN",e);this.#vs.warn(t)}error(...e){if(this.#ys>Rs)return;const t=this.#Ss("ERROR",e);this.#vs.error(t)}fatal(...e){const t=this.#Ss("FATAL",e);this.#vs.error(t)}#Ss(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Es(e)).join(" ")}`}#Es(e,t=0){let s;switch(typeof e){case"string":s=e;break;case"object":s=this.#bs(e,t+1);break;case"undefined":s="undefined";break;case"function":s="function";break;default:s=String(e)}return`${this.#xs(t)}${s}`}#bs(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Es(e,t)).join(",\n")}\n${this.#xs(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#xs(e){return" ".repeat(e)}}const Ps="starting",Ls="started",ks="stopping",Ds="stopped";class Fs extends a{constructor(){super("Invalid middleware")}}class Vs{#ce=Ds;#Os=[];#j;#As;constructor(e,t=[]){this.#j=e,this.#As=t}get state(){return this.#ce}async start(){if(this.#ce===Ds)try{this.#ce=Ps,await this.#Cs(),this.#ce=Ls}catch(e){throw this.#ce=Ds,e}}async stop(){if(this.#ce===Ls)try{this.#ce=ks,this.clearMiddlewares(),this.#ce=Ds}catch(e){throw this.#ce=Ls,e}}async loadMiddleware(e){const t=await this.#Is(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Fs;this.#Os.push(e)}getMiddleware(e){return this.#Os.find(t=>t instanceof e)}clearMiddlewares(){this.#Os=[]}handle(e){return this.#Ns(e,0)()}async#Cs(){(await Promise.all(this.#As.map(e=>this.#Is(e)))).forEach(e=>this.addMiddleware(e))}async#Is(e){return(await this.#j.import(e)).default}#Ns(e,t){const s=this.#Os[t];if(void 0===s)return async()=>new D(p);const r=this.#Ns(e,t+1);return async()=>await s.handle(e,r)}}class js{#Ms;#Ts;#Rs;#zs=null;constructor(e,t,s=5e3){this.#Ms=e,this.#Ts=t,this.#Rs=s}start(){this.#Ps()}stop(){null!==this.#zs&&(clearTimeout(this.#zs),this.#zs=null)}#Ps(){this.#zs=setTimeout(async()=>{null!==this.#zs&&(await this.#Ls(),this.#Ps())},this.#Rs),this.#zs.unref()}async#Ls(){try{await this.#Ts()}catch(e){this.#Ms.warn("Scheduled task failed",e)}}}class $s{#ks=[];#Ms;constructor(e){this.#Ms=e}create(e,t){const s=new js(this.#Ms,e,t);return this.#ks.push(s),s}remove(e){const t=this.#ks.indexOf(e);t<0||this.#ks.splice(t,1)}startAll(){this.#ks.forEach(e=>e.start())}stopAll(){this.#ks.forEach(e=>e.stop())}}class Hs{#Ds;constructor(e){this.#Ds=e}build(e){const t=e.remoteUrl,s=e.middleware,r=e.segments,n=new zs(e.logLevel??Ts),a=this.#Ds.build(t),i=new ge(t),o=this.#Fs(i),c=this.#Vs(i,s),u=this.#js(i,r),l=this.#$s(n);return new Es({remoteUrl:t,remote:a,healthManager:o,middlewareManager:c,executionManager:u,scheduleManager:l})}#Fs(e){return new Is(e)}#Vs(e,t=[]){const s=new Vs(e);return t.forEach(e=>s.addMiddleware(e)),s}#js(e,t=[]){const s=new _(e);return t.forEach(e=>s.addSegment(e)),s}#$s(e){return new $s(e)}}class Us{#Hs;constructor(e=!0){this.#Hs=e}validate(e,t){const s=[];this.#Us("",e,t,s);return{valid:0===s.length,errors:s}}#Us(e,t,s,r){this.#Hs&&this.#Gs(e,t,s,r),this.#qs(e,t,s,r)}#Gs(e,t,s,r){const n=Object.keys(t),a=Object.keys(s);for(const t of n)if(!1===a.includes(t)){const s=this.#Bs(e,t);r.push(`Unknown field '${s}'`)}}#qs(e,t,s,r){const n=Object.keys(s);for(const a of n){const n=this.#Bs(e,a),i=s[a],o=t[a];this.#Ws(n,o,i,r)}}#Ws(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#_s(e,t,s,r);case"integer":return this.#Ks(e,t,s,r);case"real":return this.#Ys(e,t,s,r);case"boolean":return this.#Xs(e,t,s,r);case"url":return this.#Js(e,t,s,r);case"group":return this.#Qs(e,t,s,r);case"list":return this.#Zs(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#_s(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#Ks(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Ys(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Xs(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#Js(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#Qs(e,t,s,r){"object"==typeof t?this.#Us(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#Zs(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Bs(e,t),i=n[t];this.#Ws(a,i,s.items,r)}}#Bs(e,t){return""===e?t:`${e}.${t}`}}const Gs="content-type",qs="x-jitar-content-type",Bs="x-jitar-procedure-version",Ws="application/json",_s="application/octet-stream";class Ks extends Error{constructor(){super("Invalid worker id")}}class Ys{#he;#er;#U=new H;#tr=new Us;constructor(e,t){this.#he=e,this.#er=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#he}/${e}`,s=await this.#sr(t,{method:"GET"}),r=s.headers.get(Gs)??_s,n=await s.arrayBuffer(),a=Buffer.from(n);return new ae(e,r,a)}async isHealthy(){const e=`${this.#he}/health/status`,t=await this.#sr(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#he}/health`,t=await this.#sr(e,{method:"GET"}),s=await t.json();return new Map(Object.entries(s))}async addWorker(e,t,s){const r=`${this.#he}/workers`,n={url:e,procedureNames:t,trustKey:s},a={method:"POST",headers:{"Content-Type":Ws},body:JSON.stringify(n)},i=await this.#sr(r,a),o=i.headers.get(Gs);if(null===o||!1===o.includes(Ws))throw new Ks;const c=await i.json();if(!1===this.#tr.validate(c,{id:{type:"string",required:!0}}).valid)throw new Ks;return c.id}async reportWorker(e,t){const s=`${this.#he}/workers/${e}/report`,r={state:t},n={method:"POST",headers:{"Content-Type":Ws},body:JSON.stringify(r)};await this.#sr(s,n)}async removeWorker(e){const t=`${this.#he}/workers/${e}`,s={method:"DELETE",headers:{"Content-Type":Ws}};await this.#sr(t,s)}async run(e){e.setHeader(Gs,Ws);const t=Object.fromEntries(e.args),s=Object.fromEntries(e.headers),r=e.version.toString();s[Bs]=r;const n=`${this.#he}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:s,body:await this.#rr(t)},i=await this.#sr(n,a,!1),o=i.status,c=await this.#nr(i),u=this.#ar(i);return new D(o,c,u)}async#sr(e,t,s=!0){const r=await this.#er.execute(e,t);if(s&&this.#ir(r)){const e=await this.#nr(r);throw this.#U.fromStatus(r.status,String(e))}return r}#ir(e){return e.status<200||e.status>399}async#rr(e){return JSON.stringify(e)}async#nr(e){const t=e.headers.get(qs)??e.headers.get(Gs);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const s=await e.text();return t?.includes("boolean")?"true"===s:t?.includes("number")?Number(s):s}#ar(e){const t=new Map;for(const[s,r]of e.headers)t.set(s,r);return t}}class Xs{async execute(e,t){return fetch(e,t)}}class Js{#er;constructor(e=new Xs){this.#er=e}build(e){return new Ys(e,this.#er)}}export{P as ArrayParameter,e as BadRequest,C as Class,Hs as ClientBuilder,t as Forbidden,Js as HttpRemoteBuilder,M as Implementation,R as NamedParameter,s as NotFound,r as NotImplemented,L as ObjectParameter,n as PaymentRequired,N as Procedure,k as Request,D as Response,A as Segment,a as ServerError,i as Teapot,o as Unauthorized,I as Version};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jitar",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.6",
|
|
4
4
|
"description": "Distributed runtime for JavaScript and TypeScript to chop monolithic applications into micros.",
|
|
5
5
|
"author": "Masking Technology <info@masking.tech> (https://jitar.dev)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,9 +30,9 @@
|
|
|
30
30
|
"prepublishOnly": "npm run clean && npm run build"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"dotenv": "17.2.
|
|
33
|
+
"dotenv": "17.2.4",
|
|
34
34
|
"express": "5.2.1",
|
|
35
|
-
"glob": "13.0.
|
|
35
|
+
"glob": "13.0.1",
|
|
36
36
|
"mime-types": "3.0.2"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@rollup/plugin-replace": "6.0.3",
|
|
49
49
|
"@rollup/plugin-terser": "0.4.4",
|
|
50
50
|
"@rollup/plugin-typescript": "12.3.0",
|
|
51
|
-
"rollup": "4.
|
|
51
|
+
"rollup": "4.57.1",
|
|
52
52
|
"rollup-plugin-dts": "6.3.0"
|
|
53
53
|
},
|
|
54
54
|
"engines": {
|