jitar 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ConfigurationManager-BWtWRzof.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/lib.d.ts +6 -0
- package/dist/lib.js +1 -1
- package/dist/templates/backend/package.json +2 -2
- package/dist/templates/backend/services/standalone.json +1 -1
- package/dist/templates/react/package.json +12 -9
- package/dist/templates/react/services/standalone.json +2 -0
- package/dist/templates/vue/package.json +10 -7
- package/dist/templates/vue/services/standalone.json +2 -0
- package/dist/templates/vue/src/env.d.ts +1 -0
- package/package.json +17 -15
- package/dist/ConfigurationManager-CQWv0Wmk.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import fs,{promises}from"node:fs";import path from"node:path";import{glob}from"glob";import mime from"mime-types";import dotenv from"dotenv";const Files$1={MODULE_PATTERN:"**/*.js",RESOURCE_PATTERN:"**/*.json",SEGMENT_PATTERN:"**/*.json"};class InvalidPath extends Error{constructor(location){super(`Invalid location '${location}'`)}}class FileNotFound extends Error{constructor(filename){super(`File could not be found from '${filename}'`)}}class File{#location;#type;#content;constructor(location,type,content){this.#location=location,this.#type=type,this.#content=content}get location(){return this.#location}get type(){return this.#type}get content(){return this.#content}get size(){return this.#content.length}}class FileManager{#rootLocation;#fileSystem;constructor(fileSystem,location,root=""){const joinedLocation=fileSystem.join(root,location),rootLocation=fileSystem.resolve(joinedLocation);this.#rootLocation=fileSystem.normalize(rootLocation),this.#fileSystem=fileSystem}normalizeLocation(location){return this.#fileSystem.normalize(location)}getAbsoluteLocation(filename){const location=this.#fileSystem.isAbsolute(filename)?filename:this.#fileSystem.join(this.#rootLocation,filename),absoluteLocation=this.#fileSystem.resolve(location),normalizedLocation=this.normalizeLocation(absoluteLocation);return this.#validateLocation(normalizedLocation,filename),normalizedLocation}getRelativeLocation(filename){const absoluteLocation=this.getAbsoluteLocation(filename),relativeLocation=this.#fileSystem.relative(this.#rootLocation,absoluteLocation);return this.normalizeLocation(relativeLocation)}async getType(filename){const location=this.getAbsoluteLocation(filename);return await this.#fileSystem.mimeType(location)??"application/octet-stream"}async getContent(filename){const location=this.getAbsoluteLocation(filename);if(!1===await this.#fileSystem.exists(location))throw new FileNotFound(filename);return this.#fileSystem.read(location)}async exists(filename){const location=this.getAbsoluteLocation(filename);return this.#fileSystem.exists(location)}isDirectory(filename){const location=this.getAbsoluteLocation(filename);return this.#fileSystem.isDirectory(location)}async read(filename){const[type,content]=await Promise.all([this.getType(filename),this.getContent(filename)]);return new File(filename,type,content)}async write(filename,content){const location=this.getAbsoluteLocation(filename);return this.#fileSystem.write(location,content)}async copy(source,destination){const sourceLocation=this.getAbsoluteLocation(source),destinationLocation=this.getAbsoluteLocation(destination);return this.#fileSystem.copy(sourceLocation,destinationLocation)}async delete(filename){const location=this.getAbsoluteLocation(filename);return this.#fileSystem.delete(location)}async filter(pattern){const normalizedPattern=this.normalizeLocation(pattern);return(await this.#fileSystem.filter(this.#rootLocation,normalizedPattern)).map(filename=>this.normalizeLocation(filename))}async filterWithIgnores(pattern,ignorePatterns){const allFilenames=await this.filter(pattern),ignoreFilters=ignorePatterns.map(pattern=>this.filter(pattern)),ignoredFilenames=await Promise.all(ignoreFilters),ignoredSet=new Set(ignoredFilenames.flat());return allFilenames.filter(filename=>!1===ignoredSet.has(filename))}#validateLocation(location,filename){const relativePath=this.#fileSystem.relative(this.#rootLocation,location),normalizedPath=this.normalizeLocation(relativePath);if(".."===normalizedPath||normalizedPath.startsWith("../"))throw new InvalidPath(filename);if(this.#fileSystem.isAbsolute(normalizedPath))throw new InvalidPath(filename)}}class LocalFileSystem{copy(source,destination){return promises.cp(source,destination,{recursive:!0,force:!0})}delete(location){return promises.rm(location,{recursive:!0,force:!0})}async exists(location){try{return await promises.stat(location),!0}catch{return!1}}isAbsolute(location){return path.isAbsolute(location)}isDirectory(location){try{return fs.statSync(location).isDirectory()}catch{return!1}}filter(location,pattern){return glob(`${location}/${pattern}`,{absolute:!0})}join(...paths){return path.join(...paths)}read(location){return promises.readFile(location)}resolve(location){return path.resolve(location)}relative(from,to){return path.relative(from,to)}normalize(location){return location.replaceAll(path.win32.sep,path.posix.sep)}async mimeType(location){const mimeType=mime.lookup(location);if(!1!==mimeType)return mimeType}async write(location,content){const directory=path.dirname(location);return fs.mkdirSync(directory,{recursive:!0}),promises.writeFile(location,content)}}class LocalFileManager extends FileManager{constructor(location,root){super(new LocalFileSystem,location,root)}}class Application{#repository;#resources;#segmentation;constructor(repository,resources,segmentation){this.#repository=repository,this.#resources=resources,this.#segmentation=segmentation}get resources(){return this.#resources}get repository(){return this.#repository}get segmentation(){return this.#segmentation}}class ResourcesList{#resources;constructor(resources){this.#resources=resources}isResourceModule(moduleFilename){return this.#resources.includes(moduleFilename)}}const Defaults_ACCESS_LEVEL="private",Defaults_VERSION_NUMBER="0.0.0",Files_INDEX="index.js",Files_JSON=".json",Keywords$1_DEFAULT="default";class IdGenerator{#id=0;next(){return"$"+ ++this.#id}}const EXTENSION_PATTERN=/\.js$/,APPLICATION_MODULE_INDICATORS=[".","/","http:","https:"];class FileHelper{translatePath(filename){const parts=filename.split("/"),translated=[];for(const part of parts){switch(part.trim()){case"":case".":continue;case"..":translated.pop();continue}translated.push(part)}return translated.join("/")}makePathRelative(absoluteFilename,relativeToPath){if(""===relativeToPath)return`./${absoluteFilename}`;const absoluteFilenameParts=absoluteFilename.split("/"),relativeToParts=relativeToPath.split("/");for(;absoluteFilenameParts[0]===relativeToParts[0];)absoluteFilenameParts.shift(),relativeToParts.shift();const relativePath=relativeToParts.map(()=>"..").join("/");return`${relativeToParts.length>0?relativePath:"."}/${absoluteFilenameParts.join("/")}`}makePathAbsolute(relativeFilename,relativeToPath,prefix="/"){const fullPath=""!==relativeToPath?`${relativeToPath}/${relativeFilename}`:relativeFilename;return`${prefix}${this.translatePath(fullPath)}`}extractPath(filename){return filename.split("/").slice(0,-1).join("/")}extractFilename(filename){return filename.split("/").pop()}assureExtension(filename){return filename.endsWith(".js")?filename:`${filename}.js`}addSubExtension(filename,subExtension){return filename.replace(EXTENSION_PATTERN,`.${subExtension}.js`)}isApplicationModule(from){return APPLICATION_MODULE_INDICATORS.some(indicator=>from.startsWith(indicator))}}class ReadingResourcesFailed extends Error{constructor(filename,cause){super(`Failed reading resources from '${filename}'`,{cause:cause})}}class ResourceReader{#resourcesFileManager;#sourceFileManager;#fileHelper=new FileHelper;constructor(resourcesFileManager,sourceFileManager){this.#resourcesFileManager=resourcesFileManager,this.#sourceFileManager=sourceFileManager}async readAll(filenames){const resources=await Promise.all(filenames.map(filename=>this.#loadResourceDefinition(filename)));return new ResourcesList(resources.flat())}async#loadResourceDefinition(filename){try{const content=await this.#resourcesFileManager.getContent(filename);return JSON.parse(content.toString()).map(resource=>this.#makeResourceFilename(resource))}catch(error){throw new ReadingResourcesFailed(filename,error)}}#makeResourceFilename(filename){const normalizedFilename=this.#sourceFileManager.normalizeLocation(filename),fullFilename=this.#sourceFileManager.isDirectory(normalizedFilename)?`${normalizedFilename}/${Files_INDEX}`:this.#fileHelper.assureExtension(normalizedFilename);return fullFilename.startsWith("./")?fullFilename.substring(2):fullFilename.startsWith("/")?fullFilename.substring(1):fullFilename}}let Module$1=class{#filename;#model;constructor(filename,model){this.#filename=filename,this.#model=model}get filename(){return this.#filename}get model(){return this.#model}};class Repository{#modules;constructor(modules){this.#modules=modules}get modules(){return this.#modules}get(filename){return this.#modules.find(module=>module.filename===filename)}}class ESBinding{}class ESArrayBinding extends ESBinding{elements;constructor(elements){super(),this.elements=elements}clone(){const elements=this.elements.map(element=>element.clone());return new ESArrayBinding(elements)}toString(){return`[${this.elements.map(element=>element.toString()).join(",")}]`}}class ESStatement{}class ESDeclaration extends ESStatement{identifier;constructor(identifier){super(),this.identifier=identifier}is(identifier){return this.identifier===identifier}}class ESFunction extends ESDeclaration{parameters;body;isAsync;constructor(identifier,parameters,body,isAsync=!1){super(identifier),this.parameters=parameters,this.body=body,this.isAsync=isAsync}clone(){const parameters=this.parameters.map(parameter=>parameter.clone()),body=this.body.clone();return new ESFunction(this.identifier,parameters,body,this.isAsync)}toString(){const prefix=this.isAsync?"async ":"",identifier=this.identifier?` ${this.identifier}`:"",parameters=this.parameters.map(parameter=>parameter.toString()),body=this.body.toString();return`${prefix}function${identifier}(${parameters.join(",")})${body}`}}class ESArrowFunction extends ESFunction{constructor(parameters,body,isAsync=!1){super(void 0,parameters,body,isAsync)}clone(){const parameters=this.parameters.map(parameter=>parameter.clone()),body=this.body.clone();return new ESArrowFunction(parameters,body,this.isAsync)}toString(){const prefix=this.isAsync?"async ":"",parameters=this.parameters.map(parameter=>parameter.toString()),body=this.body.toString();return`${prefix}(${parameters.join(", ")})=>${body}`}}class ESBindingElement{binding;initializer;constructor(binding,initializer){this.binding=binding,this.initializer=initializer}clone(){const binding=this.binding.clone(),initializer=this.initializer?.clone();return new ESBindingElement(binding,initializer)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class ESBlock extends ESStatement{code;constructor(code){super(),this.code=code}clone(){return new ESBlock(this.code)}toString(){return this.code}}class ESClassMember{identifier;visibility;location;constructor(identifier,visibility,location){this.identifier=identifier,this.visibility=visibility,this.location=location}is(identifier){return this.identifier===identifier}}class ESConstructor extends ESClassMember{parameters;body;constructor(parameters,body){super("constructor","public","instance"),this.parameters=parameters,this.body=body}clone(){const parameters=this.parameters.map(parameter=>parameter.clone()),body=this.body.clone();return new ESConstructor(parameters,body)}toString(){const parameters=this.parameters.map(parameter=>parameter.toString()),body=this.body.toString();return`${this.identifier}(${parameters.join(",")}) ${body}`}}class ESGetter extends ESClassMember{body;constructor(identifier,visibility,location,body){super(identifier,visibility,location),this.body=body}clone(){const body=this.body.clone();return new ESGetter(this.identifier,this.visibility,this.location,body)}toString(){const location="static"===this.location?"static ":"",visibility="private"===this.visibility?"#":"",body=this.body.toString();return`${location}get ${visibility}${this.identifier}()${body}`}}class ESSetter extends ESClassMember{parameter;body;constructor(identifier,visibility,location,parameter,body){super(identifier,visibility,location),this.parameter=parameter,this.body=body}clone(){const parameter=this.parameter.clone(),body=this.body.clone();return new ESSetter(this.identifier,this.visibility,this.location,parameter,body)}toString(){const location="static"===this.location?"static ":"",visibility="private"===this.visibility?"#":"",parameter=this.parameter.toString(),body=this.body.toString();return`${location}set ${visibility}${this.identifier}(${parameter})${body}`}}class ESMethod extends ESClassMember{parameters;body;isAsync;constructor(identifier,visibility,location,parameters,body,isAsync=!1){super(identifier,visibility,location),this.parameters=parameters,this.body=body,this.isAsync=isAsync}clone(){const parameters=this.parameters.map(parameter=>parameter.clone()),body=this.body.clone();return new ESMethod(this.identifier,this.visibility,this.location,parameters,body,this.isAsync)}toString(){const location="static"===this.location?"static ":"",visibility="private"===this.visibility?"#":"",prefix=this.isAsync?"async ":"",parameters=this.parameters.map(parameter=>parameter.toString()),body=this.body.toString();return`${location}${prefix}${visibility}${this.identifier}(${parameters.join(",")})${body}`}}class ESField extends ESClassMember{initializer;constructor(identifier,visibility,location,initializer){super(identifier,visibility,location),this.initializer=initializer}clone(){const initializer=this.initializer?.clone();return new ESField(this.identifier,this.visibility,this.location,initializer)}toString(){const location="static"===this.location?"static ":"",visibility="private"===this.visibility?"#":"",initializer=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${location}${visibility}${this.identifier}${initializer}`}}class ESClass extends ESDeclaration{parent;members;constructor(identifier,parent,members){super(identifier),this.parent=parent,this.members=members}get construct(){return this.members.find(member=>member instanceof ESConstructor)}get fields(){return this.members.filter(member=>member instanceof ESField)}get getters(){return this.members.filter(member=>member instanceof ESGetter)}get setters(){return this.members.filter(member=>member instanceof ESSetter)}get methods(){return this.members.filter(member=>member instanceof ESMethod)}get publicFields(){return this.fields.filter(member=>"public"===member.visibility)}get publicGetters(){return this.getters.filter(member=>"public"===member.visibility)}get publicSetters(){return this.setters.filter(member=>"public"===member.visibility)}get publicMethods(){return this.methods.filter(member=>"public"===member.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(identifier){return this.members.find(member=>member.is(identifier))}hasMember(identifier){return this.members.some(member=>member.is(identifier))}getField(identifier){return this.fields.find(member=>member.is(identifier))}hasField(identifier){return this.fields.some(member=>member.is(identifier))}getGetter(identifier){return this.getters.find(member=>member.is(identifier))}hasGetter(identifier){return this.getters.some(member=>member.is(identifier))}getSetter(identifier){return this.setters.find(member=>member.is(identifier))}hasSetter(identifier){return this.setters.some(member=>member.is(identifier))}getMethod(identifier){return this.methods.find(member=>member.is(identifier))}hasMethod(identifier){return this.methods.some(member=>member.is(identifier))}canRead(identifier){return this.readable.some(member=>member.is(identifier))}canWrite(identifier){return this.writable.some(member=>member.is(identifier))}clone(){const members=this.members.map(member=>member.clone());return new ESClass(this.identifier,this.parent,members)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(member=>member.toString()).join("")}}`}}class ESExport extends ESStatement{members;from;constructor(members,from){super(),this.members=members,this.from=from}hasMember(identifier){return this.members.some(member=>member.is(identifier))}getMember(identifier){return this.members.find(member=>member.is(identifier))}clone(){const members=this.members.map(member=>member.clone());return new ESExport(members,this.from)}toString(){const members=this.members.map(member=>member.toString()),postfix=this.from?` from '${this.from}'`:"";return`export {${members.join(",")}}${postfix};`}}class ESExpression extends ESStatement{code;constructor(code){super(),this.code=code}clone(){return new ESExpression(this.code)}toString(terminate=!0){const terminator=!1===terminate||this.code.endsWith("}")?"":";";return`${this.code}${terminator}`}}class ESGeneratorFunction extends ESFunction{clone(){const parameters=this.parameters.map(parameter=>parameter.clone()),body=this.body.clone();return new ESGeneratorFunction(this.identifier,parameters,body,this.isAsync)}toString(){const prefix=this.isAsync?"async ":"",identifier=this.identifier??"",parameters=this.parameters.map(parameter=>parameter.toString()),body=this.body.toString();return`${prefix}function* ${identifier}(${parameters.join(",")})${body}`}}class ESGeneratorMethod extends ESMethod{clone(){const parameters=this.parameters.map(parameter=>parameter.clone()),body=this.body.clone();return new ESGeneratorMethod(this.identifier,this.visibility,this.location,parameters,body,this.isAsync)}toString(){const prefix=this.isAsync?"async ":"",identifier=this.identifier,parameters=this.parameters.map(parameter=>parameter.toString()),body=this.body.toString();return`${prefix}*${identifier}(${parameters.join(",")})${body}`}}class ESIdentifierBinding extends ESBinding{identifier;isRest;constructor(identifier,isRest=!1){super(),this.identifier=identifier,this.isRest=isRest}clone(){return new ESIdentifierBinding(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class ESImport extends ESStatement{members;from;constructor(members,from){super(),this.members=members,this.from=from}hasMember(identifier){return this.members.some(member=>member.is(identifier))}getMember(identifier){return this.members.find(member=>member.is(identifier))}clone(){const members=this.members.map(member=>member.clone());return new ESImport(members,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(member=>member.toString()).join(",")}} from '${this.from}';`}}class ESVariable extends ESDeclaration{type;binding;initializer;constructor(type,binding,initializer){super(binding.toString()),this.type=type,this.binding=binding,this.initializer=initializer}clone(){const binding=this.binding.clone(),initializer=this.initializer?.clone();return new ESVariable(this.type,binding,initializer)}toString(){const initializer=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",terminator=initializer.endsWith(";")?"":";";return`${this.type} ${this.identifier}${initializer}${terminator}`}}class ESModule{statements;constructor(statements){this.statements=statements}get exports(){return this.statements.filter(statement=>statement instanceof ESExport)}get imports(){return this.statements.filter(statement=>statement instanceof ESImport)}get expressions(){return this.statements.filter(statement=>statement instanceof ESExpression)}get declarations(){return this.statements.filter(statement=>statement instanceof ESDeclaration)}get variables(){return this.statements.filter(statement=>statement instanceof ESVariable)}get functions(){return this.statements.filter(statement=>statement instanceof ESFunction)}get classes(){return this.statements.filter(statement=>statement instanceof ESClass)}get exported(){const declarations=[];for(const entry of this.exports)for(const member of entry.members){const declaration=this.getDeclaration(member.identifier);void 0!==declaration&&declarations.push(declaration)}return declarations}get exportedVariables(){return this.exported.filter(declaration=>declaration instanceof ESVariable)}get exportedFunctions(){return this.exported.filter(declaration=>declaration instanceof ESFunction)}get exportedClasses(){return this.exported.filter(declaration=>declaration instanceof ESClass)}getExport(name){return this.exports.find(entry=>entry.hasMember(name))}getImport(name){return this.imports.find(entry=>entry.hasMember(name))}hasDeclaration(identifier){return this.declarations.some(entry=>entry.is(identifier))}getDeclaration(identifier){return this.declarations.find(entry=>entry.is(identifier))}hasVariable(identifier){return this.variables.some(entry=>entry.is(identifier))}getVariable(identifier){return this.variables.find(entry=>entry.is(identifier))}hasFunction(identifier){return this.functions.some(entry=>entry.is(identifier))}getFunction(identifier){return this.functions.find(entry=>entry.is(identifier))}hasClass(identifier){return this.classes.some(entry=>entry.is(identifier))}getClass(identifier){return this.classes.find(entry=>entry.is(identifier))}clone(){const statements=this.statements.map(statement=>statement.clone());return new ESModule(statements)}toString(){return this.statements.map(statement=>statement.toString(!0)).join("\n")}}class ESModuleMember{identifier;alias;constructor(identifier,alias){this.identifier=identifier,this.alias=alias}is(identifier){return this.alias===identifier||void 0===this.alias&&this.identifier===identifier}clone(){return new ESModuleMember(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class ESObjectBinding extends ESBinding{elements;constructor(elements){super(),this.elements=elements}clone(){const elements=this.elements.map(element=>element.clone());return new ESObjectBinding(elements)}toString(){return`{${this.elements.map(element=>element.toString()).join(",")}}`}}const Comment={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},Comments=Object.values(Comment);const Punctuation_DOT=".",Punctuation_LEFT_PARENTHESIS="(",Punctuation_RIGHT_PARENTHESIS=")",Punctuation_LEFT_BRACKET="[",Punctuation_RIGHT_BRACKET="]",Punctuation_LEFT_BRACE="{",Punctuation_RIGHT_BRACE="}",Punctuation_UNDERSCORE="_",Divider={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},Divisions=Object.values(Divider);function isDivider(value){return Divisions.includes(value)}const Empty={UNDEFINED:void 0,NULL:null,STRING:""},NOTHING=["null","undefined"],Empties=Object.values(Empty);function isEmpty(value){return Empties.includes(value)}const Group={OPEN:Punctuation_LEFT_PARENTHESIS,CLOSE:Punctuation_RIGHT_PARENTHESIS};function isGroup(value){return value===Group.OPEN||value===Group.CLOSE}const Keyword={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally",TYPEOF:"typeof",INSTANCEOF:"instanceof"},Keywords=Object.values(Keyword),RootKeywords=[Keyword.IMPORT,Keyword.EXPORT,Keyword.VAR,Keyword.LET,Keyword.CONST,Keyword.FUNCTION,Keyword.CLASS,Keyword.ASYNC],DeclarationKeywords=[Keyword.VAR,Keyword.LET,Keyword.CONST,Keyword.FUNCTION,Keyword.CLASS,Keyword.USING],ContextualKeywords=[Keyword.AS,Keyword.ASYNC,Keyword.GET,Keyword.SET,Keyword.OF,Keyword.YIELD,Keyword.FROM,Keyword.STATIC];function isRootKeyword(value){return RootKeywords.includes(value)}function isContextualKeyword(value){return ContextualKeywords.includes(value)}const List={OPEN:Punctuation_LEFT_BRACKET,CLOSE:Punctuation_RIGHT_BRACKET};function isList(value){return value===List.OPEN||value===List.CLOSE}const Literals=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function isLiteral(value){return Literals.includes(value)}const Operator={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},Operators=Object.values(Operator);function isOperator(value){return Operators.includes(value)}const Scope={OPEN:Punctuation_LEFT_BRACE,CLOSE:Punctuation_RIGHT_BRACE};function isScope(value){return value===Scope.OPEN||value===Scope.CLOSE}const TokenType={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},Whitespace={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Whitespaces=Object.values(Whitespace);function isWhitespace(value){return Whitespaces.includes(value)}class ItemList{#items;#position;constructor(items){this.#items=items,this.#position=0}get items(){return this.#items}get position(){return this.#position}get size(){return this.#items.length}get eol(){return this.#position>=this.#items.length}get current(){return this.#items[this.#position]}get next(){return this.#items[this.#position+1]}get previous(){return this.#items[this.#position-1]}notAtEnd(){return!1===this.eol}get(index){return this.#items[index]}step(amount=1){return this.#position+=amount,this.current}stepBack(amount=1){return this.#position-=amount,this.current}hasNext(){return this.#position+1<this.#items.length}insert(...item){this.#items.splice(this.#position,0,...item)}}class CharList extends ItemList{constructor(code){super(code.split(""))}}class Token{#type;#value;#start;#end;constructor(type,value,start,end){this.#type=type,this.#value=value,this.#start=start,this.#end=end}get type(){return this.#type}get value(){return this.#value}get start(){return this.#start}get end(){return this.#end}isType(type){return this.#type===type}hasValue(value){return this.#value===value}toString(){return`${this.#value}`}}class TokenList extends ItemList{}const BOOLEAN=["true","false"];const NUMBERS=["0","1","2","3","4","5","6","7","8","9"],HEXADECIMAL=[...NUMBERS,"a","b","c","d","e","f","A","B","C","D","E","F"],BINARY=["0","1"];function isNumber(value){return NUMBERS.includes(value)}const Indicator={GENERATOR:"*",PRIVATE:"#"},Indicators=Object.values(Indicator);class Lexer{tokenize(code){const charList=new CharList(code),tokens=[];let last;for(;charList.notAtEnd();){const token=this.#getNextToken(charList,last);if(void 0===token)break;token.isType(TokenType.WHITESPACE)||token.isType(TokenType.COMMENT)?charList.step():(tokens.push(token),this.#isCodeToken(token)&&(last=token),charList.step())}return new TokenList(tokens)}#isCodeToken(token){return!1===[TokenType.WHITESPACE,TokenType.COMMENT].includes(token.type)}#getNextToken(charList,lastToken){const char=charList.current,start=charList.position;if(isWhitespace(char)){const end=charList.position;return new Token(TokenType.WHITESPACE,char,start,end)}if(function(value){return Comments.includes(value)}(char+charList.next)){const value=this.#readComment(charList),end=charList.position;return new Token(TokenType.COMMENT,value,start,end)}if(this.#startsRegex(char,lastToken)){const value=this.#readRegex(charList),end=charList.position;return new Token(TokenType.REGEX,value,start,end)}if(this.#startsNumber(charList,lastToken)){const value=this.#readNumber(charList),end=charList.position;return new Token(TokenType.NUMBER,value,start,end)}if(isLiteral(char)){const value=this.#readLiteral(charList),end=charList.position;return new Token(TokenType.LITERAL,value,start,end)}if(isOperator(char)){const value=this.#readOperation(charList),end=charList.position;return new Token(TokenType.OPERATOR,value,start,end)}if(function(value){return Indicators.includes(value)}(char)){const value=this.#readOperation(charList),end=charList.position;return new Token(TokenType.INDICATOR,value,start,end)}if(isDivider(char)){const end=charList.position;return new Token(TokenType.DIVIDER,char,start,end)}if(isGroup(char)){const end=charList.position;return new Token(TokenType.GROUP,char,start,end)}if(isScope(char)){const end=charList.position;return new Token(TokenType.SCOPE,char,start,end)}if(isList(char)){const end=charList.position;return new Token(TokenType.LIST,char,start,end)}if(isEmpty(char))return;const value=this.#readIdentifier(charList),end=charList.position;return function(value){return Keywords.includes(value)}(value)?new Token(TokenType.KEYWORD,value,start,end):function(value){return BOOLEAN.includes(value)}(value)?new Token(TokenType.BOOLEAN,value,start,end):function(value){return NOTHING.includes(value)}(value)?new Token(TokenType.NOTHING,value,start,end):new Token(TokenType.IDENTIFIER,value,start,end)}#readComment(charList){const isMulti=charList.current+charList.next===Comment.MULTI_START,terminator=isMulti?Comment.MULTI_END:Whitespace.NEWLINE;let value=isMulti?Comment.MULTI_START:Comment.SINGLE;for(charList.step(2);charList.notAtEnd();){const char=charList.current;if((isMulti?char+charList.next:char)===terminator){charList.step(terminator.length-1);break}value+=char,charList.step()}return isMulti?value+Comment.MULTI_END:value.trim()}#startsRegex(char,lastToken){return char===Operator.DIVIDE&&(void 0===lastToken||([TokenType.OPERATOR,TokenType.DIVIDER,TokenType.KEYWORD].includes(lastToken.type)||[Group.OPEN,List.OPEN].includes(lastToken.value)))}#endsRegex(char){return isWhitespace(char)||char==Punctuation_DOT||!1===this.#isIdentifier(char)}#readRegex(charList){let value=charList.current,closed=!1;for(charList.step();charList.notAtEnd();){const current=charList.current,previous=charList.previous;if(current===Operator.DIVIDE&&"\\"!==previous)closed=!0;else if(!0===closed&&this.#endsRegex(current)){charList.stepBack();break}value+=current,charList.step()}return value}#startsNumber(charList,lastToken){const current=charList.current,next=charList.next;return!!isNumber(current)||current===Operator.SUBTRACT&&(!lastToken?.isType(TokenType.NUMBER)&&isNumber(next))}#endsNumber(char,hexadecimal,binary){return hexadecimal?!1===(value=char,HEXADECIMAL.includes(value))&&char!==Punctuation_UNDERSCORE:binary?!1===function(value){return BINARY.includes(value)}(char)&&char!==Punctuation_UNDERSCORE:!1===isNumber(char)&&char!==Punctuation_DOT&&char!==Punctuation_UNDERSCORE&&"e"!==char;var value}#readNumber(charList){let value=charList.current;value===Operator.SUBTRACT&&(value+=charList.step()),charList.step();const hexadecimal="x"===charList.current,binary="b"===charList.current;for((hexadecimal||binary)&&(value+=charList.current,charList.step());charList.notAtEnd();){const char=charList.current;if(this.#endsNumber(char,hexadecimal,binary)){charList.stepBack();break}value+=char,charList.step()}return value}#readLiteral(charList){const identifier=charList.current;let value=identifier,escaped=!1;for(charList.step();charList.notAtEnd();){const char=charList.current;if(!1===escaped){if(char===identifier){value+=char;break}"\\"===char&&(escaped=!0)}else escaped=!1;value+=char,charList.step()}return value}#isIdentifier(char){return!1===(isEmpty(char)||isWhitespace(char)||isOperator(char)||isLiteral(char)||isDivider(char)||isGroup(char)||isScope(char)||isList(char))}#readIdentifier(charList){let value="";for(;charList.notAtEnd();){const char=charList.current;if(!1===this.#isIdentifier(char)){charList.stepBack();break}value+=char,charList.step()}return value}#readOperation(charList){let value=charList.current;for(charList.step();charList.notAtEnd();){const char=charList.current;if(!1===isOperator(char)||!1===isOperator(value+char)){charList.stepBack();break}value+=char,charList.step()}return value}}class ExpectedKeyword extends Error{constructor(value,position){super(`Expected keyword '${value}' at position ${position}`)}}class ExpectedToken extends Error{constructor(value,position){super(`Expected token '${value}' at position ${position}`)}}class UnexpectedKeyword extends Error{constructor(keyword,position){super(`Unexpected keyword '${keyword}' at position ${position}`)}}class UnexpectedParseResult extends Error{constructor(expected){super(`The given code does not contain ${expected}`)}}class UnexpectedToken extends Error{constructor(value,position){super(`Unexpected token '${value}' at position ${position}`)}}const NO_TOKEN=new Token(TokenType.NONE,"",-1,0);class Coder{#tokens;constructor(tokens=[]){this.#tokens=tokens}get tokens(){return this.#tokens}append(...tokens){this.#tokens.push(...tokens)}merge(coder){this.append(...coder.tokens)}generate(){let code="";for(let index=0;index<this.#tokens.length;index++){const previous=this.#tokens[index-1]??NO_TOKEN,current=this.#tokens[index],next=this.#tokens[index+1]??NO_TOKEN,prefix=this.#needsSpacingBefore(previous,current)?" ":"",postfix=this.#needsSpacingAfter(current,next)?" ":"";code+=`${prefix}${current.value}${postfix}`}return code}#needsSpacingBefore(previous,current){return!(!current.isType(TokenType.KEYWORD)||!this.#isTextType(previous))||!(!current.isType(TokenType.OPERATOR)||!previous.isType(TokenType.OPERATOR))}#needsSpacingAfter(current,next){return current.isType(TokenType.KEYWORD)&&(next.isType(TokenType.KEYWORD)||this.#isTextType(next))}#isTextType(token){return token.isType(TokenType.IDENTIFIER)||token.isType(TokenType.BOOLEAN)||token.isType(TokenType.NOTHING)||token.isType(TokenType.NUMBER)}}class Parser{#lexer;constructor(lexer=new Lexer){this.#lexer=lexer}parse(code){const tokenList=this.#lexer.tokenize(code),statements=this.#parseAll(tokenList);return new ESModule(statements)}parseStatement(code){const tokenList=this.#lexer.tokenize(code),statement=this.#parseNext(tokenList);if(void 0===statement)throw new UnexpectedParseResult("a statement");return statement}parseImport(code){const tokenList=this.#lexer.tokenize(code),declaration=this.#parseKeyword(tokenList);if(declaration instanceof ESImport==!1)throw new UnexpectedParseResult("an import definition");return declaration}parseExport(code){const tokenList=this.#lexer.tokenize(code),declaration=this.#parseKeyword(tokenList);if(declaration instanceof ESExport==!1)throw new UnexpectedParseResult("an export definition");return declaration}parseVariable(code){const tokenList=this.#lexer.tokenize(code),declaration=this.#parseKeyword(tokenList);if(declaration instanceof ESVariable==!1)throw new UnexpectedParseResult("a variable definition");return declaration}parseFunction(code){const tokenList=this.#lexer.tokenize(code),declaration=this.#parseKeyword(tokenList);if(declaration instanceof ESFunction==!1)throw new UnexpectedParseResult("a function definition");return declaration}parseClass(code){const tokenList=this.#lexer.tokenize(code),declaration=this.#parseKeyword(tokenList);if(declaration instanceof ESClass==!1)throw new UnexpectedParseResult("a class definition");return declaration}#parseAll(tokenList){const statements=[];for(;tokenList.notAtEnd();){const statement=this.#parseNext(tokenList);void 0!==statement&&statements.push(statement)}return statements}#parseNext(tokenList,isAsync=!1){const token=tokenList.current;if(this.#isValue(token))return this.#parseExpression(tokenList);if(token.isType(TokenType.IDENTIFIER)){const next=tokenList.next;return next?.hasValue(Operator.ARROW)?this.#parseArrowFunction(tokenList,isAsync):this.#parseExpression(tokenList)}if(token.isType(TokenType.KEYWORD)){if(isContextualKeyword(token.value)){const next=tokenList.next,nextIsFunction=void 0!==next&&(next.hasValue(Keyword.FUNCTION)||next.hasValue(Group.OPEN));if(token.hasValue(Keyword.ASYNC)&&nextIsFunction)return tokenList.step(),this.#parseNext(tokenList,!0);if(void 0===next||this.#atEndOfExpression(next))return this.#parseExpression(tokenList)}return token.hasValue(Keyword.RETURN)?this.#parseExpression(tokenList):!1===isRootKeyword(token.value)?this.#parseExpression(tokenList):this.#parseKeyword(tokenList,isAsync)}if(token.isType(TokenType.REGEX))return this.#parseExpression(tokenList);if(token.hasValue(Group.OPEN)){const next=this.#peekAfterCollection(tokenList,Group.OPEN,Group.CLOSE);return next?.hasValue(Operator.ARROW)?this.#parseArrowFunction(tokenList,isAsync):this.#parseExpression(tokenList)}if(token.hasValue(Scope.OPEN))return this.#parseExpression(tokenList);if(token.hasValue(List.OPEN))return this.#parseExpression(tokenList);if(token.hasValue(Operator.NOT)||token.hasValue(Operator.SUBTRACT))return this.#parseExpression(tokenList);if(!isDivider(token.value))throw new UnexpectedToken(token.value,token.start);tokenList.step()}#isValue(token){return token.isType(TokenType.LITERAL)||token.isType(TokenType.NUMBER)||token.isType(TokenType.BOOLEAN)||token.isType(TokenType.NOTHING)||token.hasValue(Keyword.NEW)}#parseKeyword(tokenList,isAsync=!1){const token=tokenList.current;switch(tokenList.step(),token.value){case Keyword.IMPORT:return this.#parseImport(tokenList);case Keyword.EXPORT:return this.#parseExport(tokenList);case Keyword.CLASS:return this.#parseClass(tokenList);case Keyword.FUNCTION:return this.#parseFunction(tokenList,isAsync);case Keyword.VAR:return this.#parseVariable(tokenList,"var");case Keyword.LET:return this.#parseVariable(tokenList,"let");case Keyword.CONST:return this.#parseVariable(tokenList,"const");case Keyword.ASYNC:return this.#parseNext(tokenList,!0);default:throw new UnexpectedKeyword(token.value,token.start)}}#parseImport(tokenList){const members=[];let token=tokenList.current;if(token.isType(TokenType.LITERAL)){const from=this.#parseFrom(token.value);return new ESImport(members,from)}if(token.hasValue(Group.OPEN)){token=tokenList.step();const from=this.#parseFrom(token.value);return tokenList.step(2),new ESImport(members,from)}if(!1===token.hasValue(Scope.OPEN)){const identifier=token.hasValue(Operator.MULTIPLY)?Operator.MULTIPLY:"default";let alias=token.value;token=tokenList.step(),token.hasValue(Keyword.AS)&&(token=tokenList.step(),alias=token.value,token=tokenList.step()),members.push(new ESModuleMember(identifier,alias))}if(token.hasValue(Divider.SEPARATOR)&&(token=tokenList.step()),token.hasValue(Scope.OPEN)){const parsedMembers=this.#parseModuleMembers(tokenList);members.push(...parsedMembers),token=tokenList.current}if(!1===token.hasValue(Keyword.FROM))throw new ExpectedKeyword(Keyword.FROM,token.start);token=tokenList.step();const from=this.#parseFrom(token.value);return tokenList.step(),new ESImport(members,from)}#parseExport(tokenList){switch(tokenList.current.value){case Keyword.DEFAULT:return tokenList.step(),this.#parseSingleExport(tokenList,!0);case Scope.OPEN:return this.#parseMultiExport(tokenList);default:return this.#parseSingleExport(tokenList,!1)}}#parseSingleExport(tokenList,isDefault){let token=tokenList.current,stepSize=0;if(isDefault&&this.#doesExportValue(tokenList)){const identifier=`$_EXPORT_${token.start}_${token.end}`;tokenList.insert(new Token(TokenType.KEYWORD,Keyword.CONST,0,0),new Token(TokenType.IDENTIFIER,identifier,0,0),new Token(TokenType.OPERATOR,Operator.ASSIGN,0,0)),token=tokenList.current}var value;if(token.hasValue(Keyword.ASYNC)&&(token=tokenList.step(),stepSize++),value=token.value,DeclarationKeywords.includes(value)&&(token=tokenList.step(),stepSize++,token.hasValue(Indicator.GENERATOR)&&(token=tokenList.step(),stepSize++)),token.hasValue(Keyword.EXTENDS)||token.hasValue(Group.OPEN)||token.hasValue(Scope.OPEN)){const identifier=`$_EXPORT_${token.start}_${token.end}`;tokenList.insert(new Token(TokenType.IDENTIFIER,identifier,0,0)),token=tokenList.current}const identifier=this.#isIdentifier(token)?token.value:"",alias=isDefault?"default":void 0;let from;token=tokenList.step(),token?.hasValue(Keyword.FROM)&&(token=tokenList.step(),from=this.#parseFrom(token.value)),stepSize>0&&(stepSize++,tokenList.stepBack(stepSize));const member=new ESModuleMember(identifier,alias);return new ESExport([member],from)}#doesExportValue(tokenList){const current=tokenList.current;if(this.#isValue(current))return!0;const next=tokenList.next;return this.#isIdentifier(current)&&next?.hasValue(Group.OPEN)}#parseMultiExport(tokenList){const members=this.#parseModuleMembers(tokenList);let from,token=tokenList.current;return token?.hasValue(Keyword.FROM)&&(token=tokenList.step(),from=this.#parseFrom(token.value)),tokenList.step(),new ESExport(members,from)}#parseFrom(from){return from.slice(1,-1)}#parseModuleMembers(tokenList){const members=[];let token=tokenList.step();for(;tokenList.notAtEnd();){if(token.hasValue(Scope.CLOSE)){tokenList.step();break}if(token.hasValue(Divider.SEPARATOR)){token=tokenList.step();continue}const member=this.#parseModuleMember(tokenList);members.push(member),token=tokenList.step()}return members}#parseModuleMember(tokenList){let token=tokenList.current;const identifier=token.value;let alias;return tokenList.next.hasValue(Keyword.AS)&&(token=tokenList.step(2),alias=token.value),new ESModuleMember(identifier,alias)}#parseVariable(tokenList,type){const binding=this.#parseBinding(tokenList),initializer=this.#parseInitializer(tokenList);return tokenList.notAtEnd()&&tokenList.current.hasValue(Divider.SEPARATOR)&&(tokenList.step(),tokenList.insert(new Token(TokenType.KEYWORD,type,0,0))),new ESVariable(type,binding,initializer)}#parseBinding(tokenList){const token=tokenList.current;return token.hasValue(List.OPEN)?this.#parseArrayBinding(tokenList):token.hasValue(Scope.OPEN)?this.#parseObjectBinding(tokenList):this.#parseIdentifierBinding(tokenList)}#parseArrayBinding(tokenList){const elements=this.#parseBindingElements(tokenList,List.CLOSE);return new ESArrayBinding(elements)}#parseObjectBinding(tokenList){const elements=this.#parseBindingElements(tokenList,Scope.CLOSE);return new ESObjectBinding(elements)}#parseBindingElements(tokenList,closeId){const elements=[];for(tokenList.step();tokenList.notAtEnd();){const token=tokenList.current;if(token.hasValue(closeId)){tokenList.step();break}if(token.hasValue(Divider.SEPARATOR)){tokenList.step();continue}const binding=this.#parseBinding(tokenList),initializer=this.#parseInitializer(tokenList),element=new ESBindingElement(binding,initializer);elements.push(element)}return elements}#parseIdentifierBinding(tokenList){let token=tokenList.current,isRest=!1;token.hasValue(Operator.SPREAD)&&(isRest=!0,token=tokenList.step());const identifier=token.value;return tokenList.step(),new ESIdentifierBinding(identifier,isRest)}#parseInitializer(tokenList){const token=tokenList.current;if(!1!==token.hasValue(Operator.ASSIGN))return tokenList.step(),this.#parseNext(tokenList,!1);token.hasValue(Divider.TERMINATOR)&&tokenList.step()}#parseFunction(tokenList,isAsync){let identifier,token=tokenList.current,isGenerator=!1;token.hasValue(Indicator.GENERATOR)&&(isGenerator=!0,token=tokenList.step()),this.#isIdentifier(token)&&(identifier=token.value,tokenList.step());const parameters=this.#parseBindingElements(tokenList,Group.CLOSE);if(token=tokenList.current,!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const body=this.#parseBlock(tokenList);return isGenerator?new ESGeneratorFunction(identifier,parameters,body,isAsync):new ESFunction(identifier,parameters,body,isAsync)}#parseArrowFunction(tokenList,isAsync){let parameters,body,token=tokenList.current;if(token.hasValue(Group.OPEN))parameters=this.#parseBindingElements(tokenList,Group.CLOSE);else{const binding=this.#parseIdentifierBinding(tokenList);parameters=[new ESBindingElement(binding,void 0)]}if(token=tokenList.current,!1===token.hasValue(Operator.ARROW))throw new ExpectedToken(Operator.ARROW,token.start);if(token=tokenList.step(),token.hasValue(Scope.OPEN))body=this.#parseBlock(tokenList);else{const expression=this.#parseExpression(tokenList);body=new ESBlock(expression.code)}return new ESArrowFunction(parameters,body,isAsync)}#parseClass(tokenList){let identifier,parent,token=tokenList.current;if(this.#isIdentifier(token)&&(identifier=token.value,token=tokenList.step()),token.hasValue(Keyword.EXTENDS)&&(token=tokenList.step(),parent=token.value,token=tokenList.step()),!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const members=this.#parseClassMembers(tokenList);return new ESClass(identifier,parent,members)}#parseClassMembers(tokenList){let token=tokenList.step();const members=[];for(;tokenList.notAtEnd();){if(token.hasValue(Scope.CLOSE)){tokenList.step();break}const member=this.#parseClassMember(tokenList);members.push(member),token=tokenList.current}return members}#parseClassMember(tokenList){let token=tokenList.current,visibility="public",location="instance",isAsync=!1;for(;tokenList.notAtEnd();){if(token.hasValue(Indicator.PRIVATE))visibility="private";else if(token.hasValue(Keyword.STATIC))location="static";else{if(!token.hasValue(Keyword.ASYNC)){if(token.hasValue(Keyword.CONSTRUCTOR))return this.#parseConstructor(tokenList);if(token.hasValue(Keyword.GET))return this.#parseGetter(tokenList,location);if(token.hasValue(Keyword.SET))return this.#parseSetter(tokenList,location);if(token.hasValue(Indicator.GENERATOR))return tokenList.step(),this.#parseMethod(tokenList,visibility,location,isAsync,!0);break}isAsync=!0}token=tokenList.step()}return tokenList.next.hasValue(Group.OPEN)?this.#parseMethod(tokenList,visibility,location,isAsync,!1):this.#parseField(tokenList,visibility,location)}#parseConstructor(tokenList){tokenList.step();const parameters=this.#parseBindingElements(tokenList,Group.CLOSE),token=tokenList.current;if(!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const body=this.#parseBlock(tokenList);return new ESConstructor(parameters,body)}#parseGetter(tokenList,location){let visibility="public",token=tokenList.step();token.hasValue(Indicator.PRIVATE)&&(visibility="private",token=tokenList.step());const identifier=token.value;tokenList.step();if(0!==this.#parseBindingElements(tokenList,Group.CLOSE).length)throw new UnexpectedParseResult("an empty parameter list");if(token=tokenList.current,!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const body=this.#parseBlock(tokenList);return new ESGetter(identifier,visibility,location,body)}#parseSetter(tokenList,location){let visibility="public",token=tokenList.step();token.hasValue(Indicator.PRIVATE)&&(visibility="private",token=tokenList.step());const identifier=token.value;tokenList.step();const parameters=this.#parseBindingElements(tokenList,Group.CLOSE);if(token=tokenList.current,1!==parameters.length)throw new UnexpectedParseResult("exactly one setter parameter");if(!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const body=this.#parseBlock(tokenList);return new ESSetter(identifier,visibility,location,parameters[0],body)}#parseMethod(tokenList,visibility,location,isAsync,isGenerator){let token=tokenList.current;const identifier=token.value;tokenList.step();const parameters=this.#parseBindingElements(tokenList,Group.CLOSE);if(token=tokenList.current,!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const body=this.#parseBlock(tokenList);return isGenerator?new ESGeneratorMethod(identifier,visibility,location,parameters,body,isAsync):new ESMethod(identifier,visibility,location,parameters,body,isAsync)}#parseField(tokenList,visibility,location){const identifier=tokenList.current.value;tokenList.step();const initializer=this.#parseInitializer(tokenList);return new ESField(identifier,visibility,location,initializer)}#parseBlock(tokenList){const code=this.#parseCollectionToCode(tokenList,Scope.OPEN,Scope.CLOSE).generate();return new ESBlock(code)}#parseExpression(tokenList){const coder=new Coder;let token=tokenList.current;for(;tokenList.notAtEnd();){if(token.hasValue(List.OPEN)){const array=this.#parseCollectionToCode(tokenList,List.OPEN,List.CLOSE);coder.merge(array),token=tokenList.current}else if(token.hasValue(Group.OPEN)){const group=this.#parseCollectionToCode(tokenList,Group.OPEN,Group.CLOSE);coder.merge(group),token=tokenList.current}else if(token.hasValue(Scope.OPEN)){const scope=this.#parseCollectionToCode(tokenList,Scope.OPEN,Scope.CLOSE);coder.merge(scope),token=tokenList.current}else coder.append(token),token=tokenList.step();if(void 0===token)break;if(this.#atEndOfExpression(token)){token.hasValue(Divider.TERMINATOR)&&tokenList.step();break}}const code=coder.generate();return new ESExpression(code)}#parseCollectionToCode(tokenList,openId,closeId){let token=tokenList.current;const coder=new Coder([token]);for(token=tokenList.step();tokenList.notAtEnd();){if(token.hasValue(openId)){const collection=this.#parseCollectionToCode(tokenList,openId,closeId);coder.merge(collection),token=tokenList.current;continue}if(token.hasValue(closeId))return tokenList.step(),coder.append(token),coder;coder.append(token),token=tokenList.step()}return coder}#peekAfterCollection(tokenList,openId,closeId){const start=tokenList.position;this.#parseCollectionToCode(tokenList,openId,closeId);const token=tokenList.current,end=tokenList.position;return tokenList.stepBack(end-start),token}#atEndOfExpression(token){return[Divider.TERMINATOR,Divider.SEPARATOR].includes(token.value)||[List.CLOSE,Group.CLOSE,Scope.CLOSE].includes(token.value)||isRootKeyword(token.value)}#isIdentifier(token){return token.isType(TokenType.IDENTIFIER)||token.isType(TokenType.KEYWORD)&&isContextualKeyword(token.value)}}class ReadingModuleFailed extends Error{constructor(filename,cause){super(`Failed reading module from '${filename}'`,{cause:cause})}}class LocationRewriter{#sourceFileManager;#fileHelper=new FileHelper;constructor(sourceFileManager){this.#sourceFileManager=sourceFileManager}rewrite(module,filename){module.imports.forEach(item=>this.#rewriteImport(item,filename)),module.exports.forEach(item=>this.#rewriteExport(item,filename))}#rewriteImport(item,filename){const normalizedFrom=this.#sourceFileManager.normalizeLocation(item.from);!1!==this.#fileHelper.isApplicationModule(normalizedFrom)&&(item.from=this.#rewriteFrom(filename,normalizedFrom))}#rewriteExport(item,filename){if(void 0===item.from)return;const normalizedFrom=this.#sourceFileManager.normalizeLocation(item.from);!1!==this.#fileHelper.isApplicationModule(normalizedFrom)&&(item.from=this.#rewriteFrom(filename,normalizedFrom))}#rewriteFrom(filename,from){const callingModulePath=this.#fileHelper.extractPath(filename),translated=this.#fileHelper.makePathAbsolute(from,callingModulePath,"");return this.#sourceFileManager.isDirectory(translated)?`${from}/${Files_INDEX}`:this.#fileHelper.assureExtension(from)}}let Reader$1=class{#sourceFileManager;#parser;#locationRewriter;constructor(sourceFileManager,parser=new Parser){this.#sourceFileManager=sourceFileManager,this.#parser=parser,this.#locationRewriter=new LocationRewriter(sourceFileManager)}async readAll(filenames){const modules=await Promise.all(filenames.map(filename=>this.read(filename)));return new Repository(modules)}async read(filename){try{const relativeLocation=this.#sourceFileManager.getRelativeLocation(filename),code=await this.#loadCode(filename),module=this.#parser.parse(code);return this.#locationRewriter.rewrite(module,relativeLocation),new Module$1(relativeLocation,module)}catch(error){throw new ReadingModuleFailed(filename,error)}}async#loadCode(filename){return(await this.#sourceFileManager.getContent(filename)).toString()}},Segment$1=class{#name;#modules=new Map;#classes=new Map;#procedures=new Map;constructor(name){this.#name=name}get name(){return this.#name}get modules(){return[...this.#modules.values()]}get classes(){return[...this.#classes.values()]}get procedures(){return[...this.#procedures.values()]}hasModule(filename){return this.#modules.has(filename)}getModule(filename){return this.#modules.get(filename)}getSegmentedModules(){return this.modules.filter(module=>module.segmented)}setModule(module){this.#modules.set(module.filename,module)}hasProcedure(fqn){return this.#procedures.has(fqn)}getProcedure(fqn){return this.#procedures.get(fqn)}setProcedure(procedure){this.#procedures.set(procedure.fqn,procedure)}setClass(klass){this.#classes.set(klass.fqn,klass)}};class Member{#id;#importKey;#fqn;constructor(id,importKey,fqn){this.#id=id,this.#importKey=importKey,this.#fqn=fqn}get id(){return this.#id}get importKey(){return this.#importKey}get fqn(){return this.#fqn}}let Class$1=class extends Member{#model;constructor(id,importKey,fqn,model){super(id,importKey,fqn),this.#model=model}get model(){return this.#model}};class Implementation extends Member{#access;#version;#model;constructor(id,importKey,fqn,access,version,model){super(id,importKey,fqn),this.#access=access,this.#version=version,this.#model=model}get access(){return this.#access}get version(){return this.#version}get model(){return this.#model}}class Module{#filename;#location;#imports;#members=[];#segmented;constructor(filename,location,imports,segmented){this.#filename=filename,this.#location=location,this.#imports=imports,this.#segmented=segmented}get filename(){return this.#filename}get location(){return this.#location}get imports(){return this.#imports}get members(){return this.#members}get classes(){return this.#members.filter(member=>member instanceof Class$1)}get implementations(){return this.#members.filter(member=>member instanceof Implementation)}get segmented(){return this.#segmented}hasClasses(){return this.#members.some(member=>member instanceof Class$1)}hasImplementations(){return this.#members.some(member=>member instanceof Implementation)}importsImplementation(importKey){return void 0!==this.implementations.find(implementation=>implementation.importKey===importKey)}addMember(members){this.#members.push(members)}addImports(imports){const keys=Object.keys(imports);for(const key of keys){const identifier=key.trim();this.#imports[identifier]=imports[key]}}}class Procedure{#fqn;#implementations=[];constructor(fqn,implementations=[]){this.#fqn=fqn,this.#implementations=implementations}get fqn(){return this.#fqn}get implementations(){return this.#implementations}addImplementation(implementation){this.#implementations.push(implementation)}}class Segmentation{#segments;constructor(segments){this.#segments=segments}get segments(){return this.#segments}getSegment(segmentName){return this.#segments.find(segment=>segment.name===segmentName)}isSegmentedModule(moduleFilename){return this.#segments.some(segment=>segment.hasModule(moduleFilename))}getSegments(moduleFilename){return this.#segments.filter(segment=>segment.hasModule(moduleFilename))}}class FunctionNotAsync extends Error{constructor(filename,functionName){super(`Function '${functionName}' from file '${filename}' is not async`)}}class InvalidFilename extends Error{constructor(filename){super(`Segment filename '${filename}' is invalid`)}}class FileNotLoaded extends Error{constructor(filename,message){super(`Failed to load segment file '${filename}' because of: ${message}`)}}class InvalidModuleExport extends Error{constructor(filename,exportKey){super(`The export '${exportKey}' from file '${filename}' is not a function or a class.`)}}class ReadingSegmentFailed extends Error{constructor(filename,cause){super(`Failed reading segment from '${filename}'`,{cause:cause})}}class MissingModuleExport extends Error{constructor(filename,key){super(`Module '${filename}' does not export '${key}'`)}}class ModuleNotFound extends Error{constructor(filename){super(`Segmented module not found '${filename}'`)}}class MemberLocator{#repository;#fileHelper=new FileHelper;constructor(repository){this.#repository=repository}locate(filename,importKey){const trace=[];return{trace:trace,model:this.#locate(filename,importKey,trace)}}#locate(filename,importKey,trace){trace.push({filename:filename,importKey:importKey});const module=this.#getModule(filename);return this.#isReexported(module,importKey)?this.#relocate(module,importKey,trace):this.#extract(module,importKey)}#getModule(filename){const module=this.#repository.get(filename);if(void 0===module)throw new ModuleNotFound(filename);return module}#isReexported(module,importKey){const importItem=module.model.getImport(importKey),exportItem=module.model.getExport(importKey);return void 0!==importItem||void 0!==exportItem?.from}#relocate(module,importKey,trace){const relocateInfo=this.#getImportInfo(module,importKey)??this.#getExportInfo(module,importKey),relocatePath=relocateInfo?.from,relocateKey=relocateInfo?.name,callingModulePath=this.#fileHelper.extractPath(module.filename),relativeFrom=relocatePath,absoluteFrom=this.#fileHelper.makePathAbsolute(relativeFrom,callingModulePath,"");return this.#locate(absoluteFrom,relocateKey,trace)}#extract(module,importKey){const exportInfo=this.#getExportInfo(module,importKey);if(void 0===exportInfo)throw new MissingModuleExport(module.filename,importKey);const member=module.model.getDeclaration(exportInfo.name);if(void 0===member)throw new MissingModuleExport(module.filename,exportInfo.name);return member}#getExportInfo(module,importKey){const exportItem=module.model.getExport(importKey),exportMember=exportItem?.getMember(importKey);if(void 0!==exportMember)return{from:exportItem?.from,name:exportMember.identifier}}#getImportInfo(module,importKey){const importItem=module.model.getImport(importKey),importMember=importItem?.getMember(importKey);if(void 0!==importItem&&void 0!==importMember)return{from:importItem.from,name:importMember.identifier}}}class SegmentReader{#segmentsFileManager;#sourceFileManager;#memberLocator;#fileHelper=new FileHelper;constructor(segmentsFileManager,sourceFileManager,repository){this.#segmentsFileManager=segmentsFileManager,this.#sourceFileManager=sourceFileManager,this.#memberLocator=new MemberLocator(repository)}async readAll(filenames){const segments=await Promise.all(filenames.map(filename=>this.#read(filename)));return new Segmentation(segments)}async#read(filename){try{const definition=await this.#loadSegmentDefinition(filename),name=this.#extractSegmentName(filename),segment=new Segment$1(name);return this.#registerModules(segment,definition),this.#registerMembers(segment),segment}catch(error){throw new ReadingSegmentFailed(filename,error)}}#extractSegmentName(filename){const file=filename.split("/").pop();if(void 0===file||""===file)throw new InvalidFilename(filename);return file.replace(Files_JSON,"")}async#loadSegmentDefinition(filename){try{const content=await this.#segmentsFileManager.getContent(filename);return JSON.parse(content.toString())}catch(error){const message=error instanceof Error?error.message:String(error);throw new FileNotLoaded(filename,message)}}#registerModules(segment,definition){for(const[filename,moduleImports]of Object.entries(definition))this.#createModule(segment,filename,moduleImports,!0)}#createModule(segment,filename,moduleImports,segmented){const moduleFilename=this.#makeModuleFilename(filename),location=this.#fileHelper.extractPath(moduleFilename),module=segment.hasModule(moduleFilename)?segment.getModule(moduleFilename):new Module(moduleFilename,location,{},segmented);module.addImports(moduleImports),segment.setModule(module)}#makeModuleFilename(filename){const trimmedFilename=filename.trim(),normalizedFilename=this.#sourceFileManager.normalizeLocation(trimmedFilename),fullFilename=this.#sourceFileManager.isDirectory(normalizedFilename)?`${normalizedFilename}/${Files_INDEX}`:this.#fileHelper.assureExtension(normalizedFilename);return fullFilename.startsWith("./")?fullFilename.substring(2):fullFilename.startsWith("/")?fullFilename.substring(1):fullFilename}#registerMembers(segment){const idGenerator=new IdGenerator;for(const module of segment.modules)for(const importKey in module.imports)this.#registerModuleMember(segment,module,importKey,idGenerator)}#registerModuleMember(segment,module,importKey,idGenerator){const{model:model,trace:trace}=this.#memberLocator.locate(module.filename,importKey),properties=this.#constructProperties(module,model,importKey,idGenerator);this.#createMember(segment,module,model,properties),trace.shift();for(const entry of trace){const entryImport={[entry.importKey]:{access:properties.access}};this.#createModule(segment,entry.filename,entryImport,!1)}}#constructProperties(module,model,importKey,idGenerator){const configuration=module.imports[importKey],id=idGenerator.next(),name=configuration.as??model.identifier;return{id:id,importKey:importKey,name:name,access:configuration.access??Defaults_ACCESS_LEVEL,version:configuration.version??Defaults_VERSION_NUMBER,fqn:this.#constructFqn(module,name,importKey)}}#constructFqn(module,name,importKey){return this.#isRootModule(module)?name:this.#isIndexModule(module)&&this.#isDefaultImport(importKey)?module.location:`${module.location}/${name}`}#isRootModule(module){return""===module.location}#isIndexModule(module){return module.filename.endsWith(Files_INDEX)}#isDefaultImport(importKey){return importKey===Keywords$1_DEFAULT}#createMember(segment,module,model,properties){if(model instanceof ESClass)return this.#createClass(segment,module,model,properties);if(model instanceof ESFunction)return this.#createImplementation(segment,module,model,properties);throw new InvalidModuleExport(module.filename,properties.importKey)}#createClass(segment,module,model,properties){const clazz=new Class$1(properties.id,properties.importKey,properties.fqn,model);module.addMember(clazz),segment.setClass(clazz)}#createImplementation(segment,module,model,properties){if(!1===model.isAsync)throw new FunctionNotAsync(module.filename,properties.name);const implementation=new Implementation(properties.id,properties.importKey,properties.fqn,properties.access,properties.version,model);this.#createProcedure(segment,module,implementation)}#createProcedure(segment,module,implementation){const procedure=segment.hasProcedure(implementation.fqn)?segment.getProcedure(implementation.fqn):new Procedure(implementation.fqn);procedure.addImplementation(implementation),module.addMember(implementation),segment.setProcedure(procedure)}}class Reader{#projectFileManager;constructor(projectFileManager){this.#projectFileManager=projectFileManager}async read(moduleFiles,resourceFiles,segmentFiles){const sourceFileManager=this.#projectFileManager.source,resourceFileManager=this.#projectFileManager.resource,segmentFileManager=this.#projectFileManager.segment,moduleReader=new Reader$1(sourceFileManager),repository=await moduleReader.readAll(moduleFiles),resourceReader=new ResourceReader(resourceFileManager,sourceFileManager),resources=await resourceReader.readAll(resourceFiles),segmentReader=new SegmentReader(segmentFileManager,sourceFileManager,repository),segmentation=await segmentReader.readAll(segmentFiles);return new Application(repository,resources,segmentation)}}class RewriteItemFound extends Error{constructor(definition){super(`Could not find the rewrite item: ${definition}`)}}class LocalGenerator{#module;#resources;#segmentation;#segment;#fileHelper=new FileHelper;constructor(module,resources,segmentation,segment){this.#module=module,this.#resources=resources,this.#segmentation=segmentation,this.#segment=segment}generate(){const model=this.#module.model.clone();return this.#rewriteItems(model,model.imports),this.#rewriteItems(model,model.exports),model.toString()}#rewriteItems(model,items){for(const item of items){const rewritten=this.#rewriteItem(item);if(0===rewritten.length)continue;const index=model.statements.indexOf(item);if(-1===index)throw new RewriteItemFound(item.toString());model.statements.splice(index,1,...rewritten)}}#rewriteItem(item){if(this.#skipRewrite(item))return[];const targetModuleFilename=this.#getTargetModuleFilename(item);return this.#resources.isResourceModule(targetModuleFilename)?this.#rewriteToResource(item,targetModuleFilename):this.#rewriteToApplication(item,targetModuleFilename)}#skipRewrite(item){return void 0===item.from||this.#isRuntimeModule(item)}#isRuntimeModule(item){return!1===this.#fileHelper.isApplicationModule(item.from)}#getTargetModuleFilename(item){const from=item.from,callingModulePath=this.#fileHelper.extractPath(this.#module.filename);return this.#fileHelper.makePathAbsolute(from,callingModulePath,"")}#rewriteToResource(item,targetModuleFilename){const clone=item.clone();return clone.from=this.#rewriteApplicationFrom(targetModuleFilename),[clone]}#rewriteToApplication(item,targetModuleFilename){if(0===item.members.length)return[this.#rewriteToCommon(targetModuleFilename,item,[])];const{segmentKeys:segmentKeys,remoteKeys:remoteKeys,commonKeys:commonKeys}=this.#getModuleImplementationImportKeys(targetModuleFilename,item),rewrites=[];return segmentKeys.length>0&&rewrites.push(this.#rewriteToSegment(targetModuleFilename,item,segmentKeys)),remoteKeys.length>0&&rewrites.push(this.#rewriteToRemote(targetModuleFilename,item,remoteKeys)),commonKeys.length>0&&rewrites.push(this.#rewriteToCommon(targetModuleFilename,item,commonKeys)),rewrites}#getModuleImplementationImportKeys(targetModuleFilename,item){const moduleSegmentKeys=this.#getSegmentImplementationImportKeys(targetModuleFilename,this.#segment),moduleRemoteKeys=this.#getRemoteImplementationImportKeys(targetModuleFilename,moduleSegmentKeys),segmentKeys=this.#filterMemberKeys(item,moduleSegmentKeys),remoteKeys=this.#filterMemberKeys(item,moduleRemoteKeys);return{segmentKeys:segmentKeys,remoteKeys:remoteKeys,commonKeys:this.#extractUnsegmentedImportKeys(item,[...segmentKeys,...remoteKeys])}}#getSegmentImplementationImportKeys(targetModuleFilename,segment){if(void 0===segment)return[];const module=segment.getModule(targetModuleFilename);if(void 0===module)return[];return Object.keys(module.imports).filter(key=>module.importsImplementation(key))}#getRemoteImplementationImportKeys(targetModuleFilename,segmentKeys){const importKeys=this.#segmentation.getSegments(targetModuleFilename).filter(segment=>segment!==this.#segment).flatMap(segment=>this.#getSegmentImplementationImportKeys(targetModuleFilename,segment));return[...new Set(importKeys)].filter(key=>!1===segmentKeys.includes(key))}#filterMemberKeys(item,keys){return item.members.filter(member=>keys.includes(member.identifier)).map(member=>member.identifier)}#extractUnsegmentedImportKeys(item,segmentedKeys){return item.members.filter(member=>!1===segmentedKeys.includes(member.identifier)).map(member=>member.identifier)}#rewriteToSegment(targetModuleFilename,item,keys){const clone=item.clone();return clone.from=this.#rewriteApplicationFrom(targetModuleFilename,this.#segment?.name),clone.members=this.#filterMembers(item.members,keys),clone}#rewriteToRemote(targetModuleFilename,item,keys){const clone=item.clone();return clone.from=this.#rewriteApplicationFrom(targetModuleFilename,"remote"),clone.members=this.#filterMembers(item.members,keys),clone}#rewriteToCommon(targetModuleFilename,item,keys){const clone=item.clone();return clone.from=this.#rewriteApplicationFrom(targetModuleFilename),clone.members=this.#filterMembers(item.members,keys),clone}#filterMembers(members,keys){const filtered=[];for(const key of keys){const member=members.find(member=>member.identifier===key);void 0!==member&&filtered.push(member)}return filtered}#rewriteApplicationFrom(filename,scope){const callingModulePath=this.#fileHelper.extractPath(this.#module.filename),relativeFilename=this.#fileHelper.makePathRelative(filename,callingModulePath);return void 0!==scope?this.#fileHelper.addSubExtension(relativeFilename,scope):relativeFilename}}const AccessLevels={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class BadRequest extends Error{constructor(message="Invalid request"){super(message)}}class Forbidden extends Error{constructor(message="Forbidden"){super(message)}}class NotFound extends Error{constructor(message="Not found"){super(message)}}class NotImplemented extends Error{constructor(message="Not implemented"){super(message)}}class PaymentRequired extends Error{constructor(message="Payment required"){super(message)}}class ServerError extends Error{constructor(message="Server error"){super(message)}}class Teapot extends Error{constructor(message="I'm a teapot"){super(message)}}class Unauthorized extends Error{constructor(message="Unauthorized"){super(message)}}class InvalidVersionNumber extends BadRequest{#number;constructor(number){super(`Invalid version number '${number}'`),this.name="InvalidVersionNumber",this.#number=number}get number(){return this.#number}}class Segment{#id;#classes=new Map;#procedures=new Map;constructor(id){this.#id=id}get id(){return this.#id}addClass(clazz){return this.#classes.set(clazz.fqn,clazz),this}hasClass(fqn){return void 0!==this.getClass(fqn)}getClass(fqn){return this.#classes.get(fqn)}getClassByImplementation(implementation){return this.getClasses().find(clazz=>clazz.implementation===implementation)}getClasses(){return[...this.#classes.values()]}addProcedure(procedure){return this.#procedures.set(procedure.fqn,procedure),this}hasProcedure(fqn){return this.#procedures.has(fqn)}getProcedure(fqn){return this.#procedures.get(fqn)}getExposedProcedures(){return[...this.#procedures.values()].filter(procedure=>procedure.public||procedure.protected)}}class Class{#fqn;#implementation;constructor(fqn,implementation){this.#fqn=fqn,this.#implementation=implementation}get fqn(){return this.#fqn}get implementation(){return this.#implementation}}class Version{static get DEFAULT(){return new Version(0,0,0)}#major;#minor;#patch;constructor(major=0,minor=0,patch=0){this.#major=major,this.#minor=minor,this.#patch=patch}get major(){return this.#major}get minor(){return this.#minor}get patch(){return this.#patch}equals(version){return this.#major===version.major&&this.#minor===version.minor&&this.#patch===version.patch}greater(version){return this.#major!==version.major?this.#major>version.major:this.#minor!==version.minor?this.#minor>version.minor:this.#patch!==version.patch&&this.#patch>version.patch}less(version){return this.#major!==version.major?this.#major<version.major:this.#minor!==version.minor?this.#minor<version.minor:this.#patch!==version.patch&&this.#patch<version.patch}toString(){return`${this.#major}.${this.#minor}.${this.#patch}`}}class Parameter{#name;#isOptional;constructor(name,isOptional=!1){this.#name=name,this.#isOptional=isOptional}get name(){return this.#name}get isOptional(){return this.#isOptional}}class NamedParameter extends Parameter{}class DestructuredParameter extends Parameter{#variables;constructor(variables,name,isOptional){super(name??"(anonymous)",isOptional),this.#variables=variables}get variables(){return this.#variables}}class ArrayParameter extends DestructuredParameter{}class ObjectParameter extends DestructuredParameter{}class Request{#fqn;#version;#args;#headers=new Map;#mode;constructor(fqn,version,args,headers,mode){this.#fqn=fqn,this.#version=version,this.#args=args,this.#headers=headers,this.#mode=mode}get fqn(){return this.#fqn}get version(){return this.#version}get args(){return this.#args}get headers(){return this.#headers}get mode(){return this.#mode}clearArguments(){this.#args.clear()}setArgument(name,value){this.#args.set(name,value)}getArgument(name){return this.#args.get(name)}hasArgument(name){return this.#args.has(name)}removeArgument(name){this.#args.delete(name)}clearHeaders(){this.#headers.clear()}setHeader(name,value){this.#headers.set(name.toLowerCase(),value)}getHeader(name){return this.#headers.get(name.toLowerCase())}hasHeader(name){return this.#headers.has(name.toLowerCase())}removeHeader(name){this.#headers.delete(name.toLowerCase())}}class Response{#status;#result;#headers;constructor(status,result=void 0,headers=new Map){this.#status=status,this.#result=result,this.#headers=headers}get status(){return this.#status}get result(){return this.#result}set result(value){this.#result=value}get headers(){return this.#headers}clearHeaders(){this.#headers.clear()}setHeader(name,value){this.#headers.set(name.toLowerCase(),value)}getHeader(name){return this.#headers.get(name.toLowerCase())}hasHeader(name){return this.#headers.has(name.toLowerCase())}removeHeader(name){this.#headers.delete(name.toLowerCase())}}const VERSION_EXPRESSION=/^\d+(?:\.\d+){0,2}$/;class VersionParser{parse(number){if(0===number.trim().length)return Version.DEFAULT;if(!1===VERSION_EXPRESSION.test(number))throw new InvalidVersionNumber(number);const parts=number.split(".");switch(parts.length){case 1:return new Version(Number.parseInt(parts[0]));case 2:return new Version(Number.parseInt(parts[0]),Number.parseInt(parts[1]));default:return new Version(Number.parseInt(parts[0]),Number.parseInt(parts[1]),Number.parseInt(parts[2]))}}}class RemoteGenerator{#module;#segments;constructor(module,segments){this.#module=module,this.#segments=segments}generate(){const statements=[],implementations=this.#getImplementations();for(const implementation of implementations){const declarations=implementation.access===AccessLevels.PRIVATE?this.#createPrivate(implementation):this.#createPublic(implementation);statements.push(...declarations)}return new ESModule(statements).toString()}#getImplementations(){const implementations=this.#segments.map(segment=>segment.getModule(this.#module.filename)).flatMap(segmentModule=>segmentModule.implementations),unique=new Map;for(const implementation of implementations){const key=`${implementation.fqn}:${implementation.version.toString()}`;unique.set(key,implementation)}return[...unique.values()]}#createPrivate(implementation){const code=`throw new ProcedureNotAccessible('${implementation.fqn}','${implementation.version}');`;return[this.#createExport(implementation),this.#createFunction(implementation,code)]}#createPublic(implementation){const code=`return __run('${implementation.fqn}','${implementation.version}',{${this.#createArguments(implementation.model.parameters)}},this);`;return[this.#createExport(implementation),this.#createFunction(implementation,code)]}#createExport(implementation){const identifier=implementation.model.identifier,alias=implementation.importKey===Keywords$1_DEFAULT?Keywords$1_DEFAULT:void 0,member=new ESModuleMember(identifier,alias);return new ESExport([member],void 0)}#createFunction(implementation,code){const identifier=implementation.model.identifier,parameters=implementation.model.parameters,body=new ESBlock(`{${code}}`),isAsync=implementation.model.isAsync;return new ESFunction(identifier,parameters,body,isAsync)}#createArguments(parameters){return this.#extractArguments(parameters).join(",")}#extractArguments(parameters){const result=[];for(const parameter of parameters)if(parameter.binding instanceof ESIdentifierBinding){const argument=this.#createNamedArgument(parameter.binding);result.push(argument)}else if(parameter.binding instanceof ESArrayBinding){const argumentz=this.#extractArguments(parameter.binding.elements);result.push(...argumentz)}else if(parameter.binding instanceof ESObjectBinding){const argumentz=this.#extractArguments(parameter.binding.elements);result.push(...argumentz)}return result}#createNamedArgument(binding){return`'${binding.identifier}':${binding.toString()}`}}const JITAR_IMPORTS=["Segment","Class","Procedure","Implementation","Version","NamedParameter","ArrayParameter","ObjectParameter"];class Generator{#segment;#fileHelper=new FileHelper;#versionParser=new VersionParser;constructor(segment){this.#segment=segment}generate(){const imports=this.#createImports(),exported=this.#createExport(),declaration=this.#createDeclaration();return new ESModule([...imports,exported,declaration]).toString()}#createImports(){return[this.#createRuntimeImport(),...this.#createModuleImports()]}#createRuntimeImport(){const members=JITAR_IMPORTS.map(identifier=>new ESModuleMember(identifier));return new ESImport(members,"jitar")}#createModuleImports(){const segmentName=this.#segment.name,modules=this.#segment.getSegmentedModules(),imports=[];for(const module of modules){const segmentedFrom=`./${this.#fileHelper.addSubExtension(module.filename,segmentName)}`;if(0===module.members.length){const model=new ESImport([],segmentedFrom);imports.push(model);continue}const classes=module.classes,implementations=module.implementations;if(classes.length>0){const commonFrom=`./${module.filename}`,model=this.#createModuleImport(classes,commonFrom);imports.push(model)}if(implementations.length>0){const model=this.#createModuleImport(implementations,segmentedFrom);imports.push(model)}}return imports}#createModuleImport(segmentMembers,from){if(0===segmentMembers.length)return new ESImport([],from);const importMembers=segmentMembers.map(member=>new ESModuleMember(member.importKey,member.id));return new ESImport(importMembers,from)}#createExport(){const member=new ESModuleMember("segment","default");return new ESExport([member],void 0)}#createDeclaration(){const lines=[],segmentName=this.#segment.name,classes=this.#segment.classes,procedures=this.#segment.procedures;lines.push(`new Segment("${segmentName}")`);for(const clazz of classes)lines.push(`\t.addClass(new Class("${clazz.fqn}", ${clazz.id}))`);for(const procedure of procedures){lines.push(`\t.addProcedure(new Procedure("${procedure.fqn}")`);for(const implementation of procedure.implementations){const version=this.#createVersionCode(implementation.version),parameters=this.#createParametersCode(implementation.model);lines.push(`\t\t.addImplementation(new Implementation(${version}, "${implementation.access}", ${parameters}, ${implementation.id}))`)}lines.push("\t)")}const code=lines.join("\n"),initializer=new ESExpression(code),binding=new ESIdentifierBinding("segment");return new ESVariable("const",binding,initializer)}#createVersionCode(versionString){const version=this.#versionParser.parse(versionString);return`new Version(${version.major}, ${version.minor}, ${version.patch})`}#createParametersCode(model){return`[${this.#extractParameters(model.parameters).join(", ")}]`}#extractParameters(parameters){const result=[];for(const parameter of parameters)result.push(this.#extractParameter(parameter));return result}#extractParameter(parameter){return parameter.binding instanceof ESArrayBinding?this.#createArrayParameter(parameter):parameter.binding instanceof ESObjectBinding?this.#createObjectParameter(parameter):this.#createNamedParameter(parameter)}#createNamedParameter(parameter){return`new NamedParameter("${parameter.binding}", ${void 0!==parameter.initializer})`}#createArrayParameter(parameter){const binding=parameter.binding;return`new ArrayParameter([${this.#extractParameters(binding.elements).join(", ")}])`}#createObjectParameter(parameter){const binding=parameter.binding;return`new ObjectParameter([${this.#extractParameters(binding.elements).join(", ")}])`}}class ProjectFileManager{#source;#target;#resource;#segment;#sourceIgnores;constructor(source,target,resource,segment,sourceIgnores){this.#source=source,this.#target=target,this.#resource=resource,this.#segment=segment,this.#sourceIgnores=sourceIgnores}get source(){return this.#source}get target(){return this.#target}get resource(){return this.#resource}get segment(){return this.#segment}get sourceIgnores(){return this.#sourceIgnores}}class Validator{#strict;constructor(strict=!0){this.#strict=strict}validate(data,scheme){const errors=[];this.#validateData("",data,scheme,errors);return{valid:0===errors.length,errors:errors}}#validateData(key,data,scheme,errors){this.#strict&&this.#validateKeys(key,data,scheme,errors),this.#validateValues(key,data,scheme,errors)}#validateKeys(key,data,scheme,errors){const dataKeys=Object.keys(data),schemeKeys=Object.keys(scheme);for(const dataKey of dataKeys)if(!1===schemeKeys.includes(dataKey)){const absoluteKey=this.#composeKey(key,dataKey);errors.push(`Unknown field '${absoluteKey}'`)}}#validateValues(key,data,scheme,errors){const valueKeys=Object.keys(scheme);for(const valueKey of valueKeys){const absoluteKey=this.#composeKey(key,valueKey),fieldScheme=scheme[valueKey],value=data[valueKey];this.#validateValue(absoluteKey,value,fieldScheme,errors)}}#validateValue(key,value,scheme,errors){if(void 0!==value)switch(scheme.type){case"string":return this.#validateString(key,value,scheme,errors);case"integer":return this.#validateInteger(key,value,scheme,errors);case"real":return this.#validateReal(key,value,scheme,errors);case"boolean":return this.#validateBoolean(key,value,scheme,errors);case"url":return this.#validateUrl(key,value,scheme,errors);case"group":return this.#validateGroup(key,value,scheme,errors);case"list":return this.#validateList(key,value,scheme,errors);case"enum":return this.#validateEnum(key,value,scheme,errors)}else!0===scheme.required&&errors.push(`Field '${key}' is required`)}#validateString(key,value,scheme,errors){"string"!=typeof value&&errors.push(`Field '${key}' is not a string`)}#validateInteger(key,value,scheme,errors){"number"==typeof value&&!1!==Number.isInteger(value)||errors.push(`Field '${key}' is not an integer`)}#validateReal(key,value,scheme,errors){"number"!=typeof value&&errors.push(`Field '${key}' is not a real number`)}#validateBoolean(key,value,scheme,errors){"boolean"!=typeof value&&errors.push(`Field '${key}' is not a boolean`)}#validateUrl(key,value,scheme,errors){"string"==typeof value&&!1!==value.startsWith("http")||errors.push(`Field '${key}' is not a valid URL`)}#validateGroup(key,value,scheme,errors){"object"==typeof value?this.#validateData(key,value,scheme.fields,errors):errors.push(`Field '${key}' is not an object`)}#validateList(key,value,scheme,errors){if(!Array.isArray(value))return void errors.push(`Field '${key}' is not a list`);const data=value;for(const itemIndex in data){const itemKey=this.#composeKey(key,itemIndex),itemValue=data[itemIndex];this.#validateValue(itemKey,itemValue,scheme.items,errors)}}#validateEnum(key,value,scheme,errors){if(!1===scheme.options.includes(value)){const options=scheme.options.map(option=>String(option));errors.push(`Field '${key}' is not one of: ${options.join(", ")}`)}}#composeKey(parent,key){return""===parent?key:`${parent}.${key}`}}class Configurator{#fileManager;constructor(fileManager){this.#fileManager=fileManager}async configure(filename){const path=this.#fileManager.getAbsoluteLocation(filename);dotenv.config({path:path})}}class RuntimeConfigurationInvalid extends Error{constructor(filename,validation){super(`Invalid runtime configuration '${filename}'\n${validation.errors.join("\n")}`)}}const DefaultValues_FILENAME="./jitar.json",DefaultValues_SOURCE="./src",DefaultValues_TARGET="./dist",DefaultValues_SEGMENTS="./segments",DefaultValues_RESOURCES="./resources",DefaultValues_BUILD={ignore:[]},DefaultValues_BUILD_IGNORE=[],validationScheme$8={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1},build:{type:"group",fields:{ignore:{type:"list",items:{type:"string"},required:!1}},required:!1}};let ConfigurationBuilder$1=class{#reader;#validator;constructor(reader,validator){this.#reader=reader,this.#validator=validator}async build(filename=DefaultValues_FILENAME){const configuration=await this.#reader.read(filename),validation=this.#validator.validate(configuration,validationScheme$8);if(!1===validation.valid)throw new RuntimeConfigurationInvalid(filename,validation);return configuration.source??=DefaultValues_SOURCE,configuration.target??=DefaultValues_TARGET,configuration.segments??=DefaultValues_SEGMENTS,configuration.resources??=DefaultValues_RESOURCES,configuration.build??=DefaultValues_BUILD,configuration.build.ignore??=DefaultValues_BUILD_IGNORE,configuration.meta={root:this.#reader.getRootLocation(),configFile:filename},configuration}};class ServiceConfigurationInvalid extends Error{constructor(filename,validation){super(`Invalid server configuration '${filename}'\n => ${validation.errors.join("\n => ")}`)}}const validationScheme$4={directoryIndex:{type:"string",required:!1},fallback:{type:"string",required:!1},assetRoot:{type:"string",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}},validationScheme$3={gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}},validationScheme={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"}},http:{type:"group",required:!1,fields:{bodyLimit:{type:"integer",required:!1},proxied:{type:"boolean",required:!1}}},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:validationScheme$4},standalone:{type:"group",required:!1,fields:{...validationScheme$4,segments:validationScheme$3.segments}},worker:{type:"group",required:!1,fields:validationScheme$3},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class ConfigurationBuilder{#reader;#validator;constructor(reader,validator){this.#reader=reader,this.#validator=validator}async build(filename){const configuration=await this.#reader.read(filename),validation=this.#validator.validate(configuration,validationScheme);if(!1===validation.valid)throw new ServiceConfigurationInvalid(filename,validation);return configuration.meta={root:this.#reader.getRootLocation(),configFile:filename},configuration}}class InvalidConfigurationFile extends Error{constructor(filename){super(`${filename} is not a valid configuration file.`)}}const ENVIRONMENT_VARIABLE_REGEX=/\${([^}]*)}/g;class ConfigurationReader{#fileManager;constructor(fileManager){this.#fileManager=fileManager}getRootLocation(){return this.#fileManager.getAbsoluteLocation(".")}async read(filename){if(!1===await this.#fileManager.exists(filename))return{};const file=await this.#fileManager.read(filename);if(!1===file.type.includes("json"))throw new InvalidConfigurationFile(filename);const content=file.content.toString(),configuration=this.#replaceEnvironmentVariables(content);return this.#parseJson(configuration)}#replaceEnvironmentVariables(content){return content.replace(ENVIRONMENT_VARIABLE_REGEX,(match,key)=>process.env[key]??"null")}#parseJson(configuration){return JSON.parse(configuration)}}class ConfigurationManager{#environmentConfigurator;#runtimeConfigurationBuilder;#serviceConfigurationBuilder;constructor(rootPath="./"){const fileManager=new LocalFileManager(rootPath),reader=new ConfigurationReader(fileManager),validator=new Validator;this.#environmentConfigurator=new Configurator(fileManager),this.#runtimeConfigurationBuilder=new ConfigurationBuilder$1(reader,validator),this.#serviceConfigurationBuilder=new ConfigurationBuilder(reader,validator)}configureEnvironment(filename=".env"){return this.#environmentConfigurator.configure(filename)}getRuntimeConfiguration(filename){return this.#runtimeConfigurationBuilder.build(filename)}getServiceConfiguration(filename){return this.#serviceConfigurationBuilder.build(filename)}}export{ArrayParameter as A,BadRequest as B,ConfigurationManager as C,ESClass as E,Forbidden as F,Generator as G,InvalidVersionNumber as I,LocalFileManager as L,NotFound as N,ObjectParameter as O,Parser as P,Response as R,ServerError as S,Teapot as T,Unauthorized as U,Validator as V,ESIdentifierBinding as a,ESExpression as b,ESVariable as c,ESModule as d,ESField as e,ESConstructor as f,ESGetter as g,ESSetter as h,ESMethod as i,NamedParameter as j,NotImplemented as k,PaymentRequired as l,Segment as m,FileHelper as n,LocalGenerator as o,RemoteGenerator as p,ProjectFileManager as q,Reader as r,Files$1 as s,File as t,FileNotFound as u,Request as v,VersionParser as w,Class as x,Version as y,AccessLevels as z};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e from"node:process";import{promises as t}from"node:fs";import r from"node:path";import{fileURLToPath as s}from"node:url";import{L as a,E as n,P as i,a as o,b as c,c as l,d as u,e as h,f as d,g as p,h as g,i as m,N as w,F as f,B as y,j as v,A as b,O as M,k as S,l as x,T as k,U as P,S as A,m as z,R,n as E,o as C,p as H,G as T,q as O,r as I,s as N,C as j,V as $,t as L,u as W,v as B,w as q,x as D}from"./ConfigurationManager-CQWv0Wmk.js";import F from"node:crypto";import V from"express";import"glob";import"mime-types";import"dotenv";class K extends Error{constructor(e){super(`Missing argument '${e}'`)}}class U{#e;#t;constructor(e){this.#e=e[2],this.#t=this.#r(e)}getCommand(){return this.#e}containsKey(e){return this.#t.has(e)}getRequiredArgument(e){const t=this.#t.get(e);if(void 0===t)throw new K(e);return t}getOptionalArgument(e,t){return this.#t.get(e)??t}#r(e){const t=e.slice(3),r=new Map;return t.forEach(e=>{const[t,s]=e.split("=");r.set(t.trim(),s?.trim())}),r}}class _{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#s;constructor(e){this.#s=e}async execute(e){for(const t of this.#s.values())if(e.containsKey(t.name))return this.#a(t);this.#n()}#n(){console.log("\njitar <command>\n"),console.log("Available commands:");const e=[...this.#s.values()],t=e.map(e=>e.name),r=this.#i(t);for(const t of e){const e=t.name.padEnd(r," "),s=t.description;console.log(` ${e} ${s}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#a(e){console.log(`\n${e.description}\n`);const t=e.options;if(0===t.length)return void console.log("No options available.\n");console.log("Options:");const r=t.map(e=>e.key),s=this.#i(r);for(const e of t){const t=e.key.padEnd(s," "),r=e.description,a=e.defaultValue?`default: ${e.defaultValue}`:"no default value",n=e.required?"required":`optional - ${a}`;console.log(` ${t} ${r} (${n})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class G{name="about";description="Shows information about Jitar.";options=[];async execute(e){console.log("\nJitar is a JavaScript Distributed Runtime created and maintained by Masking Technology.\n\nMore information can be found at:\n- https://jitar.dev\n- https://masking.tech\n")}}class J{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.12.0")}}class X extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class Q extends Error{constructor(e){super(`Unknown template: ${e}`)}}const Z=/^[a-zA-Z.\-_]+$/;class Y{#o;#c;constructor(e="./"){this.#o=this.#l(),this.#c=this.#u(e)}async init(e,t){this.#h(e,"project"),this.#h(t,"template");if(!1===await this.#d(t))throw new Q(t);await this.#p(e,t)}#l(){const e=r.dirname(s(import.meta.url));return r.join(e,"templates")}#u(e){return r.resolve(e)}#h(e,t){if(!1===Z.test(e))throw new X(e,t)}async#d(e){try{const s=r.join(this.#o,e);return(await t.stat(s)).isDirectory()}catch{return!1}}#p(e,s){const a=r.join(this.#o,s),n=r.join(this.#c,e);return t.cp(a,n,{recursive:!0,force:!0})}}class ee{name="init";description="Initializes a new Jitar project from a template.";options=[{key:"--name",required:!0,description:"Project name used for creating the project folder"},{key:"--template",required:!0,description:"Template to use [react, vue, backend]"},{key:"--location",required:!1,description:"The root location of the project",defaultValue:"./"}];async execute(e){const t=e.getRequiredArgument("--name"),r=e.getRequiredArgument("--template"),s=e.getOptionalArgument("--location",void 0);this.#g(t,r),await this.#m(t,r,s),this.#w(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#m(e,t,r){return new Y(r).init(e,t)}#w(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}class te extends Error{constructor(e,t){super(`Module could not be loaded from '${e}'`,{cause:t})}}class re{#f;constructor(e){this.#f=e}async import(e){const t=this.#f.locate(e);try{return await(import(t))}catch(e){throw new te(t,e)}}}class se{#y;constructor(e){this.#y=e}locate(e){return`file://${e.startsWith("/")?this.#y.getAbsoluteLocation(`.${e}`):this.#y.getAbsoluteLocation(e)}`}}class ae extends re{constructor(e){super(new se(e))}}class ne{#y;#v;constructor(e,t){this.#y=e,this.#v=t}get fileManager(){return this.#y}get importManager(){return this.#v}async filter(...e){return(await Promise.all(e.map(e=>this.#y.filter(e)))).flat().map(e=>this.#y.getRelativeLocation(e))}exists(e){return this.#y.exists(e)}read(e){return this.#y.read(e)}import(e){return this.#v.import(e)}}class ie extends ne{constructor(e){const t=new a(e);super(t,new ae(t))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new ie(t)}}class oe{merge(e,t){const r=void 0!==e.construct?[e.construct]:[],s=[...this.#b(e.fields,t.fields),...r,...this.#b(e.methods,t.methods),...this.#b(e.getters,t.getters),...this.#b(e.setters,t.setters)];return new n(e.identifier,t.identifier,s)}#b(e,t){const r=new Map;return t.forEach(e=>r.set(e.identifier,e)),e.forEach(e=>r.set(e.identifier,e)),[...r.values()]}}class ce{#M=new i;#S=new oe;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,a]of r){if("function"!=typeof a.toString)continue;const r=a.toString();if(r.startsWith("class"))s.push(this.fromClass(a,t));else if(r.startsWith("function"))s.push(this.fromFunction(a));else{const t=new o(e,!1),a=new c(r);s.push(new l("var",t,a))}}return new u(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#x(e):this.#k(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const a=this.fromClass(s,!0);return this.#S.merge(r,a)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#M.parseFunction(t)}createInstance(e,t=[]){return new e(...t)}getClass(e){return e.constructor}getParentClass(e){return Object.getPrototypeOf(e)}isClassObject(e){return this.isClass(e.constructor)}isFunctionObject(e){return this.isFunction(e.constructor)}isClass(e){return e.toString().startsWith("class")}isFunction(e){return e.toString().startsWith("function")||e.toString().startsWith("async function")}#x(e){const t=e.toString();return this.#M.parseClass(t)}#k(e){const t=this.createInstance(e),r=this.#P(e,t);return new n(e.name,void 0,r)}#P(e,t){return[...this.#A(t),...this.#z(e)]}#A(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],a=void 0!==t?new c(String(t)):void 0,n=new h(e,"public","instance",a);s.push(n)}return s}#z(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],a=s.value;if(a instanceof Function==!1)continue;const n=this.fromFunction(a);"constructor"===n.identifier?r.push(new d(n.parameters,n.body)):void 0!==s.get?r.push(new p(n.identifier,"public","instance",n.body)):void 0!==s.set?r.push(new g(n.identifier,"public","instance",n.parameters[0],n.body)):r.push(new m(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return r}}class le extends Error{constructor(e,t){super(`Failed building module for '${e}'`,{cause:t})}}const ue="normal",he="dry",de=200,pe=400,ge=401,me=402,we=403,fe=404,ye=418,ve=500,be=501;class Me extends w{#R;constructor(e){super(`Procedure '${e}' not found`),this.#R=e}get fqn(){return this.#R}}class Se extends f{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class xe extends y{#E;constructor(e){super(`Unknown parameter ${e}`),this.#E=e}get parameterName(){return this.#E}}class ke extends y{#E;constructor(e){super(`Missing value for parameter '${e}'`),this.#E=e}get parameterName(){return this.#E}}class Pe extends y{#E;constructor(e){super(`Invalid value for parameter '${e}'`),this.#E=e}get parameterName(){return this.#E}}class Ae{extract(e,t){const r=this.#C(e,t),s=[];for(const t of e){const e=this.#H(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new xe(e)}return s}#C(e,t){const r=new Map;for(const[s,a]of t){if(this.#T(s)){const t=this.#O(s);!0===this.#I(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#T(e){return e.startsWith("*")}#O(e){return e.substring(1)}#I(e,t){return void 0!==e.find(e=>e.name===t)}#H(e,t,r){return e instanceof v?this.#N(e,t,r):this.#j(e,t)}#N(e,t,r){const s=t.get(e.name);if(this.#$(e,s,r))throw new ke(e.name);if(this.#L(e,s,r))throw new Pe(e.name);return t.delete(e.name),s}#j(e,t){return e instanceof b?this.#W(e,t):this.#B(e,t)}#W(e,t){const r=this.#q(e,t);return void 0!==r?Object.values(r):void 0}#B(e,t){return this.#q(e,t)}#q(e,t){const r=e instanceof b,s={},a=[];let n=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,l=this.#H(o,t,e);void 0!==l?n=!0:!1===o.isOptional&&a.push(o.name),s[c]=l}if(!0===n&&a.length>0)throw new ke(a[0]);return n?s:void 0}#$(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#L(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof b&&t instanceof Array==!1||r instanceof M&&t instanceof Object==!1)}}class ze{toStatus(e){return e instanceof y?pe:e instanceof f?we:e instanceof w?fe:e instanceof S?be:e instanceof x?me:e instanceof k?ye:e instanceof P?ge:ve}fromStatus(e,t){switch(e){case pe:return new y(t);case we:return new f(t);case fe:return new w(t);case be:return new S(t);case me:return new x(t);case ye:return new k(t);case ge:return new P(t);default:return new A(t)}}}class Re extends w{#R;#D;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#R=e,this.#D=t}get fqn(){return this.#R}get version(){return this.#D}}class Ee extends A{constructor(){super("Invalid segment")}}class Ce extends Error{constructor(e){super("Starting execution manager failed",{cause:e})}}class He extends Error{constructor(e){super("Stopping execution manager failed",{cause:e})}}class Te{#F=new Map;addSegment(e){this.#F.set(e.id,e)}clearSegments(){this.#F.clear()}getClassNames(){const e=new Set;for(const t of this.#F.values()){t.getClasses().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasClass(e){return this.getClassNames().includes(e)}getClass(e){for(const t of this.#F.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#F.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#F.values()){t.getExposedProcedures().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}getProcedure(e){for(const t of this.#F.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Oe{#V;#K;#U=new Ae;#_=new ze;#G=new Te;constructor(e,t=[]){this.#V=e,this.#K=t}async start(){try{await this.#J()}catch(e){throw new Ce(e)}}async stop(){try{return this.#X()}catch(e){throw new He(e)}}async loadSegment(e){const t=await this.#V.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof z==!1)throw new Ee;this.#G.addSegment(e)}getClassNames(){return this.#G.getClassNames()}hasClass(e){return this.#G.hasClass(e)}getClass(e){return this.#G.getClass(e)}getClassByImplementation(e){return this.#G.getClassByImplementation(e)}getProcedureNames(){return this.#G.getProcedureNames()}hasProcedure(e){return this.#G.hasProcedure(e)}getProcedure(e){return this.#G.getProcedure(e)}async run(e){const t=this.#Q(e.fqn,e.version),r=this.#U.extract(t.parameters,e.args);return e.mode===he?new R(de,void 0):this.#Z(e,t,r)}async#J(){await Promise.all(this.#K.map(e=>this.loadSegment(e)))}#X(){this.#G.clearSegments()}#Q(e,t){const r=this.#G.getProcedure(e);if(void 0===r)throw new Me(e);const s=r.getImplementation(t);if(void 0===s)throw new Re(r.fqn,t.toString());return s}async#Z(e,t,r){try{const s=await t.executable.call(e,...r);return new R(de,s)}catch(e){const t=this.#_.toStatus(e);return new R(t,e)}}}let Ie=class{#Y;#ee=new E;constructor(e){this.#Y=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,a=t.modules.map(e=>this.#te(e,s,r));await Promise.all(a)}async#te(e,t,r){try{const s=r.getSegments(e.filename);if(0===s.length)return void await this.#re(e,t,r);const a=s.filter(t=>t.getModule(e.filename)?.hasImplementations()),n=this.#re(e,t,r),i=a.map(s=>this.#se(e,t,s,r)),o=a.length>0?this.#ae(e,s):Promise.resolve();await Promise.all([n,...i,o])}catch(t){throw new le(e.filename,t)}}async#re(e,t,r){const s=e.filename,a=new C(e,t,r).generate();return this.#Y.write(s,a)}async#se(e,t,r,s){const a=this.#ee.addSubExtension(e.filename,r.name),n=new C(e,t,s,r).generate();return this.#Y.write(a,n)}async#ae(e,t){const r=this.#ee.addSubExtension(e.filename,"remote"),s=new H(e,t).generate();return this.#Y.write(r,s)}};class Ne extends Error{constructor(e,t){super(`Failed building segment '${e}'`,{cause:t})}}let je=class{#Y;#ne;constructor(e,t){this.#Y=e,this.#ne=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ie(e));await Promise.all(t)}async#ie(e){try{const t=`${e.name}.segment.js`,r=new T(e).generate();await this.#Y.write(t,r),this.#ne.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}catch(t){throw new Ne(e.name,t)}}};class $e{#oe;#ce;constructor(e,t){const r=e.target;this.#oe=new Ie(r),this.#ce=new je(r,t)}async build(e){await Promise.all([this.#oe.build(e),this.#ce.build(e)])}}const Le=0,We=1,Be=2,qe=3,De=4;class Fe{#le;#ue;constructor(e=We,t=console){this.#le=e,this.#ue=t}debug(...e){if(this.#le>Le)return;const t=this.#he("DEBUG",e);this.#ue.debug(t)}info(...e){if(this.#le>We)return;const t=this.#he("INFO",e);this.#ue.info(t)}warn(...e){if(this.#le>Be)return;const t=this.#he("WARN",e);this.#ue.warn(t)}error(...e){if(this.#le>qe)return;const t=this.#he("ERROR",e);this.#ue.error(t)}fatal(...e){const t=this.#he("FATAL",e);this.#ue.error(t)}#he(e,t){return`[${(new Date).toISOString()}][${e}] ${t.map(e=>this.#de(e)).join(" ")}`}#de(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#pe(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#ge(t)}${r}`}#pe(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#de(e,t)).join(",\n")}\n${this.#ge(t-1)}]`}if(e instanceof Error){const r=void 0!==e.cause?this.#de(e.cause,t+1):void 0,s=void 0!==r?`\n=>${r}`:"";return`${e.message}${s}`}return JSON.stringify(e)}#ge(e){return" ".repeat(e)}}class Ve extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class Ke{parse(e){switch(e.toUpperCase()){case"DEBUG":return Le;case"INFO":return We;case"WARN":return Be;case"ERROR":return qe;case"FATAL":return De;default:throw new Ve(e)}}}class Ue extends Error{constructor(e){super("Build failed",{cause:e})}}class _e{#ne;#ee;#y;#me;#we;constructor(e,t){this.#ne=new Fe(t),this.#ee=new E;const r=this.#ee.makePathAbsolute(e.source,e.meta.root),s=this.#ee.makePathAbsolute(e.target,e.meta.root),n=this.#ee.makePathAbsolute(e.resources,e.meta.root),i=this.#ee.makePathAbsolute(e.segments,e.meta.root);this.#y=new O(new a(r),new a(s),new a(n),new a(i),e.build.ignore),this.#me=new I(this.#y),this.#we=new $e(this.#y,this.#ne)}async build(){try{const e=this.#y.source,t=this.#y.resource,r=this.#y.segment,s=await e.filterWithIgnores(N.MODULE_PATTERN,this.#y.sourceIgnores),a=await t.filter(N.RESOURCE_PATTERN),n=await r.filter(N.SEGMENT_PATTERN),i=await this.#me.read(s,a,n);await this.#we.build(i)}catch(e){throw new Ue(e)}}}class Ge{name="build";description="Builds the application (creates segment bundles).";options=[{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getOptionalArgument("--log-level",void 0),a=this.#fe(s),n=new j;await n.configureEnvironment(t);const i=await n.getRuntimeConfiguration(r);return new _e(i,a).build()}#fe(e){if(void 0===e)return;return(new Ke).parse(e)}}const Je="content-type",Xe="x-content-type-options",Qe="x-jitar-content-type",Ze="x-jitar-procedure-version",Ye="x-powered-by",et="nosniff",tt="application/json",rt="application/octet-stream";class st extends Error{constructor(){super("Invalid worker id")}}class at{#ye;#ve;#_=new ze;#be=new $;constructor(e,t){this.#ye=e,this.#ve=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#ye}/${e}`,r=await this.#Me(t,{method:"GET"}),s=r.headers.get(Je)??rt,a=await r.arrayBuffer(),n=Buffer.from(a);return new L(e,s,n)}async isHealthy(){const e=`${this.#ye}/health/status`,t=await this.#Me(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#ye}/health`,t=await this.#Me(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#ye}/workers`,a={url:e,procedureNames:t,trustKey:r},n={method:"POST",headers:{"Content-Type":tt},body:JSON.stringify(a)},i=await this.#Me(s,n),o=i.headers.get(Je);if(null===o||!1===o.includes(tt))throw new st;const c=await i.json();if(!1===this.#be.validate(c,{id:{type:"string",required:!0}}).valid)throw new st;return c.id}async reportWorker(e,t){const r=`${this.#ye}/workers/${e}/report`,s={state:t},a={method:"POST",headers:{"Content-Type":tt},body:JSON.stringify(s)};await this.#Me(r,a)}async removeWorker(e){const t=`${this.#ye}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":tt}};await this.#Me(t,r)}async run(e){e.setHeader(Je,tt);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[Ze]=s;const a=`${this.#ye}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:r,body:await this.#Se(t)},i=await this.#Me(a,n,!1),o=i.status,c=await this.#xe(i),l=this.#ke(i);return new R(o,c,l)}async#Me(e,t,r=!0){const s=await this.#ve.execute(e,t);if(r&&this.#Pe(s)){const e=await this.#xe(s);throw this.#_.fromStatus(s.status,String(e))}return s}#Pe(e){return e.status<200||e.status>399}async#Se(e){return JSON.stringify(e)}async#xe(e){const t=e.headers.get(Qe)??e.headers.get(Je);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const r=await e.text();return t?.includes("boolean")?"true"===r:t?.includes("number")?Number(r):r}#ke(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class nt{async execute(e,t){return fetch(e,t)}}class it{#ve;constructor(e=new nt){this.#ve=e}build(e){return new at(e,this.#ve)}}const ot={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class ct{get url(){throw new S}get state(){return ot.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ot.AVAILABLE}provide(e){throw new S}}class lt{get url(){throw new S}get state(){return ot.AVAILABLE}get trustKey(){throw new S}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ot.AVAILABLE}getProcedureNames(){throw new S}hasProcedure(e){throw new S}run(e){throw new S}}class ut{#Ae=ot.STOPPED;get state(){return this.#Ae}set state(e){this.#Ae=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#ze(ot.STOPPED)}isStopped(){return this.#Re(ot.STOPPED)}isAvailable(){return this.#Re(ot.AVAILABLE)}setStarting(){this.#Ae=ot.STARTING}setAvailable(){this.#Ae=ot.AVAILABLE}setUnavailable(){this.#Ae=ot.UNAVAILABLE}setAvailability(e){return this.#Ae=e?ot.AVAILABLE:ot.UNAVAILABLE,this.#Ae}setStopping(){this.#Ae=ot.STOPPING}setStopped(){this.#Ae=ot.STOPPED}#Re(...e){return e.includes(this.#Ae)}#ze(...e){return!1===this.#Re(...e)}}class ht extends P{constructor(){super("Invalid trust key")}}class dt{#ye;#Ee;#Ce;#He;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#Ce=e.healthManager,this.#He=e.workerManager}get url(){return this.#ye}get state(){return this.#Te.state}get trustKey(){return this.#Ee}async start(){return this.#Te.start(async()=>{await this.#Ce.start(),this.#He.start(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{this.#He.stop(),await this.#Ce.stop()})}async isHealthy(){return this.#Ce.isHealthy()}async getHealth(){return this.#Ce.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}async addWorker(e){if(this.#Oe(e.trustKey))throw new ht;return await e.start(),this.#He.addWorker(e)}getWorker(e){return this.#He.getWorker(e)}async reportWorker(e,t){return this.#He.reportWorker(e,t)}async removeWorker(e){return this.#He.removeWorker(e).stop()}getProcedureNames(){return this.#He.getProcedureNames()}hasProcedure(e){return this.#He.hasProcedure(e)}async run(e){return this.#He.run(e)}#Oe(e){return void 0!==this.#Ee&&e!==this.#Ee}}class pt{#ye;#Ie;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ie=e.remote}get url(){return this.#ye}get state(){return this.#Te.state}get trustKey(){}async start(){return this.#Te.start(async()=>{await this.#Ie.connect(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ie.disconnect()})}isHealthy(){return this.#Ie.isHealthy()}getHealth(){return this.#Ie.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}getProcedureNames(){throw new S}hasProcedure(e){throw new S}addWorker(e){return this.#Ie.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Ie.reportWorker(e,t)}removeWorker(e){return this.#Ie.removeWorker(e)}run(e){return this.#Ie.run(e)}}class gt extends A{#Ne;constructor(e){super(`No worker available for procedure '${e}'`),this.#Ne=e}get name(){return this.#Ne}}class mt{#je=[];#$e=0;get workers(){return this.#je}addWorker(e){this.#je.includes(e)||this.#je.push(e)}removeWorker(e){const t=this.#je.indexOf(e);-1!==t&&this.#je.splice(t,1)}getNextWorker(){const e=this.#je.filter(e=>e.isAvailable());if(0!==e.length)return this.#$e>=e.length&&(this.#$e=0),e[this.#$e++];this.#$e=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new gt(e.fqn);return t.run(e)}}class wt{generate(){return F.randomUUID()}}class ft extends A{#Le;constructor(e){super(`Unknown worker id '${e}'`),this.#Le=e}get id(){return this.#Le}}class yt{#je=new Map;#We=new Map;#Be=new wt;#qe;constructor(e,t){this.#qe=e.create(()=>this.#De(),t)}get workers(){return[...this.#je.values()]}get balancers(){return this.#We}start(){this.#qe.start()}stop(){this.#qe.stop()}getProcedureNames(){const e=this.workers.map(e=>e.getProcedureNames());return[...new Set(e.flat()).values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}addWorker(e){e.id=this.#Be.generate(),this.#je.set(e.id,e);for(const t of e.getProcedureNames()){this.#Fe(t).addWorker(e)}return e.id}getWorker(e){const t=this.#je.get(e);if(void 0===t)throw new ft(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#je.delete(e);for(const e of t.getProcedureNames()){const r=this.#Ve(e);void 0!==r&&r.removeWorker(t)}return t}#Ve(e){return this.#We.get(e)}#Fe(e){let t=this.#Ve(e);return void 0===t&&(t=new mt,this.#We.set(e,t)),t}async run(e){const t=this.#Ve(e.fqn);if(void 0===t)throw new Me(e.fqn);return t.run(e)}async#De(){const e=this.workers.map(e=>this.#Ke(e));await Promise.allSettled(e)}async#Ke(e){await e.updateState()===ot.STOPPED&&this.removeWorker(e.id)}}class vt{#ye;#Ue;#_e;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ue=e.provider,this.#_e=e.runner}get url(){return this.#ye}get state(){return this.#Te.state}get trustKey(){return this.#_e.trustKey}get provider(){return this.#Ue}get runner(){return this.#_e}async start(){return this.#Te.start(async()=>{await Promise.all([this.#Ue.start(),this.#_e.start()]),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await Promise.allSettled([this.#_e.stop(),this.#Ue.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#Ue.isHealthy(),this.#_e.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#Ue.getHealth(),this.#_e.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}provide(e){return this.#Ue.provide(e)}getProcedureNames(){return this.#_e.getProcedureNames()}hasProcedure(e){return this.#_e.hasProcedure(e)}run(e){return this.#_e.run(e)}}class bt{#ye;#Ce;#Ge;#Je;#Xe;#Qe;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ce=e.healthManager,this.#Ge=e.sourcingManager,this.#Je=e.assets,this.#Xe=e.directoryIndex??"index.html",this.#Qe=e.fallback}get url(){return this.#ye}get state(){return this.#Te.state}async start(){return this.#Te.start(async()=>{await this.#Ce.start(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ce.stop()})}isHealthy(){return this.#Ce.isHealthy()}getHealth(){return this.#Ce.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}async provide(e){if(this.#Je.has(e))return this.#Ge.read(e);const t=this.#Ze(e);if(this.#Je.has(t))return this.#Ge.read(t);if(void 0!==this.#Qe&&this.#Je.has(this.#Qe))return this.#Ge.read(this.#Qe);throw new W(e)}#Ze(e){return""===e||"/"===e?this.#Xe:e.endsWith("/")?`${e}${this.#Xe}`:`${e}/${this.#Xe}`}}class Mt{#ye;#Ie;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ie=e.remote}get url(){return this.#ye}get state(){return this.#Te.state}async start(){return this.#Te.start(async()=>{await this.#Ie.connect(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ie.disconnect()})}isHealthy(){return this.#Ie.isHealthy()}getHealth(){return this.#Ie.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}provide(e){return this.#Ie.provide(e)}}class St extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class xt extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class kt extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Pt extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class At{#Ye=[];addSerializer(e){e.parent=this,this.#Ye.unshift(e)}async serialize(e){const t=this.#Ye.find(t=>t.canSerialize(e));if(void 0===t)throw new Pt(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Ye.find(t=>t.canDeserialize(e));if(void 0===t)throw new kt(typeof e);return t.deserialize(e)}}class zt extends Error{constructor(){super("Parent serializer not set")}}class Rt{#et;set parent(e){this.#et=e}serializeOther(e){if(void 0===this.#et)throw new zt;return this.#et.serialize(e)}deserializeOther(e){if(void 0===this.#et)throw new zt;return this.#et.deserialize(e)}}class Et extends Rt{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const r of e)t.push(await this.serializeOther(r));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Ct extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Ht extends Rt{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new Ct(e.value)}}}class Tt extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ot extends Rt{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Tt(e.base64)}}}const It=new ce;class Nt extends Rt{#tt;constructor(e){super(),this.#tt=e}canSerialize(e){return e instanceof Object&&It.isClassObject(e)}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"class"===t.name&&"string"==typeof t.key&&t.args instanceof Object&&t.args.constructor===Object&&t.fields instanceof Object&&t.fields.constructor===Object}async serialize(e){const t=It.getClass(e),r=It.fromClass(t,!0),s=this.#rt(r),a=this.#tt.resolveKey(t);if(void 0===a)throw new St(t.name);return{serialized:!0,key:a,name:"class",args:await this.#st(r,s,e),fields:await this.#at(r,s,e)}}#rt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#st(e,t,r){const s={};for(const[a,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(r[n]):void 0;s[a.toString()]=t}return s}async#at(e,t,r){const s={};for(const a of e.writable){const n=a.identifier;t.includes(n)||!1===e.canRead(n)||(s[n]=await this.serializeOther(r[n]))}return s}async deserialize(e){const t=await this.#nt(e);if(void 0===t)throw new St(e.key);if(t instanceof Function==!1)throw new xt(e.key);const r=await this.#it(t,e.args),s=It.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#it(e,t){const r=It.fromClass(e,!0).construct,s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),a=t[s];return this.deserializeOther(a)});return Promise.all(s)}async#nt(e){return globalThis[e.key]??this.#tt.resolveClass(e.key)}}class jt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class $t extends Rt{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new jt(e.value);return t}}class Lt extends Rt{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class Wt extends Rt{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],r=[];for(const[s,a]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(a));return{serialized:!0,name:"Map",entries:{keys:t,values:r}}}async deserialize(e){const t=e.entries.keys,r=e.entries.values,s=new Map;for(let e=0;e<t.length;e++){const a=await this.deserializeOther(t[e]),n=await this.deserializeOther(r[e]);s.set(a,n)}return s}}class Bt extends Rt{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.serializeOther(s)}return t}async deserialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.deserializeOther(s)}return t}}class qt extends Rt{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class Dt extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Ft extends Rt{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new Dt(e.source,e.flags)}}}class Vt extends Rt{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const r of e.values())t.push(await this.serializeOther(r));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const Kt=new ce;class Ut extends Rt{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,r=new DataView(e.buffer),s=[];for(let e=0;e<r.byteLength;e++)s.push(r.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:s}}async deserialize(e){const t=e.type,r=e.bytes,s=new ArrayBuffer(r.length),a=new DataView(s);for(let e=0;e<r.length;e++)a.setUint8(e,r[e]);const n=globalThis[t];return Kt.createInstance(n,[s])}}class _t extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class Gt extends Rt{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new _t(e.value)}}}class Jt{static build(e){const t=new At;return t.addSerializer(new qt),t.addSerializer(new Bt),void 0!==e&&t.addSerializer(new Nt(e)),t.addSerializer(new Lt),t.addSerializer(new Ft),t.addSerializer(new Ht),t.addSerializer(new Gt),t.addSerializer(new $t),t.addSerializer(new Vt),t.addSerializer(new Wt),t.addSerializer(new Et),t.addSerializer(new Ut),"undefined"!=typeof Buffer&&t.addSerializer(new Ot),t}}class Xt{#ot;constructor(e){this.#ot=e}resolveKey(e){const t=this.#ot.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#ot.getClass(e);return t?.implementation}}class Qt extends P{constructor(){super("Request not trusted")}}const Zt="X-Jitar-Trust-Key",Yt="X-Jitar-Data-Encoding",er="serialized";class tr{#Le;#ye;#Ee;#ct;#lt;#ot;#Ce;#ut;#ht;#Te=new ut;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#ct=e.gateway,this.#lt=!0===e.registerAtGateway,this.#ot=e.executionManager,this.#Ce=e.healthManager;const t=e.scheduleManager;this.#ut=t.create(()=>this.#dt(),e.reportInterval);const r=new Xt(this.#ot);this.#ht=Jt.build(r)}get id(){return this.#Le}set id(e){this.#Le=e}get state(){return this.#Te.state}get url(){return this.#ye}get trustKey(){return this.#Ee}async start(){return this.#Te.start(async()=>{await Promise.all([this.#ot.start(),this.#Ce.start()]),void 0!==this.#ct&&(await this.#ct.start(),this.#lt&&(this.#Le=await this.#ct.addWorker(this),this.#ut.start())),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{void 0!==this.#ct&&(void 0!==this.#Le&&(this.#ut.stop(),await this.#ct.removeWorker(this.#Le)),await this.#ct.stop()),await Promise.all([this.#Ce.stop(),this.#ot.stop()])})}getProcedureNames(){return this.#ot.getProcedureNames()}hasProcedure(e){return this.#ot.hasProcedure(e)}isHealthy(){return this.#Ce.isHealthy()}getHealth(){return this.#Ce.getHealth()}isAvailable(){return this.#Te.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Te.setAvailability(e)}async reportState(e){if(void 0!==this.#ct&&void 0!==this.#Le)return this.#ct.reportWorker(this.#Le,e)}async run(e){return this.#pt(e)?this.#gt(e):this.#mt(e)}#pt(e){return void 0===this.#ct||this.#ot.hasProcedure(e.fqn)}async#gt(e){const t=this.#ot.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#wt(r))throw new Me(e.fqn);if(this.#ft(e,r))throw new Qt;const s=e.getHeader(Yt);s===er&&(e=await this.#yt(e)),e.removeHeader(Yt);const a=await this.#ot.run(e);return s===er?this.#vt(a):a}#wt(e){return void 0===e||e.private}#ft(e,t){if(t.public)return!1;const r=e.getHeader(Zt);return this.#Ee!==r}async#mt(e){(e=await this.#bt(e)).setHeader(Yt,er),void 0!==this.#Ee&&e.setHeader(Zt,this.#Ee);const t=await this.#ct.run(e);return this.#Mt(t)}async#bt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#ht.serialize(s);t.set(r,e)}return new B(e.fqn,e.version,t,e.headers,e.mode)}async#yt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#ht.deserialize(s);t.set(r,e)}return new B(e.fqn,e.version,t,e.headers,e.mode)}async#vt(e){const t=await this.#ht.serialize(e.result);return new R(e.status,t,e.headers)}async#Mt(e){const t=await this.#ht.deserialize(e.result);return new R(e.status,t,e.headers)}async#dt(){const e=await this.updateState();return this.reportState(e)}}class rr extends ut{#St;#xt;#kt=Date.now();#Pt=Date.now();constructor(e=6e3,t=18e3){super(),this.#St=e,this.#xt=t}report(e){this.#kt=Date.now(),this.state=e}update(){this.#Pt=Date.now();const e=this.#Pt-this.#kt;return e>=this.#St&&(this.state=e>=this.#xt?ot.STOPPED:ot.UNAVAILABLE),this.state}}class sr{#Le;#ye;#Ee;#At;#Ie;#Te;constructor(e){this.#ye=e.url,this.#Ee=e.trustKey,this.#At=e.procedureNames,this.#Ie=e.remote,this.#Te=new rr(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#Le}set id(e){this.#Le=e}get state(){return this.#Te.state}get url(){return this.#ye}get trustKey(){return this.#Ee}async start(){return this.#Te.start(async()=>{await this.#Ie.connect(),await this.updateState()})}async stop(){return this.#Te.stop(async()=>{await this.#Ie.disconnect()})}getProcedureNames(){return[...this.#At.values()]}hasProcedure(e){return this.#At.has(e)}isHealthy(){return this.#Ie.isHealthy()}getHealth(){return this.#Ie.getHealth()}isAvailable(){return this.#Te.isAvailable()}async updateState(){return this.#Te.update()}async reportState(e){this.#Te.report(e)}run(e){return this.#Ie.run(e)}}class ar{#zt;#St;#xt;constructor(e,t,r){this.#zt=e,this.#St=t,this.#xt=r}build(e,t,r){const s=this.#zt.build(e),a=new Set(t),n=this.#St,i=this.#xt;return new sr({url:e,trustKey:r,remote:s,procedureNames:a,unavailableThreshold:n,stoppedThreshold:i})}}class nr{#_e;constructor(e){this.#_e=e}async handle(e,t){return this.#_e.run(e)}}class ir{#Rt=new q;constructor(){this.#Et()}#Et(){const e=globalThis;e.__run=this.#Ct.bind(this),e.ProcedureNotAccessible=Se}async#Ct(e,t,r,s){const a=this.#Rt.parse(t),n=new Map(Object.entries(r)),i=s instanceof B?s.headers:new Map,o=new B(e,a,n,i,ue),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const l=await this.runInternal(o);if(l.status!==de)throw l.result;return l.result}}const or="starting",cr="started",lr="stopping",ur="stopped";class hr extends A{constructor(){super("Invalid health check")}}class dr extends Error{constructor(e){super("Starting health manager failed",{cause:e})}}class pr extends Error{constructor(e){super("Stopping health manager failed",{cause:e})}}class gr{#Ae=ur;#Ht=new Map;#V;#Tt;constructor(e,t=[]){this.#V=e,this.#Tt=t}get state(){return this.#Ae}async start(){if(this.#Ae===ur)try{this.#Ae=or,await this.#Ot(),this.#Ae=cr}catch(e){throw this.#Ae=ur,new dr(e)}}async stop(){if(this.#Ae===cr)try{this.#Ae=lr,this.clearHealthChecks(),this.#Ae=ur}catch(e){throw this.#Ae=cr,new pr(e)}}async loadHealthCheck(e){const t=await this.#It(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new hr;this.#Ht.set(e.name,e)}clearHealthChecks(){this.#Ht.clear()}async isHealthy(){const e=[];for(const t of this.#Ht.values()){const r=this.#Nt(t);e.push(r)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,r]of this.#Ht){const s=this.#Nt(r).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(s)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#jt(e,t))).then(()=>t)}async#Ot(){(await Promise.all(this.#Tt.map(e=>this.#It(e)))).forEach(e=>this.addHealthCheck(e))}async#It(e){return(await this.#V.import(e)).default}#jt(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#Nt(e){const t=e.isHealthy(),r=e.timeout;if(void 0===r)return t;const s=new Promise(e=>{setTimeout(e,r)}).then(()=>!1);return Promise.race([s,t])}}const mr="starting",wr="started",fr="stopping",yr="stopped";class vr extends A{constructor(){super("Invalid middleware")}}class br extends Error{constructor(e){super("Starting middleware manager failed",{cause:e})}}class Mr extends Error{constructor(e){super("Stopping middleware manager failed",{cause:e})}}class Sr{#Ae=yr;#$t=[];#V;#Lt;constructor(e,t=[]){this.#V=e,this.#Lt=t}get state(){return this.#Ae}async start(){if(this.#Ae===yr)try{this.#Ae=mr,await this.#Wt(),this.#Ae=wr}catch(e){throw this.#Ae=yr,new br(e)}}async stop(){if(this.#Ae===wr)try{this.#Ae=fr,this.clearMiddlewares(),this.#Ae=yr}catch(e){throw this.#Ae=wr,new Mr(e)}}async loadMiddleware(e){const t=await this.#Bt(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new vr;this.#$t.push(e)}getMiddleware(e){return this.#$t.find(t=>t instanceof e)}clearMiddlewares(){this.#$t=[]}handle(e){return this.#qt(e,0)()}async#Wt(){(await Promise.all(this.#Lt.map(e=>this.#Bt(e)))).forEach(e=>this.addMiddleware(e))}async#Bt(e){return(await this.#V.import(e)).default}#qt(e,t){const r=this.#$t[t];if(void 0===r)return async()=>new R(de);const s=this.#qt(e,t+1);return async()=>await r.handle(e,s)}}class xr{#ne;#Dt;#Ft;#Vt=null;constructor(e,t,r=5e3){this.#ne=e,this.#Dt=t,this.#Ft=r}start(){this.#Kt()}stop(){null!==this.#Vt&&(clearTimeout(this.#Vt),this.#Vt=null)}#Kt(){this.#Vt=setTimeout(async()=>{null!==this.#Vt&&(await this.#Ut(),this.#Kt())},this.#Ft),this.#Vt.unref()}async#Ut(){try{await this.#Dt()}catch(e){this.#ne.warn("Scheduled task failed",e)}}}class kr{#_t=[];#ne;constructor(e){this.#ne=e}create(e,t){const r=new xr(this.#ne,e,t);return this.#_t.push(r),r}remove(e){const t=this.#_t.indexOf(e);t<0||this.#_t.splice(t,1)}startAll(){this.#_t.forEach(e=>e.start())}stopAll(){this.#_t.forEach(e=>e.stop())}}const Pr="application/null",Ar="application/undefined",zr="application/boolean",Rr="application/number",Er="application/json",Cr="text/plain",Hr=200,Tr=400,Or=401,Ir=402,Nr=403,jr=404,$r=418,Lr=500,Wr=501;class Br extends Error{constructor(e){super("Starting server failed",{cause:e})}}class qr extends Error{constructor(e){super("Stopping server failed",{cause:e})}}class Dr extends ir{#Gt;#Jt;#Xt;#Qt;#ne;#Rt=new q;constructor(e){super(),this.#Gt=e.proxy,this.#Jt=e.remoteWorkerBuilder,this.#Xt=e.resourceManager,this.#Qt=e.middlewareManager,this.#ne=e.logger}get proxy(){return this.#Gt}getTrustKey(){return this.#Gt.trustKey}async start(){try{await this.#Zt(),this.#ne.info(`Server started at ${this.#Gt.url}`),this.#Gt.runner instanceof tr&&this.#ne.info("RPC procedures:",this.#Gt.runner.getProcedureNames())}catch(e){throw new Br(e)}}async stop(){try{await this.#Yt(),this.#ne.info("Server stopped")}catch(e){throw new qr(e)}}async getHealth(){try{const e=await this.#Gt.getHealth();return this.#ne.debug("Got health"),this.#er(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ne.error(`Failed to get health (${t})`),this.#tr(e)}}async isHealthy(){try{const e=await this.#Gt.isHealthy();return this.#ne.debug("Got health status"),this.#rr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ne.error(`Failed to get health status (${t})`),this.#tr(e)}}async provide(e){try{const t=await this.#Gt.provide(e.filename),r=t.location!==e.filename?`${e.filename} => ${t.location}`:e.filename;return this.#ne.info(`Provided file: ${r}`),this.#sr(t)}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.warn(`Failed to provide file: ${e.filename} (${r})`),this.#tr(t)}}async run(e){try{const t=this.#ar(e),r=await this.#Qt.handle(t);return this.#ne.info(`Ran request: ${t.fqn}`),this.#nr(r)}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed run request: ${e.fqn} (${r})`),this.#tr(t)}}async runInternal(e){return this.#Gt.run(e)}async addWorker(e){try{const t=this.#ir(),r=this.#Jt.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#ne.info(`Added worker: ${r.url}`),this.#or({id:s})}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed to add worker: ${e.url} (${r})`),this.#tr(t)}}async reportWorker(e){try{const t=this.#cr(e.state),r=this.#ir();return await r.reportWorker(e.id,t),this.#ne.debug(`Reported worker: ${e.id}`),this.#or()}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed to report worker: ${e.id} (${r})`),this.#tr(t)}}async removeWorker(e){try{const t=this.#ir();return await t.removeWorker(e.id),this.#ne.info(`Removed worker: ${e.id}`),this.#or()}catch(t){const r=t instanceof Error?t.message:String(t);return this.#ne.error(`Failed to remove worker: ${e.id} (${r})`),this.#tr(t)}}async#Zt(){await this.#Xt.start(),await Promise.all([this.#Gt.start(),this.#Qt.start()]);const e=new nr(this.#Gt);this.#Qt.addMiddleware(e)}async#Yt(){await Promise.all([this.#Qt.stop(),this.#Gt.stop()]),await this.#Xt.stop()}#ar(e){const t=this.#lr(e.fqn),r=this.#ur(e.version),s=this.#hr(e.args),a=this.#dr(e.headers);return new B(t,r,s,a,e.mode)}#lr(e){if(0===e.length)throw new y("Missing procedure name");if(e.includes(".."))throw new y("Invalid procedure name");return e}#ur(e){return"string"!=typeof e?D.DEFAULT:this.#Rt.parse(e)}#hr(e){return new Map(Object.entries(e))}#dr(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();t.set(e,a)}return t}#cr(e){if(!1===Object.values(ot).includes(e))throw new y("Invalid state value");return e}#er(e){return{result:Object.fromEntries(e),contentType:Er,headers:{},status:Hr}}#rr(e){return{result:e,contentType:zr,headers:{},status:Hr}}#sr(e){return{result:e.content,contentType:e.type,headers:{},status:Hr}}#nr(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#pr(t),headers:this.#gr(e.headers),status:e.status}}#tr(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#pr(t),headers:{},status:this.#mr(e)}}#or(e){return{result:e,contentType:this.#pr(e),headers:{},status:Hr}}#pr(e){if(void 0===e)return Ar;if(null===e)return Pr;switch(typeof e){case"boolean":return zr;case"number":return Rr;case"object":return Er;default:return Cr}}#gr(e){return Object.fromEntries(e)}#mr(e){return e instanceof y?Tr:e instanceof f?Nr:e instanceof w?jr:e instanceof S?Wr:e instanceof x?Ir:e instanceof k?$r:e instanceof P?Or:Lr}#ir(){const e=this.#Gt.runner;if(e instanceof dt==!1)throw new y("Cannot remove worker from remote gateway");return e}}class Fr extends Error{constructor(){super("Unknown service configured")}}class Vr{#Ge;#wr;#fr;constructor(e,t=[],r=[]){this.#Ge=e,this.#wr=t,this.#fr=r}async start(){return this.#yr()}async stop(){return this.#vr()}#yr(){return this.#br(this.#wr)}#vr(){return this.#br(this.#fr)}async#br(e){await Promise.all(e.map(e=>this.#Ge.import(e)))}}class Kr{#Ge;#zt;constructor(e,t){this.#Ge=e,this.#zt=t}async build(e,t){const r=e.setUp,s=e.tearDown,a=e.middleware,n=e.healthChecks,i=new Fe(t),o=this.#Mr(n),c=this.#Sr(i),l=await this.#xr(e,o,c),u=this.#Ge,h=this.#kr(r,s),d=this.#Pr(a),p=this.#Ar(e);return new Dr({proxy:l,sourcingManager:u,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#xr(e,t,r){if(void 0!==e.gateway)return this.#zr(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#Rr(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Er(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Cr(e.url,e.proxy);if(void 0!==e.standalone)return this.#Hr(e.url,e.standalone,t,r);throw new Fr}async#zr(e,t,r,s){const a=new ct,n=this.#Tr(e,t,r,s);return new vt({url:e,provider:a,runner:n})}async#Rr(e,t,r,s){const a=new ct,n=this.#Or(e,t,r,s);return new vt({url:e,provider:a,runner:n})}async#Er(e,t,r){const s=await this.#Ir(e,t,r),a=new lt;return new vt({url:e,provider:s,runner:a})}#Tr(e,t,r,s){const a=t.trustKey,n=t.monitorInterval,i=new yt(s,n);return new dt({url:e,trustKey:a,healthManager:r,workerManager:i})}#Nr(e){const t=this.#zt.build(e);return new pt({url:e,remote:t})}#Or(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Nr(t.gateway):void 0,i=t.reportInterval,o=void 0!==n,c=this.#jr(t.segments);return new tr({url:e,trustKey:a,reportInterval:i,gateway:n,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#Ir(e,t,r){const s=void 0!==t.assetRoot?this.#Ge.fork(t.assetRoot):this.#Ge,a=await this.#$r(s,t.assets),n=t.directoryIndex,i=t.fallback;return new bt({url:e,sourcingManager:s,assets:a,directoryIndex:n,fallback:i,healthManager:r})}#Lr(e){const t=this.#zt.build(e);return new Mt({url:e,remote:t})}async#Cr(e,t){const r=this.#Lr(t.repository),s=this.#Nr(t.gateway);return new vt({url:e,provider:r,runner:s})}async#Hr(e,t,r,s){const a=await this.#Ir(e,t,r),n=this.#Or(e,t,r,s);return new vt({url:e,provider:a,runner:n})}#kr(e=[],t=[]){const r=e.map(e=>this.#Wr(e)),s=t.map(e=>this.#Wr(e));return new Vr(this.#Ge,r,s)}#Mr(e=[]){const t=e.map(e=>this.#Wr(e));return new gr(this.#Ge,t)}#Pr(e=[]){const t=e.map(e=>this.#Wr(e));return new Sr(this.#Ge,t)}#jr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Oe(this.#Ge,t)}#Sr(e){return new kr(e)}#Ar(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new ar(this.#zt,t,r)}async#$r(e,t){if(void 0===t)return new Set;const r=await e.filter(...t);return new Set(r)}#Wr(e){return e.endsWith(".js")?e:e+".js"}}const Ur="3000",_r=204800,Gr=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class Jr{#Br;#qr;#Dr;#Fr;#be=new $;constructor(e,t=Ur,r=_r){this.#Br=e,this.#qr=t,this.#Dr=V(),this.#Vr(r),this.#Kr()}async start(){return await this.#Br.start(),this.#Ur()}async stop(){return await this.#_r(),this.#Br.stop()}#Vr(e){this.#Dr.use(V.json({limit:e})),this.#Dr.use(V.urlencoded({extended:!1})),this.#Dr.use(this.#Gr.bind(this)),this.#Dr.disable(Ye)}#Kr(){this.#Dr.get("/health",(e,t)=>{this.#Jr(e,t)}),this.#Dr.get("/health/status",(e,t)=>{this.#Xr(e,t)}),this.#Dr.get("/rpc/*procedure",(e,t)=>{this.#Qr(e,t)}),this.#Dr.post("/rpc/*procedure",(e,t)=>{this.#Zr(e,t)}),this.#Dr.options("/rpc/*procedure",(e,t)=>{this.#Yr(e,t)}),this.#Dr.post("/workers",(e,t)=>{this.#es(e,t)}),this.#Dr.post("/workers/:id/report",(e,t)=>{this.#ts(e,t)}),this.#Dr.delete("/workers/:id",(e,t)=>{this.#rs(e,t)}),this.#Dr.use((e,t)=>{this.#ss(e,t)})}#Ur(){return void 0!==this.#Fr?Promise.resolve():new Promise((e,t)=>{this.#Fr=this.#Dr.listen(this.#qr,t),e()})}#_r(){return void 0===this.#Fr?Promise.resolve():new Promise(e=>{this.#Fr.close(()=>e())})}#Gr(e,t,r){t.setHeader(Xe,et),r()}async#Jr(e,t){const r=await this.#Br.getHealth();return this.#as(t,r)}async#Xr(e,t){const r=await this.#Br.isHealthy();return this.#as(t,r)}async#Qr(e,t){const r=this.#ns(e),s=this.#is(e),a=this.#os(e),n=this.#cs(e),i=ue,o=await this.#Br.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#Zr(e,t){const r=this.#ns(e),s=this.#is(e),a=this.#ls(e),n=this.#cs(e),i=ue,o=await this.#Br.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#Yr(e,t){const r=this.#ns(e),s=this.#is(e),a=this.#ls(e),n=this.#cs(e),i=he,o=await this.#Br.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#as(t,o)}async#es(e,t){const r=this.#ls(e),s=this.#be.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.url,n=r.procedureNames,i=r.trustKey;try{const e=await this.#Br.addWorker({url:a,procedureNames:n,trustKey:i});return this.#as(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ts(e,t){const r={id:e.params.id,state:e.body.state},s=this.#be.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id,n=r.state;try{const e=await this.#Br.reportWorker({id:a,state:n});return this.#as(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#rs(e,t){const r={id:e.params.id},s=this.#be.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id;try{const e=await this.#Br.removeWorker({id:a});return this.#as(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ss(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),a=await this.#Br.provide({filename:s});return this.#as(t,a)}#ns(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#is(e){const t=e.headers[Ze];return Array.isArray(t)?t[0]:t}#os(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#ls(e){return e.body}#cs(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();Gr.includes(e)||(t[e]=a)}return t}#as(e,t){const r=this.#us(t),s=this.#hs(t);e.status(r),e.setHeader(Je,s),e.setHeader(Qe,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const a=this.#ds(t);return e.send(a)}#us(e){return void 0!==e.headers.location?302:e.status}#hs(e){const t=e.contentType.toLowerCase();switch(t){case zr:case Rr:case Ar:case Pr:return Cr}return t}#ds(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class Xr{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),a=e.getOptionalArgument("--log-level",void 0),n=this.#fe(a),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#ps(i),c=new j;await c.configureEnvironment(t);const l=await c.getRuntimeConfiguration(r),u=await c.getServiceConfiguration(s),h=await this.#gs(l,u,o,n);return this.#ms(h)}async#gs(e,t,r,s){const[,,a]=t.url.split(":"),n=new ie(e.target),i=new it,o=new Kr(n,i),c=await o.build(t,s);return new Jr(c,a,r)}#ms(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#fe(e){if(void 0===e)return;return(new Ke).parse(e)}#ps(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class Qr extends Error{constructor(e){super(`Command ${e} not found`)}}class Zr{#s=new Set;constructor(){this.#s.add(new _(this.#s)),this.#s.add(new G),this.#s.add(new J),this.#s.add(new ee),this.#s.add(new Ge),this.#s.add(new Xr)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new Qr(e)}}class Yr{#ws;#fs;constructor(){this.#ws=new U(process.argv),this.#fs=new Zr}start(){const e=this.#ws.getCommand()??"help";return this.#fs.run(e,this.#ws)}}const es=new Fe;try{const e=new Yr;await e.start()}catch(t){es.fatal(t),e.exitCode=1}
|
|
2
|
+
import process$1 from"node:process";import{createRequire}from"node:module";import{promises}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";import{L as LocalFileManager,E as ESClass,P as Parser,a as ESIdentifierBinding,b as ESExpression,c as ESVariable,d as ESModule,e as ESField,f as ESConstructor,g as ESGetter,h as ESSetter,i as ESMethod,N as NotFound,B as BadRequest,F as Forbidden,j as NamedParameter,A as ArrayParameter,O as ObjectParameter,k as NotImplemented,l as PaymentRequired,T as Teapot,U as Unauthorized,S as ServerError,m as Segment,R as Response,n as FileHelper,o as LocalGenerator,p as RemoteGenerator,G as Generator,q as ProjectFileManager,r as Reader,s as Files,C as ConfigurationManager,V as Validator,t as File,u as FileNotFound,v as Request,w as VersionParser,x as Class,I as InvalidVersionNumber,y as Version}from"./ConfigurationManager-BWtWRzof.js";import crypto from"node:crypto";import express from"express";import"glob";import"mime-types";import"dotenv";class MissingArgument extends Error{constructor(name){super(`Missing argument '${name}'`)}}class ArgumentProcessor{#command;#args;constructor(args){this.#command=args[2],this.#args=this.#parseArguments(args)}getCommand(){return this.#command}containsKey(key){return this.#args.has(key)}getRequiredArgument(name){const value=this.#args.get(name);if(void 0===value)throw new MissingArgument(name);return value}getOptionalArgument(name,defaultValue){return this.#args.get(name)??defaultValue}#parseArguments(args){const commandArgs=args.slice(3),map=new Map;return commandArgs.forEach(arg=>{const[key,value]=arg.split("=");map.set(key.trim(),value?.trim())}),map}}class ShowHelp{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#commands;constructor(commands){this.#commands=commands}async execute(args){for(const command of this.#commands.values())if(args.containsKey(command.name))return this.#showCommandDetails(command);this.#listCommands()}#listCommands(){console.log("\njitar <command>\n"),console.log("Available commands:");const commands=[...this.#commands.values()],commandNames=commands.map(command=>command.name),paddingSize=this.#determinePaddingSize(commandNames);for(const command of commands){const name=command.name.padEnd(paddingSize," "),description=command.description;console.log(` ${name} ${description}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#showCommandDetails(command){console.log(`\n${command.description}\n`);const options=command.options;if(0===options.length)return void console.log("No options available.\n");console.log("Options:");const optionKeys=options.map(option=>option.key),paddingSize=this.#determinePaddingSize(optionKeys);for(const option of options){const key=option.key.padEnd(paddingSize," "),description=option.description,defaultValue=option.defaultValue?`default: ${option.defaultValue}`:"no default value",required=option.required?"required":`optional - ${defaultValue}`;console.log(` ${key} ${description} (${required})`)}console.log()}#determinePaddingSize(labels){return labels.reduce((maxSize,label)=>label.length>maxSize?label.length:maxSize,0)+3}}class ShowAbout{name="about";description="Shows information about Jitar.";options=[];async execute(args){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")}}const require$1=createRequire(import.meta.url);class ShowVersion{name="version";description="Shows the installed version of Jitar.";options=[];#versionNumber;constructor(){this.#versionNumber=this.#getVersionNumber()}async execute(args){console.log(`v${this.#versionNumber}`)}#getVersionNumber(){try{const{version:version}=require$1("../package.json");return version??"0.0.0"}catch{return"0.0.0"}}}class InvalidName extends Error{constructor(name,type){super(`Invalid ${type} name: ${name}`)}}class UnknownTemplate extends Error{constructor(templateName){super(`Unknown template: ${templateName}`)}}const NAME_REGEX=/^[a-zA-Z.\-_]+$/;class InitManager{#templateRootPath;#projectRootPath;constructor(rootPath="./"){this.#templateRootPath=this.#createTemplateRootPath(),this.#projectRootPath=this.#createProjectRootPath(rootPath)}async init(projectName,templateName){this.#validateName(projectName,"project"),this.#validateName(templateName,"template");if(!1===await this.#verifyTemplateName(templateName))throw new UnknownTemplate(templateName);await this.#copyTemplate(projectName,templateName)}#createTemplateRootPath(){const runtimePath=path.dirname(fileURLToPath(import.meta.url));return path.join(runtimePath,"templates")}#createProjectRootPath(rootPath){return path.resolve(rootPath)}#validateName(name,type){if(!1===NAME_REGEX.test(name))throw new InvalidName(name,type)}async#verifyTemplateName(templateName){try{const location=path.join(this.#templateRootPath,templateName);return(await promises.stat(location)).isDirectory()}catch{return!1}}#copyTemplate(projectName,templateName){const templateLocation=path.join(this.#templateRootPath,templateName),projectLocation=path.join(this.#projectRootPath,projectName);return promises.cp(templateLocation,projectLocation,{recursive:!0,force:!0})}}class InitApp{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(args){const projectName=args.getRequiredArgument("--name"),templateName=args.getRequiredArgument("--template"),rootPath=args.getOptionalArgument("--location",void 0);this.#printStartupMessage(projectName,templateName),await this.#initProject(projectName,templateName,rootPath),this.#printNextSteps(projectName)}#printStartupMessage(projectName,templateName){console.log(`Initializing project '${projectName}' with '${templateName}' template.`)}#initProject(projectName,templateName,rootPath){return new InitManager(rootPath).init(projectName,templateName)}#printNextSteps(projectName){console.log(`SUCCESS! Run the following commands to continue:\ncd ${projectName}\nnpm install\nnpm run build\nnpm run standalone`)}}class ModuleNotLoaded extends Error{constructor(url,cause){super(`Module could not be loaded from '${url}'`,{cause:cause})}}class ImportManager{#moduleLocator;constructor(moduleLocator){this.#moduleLocator=moduleLocator}async import(filename){const location=this.#moduleLocator.locate(filename);try{return await(import(location))}catch(error){throw new ModuleNotLoaded(location,error)}}}class LocalModuleLocator{#fileManager;constructor(fileManager){this.#fileManager=fileManager}locate(filename){return`file://${filename.startsWith("/")?this.#fileManager.getAbsoluteLocation(`.${filename}`):this.#fileManager.getAbsoluteLocation(filename)}`}}class LocalImportManager extends ImportManager{constructor(fileManager){super(new LocalModuleLocator(fileManager))}}class SourcingManager{#fileManager;#importManager;constructor(fileManager,importManager){this.#fileManager=fileManager,this.#importManager=importManager}get fileManager(){return this.#fileManager}get importManager(){return this.#importManager}async filter(...patterns){return(await Promise.all(patterns.map(pattern=>this.#fileManager.filter(pattern)))).flat().map(file=>this.#fileManager.getRelativeLocation(file))}exists(filename){return this.#fileManager.exists(filename)}read(filename){return this.#fileManager.read(filename)}import(filename){return this.#importManager.import(filename)}}class LocalSourcingManager extends SourcingManager{constructor(location){const fileManager=new LocalFileManager(location);super(fileManager,new LocalImportManager(fileManager))}fork(location){const absoluteLocation=this.fileManager.getAbsoluteLocation(location);return new LocalSourcingManager(absoluteLocation)}}class ClassMerger{merge(model,parent){const constructors=void 0!==model.construct?[model.construct]:[],members=[...this.#mergeMembers(model.fields,parent.fields),...constructors,...this.#mergeMembers(model.methods,parent.methods),...this.#mergeMembers(model.getters,parent.getters),...this.#mergeMembers(model.setters,parent.setters)];return new ESClass(model.identifier,parent.identifier,members)}#mergeMembers(model,parent){const members=new Map;return parent.forEach(member=>members.set(member.identifier,member)),model.forEach(member=>members.set(member.identifier,member)),[...members.values()]}}class Reflector{#parser=new Parser;#merger=new ClassMerger;fromModule(module,inherit=!1){const entries=Object.entries(module),members=[];for(const[key,member]of entries){if("function"!=typeof member.toString)continue;const code=member.toString();if(code.startsWith("class"))members.push(this.fromClass(member,inherit));else if(code.startsWith("function"))members.push(this.fromFunction(member));else{const binding=new ESIdentifierBinding(key,!1),expression=new ESExpression(code);members.push(new ESVariable("var",binding,expression))}}return new ESModule(members)}fromClass(clazz,inherit=!1){const model=this.isClass(clazz)?this.#reflectClassStatic(clazz):this.#reflectClassDynamic(clazz);if(!1===inherit)return model;const parentClazz=this.getParentClass(clazz);if(""===parentClazz.name)return model;const parentModel=this.fromClass(parentClazz,!0);return this.#merger.merge(model,parentModel)}fromObject(object,inherit=!0){const clazz=this.getClass(object);return this.fromClass(clazz,inherit)}fromFunction(funktion){const code=funktion.toString();return this.#parser.parseFunction(code)}createInstance(clazz,args=[]){return new clazz(...args)}getClass(object){return object.constructor}getParentClass(clazz){return Object.getPrototypeOf(clazz)}isClassObject(object){return this.isClass(object.constructor)}isFunctionObject(object){return this.isFunction(object.constructor)}isClass(clazz){return clazz.toString().startsWith("class")}isFunction(clazz){return clazz.toString().startsWith("function")||clazz.toString().startsWith("async function")}#reflectClassStatic(clazz){const code=clazz.toString();return this.#parser.parseClass(code)}#reflectClassDynamic(clazz){const instance=this.createInstance(clazz),members=this.#getClassMembers(clazz,instance);return new ESClass(clazz.name,void 0,members)}#getClassMembers(clazz,instance){return[...this.#getClassFields(instance),...this.#getClassMethods(clazz)]}#getClassFields(instance){const fieldNames=Object.getOwnPropertyNames(instance),values=instance,models=[];for(const fieldName of fieldNames){const content=values[fieldName],initializer=void 0!==content?new ESExpression(String(content)):void 0,model=new ESField(fieldName,"public","instance",initializer);models.push(model)}return models}#getClassMethods(clazz){const functionDescriptions=Object.getOwnPropertyDescriptors(clazz.prototype),models=[];for(const functionName in functionDescriptions){const description=functionDescriptions[functionName],method=description.value;if(method instanceof Function==!1)continue;const model=this.fromFunction(method);"constructor"===model.identifier?models.push(new ESConstructor(model.parameters,model.body)):void 0!==description.get?models.push(new ESGetter(model.identifier,"public","instance",model.body)):void 0!==description.set?models.push(new ESSetter(model.identifier,"public","instance",model.parameters[0],model.body)):models.push(new ESMethod(model.identifier,"public","instance",model.parameters,model.body,model.isAsync))}return models}}class BuildingModuleFailed extends Error{constructor(filename,cause){super(`Failed building module for '${filename}'`,{cause:cause})}}const RunModes_NORMAL="normal",RunModes_DRY="dry",StatusCodes$1_OK=200,StatusCodes$1_BAD_REQUEST=400,StatusCodes$1_UNAUTHORIZED=401,StatusCodes$1_PAYMENT_REQUIRED=402,StatusCodes$1_FORBIDDEN=403,StatusCodes$1_NOT_FOUND=404,StatusCodes$1_TEAPOT=418,StatusCodes$1_SERVER_ERROR=500,StatusCodes$1_NOT_IMPLEMENTED=501;class ImplementationNotFound extends NotFound{#fqn;#version;constructor(fqn,version){super(`No implementation found for procedure '${fqn}' with version '${version}'`),this.name="ImplementationNotFound",this.#fqn=fqn,this.#version=version}get fqn(){return this.#fqn}get version(){return this.#version}}class InvalidParameterValue extends BadRequest{#parameterName;constructor(parameterName){super(`Invalid value for parameter '${parameterName}'`),this.name="InvalidParameterValue",this.#parameterName=parameterName}get parameterName(){return this.#parameterName}}class MissingParameterValue extends BadRequest{#parameterName;constructor(parameterName){super(`Missing value for parameter '${parameterName}'`),this.name="MissingParameterValue",this.#parameterName=parameterName}get parameterName(){return this.#parameterName}}class ProcedureNotAccessible extends Forbidden{constructor(fqn,versionNumber){super(`Procedure '${fqn}' (v${versionNumber}) is not accessible`)}}class ProcedureNotFound extends NotFound{#fqn;constructor(fqn){super(`Procedure '${fqn}' not found`),this.name="ProcedureNotFound",this.#fqn=fqn}get fqn(){return this.#fqn}}class UnknownParameter extends BadRequest{#parameterName;constructor(parameterName){super(`Unknown parameter ${parameterName}`),this.name="UnknownParameter",this.#parameterName=parameterName}get parameterName(){return this.#parameterName}}class ArgumentExtractor{extract(parameters,args){const argsCopy=this.#copyArguments(parameters,args),values=[];for(const parameter of parameters){const value=this.#extractArgumentValue(parameter,argsCopy);values.push(value)}if(argsCopy.size>0){const name=argsCopy.keys().next().value;throw new UnknownParameter(name)}return values}#copyArguments(parameters,args){const copy=new Map;for(const[key,value]of args){if(this.#isOptionalArgument(key)){const name=this.#getParameterName(key);!0===this.#containsParameter(parameters,name)&©.set(name,value);continue}copy.set(key,value)}return copy}#isOptionalArgument(argument){return argument.startsWith("*")}#getParameterName(argument){return argument.substring(1)}#containsParameter(parameters,name){return void 0!==parameters.find(parameter=>parameter.name===name)}#extractArgumentValue(parameter,args,parent){return parameter instanceof NamedParameter?this.#extractNamedArgumentValue(parameter,args,parent):this.#extractDestructedArgumentValue(parameter,args)}#extractNamedArgumentValue(parameter,args,parent){const value=args.get(parameter.name);if(this.#isMissingParameterValue(parameter,value,parent))throw new MissingParameterValue(parameter.name);if(this.#isInvalidRestParameter(parameter,value,parent))throw new InvalidParameterValue(parameter.name);return args.delete(parameter.name),value}#extractDestructedArgumentValue(parameter,args){return parameter instanceof ArrayParameter?this.#extractArrayArgumentValue(parameter,args):this.#extractObjectArgumentValue(parameter,args)}#extractArrayArgumentValue(parameter,args){const values=this.#extractVariableValues(parameter,args);return void 0!==values?Object.values(values):void 0}#extractObjectArgumentValue(parameter,args){return this.#extractVariableValues(parameter,args)}#extractVariableValues(parameter,args){const useIndex=parameter instanceof ArrayParameter,values={},missingValues=[];let containsValues=!1,index=0;for(const variable of parameter.variables){const key=useIndex?index++:variable.name,value=this.#extractArgumentValue(variable,args,parameter);void 0!==value?containsValues=!0:!1===variable.isOptional&&missingValues.push(variable.name),values[key]=value}if(!0===containsValues&&missingValues.length>0)throw new MissingParameterValue(missingValues[0]);return containsValues?values:void 0}#isMissingParameterValue(parameter,value,parent){return void 0===value&&(!0!==parameter.isOptional&&!0!==parent?.isOptional)}#isInvalidRestParameter(parameter,value,parent){return!1!==parameter.name.startsWith("...")&&(void 0===parent&&value instanceof Array==!1||parent instanceof ArrayParameter&&value instanceof Array==!1||parent instanceof ObjectParameter&&value instanceof Object==!1)}}class ErrorConverter{toStatus(error){return error instanceof BadRequest?StatusCodes$1_BAD_REQUEST:error instanceof Forbidden?StatusCodes$1_FORBIDDEN:error instanceof NotFound?StatusCodes$1_NOT_FOUND:error instanceof NotImplemented?StatusCodes$1_NOT_IMPLEMENTED:error instanceof PaymentRequired?StatusCodes$1_PAYMENT_REQUIRED:error instanceof Teapot?StatusCodes$1_TEAPOT:error instanceof Unauthorized?StatusCodes$1_UNAUTHORIZED:StatusCodes$1_SERVER_ERROR}fromStatus(status,message){switch(status){case StatusCodes$1_BAD_REQUEST:return new BadRequest(message);case StatusCodes$1_FORBIDDEN:return new Forbidden(message);case StatusCodes$1_NOT_FOUND:return new NotFound(message);case StatusCodes$1_NOT_IMPLEMENTED:return new NotImplemented(message);case StatusCodes$1_PAYMENT_REQUIRED:return new PaymentRequired(message);case StatusCodes$1_TEAPOT:return new Teapot(message);case StatusCodes$1_UNAUTHORIZED:return new Unauthorized(message);default:return new ServerError(message)}}}class InvalidSegment extends ServerError{constructor(){super("Invalid segment")}}class StartingExecutionManagerFailed extends Error{constructor(cause){super("Starting execution manager failed",{cause:cause})}}class StoppingExecutionManagerFailed extends Error{constructor(cause){super("Stopping execution manager failed",{cause:cause})}}class Application{#segments=new Map;addSegment(segment){this.#segments.set(segment.id,segment)}clearSegments(){this.#segments.clear()}getClassNames(){const names=new Set;for(const segment of this.#segments.values()){segment.getClasses().forEach(clazz=>names.add(clazz.fqn))}return[...names.values()]}hasClass(fqn){return this.getClassNames().includes(fqn)}getClass(fqn){for(const segment of this.#segments.values())if(segment.hasClass(fqn))return segment.getClass(fqn)}getClassByImplementation(implementation){for(const segment of this.#segments.values()){const clazz=segment.getClassByImplementation(implementation);if(void 0!==clazz)return clazz}}getProcedureNames(){const names=new Set;for(const segment of this.#segments.values()){segment.getExposedProcedures().forEach(procedure=>names.add(procedure.fqn))}return[...names.values()]}hasProcedure(fqn){return this.getProcedureNames().includes(fqn)}getProcedure(fqn){for(const segment of this.#segments.values())if(segment.hasProcedure(fqn))return segment.getProcedure(fqn)}}class ExecutionManager{#moduleImporter;#segmentFiles;#argumentConstructor=new ArgumentExtractor;#errorConverter=new ErrorConverter;#application=new Application;constructor(moduleImporter,segmentFiles=[]){this.#moduleImporter=moduleImporter,this.#segmentFiles=segmentFiles}async start(){try{await this.#loadSegments()}catch(error){throw new StartingExecutionManagerFailed(error)}}async stop(){try{return this.#clearSegments()}catch(error){throw new StoppingExecutionManagerFailed(error)}}async loadSegment(filename){const module=await this.#moduleImporter.import(filename);this.addSegment(module.default)}async addSegment(segment){if(segment instanceof Segment==!1)throw new InvalidSegment;this.#application.addSegment(segment)}getClassNames(){return this.#application.getClassNames()}hasClass(fqn){return this.#application.hasClass(fqn)}getClass(fqn){return this.#application.getClass(fqn)}getClassByImplementation(implementation){return this.#application.getClassByImplementation(implementation)}getProcedureNames(){return this.#application.getProcedureNames()}hasProcedure(fqn){return this.#application.hasProcedure(fqn)}getProcedure(fqn){return this.#application.getProcedure(fqn)}async run(request){const implementation=this.#getImplementation(request.fqn,request.version),args=this.#argumentConstructor.extract(implementation.parameters,request.args);return request.mode===RunModes_DRY?new Response(StatusCodes$1_OK,void 0):this.#runImplementation(request,implementation,args)}async#loadSegments(){await Promise.all(this.#segmentFiles.map(filename=>this.loadSegment(filename)))}#clearSegments(){this.#application.clearSegments()}#getImplementation(fqn,version){const procedure=this.#application.getProcedure(fqn);if(void 0===procedure)throw new ProcedureNotFound(fqn);const implementation=procedure.getImplementation(version);if(void 0===implementation)throw new ImplementationNotFound(procedure.fqn,version.toString());return implementation}async#runImplementation(request,implementation,args){try{const result=await implementation.executable.call(request,...args);return new Response(StatusCodes$1_OK,result)}catch(error){const status=this.#errorConverter.toStatus(error);return new Response(status,error)}}}let Builder$2=class{#targetFileManager;#fileHelper=new FileHelper;constructor(targetFileManager){this.#targetFileManager=targetFileManager}async build(application){const repository=application.repository,segmentation=application.segmentation,resources=application.resources,builds=repository.modules.map(module=>this.#buildModule(module,resources,segmentation));await Promise.all(builds)}async#buildModule(module,resources,segmentation){try{const moduleSegments=segmentation.getSegments(module.filename);if(0===moduleSegments.length)return void await this.#buildCommonModule(module,resources,segmentation);const implementationSegments=moduleSegments.filter(segment=>segment.getModule(module.filename)?.hasImplementations()),commonBuild=this.#buildCommonModule(module,resources,segmentation),segmentBuilds=implementationSegments.map(segment=>this.#buildSegmentModule(module,resources,segment,segmentation)),remoteBuild=implementationSegments.length>0?this.#buildRemoteModule(module,moduleSegments):Promise.resolve();await Promise.all([commonBuild,...segmentBuilds,remoteBuild])}catch(error){throw new BuildingModuleFailed(module.filename,error)}}async#buildCommonModule(module,resources,segmentation){const filename=module.filename,code=new LocalGenerator(module,resources,segmentation).generate();return this.#targetFileManager.write(filename,code)}async#buildSegmentModule(module,resources,segment,segmentation){const filename=this.#fileHelper.addSubExtension(module.filename,segment.name),code=new LocalGenerator(module,resources,segmentation,segment).generate();return this.#targetFileManager.write(filename,code)}async#buildRemoteModule(module,segments){const filename=this.#fileHelper.addSubExtension(module.filename,"remote"),code=new RemoteGenerator(module,segments).generate();return this.#targetFileManager.write(filename,code)}};class BuildingSegmentFailed extends Error{constructor(segmentName,cause){super(`Failed building segment '${segmentName}'`,{cause:cause})}}let Builder$1=class{#targetFileManager;#logger;constructor(targetFileManager,logger){this.#targetFileManager=targetFileManager,this.#logger=logger}async build(application){const builds=application.segmentation.segments.map(segment=>this.#buildSegment(segment));await Promise.all(builds)}async#buildSegment(segment){try{const filename=`${segment.name}.segment.js`,code=new Generator(segment).generate();await this.#targetFileManager.write(filename,code),this.#logger.info(`Built ${segment.name} segment (${segment.modules.length} modules, ${segment.procedures.length} procedures, ${segment.classes.length} classes)`)}catch(error){throw new BuildingSegmentFailed(segment.name,error)}}};class Builder{#moduleBuilder;#segmentBuilder;constructor(projectFileManager,logger){const targetFileManager=projectFileManager.target;this.#moduleBuilder=new Builder$2(targetFileManager),this.#segmentBuilder=new Builder$1(targetFileManager,logger)}async build(application){await Promise.all([this.#moduleBuilder.build(application),this.#segmentBuilder.build(application)])}}const LogLevels_DEBUG=0,LogLevels_INFO=1,LogLevels_WARN=2,LogLevels_ERROR=3,LogLevels_FATAL=4;class Logger{#logLevel;#writer;constructor(logLevel=LogLevels_INFO,writer=console){this.#logLevel=logLevel,this.#writer=writer}debug(...message){if(this.#logLevel>LogLevels_DEBUG)return;const messageString=this.#createMessage("DEBUG",message);this.#writer.debug(messageString)}info(...message){if(this.#logLevel>LogLevels_INFO)return;const messageString=this.#createMessage("INFO",message);this.#writer.info(messageString)}warn(...message){if(this.#logLevel>LogLevels_WARN)return;const messageString=this.#createMessage("WARN",message);this.#writer.warn(messageString)}error(...message){if(this.#logLevel>LogLevels_ERROR)return;const messageString=this.#createMessage("ERROR",message);this.#writer.error(messageString)}fatal(...message){const messageString=this.#createMessage("FATAL",message);this.#writer.error(messageString)}#createMessage(logLevel,messages){return`[${(new Date).toISOString()}][${logLevel}] ${messages.map(value=>this.#interpretValue(value)).join(" ")}`}#interpretValue(value,level=0){let result;switch(typeof value){case"string":result=value;break;case"object":result=this.#interpretObject(value,level+1);break;case"undefined":result="undefined";break;case"function":result="function";break;default:result=String(value)}return`${this.#indent(level)}${result}`}#interpretObject(object,level){if(null===object)return"null";if(Array.isArray(object)){return`[\n${object.map(value=>this.#interpretValue(value,level)).join(",\n")}\n${this.#indent(level-1)}]`}if(object instanceof Error){const causeValue=void 0!==object.cause?this.#interpretValue(object.cause,level+1):void 0,cause=void 0!==causeValue?`\n=>${causeValue}`:"";return`${object.message}${cause}`}return JSON.stringify(object)}#indent(level){return" ".repeat(level)}}class InvalidLogLevel extends Error{constructor(logLevel){super(`Invalid log level: ${logLevel}`)}}class LogLevelParser{parse(logLevel){switch(logLevel.toUpperCase()){case"DEBUG":return LogLevels_DEBUG;case"INFO":return LogLevels_INFO;case"WARN":return LogLevels_WARN;case"ERROR":return LogLevels_ERROR;case"FATAL":return LogLevels_FATAL;default:throw new InvalidLogLevel(logLevel)}}}class BuildFailed extends Error{constructor(cause){super("Build failed",{cause:cause})}}class BuildManager{#logger;#fileManager;#applicationReader;#applicationBuilder;constructor(configuration,logLevel){this.#logger=new Logger(logLevel),this.#fileManager=new ProjectFileManager(new LocalFileManager(configuration.source,configuration.meta.root),new LocalFileManager(configuration.target,configuration.meta.root),new LocalFileManager(configuration.resources,configuration.meta.root),new LocalFileManager(configuration.segments,configuration.meta.root),configuration.build.ignore),this.#applicationReader=new Reader(this.#fileManager),this.#applicationBuilder=new Builder(this.#fileManager,this.#logger)}async build(){try{const sourceFileManager=this.#fileManager.source,resourceFileManager=this.#fileManager.resource,segmentFileManager=this.#fileManager.segment,moduleFiles=await sourceFileManager.filterWithIgnores(Files.MODULE_PATTERN,this.#fileManager.sourceIgnores),resourceFiles=await resourceFileManager.filter(Files.RESOURCE_PATTERN),segmentFiles=await segmentFileManager.filter(Files.SEGMENT_PATTERN),applicationModel=await this.#applicationReader.read(moduleFiles,resourceFiles,segmentFiles);await this.#applicationBuilder.build(applicationModel)}catch(error){throw new BuildFailed(error)}}}class BuildApp{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(args){const environmentFile=args.getOptionalArgument("--env-file",void 0),runtimeConfigFile=args.getOptionalArgument("--config",void 0),logLevelString=args.getOptionalArgument("--log-level",void 0),logLevel=this.#parseLogLevel(logLevelString),configurationManager=new ConfigurationManager;await configurationManager.configureEnvironment(environmentFile);const configuration=await configurationManager.getRuntimeConfiguration(runtimeConfigFile);return new BuildManager(configuration,logLevel).build()}#parseLogLevel(logLevel){if(void 0===logLevel)return;return(new LogLevelParser).parse(logLevel)}}const HeaderKeys_CONTENT_TYPE="content-type",HeaderKeys_CONTENT_TYPE_OPTIONS="x-content-type-options",HeaderKeys_JITAR_CONTENT_TYPE="x-jitar-content-type",HeaderKeys_JITAR_PROCEDURE_VERSION="x-jitar-procedure-version",HeaderKeys_X_FORWARDED_PROTO="x-forwarded-proto",HeaderKeys_X_FORWARDED_HOST="x-forwarded-host",HeaderKeys_X_FORWARDED_FOR="x-forwarded-for",HeaderKeys_POWERED_BY="x-powered-by",HeaderValues_NO_SNIFF="nosniff",HeaderValues_APPLICATION_JSON="application/json",HeaderValues_APPLICATION_STREAM="application/octet-stream";class InvalidWorkerId extends Error{constructor(){super("Invalid worker id")}}class HttpRemote{#url;#httpClient;#errorConverter=new ErrorConverter;#validator=new Validator;constructor(url,httpClient){this.#url=url,this.#httpClient=httpClient}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(filename){const remoteUrl=`${this.#url}/${filename}`,response=await this.#callRemote(remoteUrl,{method:"GET"}),type=response.headers.get(HeaderKeys_CONTENT_TYPE)??HeaderValues_APPLICATION_STREAM,result=await response.arrayBuffer(),content=Buffer.from(result);return new File(filename,type,content)}async isHealthy(){const remoteUrl=`${this.#url}/health/status`,response=await this.#callRemote(remoteUrl,{method:"GET"});return"true"===await response.text()}async getHealth(){const remoteUrl=`${this.#url}/health`,response=await this.#callRemote(remoteUrl,{method:"GET"}),health=await response.json();return new Map(Object.entries(health))}async addWorker(url,procedureNames,trustKey){const remoteUrl=`${this.#url}/workers`,body={url:url,procedureNames:procedureNames,trustKey:trustKey},options={method:"POST",headers:{"Content-Type":HeaderValues_APPLICATION_JSON},body:JSON.stringify(body)},response=await this.#callRemote(remoteUrl,options),contentType=response.headers.get(HeaderKeys_CONTENT_TYPE);if(null===contentType||!1===contentType.includes(HeaderValues_APPLICATION_JSON))throw new InvalidWorkerId;const result=await response.json();if(!1===this.#validator.validate(result,{id:{type:"string",required:!0}}).valid)throw new InvalidWorkerId;return result.id}async reportWorker(id,state){const remoteUrl=`${this.#url}/workers/${id}/report`,body={state:state},options={method:"POST",headers:{"Content-Type":HeaderValues_APPLICATION_JSON},body:JSON.stringify(body)};await this.#callRemote(remoteUrl,options)}async removeWorker(id){const remoteUrl=`${this.#url}/workers/${id}`,options={method:"DELETE",headers:{"Content-Type":HeaderValues_APPLICATION_JSON}};await this.#callRemote(remoteUrl,options)}async run(request){request.setHeader(HeaderKeys_CONTENT_TYPE,HeaderValues_APPLICATION_JSON);const argsObject=Object.fromEntries(request.args),headersObject=Object.fromEntries(request.headers),versionString=request.version.toString();headersObject[HeaderKeys_JITAR_PROCEDURE_VERSION]=versionString;const remoteUrl=`${this.#url}/rpc/${request.fqn}`,options={method:"POST",redirect:"manual",headers:headersObject,body:await this.#createRequestBody(argsObject)},response=await this.#callRemote(remoteUrl,options,!1),status=response.status,result=await this.#getResponseResult(response),headers=this.#createResponseHeaders(response);return new Response(status,result,headers)}async#callRemote(remoteUrl,options,throwOnError=!0){const response=await this.#httpClient.execute(remoteUrl,options);if(throwOnError&&this.#isErrorResponse(response)){const result=await this.#getResponseResult(response);throw this.#errorConverter.fromStatus(response.status,String(result))}return response}#isErrorResponse(response){return response.status<200||response.status>399}async#createRequestBody(body){return JSON.stringify(body)}async#getResponseResult(response){const contentType=response.headers.get(HeaderKeys_JITAR_CONTENT_TYPE)??response.headers.get(HeaderKeys_CONTENT_TYPE);if(contentType?.includes("undefined"))return;if(contentType?.includes("null"))return null;if(contentType?.includes("json"))return response.json();const content=await response.text();return contentType?.includes("boolean")?"true"===content:contentType?.includes("number")?Number(content):content}#createResponseHeaders(response){const headers=new Map;for(const[name,value]of response.headers)headers.set(name,value);return headers}}class FetchHttpClient{async execute(url,options){return fetch(url,options)}}class HttpRemoteBuilder{#httpClient;constructor(httpClient=new FetchHttpClient){this.#httpClient=httpClient}build(url){return new HttpRemote(url,this.#httpClient)}}const States$2={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class DummyProvider{get url(){throw new NotImplemented}get state(){return States$2.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return States$2.AVAILABLE}provide(filename){throw new NotImplemented}}class DummyRunner{get url(){throw new NotImplemented}get state(){return States$2.AVAILABLE}get trustKey(){throw new NotImplemented}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return States$2.AVAILABLE}getProcedureNames(){throw new NotImplemented}hasProcedure(name){throw new NotImplemented}run(request){throw new NotImplemented}}class StateManager{#state=States$2.STOPPED;get state(){return this.#state}set state(state){this.#state=state}async start(task){if(!this.isStarted())try{this.setStarting(),await task()}catch(error){throw this.setStopped(),error}}async stop(task){this.isStopped()||(this.setStopping(),await task(),this.setStopped())}isStarted(){return this.#notHasState(States$2.STOPPED)}isStopped(){return this.#hasState(States$2.STOPPED)}isAvailable(){return this.#hasState(States$2.AVAILABLE)}setStarting(){this.#state=States$2.STARTING}setAvailable(){this.#state=States$2.AVAILABLE}setUnavailable(){this.#state=States$2.UNAVAILABLE}setAvailability(available){return this.#state=available?States$2.AVAILABLE:States$2.UNAVAILABLE,this.#state}setStopping(){this.#state=States$2.STOPPING}setStopped(){this.#state=States$2.STOPPED}#hasState(...states){return states.includes(this.#state)}#notHasState(...states){return!1===this.#hasState(...states)}}class InvalidTrustKey extends Unauthorized{constructor(){super("Invalid trust key")}}class LocalGateway{#url;#trustKey;#healthManager;#workerManager;#stateManager=new StateManager;constructor(configuration){this.#url=configuration.url,this.#trustKey=configuration.trustKey,this.#healthManager=configuration.healthManager,this.#workerManager=configuration.workerManager}get url(){return this.#url}get state(){return this.#stateManager.state}get trustKey(){return this.#trustKey}async start(){return this.#stateManager.start(async()=>{await this.#healthManager.start(),this.#workerManager.start(),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{this.#workerManager.stop(),await this.#healthManager.stop()})}async isHealthy(){return this.#healthManager.isHealthy()}async getHealth(){return this.#healthManager.getHealth()}async updateState(){const healthy=await this.isHealthy();return this.#stateManager.setAvailability(healthy)}async addWorker(worker){if(this.#isInvalidTrustKey(worker.trustKey))throw new InvalidTrustKey;return await worker.start(),this.#workerManager.addWorker(worker)}getWorker(id){return this.#workerManager.getWorker(id)}async reportWorker(id,state){return this.#workerManager.reportWorker(id,state)}async removeWorker(id){return this.#workerManager.removeWorker(id).stop()}getProcedureNames(){return this.#workerManager.getProcedureNames()}hasProcedure(name){return this.#workerManager.hasProcedure(name)}async run(request){return this.#workerManager.run(request)}#isInvalidTrustKey(trustKey){return void 0!==this.#trustKey&&trustKey!==this.#trustKey}}class RemoteGateway{#url;#remote;#stateManager=new StateManager;constructor(configuration){this.#url=configuration.url,this.#remote=configuration.remote}get url(){return this.#url}get state(){return this.#stateManager.state}get trustKey(){}async start(){return this.#stateManager.start(async()=>{await this.#remote.connect(),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{await this.#remote.disconnect()})}isHealthy(){return this.#remote.isHealthy()}getHealth(){return this.#remote.getHealth()}async updateState(){const healthy=await this.isHealthy();return this.#stateManager.setAvailability(healthy)}getProcedureNames(){throw new NotImplemented}hasProcedure(name){throw new NotImplemented}addWorker(worker){return this.#remote.addWorker(worker.url,worker.getProcedureNames(),worker.trustKey)}reportWorker(id,state){return this.#remote.reportWorker(id,state)}removeWorker(id){return this.#remote.removeWorker(id)}run(request){return this.#remote.run(request)}}class NoWorkerAvailable extends ServerError{#name;constructor(name){super(`No worker available for procedure '${name}'`),this.#name=name}get name(){return this.#name}}class WorkerBalancer{#workers=[];#currentIndex=0;get workers(){return this.#workers}addWorker(worker){this.#workers.includes(worker)||this.#workers.push(worker)}removeWorker(worker){const index=this.#workers.indexOf(worker);-1!==index&&this.#workers.splice(index,1)}getNextWorker(){const workers=this.#workers.filter(worker=>worker.isAvailable());if(0!==workers.length)return this.#currentIndex>=workers.length&&(this.#currentIndex=0),workers[this.#currentIndex++];this.#currentIndex=0}async run(request){const worker=this.getNextWorker();if(void 0===worker)throw new NoWorkerAvailable(request.fqn);return worker.run(request)}}class IdGenerator{generate(){return crypto.randomUUID()}}class UnknownWorker extends ServerError{#id;constructor(id){super(`Unknown worker id '${id}'`),this.#id=id}get id(){return this.#id}}class WorkerManager{#workers=new Map;#balancers=new Map;#idGenerator=new IdGenerator;#monitorTask;constructor(scheduleManager,monitorInterval){this.#monitorTask=scheduleManager.create(()=>this.#monitor(),monitorInterval)}get workers(){return[...this.#workers.values()]}get balancers(){return this.#balancers}start(){this.#monitorTask.start()}stop(){this.#monitorTask.stop()}getProcedureNames(){const procedureNames=this.workers.map(worker=>worker.getProcedureNames());return[...new Set(procedureNames.flat()).values()]}hasProcedure(fqn){return this.getProcedureNames().includes(fqn)}addWorker(worker){worker.id=this.#idGenerator.generate(),this.#workers.set(worker.id,worker);for(const name of worker.getProcedureNames()){this.#getOrCreateBalancer(name).addWorker(worker)}return worker.id}getWorker(id){const worker=this.#workers.get(id);if(void 0===worker)throw new UnknownWorker(id);return worker}reportWorker(id,state){this.getWorker(id).reportState(state)}removeWorker(id){const worker=this.getWorker(id);this.#workers.delete(id);for(const name of worker.getProcedureNames()){const balancer=this.#getBalancer(name);void 0!==balancer&&balancer.removeWorker(worker)}return worker}#getBalancer(fqn){return this.#balancers.get(fqn)}#getOrCreateBalancer(fqn){let balancer=this.#getBalancer(fqn);return void 0===balancer&&(balancer=new WorkerBalancer,this.#balancers.set(fqn,balancer)),balancer}async run(request){const balancer=this.#getBalancer(request.fqn);if(void 0===balancer)throw new ProcedureNotFound(request.fqn);return balancer.run(request)}async#monitor(){const promises=this.workers.map(worker=>this.#checkWorker(worker));await Promise.allSettled(promises)}async#checkWorker(worker){await worker.updateState()===States$2.STOPPED&&this.removeWorker(worker.id)}}class LocalProxy{#url;#provider;#runner;#stateManager=new StateManager;constructor(configuration){this.#url=configuration.url,this.#provider=configuration.provider,this.#runner=configuration.runner}get url(){return this.#url}get state(){return this.#stateManager.state}get trustKey(){return this.#runner.trustKey}get provider(){return this.#provider}get runner(){return this.#runner}async start(){return this.#stateManager.start(async()=>{await Promise.all([this.#provider.start(),this.#runner.start()]),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{await Promise.allSettled([this.#runner.stop(),this.#provider.stop()])})}async isHealthy(){const[providerHealthy,runnerHealthy]=await Promise.all([this.#provider.isHealthy(),this.#runner.isHealthy()]);return providerHealthy&&runnerHealthy}async getHealth(){const[providerHealth,runnerHealth]=await Promise.all([this.#provider.getHealth(),this.#runner.getHealth()]);return new Map([...providerHealth,...runnerHealth])}async updateState(){const healthy=await this.isHealthy();return this.#stateManager.setAvailability(healthy)}provide(filename){return this.#provider.provide(filename)}getProcedureNames(){return this.#runner.getProcedureNames()}hasProcedure(fqn){return this.#runner.hasProcedure(fqn)}run(request){return this.#runner.run(request)}}class LocalRepository{#url;#healthManager;#sourcingManager;#assets;#directoryIndex;#fallback;#stateManager=new StateManager;constructor(configuration){this.#url=configuration.url,this.#healthManager=configuration.healthManager,this.#sourcingManager=configuration.sourcingManager,this.#assets=configuration.assets,this.#directoryIndex=configuration.directoryIndex??"index.html",this.#fallback=configuration.fallback}get url(){return this.#url}get state(){return this.#stateManager.state}async start(){return this.#stateManager.start(async()=>{await this.#healthManager.start(),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{await this.#healthManager.stop()})}isHealthy(){return this.#healthManager.isHealthy()}getHealth(){return this.#healthManager.getHealth()}async updateState(){const healthy=await this.isHealthy();return this.#stateManager.setAvailability(healthy)}async provide(filename){if(this.#assets.has(filename))return this.#sourcingManager.read(filename);const index=this.#resolveDirectoryIndex(filename);if(this.#assets.has(index))return this.#sourcingManager.read(index);if(void 0!==this.#fallback&&this.#assets.has(this.#fallback))return this.#sourcingManager.read(this.#fallback);throw new FileNotFound(filename)}#resolveDirectoryIndex(directory){return""===directory||"/"===directory?this.#directoryIndex:directory.endsWith("/")?`${directory}${this.#directoryIndex}`:`${directory}/${this.#directoryIndex}`}}class RemoteRepository{#url;#remote;#stateManager=new StateManager;constructor(configuration){this.#url=configuration.url,this.#remote=configuration.remote}get url(){return this.#url}get state(){return this.#stateManager.state}async start(){return this.#stateManager.start(async()=>{await this.#remote.connect(),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{await this.#remote.disconnect()})}isHealthy(){return this.#remote.isHealthy()}getHealth(){return this.#remote.getHealth()}async updateState(){const healthy=await this.isHealthy();return this.#stateManager.setAvailability(healthy)}provide(filename){return this.#remote.provide(filename)}}class RequestNotTrusted extends Unauthorized{constructor(){super("Request not trusted")}}class LocalWorker{#id;#url;#trustKey;#gateway;#registerAtGateway;#executionManager;#serializer;#healthManager;#reportTask;#stateManager=new StateManager;constructor(configuration){this.#url=configuration.url,this.#trustKey=configuration.trustKey,this.#gateway=configuration.gateway,this.#registerAtGateway=!0===configuration.registerAtGateway,this.#executionManager=configuration.executionManager,this.#serializer=configuration.serializer,this.#healthManager=configuration.healthManager;const scheduleManager=configuration.scheduleManager;this.#reportTask=scheduleManager.create(()=>this.#report(),configuration.reportInterval)}get id(){return this.#id}set id(id){this.#id=id}get state(){return this.#stateManager.state}get url(){return this.#url}get trustKey(){return this.#trustKey}async start(){return this.#stateManager.start(async()=>{await Promise.all([this.#executionManager.start(),this.#healthManager.start()]),void 0!==this.#gateway&&(await this.#gateway.start(),this.#registerAtGateway&&(this.#id=await this.#gateway.addWorker(this),this.#reportTask.start())),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{void 0!==this.#gateway&&(void 0!==this.#id&&(this.#reportTask.stop(),await this.#gateway.removeWorker(this.#id)),await this.#gateway.stop()),await Promise.all([this.#healthManager.stop(),this.#executionManager.stop()])})}getProcedureNames(){return this.#executionManager.getProcedureNames()}hasProcedure(name){return this.#executionManager.hasProcedure(name)}isHealthy(){return this.#healthManager.isHealthy()}getHealth(){return this.#healthManager.getHealth()}isAvailable(){return this.#stateManager.isAvailable()}async updateState(){const healthy=await this.isHealthy();return this.#stateManager.setAvailability(healthy)}async reportState(state){if(void 0!==this.#gateway&&void 0!==this.#id)return this.#gateway.reportWorker(this.#id,state)}async run(request){return this.#mustRunLocal(request)?this.#runLocal(request):this.#runRemote(request)}#mustRunLocal(request){return void 0===this.#gateway||this.#executionManager.hasProcedure(request.fqn)}async#runLocal(request){const procedure=this.#executionManager.getProcedure(request.fqn),implementation=procedure?.getImplementation(request.version);if(this.#procedureNotFound(implementation))throw new ProcedureNotFound(request.fqn);if(this.#requestNotTrusted(request,implementation))throw new RequestNotTrusted;const dataEncoding=request.getHeader("X-Jitar-Data-Encoding");"serialized"===dataEncoding&&(request=await this.#deserializeRequest(request)),request.removeHeader("X-Jitar-Data-Encoding");const response=await this.#executionManager.run(request);return"serialized"===dataEncoding?this.#serializeResponse(response):response}#procedureNotFound(implementation){return void 0===implementation||implementation.private}#requestNotTrusted(request,implementation){if(implementation.public)return!1;const trustKey=request.getHeader("X-Jitar-Trust-Key");return this.#trustKey!==trustKey}async#runRemote(request){(request=await this.#serializeRequest(request)).setHeader("X-Jitar-Data-Encoding","serialized"),void 0!==this.#trustKey&&request.setHeader("X-Jitar-Trust-Key",this.#trustKey);const response=await this.#gateway.run(request);return this.#deserializeResponse(response)}async#serializeRequest(request){const serializedArgs=new Map;for(const[key,value]of request.args){const serializedValue=await this.#serializer.serialize(value);serializedArgs.set(key,serializedValue)}return new Request(request.fqn,request.version,serializedArgs,request.headers,request.mode)}async#deserializeRequest(request){const deserializedArgs=new Map;for(const[key,value]of request.args){const deserializedValue=await this.#serializer.deserialize(value);deserializedArgs.set(key,deserializedValue)}return new Request(request.fqn,request.version,deserializedArgs,request.headers,request.mode)}async#serializeResponse(response){const serializedResult=await this.#serializer.serialize(response.result);return new Response(response.status,serializedResult,response.headers)}async#deserializeResponse(response){const deserializedResult=await this.#serializer.deserialize(response.result);return new Response(response.status,deserializedResult,response.headers)}async#report(){const state=await this.updateState();return this.reportState(state)}}class ReportedStateManager extends StateManager{#unavailableThreshold;#stoppedThreshold;#lastReport=Date.now();#lastUpdate=Date.now();constructor(unavailableThreshold=6e3,stoppedThreshold=18e3){super(),this.#unavailableThreshold=unavailableThreshold,this.#stoppedThreshold=stoppedThreshold}report(state){this.#lastReport=Date.now(),this.state=state}update(){this.#lastUpdate=Date.now();const interval=this.#lastUpdate-this.#lastReport;return interval>=this.#unavailableThreshold&&(this.state=interval>=this.#stoppedThreshold?States$2.STOPPED:States$2.UNAVAILABLE),this.state}}class RemoteWorker{#id;#url;#trustKey;#procedureNames;#remote;#stateManager;constructor(configuration){this.#url=configuration.url,this.#trustKey=configuration.trustKey,this.#procedureNames=configuration.procedureNames,this.#remote=configuration.remote,this.#stateManager=new ReportedStateManager(configuration.unavailableThreshold,configuration.stoppedThreshold)}get id(){return this.#id}set id(id){this.#id=id}get state(){return this.#stateManager.state}get url(){return this.#url}get trustKey(){return this.#trustKey}async start(){return this.#stateManager.start(async()=>{await this.#remote.connect(),await this.updateState()})}async stop(){return this.#stateManager.stop(async()=>{await this.#remote.disconnect()})}getProcedureNames(){return[...this.#procedureNames.values()]}hasProcedure(name){return this.#procedureNames.has(name)}isHealthy(){return this.#remote.isHealthy()}getHealth(){return this.#remote.getHealth()}isAvailable(){return this.#stateManager.isAvailable()}async updateState(){return this.#stateManager.update()}async reportState(state){this.#stateManager.report(state)}run(request){return this.#remote.run(request)}}class RemoteWorkerBuilder{#remoteBuilder;#unavailableThreshold;#stoppedThreshold;constructor(remoteBuilder,unavailableThreshold,stoppedThreshold){this.#remoteBuilder=remoteBuilder,this.#unavailableThreshold=unavailableThreshold,this.#stoppedThreshold=stoppedThreshold}build(url,procedures,trustKey){const remote=this.#remoteBuilder.build(url),procedureNames=new Set(procedures),unavailableThreshold=this.#unavailableThreshold,stoppedThreshold=this.#stoppedThreshold;return new RemoteWorker({url:url,trustKey:trustKey,remote:remote,procedureNames:procedureNames,unavailableThreshold:unavailableThreshold,stoppedThreshold:stoppedThreshold})}}class ProcedureRunner{#runner;constructor(runner){this.#runner=runner}async handle(request,next){return this.#runner.run(request)}}class Runtime{#versionParser=new VersionParser;constructor(){this.#initGlobals()}#initGlobals(){const globals=globalThis;globals.__run=this.#run.bind(this),globals.ProcedureNotAccessible=ProcedureNotAccessible}async#run(fqn,versionNumber,args,sourceRequest){const version=this.#versionParser.parse(versionNumber),argsMap=new Map(Object.entries(args)),headersMap=sourceRequest instanceof Request?sourceRequest.headers:new Map,targetRequest=new Request(fqn,version,argsMap,headersMap,RunModes_NORMAL),trustKey=this.getTrustKey();void 0!==trustKey&&targetRequest.setHeader("X-Jitar-Trust-Key",trustKey);const targetResponse=await this.runInternal(targetRequest);if(targetResponse.status!==StatusCodes$1_OK)throw targetResponse.result;return targetResponse.result}}const States$1_STARTING="starting",States$1_STARTED="started",States$1_STOPPING="stopping",States$1_STOPPED="stopped";class InvalidHealthCheck extends ServerError{constructor(){super("Invalid health check")}}class StartingHealthManagerFailed extends Error{constructor(cause){super("Starting health manager failed",{cause:cause})}}class StoppingHealthManagerFailed extends Error{constructor(cause){super("Stopping health manager failed",{cause:cause})}}class HealthManager{#state=States$1_STOPPED;#healthChecks=new Map;#moduleImporter;#healthCheckFiles;constructor(moduleImporter,healthCheckFiles=[]){this.#moduleImporter=moduleImporter,this.#healthCheckFiles=healthCheckFiles}get state(){return this.#state}async start(){if(this.#state===States$1_STOPPED)try{this.#state=States$1_STARTING,await this.#loadHealthChecks(),this.#state=States$1_STARTED}catch(error){throw this.#state=States$1_STOPPED,new StartingHealthManagerFailed(error)}}async stop(){if(this.#state===States$1_STARTED)try{this.#state=States$1_STOPPING,this.clearHealthChecks(),this.#state=States$1_STOPPED}catch(error){throw this.#state=States$1_STARTED,new StoppingHealthManagerFailed(error)}}async loadHealthCheck(filename){const healthCheck=await this.#loadHealthCheck(filename);this.addHealthCheck(healthCheck)}addHealthCheck(healthCheck){if(void 0===healthCheck.isHealthy)throw new InvalidHealthCheck;this.#healthChecks.set(healthCheck.name,healthCheck)}clearHealthChecks(){this.#healthChecks.clear()}async isHealthy(){const promises=[];for(const healthCheck of this.#healthChecks.values()){const promise=this.#executeHealthCheck(healthCheck);promises.push(promise)}return Promise.all(promises).then(results=>results.every(result=>result)).catch(()=>!1)}async getHealth(){const promises=[];for(const[name,healthCheck]of this.#healthChecks){const promise=this.#executeHealthCheck(healthCheck).then(result=>({name:name,isHealthy:result})).catch(()=>({name:name,isHealthy:!1}));promises.push(promise)}const healthChecks=new Map;return Promise.allSettled(promises).then(results=>results.forEach(result=>this.#handleHealthCheckResult(result,healthChecks))).then(()=>healthChecks)}async#loadHealthChecks(){(await Promise.all(this.#healthCheckFiles.map(filename=>this.#loadHealthCheck(filename)))).forEach(healthCheck=>this.addHealthCheck(healthCheck))}async#loadHealthCheck(filename){return(await this.#moduleImporter.import(filename)).default}#handleHealthCheckResult(result,healthChecks){"fulfilled"===result.status?healthChecks.set(result.value.name,result.value.isHealthy):healthChecks.set(result.reason.name,!1)}async#executeHealthCheck(healthCheck){const health=healthCheck.isHealthy(),milliseconds=healthCheck.timeout;if(void 0===milliseconds)return health;const timeout=new Promise(resolve=>{setTimeout(resolve,milliseconds)}).then(()=>!1);return Promise.race([timeout,health])}}const States_STARTING="starting",States_STARTED="started",States_STOPPING="stopping",States_STOPPED="stopped";class InvalidMiddleware extends ServerError{constructor(){super("Invalid middleware")}}class StartingMiddlewareManagerFailed extends Error{constructor(cause){super("Starting middleware manager failed",{cause:cause})}}class StoppingMiddlewareManagerFailed extends Error{constructor(cause){super("Stopping middleware manager failed",{cause:cause})}}class MiddlewareManager{#state=States_STOPPED;#middlewares=[];#moduleImporter;#middlewareFiles;constructor(moduleImporter,middlewareFiles=[]){this.#moduleImporter=moduleImporter,this.#middlewareFiles=middlewareFiles}get state(){return this.#state}async start(){if(this.#state===States_STOPPED)try{this.#state=States_STARTING,await this.#loadMiddlewares(),this.#state=States_STARTED}catch(error){throw this.#state=States_STOPPED,new StartingMiddlewareManagerFailed(error)}}async stop(){if(this.#state===States_STARTED)try{this.#state=States_STOPPING,this.clearMiddlewares(),this.#state=States_STOPPED}catch(error){throw this.#state=States_STARTED,new StoppingMiddlewareManagerFailed(error)}}async loadMiddleware(filename){const middleware=await this.#loadMiddleware(filename);this.addMiddleware(middleware)}addMiddleware(middleware){if(void 0===middleware?.handle)throw new InvalidMiddleware;this.#middlewares.push(middleware)}getMiddleware(type){return this.#middlewares.find(middleware=>middleware instanceof type)}clearMiddlewares(){this.#middlewares=[]}handle(request){return this.#getNextHandler(request,0)()}async#loadMiddlewares(){(await Promise.all(this.#middlewareFiles.map(filename=>this.#loadMiddleware(filename)))).forEach(middleware=>this.addMiddleware(middleware))}async#loadMiddleware(filename){return(await this.#moduleImporter.import(filename)).default}#getNextHandler(request,index){const next=this.#middlewares[index];if(void 0===next)return async()=>new Response(StatusCodes$1_OK);const nextHandler=this.#getNextHandler(request,index+1);return async()=>await next.handle(request,nextHandler)}}class ScheduledTask{#logger;#task;#interval;#timeout=null;constructor(logger,task,interval=5e3){this.#logger=logger,this.#task=task,this.#interval=interval}start(){this.#scheduleNextExecution()}stop(){null!==this.#timeout&&(clearTimeout(this.#timeout),this.#timeout=null)}#scheduleNextExecution(){this.#timeout=setTimeout(async()=>{null!==this.#timeout&&(await this.#executeTask(),this.#scheduleNextExecution())},this.#interval),this.#timeout.unref()}async#executeTask(){try{await this.#task()}catch(error){this.#logger.warn("Scheduled task failed",error)}}}class ScheduleManager{#scheduledTasks=[];#logger;constructor(logger){this.#logger=logger}create(task,interval){const scheduledTask=new ScheduledTask(this.#logger,task,interval);return this.#scheduledTasks.push(scheduledTask),scheduledTask}remove(scheduledTask){const index=this.#scheduledTasks.indexOf(scheduledTask);index<0||this.#scheduledTasks.splice(index,1)}startAll(){this.#scheduledTasks.forEach(scheduledTask=>scheduledTask.start())}stopAll(){this.#scheduledTasks.forEach(scheduledTask=>scheduledTask.stop())}}class ClassNotFound extends Error{constructor(name){super(`The class '${name}' could not be found`)}}class InvalidClass extends Error{constructor(name){super(`The class '${name}' is invalid`)}}class NoDeserializerFound extends Error{constructor(type){super(`No deserializer found for value of type '${type}'`)}}class NoSerializerFound extends Error{constructor(type){super(`No serializer found for value of type '${type}'`)}}class Serializer{#serializers=[];addSerializer(serializer){serializer.parent=this,this.#serializers.unshift(serializer)}async serialize(value){const serializer=this.#serializers.find(serializer=>serializer.canSerialize(value));if(void 0===serializer)throw new NoSerializerFound(typeof value);return serializer.serialize(value)}async deserialize(value){const serializer=this.#serializers.find(serializer=>serializer.canDeserialize(value));if(void 0===serializer)throw new NoDeserializerFound(typeof value);return serializer.deserialize(value)}}class ParentSerializerNotSet extends Error{constructor(){super("Parent serializer not set")}}class ValueSerializer{#parent;set parent(parent){this.#parent=parent}serializeOther(value){if(void 0===this.#parent)throw new ParentSerializerNotSet;return this.#parent.serialize(value)}deserializeOther(value){if(void 0===this.#parent)throw new ParentSerializerNotSet;return this.#parent.deserialize(value)}}class ArraySerializer extends ValueSerializer{canSerialize(value){return value instanceof Array}canDeserialize(value){return value instanceof Array}async serialize(array){const values=[];for(const value of array)values.push(await this.serializeOther(value));return values}async deserialize(array){return Promise.all(array.map(async value=>this.deserializeOther(value)))}}class InvalidBigIntString extends Error{constructor(bigIntString){super(`Invalid BigInt string '${bigIntString}'`)}}class BigIntSerializer extends ValueSerializer{canSerialize(value){return"bigint"==typeof value}canDeserialize(value){const bigInt=value;return bigInt instanceof Object&&!0===bigInt.serialized&&"BigInt"===bigInt.name&&"string"==typeof bigInt.value}async serialize(bigInt){return{serialized:!0,name:"BigInt",value:bigInt.toString()}}async deserialize(object){try{return BigInt(object.value)}catch{throw new InvalidBigIntString(object.value)}}}class InvalidBufferString extends Error{constructor(bufferString){super(`Invalid Buffer string '${bufferString}'`)}}class BufferSerializer extends ValueSerializer{canSerialize(value){return value instanceof Buffer}canDeserialize(value){const buffer=value;return buffer instanceof Object&&!0===buffer.serialized&&"Buffer"===buffer.name&&"string"==typeof buffer.base64}async serialize(buffer){return{serialized:!0,name:"Buffer",base64:buffer.toString("base64")}}async deserialize(object){try{return Buffer.from(object.base64,"base64")}catch{throw new InvalidBufferString(object.base64)}}}const reflector$1=new Reflector;class ClassSerializer extends ValueSerializer{#classResolver;constructor(classResolver){super(),this.#classResolver=classResolver}canSerialize(value){return value instanceof Object&&reflector$1.isClassObject(value)}canDeserialize(value){const object=value;return object instanceof Object&&!0===object.serialized&&"class"===object.name&&"string"==typeof object.key&&object.args instanceof Object&&object.args.constructor===Object&&object.fields instanceof Object&&object.fields.constructor===Object}async serialize(object){const clazz=reflector$1.getClass(object),model=reflector$1.fromClass(clazz,!0),parameterNames=this.#extractConstructorParameters(model),key=this.#classResolver.resolveKey(clazz);if(void 0===key)throw new ClassNotFound(clazz.name);return{serialized:!0,key:key,name:"class",args:await this.#serializeConstructor(model,parameterNames,object),fields:await this.#serializeFields(model,parameterNames,object)}}#extractConstructorParameters(model){const constructor=model.construct;return(constructor?.parameters??[]).map(parameter=>parameter.binding.identifier)}async#serializeConstructor(model,includeNames,object){const args={};for(const[index,name]of includeNames.entries()){const value=model.canRead(name)?await this.serializeOther(object[name]):void 0;args[index.toString()]=value}return args}async#serializeFields(model,excludeNames,object){const fields={};for(const property of model.writable){const name=property.identifier;excludeNames.includes(name)||!1===model.canRead(name)||(fields[name]=await this.serializeOther(object[name]))}return fields}async deserialize(object){const clazz=await this.#getClass(object);if(void 0===clazz)throw new ClassNotFound(object.key);if(clazz instanceof Function==!1)throw new InvalidClass(object.key);const args=await this.#deserializeConstructor(clazz,object.args),instance=reflector$1.createInstance(clazz,args);for(const name in object.fields){const fieldValue=object.fields[name];instance[name]=await this.deserializeOther(fieldValue)}return instance}async#deserializeConstructor(clazz,args){const constructor=reflector$1.fromClass(clazz,!0).construct,values=(constructor?.parameters??[]).map((_,index)=>{const key=index.toString(),value=args[key];return this.deserializeOther(value)});return Promise.all(values)}async#getClass(resolvable){return globalThis[resolvable.key]??this.#classResolver.resolveClass(resolvable.key)}}class InvalidDateString extends Error{constructor(dateString){super(`Invalid date string '${dateString}'`)}}class DateSerializer extends ValueSerializer{canSerialize(value){return value instanceof Date}canDeserialize(value){const date=value;return date instanceof Object&&!0===date.serialized&&"Date"===date.name&&"string"==typeof date.value}async serialize(date){return{serialized:!0,name:"Date",value:date.toISOString()}}async deserialize(object){const date=new Date(object.value);if("Invalid Date"===date.toString())throw new InvalidDateString(object.value);return date}}class ErrorSerializer extends ValueSerializer{canSerialize(value){if(value instanceof Object==!1)return!1;const error=value;return error.constructor===Error||error.constructor===EvalError||error.constructor===RangeError||error.constructor===ReferenceError||error.constructor===SyntaxError||error.constructor===TypeError||error.constructor===URIError||error.constructor===AggregateError}canDeserialize(value){const error=value;return error instanceof Object&&!0===error.serialized&&"Error"===error.name&&error.type in globalThis}async serialize(error){return{serialized:!0,name:"Error",type:error.constructor.name,stack:error.stack,message:error.message,cause:error.cause}}async deserialize(object){const error=new(0,globalThis[object.type])(object.message,{cause:object.cause});return error.stack=object.stack,error}}class MapSerializer extends ValueSerializer{canSerialize(value){return value instanceof Map}canDeserialize(value){const map=value;return map instanceof Object&&!0===map.serialized&&"Map"===map.name&&map.entries instanceof Object&&map.entries.keys instanceof Array&&map.entries.values instanceof Array}async serialize(map){const keys=[],values=[];for(const[key,value]of map)keys.push(await this.serializeOther(key)),values.push(await this.serializeOther(value));return{serialized:!0,name:"Map",entries:{keys:keys,values:values}}}async deserialize(object){const keys=object.entries.keys,values=object.entries.values,result=new Map;for(let index=0;index<keys.length;index++){const key=await this.deserializeOther(keys[index]),value=await this.deserializeOther(values[index]);result.set(key,value)}return result}}class ObjectSerializer extends ValueSerializer{canSerialize(value){return value instanceof Object&&value.constructor===Object}canDeserialize(value){return value instanceof Object&&value.constructor===Object}async serialize(object){const result={};for(const key in object){const value=object[key];result[key]=await this.serializeOther(value)}return result}async deserialize(object){const result={};for(const key in object){const value=object[key];result[key]=await this.deserializeOther(value)}return result}}class PrimitiveSerializer extends ValueSerializer{canSerialize(value){return value instanceof Object==!1}canDeserialize(value){return value instanceof Object==!1}async serialize(primitive){return primitive}async deserialize(primitive){return primitive}}class InvalidRegExp extends Error{constructor(source,flags){super(`Invalid regular expression '${source}' with flags '${flags}'`)}}class RegExpSerializer extends ValueSerializer{canSerialize(value){return value instanceof RegExp}canDeserialize(value){const regExp=value;return regExp instanceof Object&&!0===regExp.serialized&&"RegExp"===regExp.name&&"string"==typeof regExp.source&&"string"==typeof regExp.flags}async serialize(regExp){return{serialized:!0,name:"RegExp",source:regExp.source,flags:regExp.flags}}async deserialize(object){try{return new RegExp(object.source,object.flags)}catch{throw new InvalidRegExp(object.source,object.flags)}}}class SetSerializer extends ValueSerializer{canSerialize(value){return value instanceof Set}canDeserialize(value){const set=value;return set instanceof Object&&!0===set.serialized&&"Set"===set.name&&set.values instanceof Array}async serialize(set){const values=[];for(const value of set.values())values.push(await this.serializeOther(value));return{serialized:!0,name:"Set",values:values}}async deserialize(object){const values=await Promise.all(object.values.map(async value=>this.deserializeOther(value)));return new Set([...values])}}const reflector=new Reflector;class ArrayBufferSerializer extends ValueSerializer{canSerialize(value){return value instanceof Int8Array||value instanceof Uint8Array||value instanceof Uint8ClampedArray||value instanceof Int16Array||value instanceof Uint16Array||value instanceof Int32Array||value instanceof Uint32Array||value instanceof Float32Array||value instanceof Float64Array||value instanceof BigInt64Array||value instanceof BigUint64Array}canDeserialize(value){const array=value;return array instanceof Object&&!0===array.serialized&&"TypedArray"===array.name&&array.type in globalThis&&array.bytes instanceof Array}async serialize(array){const type=array.constructor.name,view=new DataView(array.buffer),bytes=[];for(let index=0;index<view.byteLength;index++)bytes.push(view.getUint8(index));return{serialized:!0,name:"TypedArray",type:type,bytes:bytes}}async deserialize(object){const type=object.type,bytes=object.bytes,buffer=new ArrayBuffer(bytes.length),view=new DataView(buffer);for(let index=0;index<bytes.length;index++)view.setUint8(index,bytes[index]);const clazz=globalThis[type];return reflector.createInstance(clazz,[buffer])}}class InvalidUrlString extends Error{constructor(urlString){super(`Invalid url string '${urlString}'`)}}class UrlSerializer extends ValueSerializer{canSerialize(value){return value instanceof URL}canDeserialize(value){const url=value;return url instanceof Object&&!0===url.serialized&&"Url"===url.name&&"string"==typeof url.value}async serialize(url){return{serialized:!0,name:"Url",value:url.toString()}}async deserialize(object){try{return new URL(object.value)}catch{throw new InvalidUrlString(object.value)}}}class SerializerBuilder{static build(classResolver){const serializer=new Serializer;return serializer.addSerializer(new PrimitiveSerializer),serializer.addSerializer(new ObjectSerializer),void 0!==classResolver&&serializer.addSerializer(new ClassSerializer(classResolver)),serializer.addSerializer(new ErrorSerializer),serializer.addSerializer(new RegExpSerializer),serializer.addSerializer(new BigIntSerializer),serializer.addSerializer(new UrlSerializer),serializer.addSerializer(new DateSerializer),serializer.addSerializer(new SetSerializer),serializer.addSerializer(new MapSerializer),serializer.addSerializer(new ArraySerializer),serializer.addSerializer(new ArrayBufferSerializer),"undefined"!=typeof Buffer&&serializer.addSerializer(new BufferSerializer),serializer}}class ExecutionClassResolver{#executionManager;constructor(executionManager){this.#executionManager=executionManager}resolveKey(clazz){const model=this.#executionManager.getClassByImplementation(clazz);return model?.fqn}resolveClass(key){const model=this.#executionManager.getClass(key);return model?.implementation}}const segment=new Segment("@jitar"),implementationNotFound=new Class("@jitar/execution/ImplementationNotFound",ImplementationNotFound),invalidParameterValue=new Class("@jitar/execution/InvalidParameterValue",InvalidParameterValue),invalidVersionNumber=new Class("@jitar/execution/InvalidVersionNumber",InvalidVersionNumber),missingParameterValue=new Class("@jitar/execution/MissingParameterValue",MissingParameterValue),procedureNotFound=new Class("@jitar/execution/ProcedureNotFound",ProcedureNotFound),unknownParameter=new Class("@jitar/execution/UnknownParameter",UnknownParameter);segment.addClass(implementationNotFound),segment.addClass(invalidParameterValue),segment.addClass(invalidVersionNumber),segment.addClass(missingParameterValue),segment.addClass(procedureNotFound),segment.addClass(unknownParameter);const ContentTypes_NULL="application/null",ContentTypes_UNDEFINED="application/undefined",ContentTypes_BOOLEAN="application/boolean",ContentTypes_NUMBER="application/number",ContentTypes_JSON="application/json",ContentTypes_TEXT="text/plain",StatusCodes_OK=200,StatusCodes_BAD_REQUEST=400,StatusCodes_UNAUTHORIZED=401,StatusCodes_PAYMENT_REQUIRED=402,StatusCodes_FORBIDDEN=403,StatusCodes_NOT_FOUND=404,StatusCodes_TEAPOT=418,StatusCodes_SERVER_ERROR=500,StatusCodes_NOT_IMPLEMENTED=501;class StartingServerFailed extends Error{constructor(cause){super("Starting server failed",{cause:cause})}}class StoppingServerFailed extends Error{constructor(cause){super("Stopping server failed",{cause:cause})}}class Server extends Runtime{#proxy;#remoteWorkerBuilder;#resourceManager;#middlewareManager;#logger;#versionParser=new VersionParser;constructor(configuration){super(),this.#proxy=configuration.proxy,this.#remoteWorkerBuilder=configuration.remoteWorkerBuilder,this.#resourceManager=configuration.resourceManager,this.#middlewareManager=configuration.middlewareManager,this.#logger=configuration.logger}get proxy(){return this.#proxy}getTrustKey(){return this.#proxy.trustKey}async start(){try{await this.#setUp(),this.#logger.info(`Server started at ${this.#proxy.url}`),this.#proxy.runner instanceof LocalWorker&&this.#logger.info("RPC procedures:",this.#proxy.runner.getProcedureNames())}catch(error){throw new StartingServerFailed(error)}}async stop(){try{await this.#tearDown(),this.#logger.info("Server stopped")}catch(error){throw new StoppingServerFailed(error)}}async getHealth(){try{const health=await this.#proxy.getHealth();return this.#logger.debug("Got health"),this.#respondHealth(health)}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.error(`Failed to get health (${message})`),this.#respondError(error)}}async isHealthy(){try{const healthy=await this.#proxy.isHealthy();return this.#logger.debug("Got health status"),this.#respondHealthy(healthy)}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.error(`Failed to get health status (${message})`),this.#respondError(error)}}async provide(provideRequest){try{const file=await this.#proxy.provide(provideRequest.filename),fileInfo=file.location!==provideRequest.filename?`${provideRequest.filename} => ${file.location}`:provideRequest.filename;return this.#logger.info(`Provided file: ${fileInfo}`),this.#respondFile(file)}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.warn(`Failed to provide file: ${provideRequest.filename} (${message})`),this.#respondError(error)}}async run(runRequest){try{const request=this.#transformRunRequest(runRequest),response=await this.#middlewareManager.handle(request);return this.#logger.info(`Ran request: ${request.fqn}`),this.#respondResponse(response)}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.error(`Failed run request: ${runRequest.fqn} (${message})`),this.#respondError(error)}}async runInternal(request){return this.#proxy.run(request)}async addWorker(addRequest){try{const gateway=this.#extractLocalGatewayFromProxy(),worker=this.#remoteWorkerBuilder.build(addRequest.url,addRequest.procedureNames,addRequest.trustKey),id=await gateway.addWorker(worker);return this.#logger.info(`Added worker: ${worker.url}`),this.#respondSuccess({id:id})}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.error(`Failed to add worker: ${addRequest.url} (${message})`),this.#respondError(error)}}async reportWorker(reportRequest){try{const state=this.#translateState(reportRequest.state),gateway=this.#extractLocalGatewayFromProxy();return await gateway.reportWorker(reportRequest.id,state),this.#logger.debug(`Reported worker: ${reportRequest.id}`),this.#respondSuccess()}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.error(`Failed to report worker: ${reportRequest.id} (${message})`),this.#respondError(error)}}async removeWorker(removeRequest){try{const gateway=this.#extractLocalGatewayFromProxy();return await gateway.removeWorker(removeRequest.id),this.#logger.info(`Removed worker: ${removeRequest.id}`),this.#respondSuccess()}catch(error){const message=error instanceof Error?error.message:String(error);return this.#logger.error(`Failed to remove worker: ${removeRequest.id} (${message})`),this.#respondError(error)}}async#setUp(){await this.#resourceManager.start(),await Promise.all([this.#proxy.start(),this.#middlewareManager.start()]);const procedureRunner=new ProcedureRunner(this.#proxy);this.#middlewareManager.addMiddleware(procedureRunner)}async#tearDown(){await Promise.all([this.#middlewareManager.stop(),this.#proxy.stop()]),await this.#resourceManager.stop()}#transformRunRequest(request){const fqn=this.#processFqn(request.fqn),version=this.#parseVersion(request.version),args=this.#mapArguments(request.args),headers=this.#mapHeaders(request.headers);return new Request(fqn,version,args,headers,request.mode)}#processFqn(fqn){if(0===fqn.length)throw new BadRequest("Missing procedure name");if(fqn.includes(".."))throw new BadRequest("Invalid procedure name");return fqn}#parseVersion(version){return"string"!=typeof version?Version.DEFAULT:this.#versionParser.parse(version)}#mapArguments(args){return new Map(Object.entries(args))}#mapHeaders(headers){const map=new Map;for(const[key,value]of Object.entries(headers)){if(void 0===value)continue;const lowerKey=key.toLowerCase(),stringValue=value.toString();map.set(lowerKey,stringValue)}return map}#translateState(state){if(!1===Object.values(States$2).includes(state))throw new BadRequest("Invalid state value");return state}#respondHealth(health){return{result:Object.fromEntries(health),contentType:ContentTypes_JSON,headers:{},status:StatusCodes_OK}}#respondHealthy(healthy){return{result:healthy,contentType:ContentTypes_BOOLEAN,headers:{},status:StatusCodes_OK}}#respondFile(file){return{result:file.content,contentType:file.type,headers:{},status:StatusCodes_OK}}#respondResponse(response){const result=response.result instanceof Error?response.result.message:response.result;return{result:result,contentType:this.#determineContentType(result),headers:this.#unmapHeaders(response.headers),status:response.status}}#respondError(error){const result=error instanceof Error?error.message:String(error);return{result:result,contentType:this.#determineContentType(result),headers:{},status:this.#determineStatusCode(error)}}#respondSuccess(result){return{result:result,contentType:this.#determineContentType(result),headers:{},status:StatusCodes_OK}}#determineContentType(content){if(void 0===content)return ContentTypes_UNDEFINED;if(null===content)return ContentTypes_NULL;switch(typeof content){case"boolean":return ContentTypes_BOOLEAN;case"number":return ContentTypes_NUMBER;case"object":return ContentTypes_JSON;default:return ContentTypes_TEXT}}#unmapHeaders(headers){return Object.fromEntries(headers)}#determineStatusCode(error){return error instanceof BadRequest?StatusCodes_BAD_REQUEST:error instanceof Forbidden?StatusCodes_FORBIDDEN:error instanceof NotFound?StatusCodes_NOT_FOUND:error instanceof NotImplemented?StatusCodes_NOT_IMPLEMENTED:error instanceof PaymentRequired?StatusCodes_PAYMENT_REQUIRED:error instanceof Teapot?StatusCodes_TEAPOT:error instanceof Unauthorized?StatusCodes_UNAUTHORIZED:StatusCodes_SERVER_ERROR}#extractLocalGatewayFromProxy(){const runner=this.#proxy.runner;if(runner instanceof LocalGateway==!1)throw new BadRequest("Cannot remove worker from remote gateway");return runner}}class UnknownServiceConfigured extends Error{constructor(){super("Unknown service configured")}}class ResourceManager{#sourcingManager;#setUpScripts;#tearDownScripts;constructor(sourcingManager,setUpScripts=[],tearDownScripts=[]){this.#sourcingManager=sourcingManager,this.#setUpScripts=setUpScripts,this.#tearDownScripts=tearDownScripts}async start(){return this.#runSetupScripts()}async stop(){return this.#runTearDownScripts()}#runSetupScripts(){return this.#runScripts(this.#setUpScripts)}#runTearDownScripts(){return this.#runScripts(this.#tearDownScripts)}async#runScripts(scripts){await Promise.all(scripts.map(script=>this.#sourcingManager.import(script)))}}class RuntimeBuilder{#sourcingManager;#remoteBuilder;constructor(sourcingManager,remoteBuilder){this.#sourcingManager=sourcingManager,this.#remoteBuilder=remoteBuilder}async build(configuration,logLevel){const setUp=configuration.setUp,tearDown=configuration.tearDown,middleware=configuration.middleware,healthChecks=configuration.healthChecks,logger=new Logger(logLevel),healthManager=this.#buildHealthManager(healthChecks),scheduleManager=this.#buildScheduleManager(logger),proxy=await this.#buildService(configuration,healthManager,scheduleManager),sourcingManager=this.#sourcingManager,resourceManager=this.#buildResourceManager(setUp,tearDown),middlewareManager=this.#buildMiddlewareManager(middleware),remoteWorkerBuilder=this.#buildRemoteWorkerBuilder(configuration);return new Server({proxy:proxy,sourcingManager:sourcingManager,resourceManager:resourceManager,middlewareManager:middlewareManager,remoteWorkerBuilder:remoteWorkerBuilder,logger:logger})}#buildService(configuration,healthManager,scheduleManager){if(void 0!==configuration.gateway)return this.#buildGatewayProxy(configuration.url,configuration.gateway,healthManager,scheduleManager);if(void 0!==configuration.worker)return this.#buildWorkerProxy(configuration.url,configuration.worker,healthManager,scheduleManager);if(void 0!==configuration.repository)return this.#buildRepositoryProxy(configuration.url,configuration.repository,healthManager);if(void 0!==configuration.proxy)return this.#buildProxy(configuration.url,configuration.proxy);if(void 0!==configuration.standalone)return this.#buildStandalone(configuration.url,configuration.standalone,healthManager,scheduleManager);throw new UnknownServiceConfigured}async#buildGatewayProxy(url,configuration,healthManager,scheduleManager){const provider=new DummyProvider,runner=this.#buildLocalGateway(url,configuration,healthManager,scheduleManager);return new LocalProxy({url:url,provider:provider,runner:runner})}async#buildWorkerProxy(url,configuration,healthManager,scheduleManager){const provider=new DummyProvider,runner=this.#buildLocalWorker(url,configuration,healthManager,scheduleManager);return new LocalProxy({url:url,provider:provider,runner:runner})}async#buildRepositoryProxy(url,configuration,healthManager){const provider=await this.#buildLocalRepository(url,configuration,healthManager),runner=new DummyRunner;return new LocalProxy({url:url,provider:provider,runner:runner})}#buildLocalGateway(url,configuration,healthManager,scheduleManager){const trustKey=configuration.trustKey,monitorInterval=configuration.monitorInterval,workerManager=new WorkerManager(scheduleManager,monitorInterval);return new LocalGateway({url:url,trustKey:trustKey,healthManager:healthManager,workerManager:workerManager})}#buildRemoteGateway(url){const remote=this.#remoteBuilder.build(url);return new RemoteGateway({url:url,remote:remote})}#buildLocalWorker(url,configuration,healthManager,scheduleManager){const trustKey=configuration.trustKey,gateway=configuration.gateway?this.#buildRemoteGateway(configuration.gateway):void 0,reportInterval=configuration.reportInterval,registerAtGateway=void 0!==gateway,executionManager=this.#buildExecutionManager(configuration.segments),serializer=this.#buildSerializer(executionManager);return new LocalWorker({url:url,trustKey:trustKey,reportInterval:reportInterval,gateway:gateway,registerAtGateway:registerAtGateway,executionManager:executionManager,serializer:serializer,healthManager:healthManager,scheduleManager:scheduleManager})}async#buildLocalRepository(url,configuration,healthManager){const sourcingManager=void 0!==configuration.assetRoot?this.#sourcingManager.fork(configuration.assetRoot):this.#sourcingManager,assets=await this.#buildAssetSet(sourcingManager,configuration.assets),directoryIndex=configuration.directoryIndex,fallback=configuration.fallback;return new LocalRepository({url:url,sourcingManager:sourcingManager,assets:assets,directoryIndex:directoryIndex,fallback:fallback,healthManager:healthManager})}#buildRemoteRepository(url){const remote=this.#remoteBuilder.build(url);return new RemoteRepository({url:url,remote:remote})}async#buildProxy(url,configuration){const provider=this.#buildRemoteRepository(configuration.repository),runner=this.#buildRemoteGateway(configuration.gateway);return new LocalProxy({url:url,provider:provider,runner:runner})}async#buildStandalone(url,configuration,healthManager,scheduleManager){const provider=await this.#buildLocalRepository(url,configuration,healthManager),runner=this.#buildLocalWorker(url,configuration,healthManager,scheduleManager);return new LocalProxy({url:url,provider:provider,runner:runner})}#buildResourceManager(setUp=[],tearDown=[]){const translatedSetUp=setUp.map(filename=>this.#assureExtension(filename)),translatedTearDown=tearDown.map(filename=>this.#assureExtension(filename));return new ResourceManager(this.#sourcingManager,translatedSetUp,translatedTearDown)}#buildHealthManager(filenames=[]){const translatedFilenames=filenames.map(filename=>this.#assureExtension(filename));return new HealthManager(this.#sourcingManager,translatedFilenames)}#buildMiddlewareManager(filenames=[]){const translatedFilenames=filenames.map(filename=>this.#assureExtension(filename));return new MiddlewareManager(this.#sourcingManager,translatedFilenames)}#buildExecutionManager(segmentNames=[]){const filenames=segmentNames.map(name=>`./${name}.segment.js`),manager=new ExecutionManager(this.#sourcingManager,filenames);return manager.addSegment(segment),manager}#buildSerializer(executionManager){const classResolver=new ExecutionClassResolver(executionManager);return SerializerBuilder.build(classResolver)}#buildScheduleManager(logger){return new ScheduleManager(logger)}#buildRemoteWorkerBuilder(configuration){const unavailableThreshold=configuration.remoteWorker?.unavailableThreshold,stoppedThreshold=configuration.remoteWorker?.stoppedThreshold;return new RemoteWorkerBuilder(this.#remoteBuilder,unavailableThreshold,stoppedThreshold)}async#buildAssetSet(sourcingManager,patterns){if(void 0===patterns)return new Set;const filenames=await sourcingManager.filter(...patterns);return new Set(filenames)}#assureExtension(filename){return filename.endsWith(".js")?filename:filename+".js"}}const Defaults={PORT_NUMBER:"3000",BODY_LIMIT:204800,PROXIED:!0},IgnoredHeaderKeys=["connection","content-length","accept-encoding","user-agent","keep-alive"];class HttpServer{#server;#port;#app;#proxied;#http;#validator=new Validator;constructor(server,configuration){this.#port=configuration.port??Defaults.PORT_NUMBER,this.#proxied=configuration.proxied??Defaults.PROXIED;const bodyLimit=configuration.bodyLimit??Defaults.BODY_LIMIT;this.#server=server,this.#app=express(),this.#setupExpress(bodyLimit),this.#setupRoutes()}async start(){return await this.#server.start(),this.#startHttp()}async stop(){return await this.#stopHttp(),this.#server.stop()}#setupExpress(bodyLimit){this.#app.use(this.#validateContentType.bind(this)),this.#app.use(express.json({limit:bodyLimit})),this.#app.use(this.#addDefaultHeaders.bind(this)),this.#app.disable(HeaderKeys_POWERED_BY)}#setupRoutes(){this.#app.get("/health",(request,response)=>{this.#getHealth(request,response)}),this.#app.get("/health/status",(request,response)=>{this.#isHealthy(request,response)}),this.#app.get("/rpc/*procedure",(request,response)=>{this.#runGet(request,response)}),this.#app.post("/rpc/*procedure",(request,response)=>{this.#runPost(request,response)}),this.#app.options("/rpc/*procedure",(request,response)=>{this.#runOptions(request,response)}),this.#app.post("/workers",(request,response)=>{this.#addWorker(request,response)}),this.#app.post("/workers/:id/report",(request,response)=>{this.#reportWorker(request,response)}),this.#app.delete("/workers/:id",(request,response)=>{this.#removeWorker(request,response)}),this.#app.use((request,response)=>{this.#provide(request,response)})}#startHttp(){return void 0!==this.#http?Promise.resolve():new Promise((resolve,reject)=>{this.#http=this.#app.listen(this.#port,reject),resolve()})}#stopHttp(){return void 0===this.#http?Promise.resolve():new Promise(resolve=>{this.#http.close(()=>resolve())})}#validateContentType(request,response,next){return"POST"!==request.method||!1!==request.is("application/json")&&null!==request.is("application/json")?next():void response.status(415).json({error:"Content-Type must be application/json"})}#addDefaultHeaders(request,response,next){return response.setHeader(HeaderKeys_CONTENT_TYPE_OPTIONS,HeaderValues_NO_SNIFF),next()}async#getHealth(request,response){const serverResponse=await this.#server.getHealth();return this.#transformResponse(response,serverResponse)}async#isHealthy(request,response){const serverResponse=await this.#server.isHealthy();return this.#transformResponse(response,serverResponse)}async#runGet(request,response){const fqn=this.#extractFqn(request),version=this.#extractVersion(request),args=this.#extractQueryArguments(request),headers=this.#extractHeaders(request),mode=RunModes_NORMAL,serverResponse=await this.#server.run({fqn:fqn,version:version,args:args,headers:headers,mode:mode});return this.#transformResponse(response,serverResponse)}async#runPost(request,response){const fqn=this.#extractFqn(request),version=this.#extractVersion(request),args=this.#extractBodyArguments(request),headers=this.#extractHeaders(request),mode=RunModes_NORMAL,serverResponse=await this.#server.run({fqn:fqn,version:version,args:args,headers:headers,mode:mode});return this.#transformResponse(response,serverResponse)}async#runOptions(request,response){const fqn=this.#extractFqn(request),version=this.#extractVersion(request),args=this.#extractBodyArguments(request),headers=this.#extractHeaders(request),mode=RunModes_DRY,serverResponse=await this.#server.run({fqn:fqn,version:version,args:args,headers:headers,mode:mode});return this.#transformResponse(response,serverResponse)}async#addWorker(request,response){const args=this.#extractBodyArguments(request),validation=this.#validator.validate(args,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===validation.valid)return response.status(400).send(validation.errors.join("\n"));const url=args.url,procedureNames=args.procedureNames,trustKey=args.trustKey;try{const serverResponse=await this.#server.addWorker({url:url,procedureNames:procedureNames,trustKey:trustKey});return this.#transformResponse(response,serverResponse)}catch(error){const message=error instanceof Error?error.message:"Server error";return response.status(500).send(message)}}async#reportWorker(request,response){const args={id:request.params.id,state:request.body.state},validation=this.#validator.validate(args,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===validation.valid)return response.status(400).send(validation.errors.join("\n"));const id=args.id,state=args.state;try{const serverResponse=await this.#server.reportWorker({id:id,state:state});return this.#transformResponse(response,serverResponse)}catch(error){const message=error instanceof Error?error.message:"Server error";return response.status(500).send(message)}}async#removeWorker(request,response){const args={id:request.params.id},validation=this.#validator.validate(args,{id:{type:"string",required:!0}});if(!1===validation.valid)return response.status(400).send(validation.errors.join("\n"));const id=args.id;try{const serverResponse=await this.#server.removeWorker({id:id});return this.#transformResponse(response,serverResponse)}catch(error){const message=error instanceof Error?error.message:"Server error";return response.status(500).send(message)}}async#provide(request,response){const path=request.path.substring(1).trim(),filename=decodeURIComponent(path),serverResponse=await this.#server.provide({filename:filename});return this.#transformResponse(response,serverResponse)}#extractFqn(request){return decodeURIComponent(request.path.trim()).substring(5).trim()}#extractVersion(request){const versionString=request.headers[HeaderKeys_JITAR_PROCEDURE_VERSION];return Array.isArray(versionString)?versionString[0]:versionString}#extractQueryArguments(request){const args={};for(const[key,value]of Object.entries(request.query))args[key]=value;return args}#extractBodyArguments(request){return request.body}#extractHeaders(request){const headers={};for(const[key,value]of Object.entries(request.headers)){if(void 0===value)continue;const lowerKey=key.toLowerCase(),stringValue=value.toString();IgnoredHeaderKeys.includes(lowerKey)||(headers[lowerKey]=stringValue)}return!1===this.#proxied&&(headers[HeaderKeys_X_FORWARDED_PROTO]=request.protocol,headers[HeaderKeys_X_FORWARDED_HOST]=request.host,headers[HeaderKeys_X_FORWARDED_FOR]=request.ip),headers}#transformResponse(response,serverResponse){const status=this.#transformStatus(serverResponse),contentType=this.#transformContentType(serverResponse);response.status(status),response.setHeader(HeaderKeys_CONTENT_TYPE,contentType),response.setHeader(HeaderKeys_JITAR_CONTENT_TYPE,serverResponse.contentType);for(const[name,value]of Object.entries(serverResponse.headers))response.setHeader(name,value);const result=this.#transformResult(serverResponse);return response.send(result)}#transformStatus(serverResponse){return void 0!==serverResponse.headers.location?302:serverResponse.status}#transformContentType(serverResponse){const contentType=serverResponse.contentType.toLowerCase();switch(contentType){case ContentTypes_BOOLEAN:case ContentTypes_NUMBER:case ContentTypes_UNDEFINED:case ContentTypes_NULL:return ContentTypes_TEXT}return contentType}#transformResult(serverResponse){const result=serverResponse.result;return"number"==typeof result||"boolean"==typeof result?String(result):result}}class StartServer{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"}];async execute(args){const environmentFile=args.getOptionalArgument("--env-file",void 0),runtimeConfigFile=args.getOptionalArgument("--config",void 0),serviceConfigFile=args.getRequiredArgument("--service"),logLevelString=args.getOptionalArgument("--log-level",void 0),logLevel=this.#parseLogLevel(logLevelString),configurationManager=new ConfigurationManager;await configurationManager.configureEnvironment(environmentFile);const runtimeConfiguration=await configurationManager.getRuntimeConfiguration(runtimeConfigFile),serviceConfiguration=await configurationManager.getServiceConfiguration(serviceConfigFile),httpServer=await this.#buildServer(runtimeConfiguration,serviceConfiguration,logLevel);return this.#runServer(httpServer)}async#buildServer(runtimeConfiguration,serviceConfiguration,logLevel){const[,,port]=serviceConfiguration.url.split(":"),configuration={port:port,bodyLimit:serviceConfiguration.http?.bodyLimit,proxied:serviceConfiguration.http?.proxied},sourcingManager=new LocalSourcingManager(runtimeConfiguration.target),remoteBuilder=new HttpRemoteBuilder,serverBuilder=new RuntimeBuilder(sourcingManager,remoteBuilder),server=await serverBuilder.build(serviceConfiguration,logLevel);return new HttpServer(server,configuration)}#runServer(httpServer){let isShuttingDown=!1;return process.on("SIGINT",async()=>{isShuttingDown||(isShuttingDown=!0,httpServer.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),httpServer.start()}#parseLogLevel(logLevel){if(void 0===logLevel)return;return(new LogLevelParser).parse(logLevel)}}class CommandNotFound extends Error{constructor(name){super(`Command ${name} not found`)}}class CommandRunner{#commands=new Set;constructor(){this.#commands.add(new ShowHelp(this.#commands)),this.#commands.add(new ShowAbout),this.#commands.add(new ShowVersion),this.#commands.add(new InitApp),this.#commands.add(new BuildApp),this.#commands.add(new StartServer)}run(name,args){for(const command of this.#commands)if(command.name===name)return command.execute(args);throw new CommandNotFound(name)}}class Cli{#argumentProcessor;#commandRunner;constructor(){this.#argumentProcessor=new ArgumentProcessor(process.argv),this.#commandRunner=new CommandRunner}start(){const commandName=this.#argumentProcessor.getCommand()??"help";return this.#commandRunner.run(commandName,this.#argumentProcessor)}}const logger=new Logger;try{const cli=new Cli;await cli.start()}catch(error){logger.fatal(error),process$1.exitCode=1}
|