jitar 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
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)&&copy.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}
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)&&copy.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(express.json({limit:bodyLimit})),this.#app.use(express.urlencoded({extended:!1})),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())})}#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}
@@ -10,7 +10,7 @@
10
10
  "hello": "jitar start --service=services/hello.json"
11
11
  },
12
12
  "dependencies": {
13
- "jitar": "^0.12.0"
13
+ "jitar": "^0.13.0"
14
14
  },
15
15
  "devDependencies": {
16
16
  "rimraf": "^6.1.3",
@@ -11,7 +11,7 @@
11
11
  "standalone": "jitar start --service=services/standalone.json"
12
12
  },
13
13
  "dependencies": {
14
- "jitar": "^0.12.0",
14
+ "jitar": "^0.13.0",
15
15
  "react": "^19.3.1",
16
16
  "react-dom": "^19.3.1"
17
17
  },
@@ -11,7 +11,7 @@
11
11
  "standalone": "jitar start --service=services/standalone.json"
12
12
  },
13
13
  "dependencies": {
14
- "jitar": "^0.12.0",
14
+ "jitar": "^0.13.0",
15
15
  "vue": "^3.5.44"
16
16
  },
17
17
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jitar",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "Distributed runtime for JavaScript and TypeScript to chop monolithic applications into micros.",
5
5
  "author": "Masking Technology <info@masking.tech> (https://jitar.dev)",
6
6
  "license": "MIT",