@interopio/gateway-server 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/changelog.md CHANGED
@@ -2,6 +2,33 @@
2
2
 
3
3
  # Change Log
4
4
 
5
+ ## 0.22.0 (2026-02-20)
6
+
7
+ ### Added
8
+ - feat: support config from gateway-server.config.{js,mjs,cjs,ts,mts,cts,json} files (with auto config file detection)
9
+ - feat: management of the server via ipc (info and shutdown commands implemented for now, more to come)
10
+ - feat: cli manage command
11
+ ### Changed
12
+ - chore: bump @interopio/gateway to 0.24.0
13
+ - feat: config is now in separate ts.d
14
+ ### Fixed
15
+ - fix: malformed http host/x-forwarded-host header handling
16
+
17
+ ## 0.21.0 (2026-01-27)
18
+
19
+ ### Added
20
+ - feat: support for static resources (+ welcome page detection)
21
+ - feat: support for config from JSON
22
+ - feat: disable auth/ssl via --no-auth/--no-ssl/--no-tls options
23
+ - feat: middleware support for test clients
24
+ - feat: support for disabling metrics and mesh via config
25
+
26
+ ### Changed
27
+ - `gateway-server` cli no longer exposes gateway by default (--gateway option is needed)
28
+
29
+ ### Fixed
30
+ - fix: headers mapping in test client
31
+
5
32
  ## 0.20.0 (2026-01-20)
6
33
 
7
34
  ### Added
@@ -0,0 +1,2 @@
1
+ "use strict";var f=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var t=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var v=(r,e)=>{for(var o in e)f(r,o,{get:e[o],enumerable:!0})},S=(r,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of t(e))!C.call(r,n)&&n!==o&&f(r,n,{get:()=>e[n],enumerable:!(i=g(e,n))||i.enumerable});return r};var m=r=>S(f({},"__esModule",{value:!0}),r);var u={};v(u,{defineConfig:()=>p});module.exports=m(u);function p(r){return r}0&&(module.exports={defineConfig});
2
+ //# sourceMappingURL=config.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/config.ts"],
4
+ "sourcesContent": ["import { ServerConfig } from '../types/config';\n\nexport function defineConfig(config: ServerConfig): ServerConfig {\n return config;\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAEO,SAASE,EAAaE,EAAoC,CAC7D,OAAOA,CACX",
6
+ "names": ["config_exports", "__export", "defineConfig", "__toCommonJS", "config"]
7
+ }
package/dist/config.js ADDED
@@ -0,0 +1,2 @@
1
+ function e(r){return r}export{e as defineConfig};
2
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/config.ts"],
4
+ "sourcesContent": ["import { ServerConfig } from '../types/config';\n\nexport function defineConfig(config: ServerConfig): ServerConfig {\n return config;\n}\n"],
5
+ "mappings": "AAEO,SAASA,EAAaC,EAAoC,CAC7D,OAAOA,CACX",
6
+ "names": ["defineConfig", "config"]
7
+ }
package/dist/index.cjs CHANGED
@@ -1,8 +1,22 @@
1
- "use strict";var Xr=Object.create;var xe=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Qr=Object.prototype.hasOwnProperty;var Dt=(t,e)=>{for(var r in e)xe(t,r,{get:e[r],enumerable:!0})},$t=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Kr(e))!Qr.call(t,o)&&o!==r&&xe(t,o,{get:()=>e[o],enumerable:!(n=Jr(e,o))||n.enumerable});return t};var ue=(t,e,r)=>(r=t!=null?Xr(Yr(t)):{},$t(e||!t||!t.__esModule?xe(r,"default",{value:t,enumerable:!0}):r,t)),Zr=t=>$t(xe({},"__esModule",{value:!0}),t);var Ao={};Dt(Ao,{GatewayServer:()=>It,default:()=>Eo});module.exports=Zr(Ao);var It={};Dt(It,{Factory:()=>Mt,VERSION:()=>Vr});var qr=ue(require("node:http"),1),zr=ue(require("node:https"),1),jr=require("node:async_hooks");var Wt=require("node:os"),en=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function ct(t){if(t>65535)throw new Error(`bad port ${t}`);return t}function*Ut(t){if(typeof t=="string")for(let e of t.split(",")){let r=e.trim(),n=en.exec(r);if(n){let o=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let s=ct(o);s<ct(i)+1;s++)yield s}else throw new Error(`'${e}' is not a valid port or range.`)}else yield ct(t)}var Nt=(()=>{function t(r){return r.length>0?r[0]:void 0}let e=Object.values((0,Wt.networkInterfaces)()).flatMap(r=>(r??[]).filter(n=>n.family==="IPv4")).reduce((r,n)=>(r[n.internal?"internal":"external"].push(n),r),{internal:[],external:[]});return(t(e.internal)??t(e.external))?.address})();function B(t){if(t)return t.family==="IPv6"?`[${t.address}]:${t.port}`:`${t.address}:${t.port}`}var Ft=ue(require("@interopio/gateway/logging/core"),1);function w(t){return Ft.getLogger(`gateway.server.${t}`)}function Gt(t,e){return e instanceof RegExp?e.toString():e}var Bt=require("@interopio/gateway"),_t=require("node:async_hooks"),N=w("ws"),tn=Bt.IOGateway.Encoding.json();function rn(t){let e;if(t.authenticated&&(e=t.name,e===void 0&&t.principal!==void 0)){let r=t.principal;typeof r=="object"&&r!==null&&("username"in r||"name"in r)&&(e=r.username??r.name),e===void 0&&(r==null?e="":e=String(r))}return e}function nn(t,e,r,n){let o=B(n),i=n?.address??"<unknown>",s={key:o,host:i,codec:tn,onAuthenticate:async()=>{let a=await r();if(a?.authenticated)return{type:"success",user:rn(a)};throw new Error(`no valid client authentication ${o}`)},onPing:()=>{e.ping(a=>{a?N.warn(`failed to ping ${o}`,a):N.info(`ping sent to ${o}`)})},onDisconnect:a=>{switch(a){case"inactive":{N.warn(`no heartbeat (ping) received from ${o}, closing socket`),e.close(4001,"ping expected");break}case"shutdown":{e.close(1001,"shutdown");break}}}};try{return t.client(a=>e.send(a),s)}catch(a){N.warn(`${o} failed to create client`,a)}}async function on(t){return N.info(`starting gateway on ${t.endpoint}`),await this.start(t),async({socket:e,handshake:r})=>{let{logPrefix:n,remoteAddress:o,principal:i}=r,s=(await i())?.name;N.info(`${n}connected on gw as ${s??"<anonymous>"}`);let a=await this.getGateway(s),c=nn(a,e,i,o);if(!c){N.error(`${n}gw client init failed`),e.terminate();return}e.on("error",u=>{N.error(`${n}websocket error: ${u}`,u)});let d=t.storage!==void 0?_t.AsyncLocalStorage.snapshot():void 0;e.on("message",(u,l)=>{Array.isArray(u)&&(u=Buffer.concat(u)),d!==void 0?d(()=>c.send(u)):c.send(u)}),e.on("close",u=>{N.info(`${n}disconnected from gw. code: ${u}`),c.close()})}}var qt=on;var dt=require("@interopio/gateway");var A=w("gateway-manager");function zt(){return globalThis.crypto.randomUUID().replaceAll("-","")}var Ee=class{#e;#r;#t=new Map;#n=new Map;#i;#s=!1;#o;constructor(e){this.#i={baseConfig:e.baseConfig,scope:e.scope??"principal"},this.#e=e.baseConfig.node??zt(),A.enabledFor("debug")&&A.debug(`creating default gateway with gateway id: ${this.#e}`),this.#r=dt.IOGateway.Factory({...e.baseConfig,node:this.#e})}async start(e){return this.#s?this:(this.#o=e,A.debug("starting default gateway"),await this.#r.start(e),this.#s=!0,this)}async getGateway(e){if(this.#i.scope==="singleton"||!e)return this.#r;let r=this.#n.get(e),n=r?this.#t.get(r):void 0;return n?A.enabledFor("debug")&&A.debug(`reusing existing gateway for principal '${e}'`):(A.enabledFor("debug")&&A.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.createPrincipalGateway(e)),n}async createPrincipalGateway(e){let r=zt(),n={...this.#i.baseConfig,node:r};A.enabledFor("debug")&&A.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let o=dt.IOGateway.Factory(n);return this.#n.set(e,r),this.#t.set(r,o),await o.start(this.#o),o}getGateways(){let e=new Map(this.#t);return e.set(this.#e,this.#r),e}info(e){if(e&&this.#e!==e){let r=this.#t.get(e);if(r)return r.info();throw new Error(`no gateway found with ID: ${e}`)}return e===this.#e?this.#r.info():{...this.#r.info(),managedGateways:this.#t.size,scope:this.#i.scope}}async stop(e){if(e&&this.#e!==e){let r=this.#t.get(e);if(r){A.info(`stopping gateway with ID: ${e}`),await r.stop(),this.#t.delete(e);for(let[n,o]of this.#n.entries())if(o===e){this.#n.delete(n);break}return r}else throw new Error(`no gateway found with ID: ${e}`)}if(e===this.#e)return A.debug("stopping default gateway (managed gateways will continue running)"),await this.#r.stop(),this.#s=!1,this.#r;A.info(`stopping all gateways (1 default + ${this.#t.size} managed)`);for(let[r,n]of this.#t.entries())A.enabledFor("debug")&&A.debug(`stopping gateway with ID: ${r}`),await n.stop();return this.#t.clear(),this.#n.clear(),A.debug("stopping default gateway"),await this.#r.stop(),this.#s=!1,this.#r}getPrincipalGatewayId(e){return this.#n.get(e)}getPrincipalGatewayIds(){return new Map(this.#n)}getDefaultGateway(){return this.#r}client(e,r){return this.#r.client(e,r)}async connect(e){return this.#r.connect(e)}getPrincipalCount(){return this.#t.size}};function jt(...t){if(!Array.isArray(t))throw new Error("middleware must be array!");let e=t.flat();for(let r of e)if(typeof r!="function")throw new Error("middleware must be compose of functions!");return async function(r,n){let o=async(i,s)=>{let a=i===e.length?n:e[i];if(a===void 0)return;let c=!1,d=!1,l=await a(s,async m=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await o(i+1,m??s)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream.
2
- You are probably missing an await or return statement in your middleware function.`);return l};return o(0,r)}}var Vt=require("node:net"),He=require("tough-cookie");function sn(t,e){let r=t.get("x-forwarded-host");if(Array.isArray(r)&&(r=r[0]),r){let n=t.one("x-forwarded-port");n&&(r=`${r}:${n}`)}return r??=t.one("host"),Array.isArray(r)&&(r=r[0]),r?r.split(",",1)[0].trim():e}function an(t){let e=t.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function cn(t,e){let r=t.get("x-forwarded-proto");return Array.isArray(r)&&(r=r[0]),r!==void 0?r.split(",",1)[0].trim():an(t)?"https":e}function dn(t,e,r){let n=r?r.port:t.protocol==="https:"?443:80,o=e.one("x-forwarded-for");if(Array.isArray(o)&&(o=o[0]),o!==void 0)return o=o.split(",",1)[0].trim(),{address:o,port:Number(n),family:(0,Vt.isIP)(o)===6?"IPv6":"IPv4"}}var Ae=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},Ce=class t extends Ae{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++t.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return ln(this.headers)}parseHost(e){return sn(this.headers,e)}parseProtocol(e){return cn(this.headers,e)}parseRemoteAddress(e){return dn(this.URL,this.headers,e)}},Pe=class extends Ae{get cookies(){return pn(this.headers)}setCookieValue(e){return new He.Cookie({key:e.name,value:e.value,maxAge:e.maxAge,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httpOnly,sameSite:e.sameSite}).toString()}};function un(t){let e=[];{let r=0,n=0;for(let o=0;o<t.length;o++)switch(t.charCodeAt(o)){case 32:r===n&&(r=n=o+1);break;case 44:e.push(t.slice(r,n)),r=n=o+1;break;default:n=n+1;break}e.push(t.slice(r,n))}return e}function Xt(t){typeof t=="string"&&(t=[t]),typeof t=="number"&&(t=[String(t)]);let e=[];if(t)for(let r of t)r&&e.push(...un(r));return e}function ln(t){return t.list("cookie").map(e=>e.split(";").map(r=>He.Cookie.parse(r))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function pn(t){return t.list("set-cookie").map(e=>{let r=He.Cookie.parse(e);if(r){let n={name:r.key,value:r.value,maxAge:Number(r.maxAge??-1)};return r.httpOnly&&(n.httpOnly=!0),r.domain&&(n.domain=r.domain),r.path&&(n.path=r.path),r.secure&&(n.secure=!0),r.httpOnly&&(n.httpOnly=!0),r.sameSite&&(n.sameSite=r.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}var le=class{constructor(){}toList(e){let r=this.get(e);return Xt(r)}},E=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let r=super.get(e.toLowerCase());return Xt(r)}set(e,r){return typeof r=="number"&&(r=String(r)),typeof r=="string"&&(r=[r]),r?super.set(e.toLowerCase(),r):(super.delete(e.toLowerCase()),this)}add(e,r){let n=super.get(e.toLowerCase());return typeof r=="string"&&(r=[r]),n&&(r=n.concat(r)),this.set(e,r),this}};var ut=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},S=class t{static CONTINUE=new t(100,"Continue");static SWITCHING_PROTOCOLS=new t(101,"Switching Protocols");static OK=new t(200,"OK");static CREATED=new t(201,"Created");static ACCEPTED=new t(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new t(203,"Non-Authoritative Information");static NO_CONTENT=new t(204,"No Content");static RESET_CONTENT=new t(205,"Reset Content");static PARTIAL_CONTENT=new t(206,"Partial Content");static MULTI_STATUS=new t(207,"Multi-Status");static IM_USED=new t(226,"IM Used");static MULTIPLE_CHOICES=new t(300,"Multiple Choices");static MOVED_PERMANENTLY=new t(301,"Moved Permanently");static BAD_REQUEST=new t(400,"Bad Request");static UNAUTHORIZED=new t(401,"Unauthorized");static FORBIDDEN=new t(403,"Forbidden");static NOT_FOUND=new t(404,"Not Found");static METHOD_NOT_ALLOWED=new t(405,"Method Not Allowed");static NOT_ACCEPTABLE=new t(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new t(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new t(408,"Request Timeout");static CONFLICT=new t(409,"Conflict");static GONE=new t(410,"Gone");static LENGTH_REQUIRED=new t(411,"Length Required");static PRECONDITION_FAILED=new t(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new t(413,"Payload Too Large");static URI_TOO_LONG=new t(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new t(415,"Unsupported Media Type");static EXPECTATION_FAILED=new t(417,"Expectation Failed");static IM_A_TEAPOT=new t(418,"I'm a teapot");static TOO_EARLY=new t(425,"Too Early");static UPGRADE_REQUIRED=new t(426,"Upgrade Required");static PRECONDITION_REQUIRED=new t(428,"Precondition Required");static TOO_MANY_REQUESTS=new t(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new t(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new t(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new t(500,"Internal Server Error");static NOT_IMPLEMENTED=new t(501,"Not Implemented");static BAD_GATEWAY=new t(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new t(503,"Service Unavailable");static GATEWAY_TIMEOUT=new t(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new t(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new t(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new t(507,"Insufficient Storage");static LOOP_DETECTED=new t(508,"Loop Detected");static NOT_EXTENDED=new t(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new t(511,"Network Authentication Required");static#e=[];static{Object.keys(t).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let r=t[e];r instanceof t&&(Object.defineProperty(r,"name",{enumerable:!0,value:e,writable:!1}),t.#e.push(r))})}static resolve(e){for(let r of t.#e)if(r.value===e)return r}#r;#t;constructor(e,r){this.#r=e,this.#t=r}get value(){return this.#r}get phrase(){return this.#t}toString(){return`${this.#r} ${this.name}`}};function Jt(t){if(typeof t=="number"){if(t<100||t>999)throw new Error(`status code ${t} should be in range 100-999`);let e=S.resolve(t);return e!==void 0?e:new ut(t)}return t}var De=ue(require("node:http"),1),ke=class extends De.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},Y=class extends De.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},Re=class extends Ce{#e;get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}},Te=class extends Pe{#e=[];#r;#t="new";#n=[];setStatusCode(e){return this.#t==="committed"?!1:(this.#r=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:Jt(e))}get statusCode(){return this.#r}addCookie(e){if(this.#t==="committed")throw new Error(`Cannot add cookie ${JSON.stringify(e)} because HTTP response has already been committed`);return this.#e.push(e),this}beforeCommit(e){this.#n.push(e)}get commited(){let e=this.#t;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let r=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(r))).catch(n=>{throw n})}catch(n){throw n}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let r=this.#t,n=Promise.resolve();if(r==="new")this.#t="committing",this.#n.length>0&&(n=this.#n.reduce((o,i)=>o.then(()=>i()),Promise.resolve()).catch(o=>{this.#t==="committing"&&(this.#t="commit-action-failed")}));else if(r==="commit-action-failed")this.#t="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#t="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},Q=class extends Re{#e;#r;#t;constructor(e){super(new pt(e)),this.#t=e}getNativeRequest(){return this.#t}get upgrade(){return this.#t.upgrade}get http2(){return this.#t.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#t.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#t.method}get host(){let e;return this.#t.httpVersionMajor>=2&&(e=this.#t.headers[":authority"]),e??=this.#t.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#t.httpVersionMajor>2&&(e=this.#t.headers[":scheme"]),e??=this.#t.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#t.socket}get remoteAddress(){let e=this.#t.socket.remoteFamily,r=this.#t.socket.remoteAddress,n=this.#t.socket.remotePort,o=!e||!r||!n?void 0:{family:e,address:r,port:n};return super.parseRemoteAddress(o)??o}initSslInfo(){if(this.#t.socketEncrypted)return new lt(this.#t.socket)}get cookies(){return this.#r??=super.cookies,this.#r}get body(){return De.default.IncomingMessage.toWeb(this.#t)}async blob(){let e=[];if(this.body!==void 0)for await(let r of this.body)e.push(r);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let r=await(await this.blob()).text();return new URLSearchParams(r)}async json(){let e=await this.blob();if(e.size===0)return;let r=await e.text();return JSON.parse(r)}initId(){let e=this.#t.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#t.socket.remotePort}`}},lt=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},pt=class extends le{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.headers[e]!==void 0}get(e){return this.#e.headers[e]}list(e){return super.toList(e)}one(e){let r=this.#e.headers[e];return Array.isArray(r)?r[0]:r}keys(){return Object.keys(this.#e.headers).values()}},ht=class extends le{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.hasHeader(e)}keys(){return this.#e.getHeaderNames().values()}get(e){return this.#e.getHeader(e)}one(e){let r=this.#e.getHeader(e);return Array.isArray(r)?r[0]:r}set(e,r){return this.#e.headersSent||(Array.isArray(r)?r=r.map(n=>typeof n=="number"?String(n):n):typeof r=="number"&&(r=String(r)),r?this.#e.setHeader(e,r):this.#e.removeHeader(e)),this}add(e,r){return this.#e.headersSent||this.#e.appendHeader(e,r),this}list(e){return super.toList(e)}},Oe=class extends Te{#e;constructor(e){super(new ht(e)),this.#e=e}getNativeResponse(){return this.#e}get statusCode(){return super.statusCode??{value:this.#e.statusCode}}applyStatusCode(){let e=super.statusCode;e!==void 0&&(this.#e.statusCode=e.value)}addCookie(e){return this.headers.add("Set-Cookie",super.setCookieValue(e)),this}async bodyInternal(e){if(this.#e.headersSent)return!1;if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported in response");{let r=await e;return await new Promise((n,o)=>{try{r===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof r=="string"?this.headers.set("content-length",Buffer.byteLength(r)):r instanceof Blob?this.headers.set("content-length",r.size):this.headers.set("content-length",r.byteLength)),this.#e.end(r,()=>{n(!0)}))}catch(i){o(i instanceof Error?i:new Error(`end failed: ${i}`))}})}}},Me=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get id(){return this.#e.id}get method(){return this.#e.method}get path(){return this.#e.path}get protocol(){return this.#e.protocol}get host(){return this.#e.host}get URL(){return this.#e.URL}get headers(){return this.#e.headers}get cookies(){return this.#e.cookies}get remoteAddress(){return this.#e.remoteAddress}get upgrade(){return this.#e.upgrade}get sslInfo(){return this.#e.sslInfo}get body(){return this.#e.body}async blob(){return await this.#e.blob()}async text(){return await this.#e.text()}async formData(){return await this.#e.formData()}async json(){return await this.#e.json()}toString(){return`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof Re)return e.getNativeRequest();if(e instanceof t)return t.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},Z=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}setStatusCode(e){return this.delegate.setStatusCode(e)}setRawStatusCode(e){return this.delegate.setRawStatusCode(e)}get statusCode(){return this.delegate.statusCode}get cookies(){return this.delegate.cookies}addCookie(e){return this.delegate.addCookie(e),this}async end(){return await this.delegate.end()}async body(e){return await this.#e.body(e)}get headers(){return this.#e.headers}toString(){return`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof Te)return e.getNativeResponse();if(e instanceof t)return t.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},Ie=class t{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get request(){return this.#e.request}get response(){return this.#e.response}attribute(e){return this.#e.attribute(e)}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${t.name} [delegate: ${this.delegate}]`}},Le=class{request;response;#e={};#r;#t="";constructor(e,r){this.#e[Kt]=e.id,this.request=e,this.response=r}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(Kt);return this.#r!==e&&(this.#r=e,this.#t=e!==void 0?`[${e}] `:""),this.#t}},Kt="io.interop.gateway.server.log_id";var $e=require("node:v8"),F=require("node:fs/promises"),b=w("monitoring"),hn={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function fn(){return(0,$e.getHeapStatistics)()}async function Yt(t){let e=t.dumpPrefix??"Heap",r=`${t.dumpLocation}/${e}.heapsnapshot`;b.enabledFor("debug")&&b.debug(`starting heap dump in ${r}`),await ft(t.dumpLocation).catch(async o=>{b.enabledFor("debug")&&b.debug(`dump location ${t.dumpLocation} does not exists. Will try to create it`);try{await(0,F.mkdir)(t.dumpLocation,{recursive:!0}),b.info(`dump location dir ${t.dumpLocation} successfully created`)}catch{b.error(`failed to create dump location ${t.dumpLocation}`)}});let n=(0,$e.writeHeapSnapshot)(r);b.info("heap dumped");try{b.debug("rolling snapshot backups");let o=`${t.dumpLocation}/${e}.${t.maxBackups}.heapsnapshot`;await ft(o).then(async()=>{b.enabledFor("debug")&&b.debug(`deleting ${o}`);try{await(0,F.unlink)(o)}catch(s){b.warn(`failed to delete ${o}`,s)}}).catch(()=>{});for(let s=t.maxBackups-1;s>0;s--){let a=`${t.dumpLocation}/${e}.${s}.heapsnapshot`,c=`${t.dumpLocation}/${e}.${s+1}.heapsnapshot`;await ft(a).then(async()=>{try{await(0,F.rename)(a,c)}catch(d){b.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${t.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,F.rename)(n,i)}catch(s){b.warn(`failed to rename ${n} to ${i}`,s)}b.debug("snapshots rolled")}catch(o){throw b.error("error rolling backups",o),o}}async function ft(t){b.enabledFor("trace")&&b.debug(`checking file ${t}`),await(0,F.access)(t)}async function gn(t,e,r){b.enabledFor("debug")&&b.debug(`processing heap stats ${JSON.stringify(t)}`);let n=Math.min(r.memoryLimit,.95*t.heap_size_limit),o=t.used_heap_size;b.info(`heap stats ${JSON.stringify(t)}`),o>=n?(b.warn(`used heap ${o} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await Yt(r)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Qt(t){let e={...hn,...t},r=!1,n={memoryLimitExceeded:!1},o=async()=>{let a=fn();await gn(a,n,e)},i=setInterval(o,e.reportInterval);return{...e,channel:async a=>{if(!r)switch(a??="run",a){case"run":{await o();break}case"dump":{await Yt(e);break}case"stop":{r=!0,clearInterval(i),b.info("exit memory diagnostic");break}}return r}}}async function mn({channel:t},e){await t(e)||b.warn(`cannot execute command "${e}" already closed`)}async function Zt(t){return await mn(t,"stop")}var wn=(t,e)=>(e??=t,async({response:r},n)=>{e!==!1&&!r.headers.has("server")&&r.headers.set("Server",e),await n()}),er=(t,e)=>wn(t,e);var pe=require("@interopio/gateway");var gt=w("gateway.ws.client-verify");function Sn(t){switch(t.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function bn(t,e){let r=t.block??t.blacklist,n=t.allow??t.whitelist;if(r.length>0&&pe.IOGateway.Filtering.valuesMatch(r,e))return gt.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&pe.IOGateway.Filtering.valuesMatch(n,e))return gt.enabledFor("debug")&&gt.debug(`origin ${e} matches allow filter`),!0}function vn(t){switch(t.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function tr(t,e){if(!e)return!0;if(t){let r=bn(e,t);return r||vn(e)}else return Sn(e)}function rr(t){if(t){let e=(t.block??t.blacklist??[]).map(pe.IOGateway.Filtering.regexify),r=(t.allow??t.whitelist??[]).map(pe.IOGateway.Filtering.regexify);return{non_matched:t.non_matched??"allow",missing:t.missing??"allow",allow:r,block:e}}}var nr=t=>async e=>{for(let r of t)if((await r(e)).match)return T();return H},ee=t=>{let e=async r=>{for(let n of t)if(!(await n(r)).match)return H;return T()};return e.toString=()=>`and(${t.map(r=>r.toString()).join(", ")})`,e},or=t=>async e=>(await t(e)).match?H:T(),he=async t=>T();he.toString=()=>"any-exchange";var ir=Object.freeze({}),H=Object.freeze({match:!1,variables:ir}),T=(t=ir)=>({match:!0,variables:t}),O=(t,e)=>{let r=e?.method,n=async o=>{let i=o.request,s=i.path;if(r!==void 0&&i.method!==r)return H;if(typeof t=="string")return s===t?T():H;{let a=t.exec(s);return a===null?H:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${t.toString()}, method=${r??"<any>"})`,n},mt=t=>{let e=r=>{if(t.ignoredMediaTypes!==void 0){for(let n of t.ignoredMediaTypes)if(r===n||n==="*/*")return!0}return!1};return async r=>{let n=r.request,o;try{o=n.headers.list("accept")}catch{return H}for(let i of o)if(!e(i)){for(let s of t.mediaTypes)if(i.startsWith(s))return T()}return H}},V=async({request:t})=>t.upgrade&&t.headers.one("upgrade")?.toLowerCase()==="websocket"?T():H;V.toString=()=>"websocket upgrade";var yt=require("@interopio/gateway");async function wt(t,e,r){let n=(i,s)=>{if(s?.cors){let a=s.cors===!0?{allowOrigins:s.origins?.allow?.map(yt.IOGateway.Filtering.regexify),allowMethods:i.method===void 0?["*"]:[i.method],allowCredentials:s.authorize?.access!=="permitted"?!0:void 0}:s.cors,c=i.path;r.cors.push([c,a])}},o=new class{handle(...i){i.forEach(({request:s,options:a,handler:c})=>{let d=O(yt.IOGateway.Filtering.regexify(s.path),{method:s.method});a?.authorize&&r.authorize.push([d,a.authorize]),n(s,a);let u=async(l,m)=>{let{match:x,variables:p}=await d(l);x?await c(l,p):await m()};r.middleware.push(u)})}socket(...i){for(let{path:s,factory:a,options:c}of i){let d=s??"/";r.sockets.set(d,{default:s===void 0,ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:rr(c?.origins)})}}};await t(o,e)}var Ne=require("@interopio/gateway");function En(t){let e=t.headers.one("origin");if(e===void 0)return!0;let r=t.URL,n=r.protocol,o=r.host,i=URL.parse(e),s=i?.host,a=i?.protocol;return n===a&&o===s}function An(t){return t.headers.has("origin")&&!En(t)}function ar(t){return t.method==="OPTIONS"&&t.headers.has("origin")&&t.headers.has("access-control-request-method")}var sr=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],Cn=(t,e)=>{let{request:r,response:n}=t,o=n.headers;if(!o.has("Vary"))o.set("Vary",sr.join(", "));else{let s=o.list("Vary");for(let a of sr)s.find(c=>c===a)||s.push(a);o.set("Vary",s.join(", "))}try{if(!An(r))return!0}catch{return M.enabledFor("debug")&&M.debug("reject: origin is malformed"),fe(n),!1}if(o.has("access-control-allow-origin"))return M.enabledFor("trace")&&M.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=ar(r);return e?Hn(t,e,i):i?(fe(n),!1):!0},Ue=["*"],St=["GET","HEAD","POST"],cr={allowOrigins:Ue,allowMethods:St,allowHeaders:Ue,maxAge:1800};function Fe(t){if(t){let e=t.allowHeaders;e&&e!==v&&(t={...t,allowHeaders:e.map(n=>n.toLowerCase())});let r=t.allowOrigins;return r&&(r==="*"?(ur(t),lr(t)):t={...t,allowOrigins:r.map(n=>typeof n=="string"&&n!==v&&(n=Ne.IOGateway.Filtering.regexify(n),typeof n=="string")?pr(n).toLowerCase():n)}),t}}function We(t,e){if(e===void 0)return t!==void 0?t===v?[v]:t:[];if(t===void 0)return e===v?[v]:e;if(t==Ue||t===St)return e===v?[v]:e;if(e==Ue||e===St)return t===v?[v]:t;if(t===v||t.includes(v)||e===v||e.includes(v))return[v];let r=new Set;return t.forEach(n=>r.add(n)),e.forEach(n=>r.add(n)),Array.from(r)}var ge=(t,e)=>e===void 0?t:{allowOrigins:We(t.allowOrigins,e?.allowOrigins),allowMethods:We(t.allowMethods,e?.allowMethods),allowHeaders:We(t.allowHeaders,e?.allowHeaders),exposeHeaders:We(t.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??t.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??t.allowPrivateNetwork,maxAge:e?.maxAge??t.maxAge},Pn=t=>{let e=t.corsConfigSource,r=t.corsProcessor??Cn;if(e===void 0)throw new Error("corsConfigSource is required");if(r===void 0)throw new Error("corsProcessor is required");return async(n,o)=>{let i=await e(n);!r(n,i)||ar(n.request)||await o()}},dr=Pn,M=w("cors");function fe(t){t.setStatusCode(S.FORBIDDEN)}function Hn(t,e,r){let{request:n,response:o}=t,i=o.headers,s=n.headers.one("origin"),a=Rn(e,s);if(a===void 0)return M.enabledFor("debug")&&M.debug(`reject: '${s}' origin is not allowed`),fe(o),!1;let c=Mn(n,r),d=Tn(e,c);if(d===void 0)return M.enabledFor("debug")&&M.debug(`reject: HTTP '${c}' is not allowed`),fe(o),!1;let u=In(n,r),l=On(e,u);if(r&&l===void 0)return M.enabledFor("debug")&&M.debug(`reject: headers '${u}' are not allowed`),fe(o),!1;i.set("Access-Control-Allow-Origin",a),r&&i.set("Access-Control-Allow-Methods",d.join(",")),r&&l!==void 0&&l.length>0&&i.set("Access-Control-Allow-Headers",l.join(", "));let m=e.exposeHeaders;return m&&m.length>0&&i.set("Access-Control-Expose-Headers",m.join(", ")),e.allowCredentials&&i.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&i.set("Access-Control-Allow-Private-Network","true"),r&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var v="*",kn=["GET","HEAD"];function ur(t){if(t.allowCredentials===!0&&t.allowOrigins===v)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function lr(t){if(t.allowPrivateNetwork===!0&&t.allowOrigins===v)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Rn(t,e){if(e){let r=t.allowOrigins;if(r){if(r===v)return ur(t),lr(t),v;let n=pr(e.toLowerCase());for(let o of r)if(o===v||Ne.IOGateway.Filtering.valueMatches(o,n))return e}}}function Tn(t,e){if(e){let r=t.allowMethods??kn;if(r===v)return[e];if(Ne.IOGateway.Filtering.valuesMatch(r,e))return r}}function On(t,e){if(e===void 0)return;if(e.length==0)return[];let r=t.allowHeaders;if(r===void 0)return;let n=r===v||r.includes(v),o=[];for(let i of e){let s=i?.trim();if(s){if(n)o.push(s);else for(let a of r)if(s.toLowerCase()===a){o.push(s);break}}}if(o.length>0)return o}function pr(t){return t.endsWith("/")?t.slice(0,-1):t}function Mn(t,e){return e?t.headers.one("access-control-request-method"):t.method}function In(t,e){let r=t.headers;return e?r.list("access-control-request-headers"):Array.from(r.keys())}var hr=t=>async e=>{for(let[r,n]of t.mappings)if((await r(e)).match)return M.debug(`resolved cors config on '${e.request.path}' using ${r}: ${JSON.stringify(n)}`),n};var fr=require("@interopio/gateway");function gr(t){let{sockets:e,cors:r}=t,n=t.corsConfig===!1?void 0:ge(cr,t.corsConfig),o=[];for(let[s,a]of e){let c=n;for(let[u,l]of r)fr.IOGateway.Filtering.valueMatches(u,s)&&(l===void 0?c=void 0:c=c===void 0?l:ge(c,l));let d=t.corsConfig===!1?void 0:{allowOrigins:a.originFilters?.allow,allowMethods:["GET","CONNECT","OPTIONS"],allowHeaders:["Upgrade","Connection","Origin","Sec-Websocket-Key","Sec-Websocket-Version","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],exposeHeaders:["Sec-Websocket-Accept","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0};c=c===void 0?d:ge(c,d),o.push([ee([V,O(s)]),Fe(c)])}let i=[];for(let[s,a]of r){let[,c]=i.find(([u])=>String(u)===String(s))??[s,n];c=c===void 0?a:ge(c,a);let d=!1;for(let u of i)if(String(u[0])===String(s)){u[1]=c,d=!0;break}d||i.push([s,c])}for(let[s,a]of i)o.push([O(s),Fe(a)]);return o.push([O(/\/api\/.*/),Fe(n)]),hr({mappings:o})}function mr(t){return t!==void 0&&typeof t.type=="string"&&typeof t.authenticated=="boolean"}var C=class extends Error{_authentication;get authentication(){return this._authentication}set authentication(e){if(e===void 0)throw new TypeError("Authentication cannot be undefined");this._authentication=e}},Ge=class extends C{},te=class extends C{},re=class extends C{constructor(e){super(e)}},me=class extends re{constructor(e){super(e)}},ye=class extends re{constructor(e){super(e)}},we=class extends re{constructor(e){super(e)}},Se=class extends re{constructor(e){super(e)}};var X=class extends Error{},G=class{constructor(e){this.granted=e}granted},_=class{#e;constructor(e){this.#e=e}async verify(e,r){if(!(await this.#e(e,r))?.granted)throw new X("Access denied")}async authorize(e,r){return await this.#e(e,r)}},ne=class extends C{};var I=t=>async e=>{let r=!0,{response:n}=e;for(let o of t.keys())n.headers.has(o)&&(r=!1);if(r)for(let[o,i]of t)n.headers.set(o,i)},Ln=()=>I(new E().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Dn=()=>I(new E().add("x-content-type-options","nosniff")),$n=(t,e,r)=>{let n=`max-age=${t}`;e&&(n+=" ; includeSubDomains"),r&&(n+=" ; preload");let o=I(new E().add("strict-transport-security",n)),i=s=>s.request.URL.protocol==="https:";return async s=>{i(s)&&await o(s)}},Wn=t=>I(new E().add("x-frame-options",t)),Un=t=>I(new E().add("x-xss-protection",t)),Nn=t=>{let e=t===void 0?void 0:I(new E().add("permissions-policy",t));return async r=>{e!==void 0&&await e(r)}},Fn=(t,e)=>{let r=e?"content-security-policy-report-only":"content-security-policy",n=t===void 0?void 0:I(new E().add(r,t));return async o=>{n!==void 0&&await n(o)}},Gn=(t="no-referrer")=>I(new E().add("referer-policy",t)),Bn=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-opener-policy",t));return async r=>{e!==void 0&&await e(r)}},_n=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-embedder-policy",t));return async r=>{e!==void 0&&await e(r)}},qn=t=>{let e=t===void 0?void 0:I(new E().add("cross-origin-resource-policy",t));return async r=>{e!==void 0&&await e(r)}},zn=(...t)=>async e=>{for(let r of t)await r(e)};function bt(t){let e=[];t?.cache?.disabled||e.push(Ln()),t?.contentType?.disabled||e.push(Dn()),t?.hsts?.disabled||e.push($n(t?.hsts?.maxAge??365*24*60*60,t?.hsts?.includeSubDomains??!0,t?.hsts?.preload??!1)),t?.frameOptions?.disabled||e.push(Wn(t?.frameOptions?.mode??"DENY")),t?.xss?.disabled||e.push(Un(t?.xss?.headerValue??"0")),t?.permissionsPolicy?.disabled||e.push(Nn(t?.permissionsPolicy?.policyDirectives)),t?.contentSecurityPolicy?.disabled||e.push(Fn(t?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",t?.contentSecurityPolicy?.reportOnly)),t?.refererPolicy?.disabled||e.push(Gn(t?.refererPolicy?.policy??"no-referrer")),t?.crossOriginOpenerPolicy?.disabled||e.push(Bn(t?.crossOriginOpenerPolicy?.policy)),t?.crossOriginEmbedderPolicy?.disabled||e.push(_n(t?.crossOriginEmbedderPolicy?.policy)),t?.crossOriginResourcePolicy?.disabled||e.push(qn(t?.crossOriginResourcePolicy?.policy)),t?.writers&&e.push(...t.writers);let r=zn(...e);return async(n,o)=>{await r(n),await o()}}var oe=t=>{let e=t.entryPoint,r=t?.rethrowAuthenticationServiceError??!0;return async({exchange:n},o)=>{if(!r||!(o instanceof ne))return e(n,o);throw o}};var jn="Realm",Vn=t=>`Basic realm="${t}"`,ie=t=>{let e=Vn(t?.realm??jn);return async(r,n)=>{let{response:o}=r;o.setStatusCode(S.UNAUTHORIZED),o.headers.set("WWW-Authenticate",e)}};var yr="Basic ",Be=t=>{let e=t?.credentialsEncoding??"utf-8";return async r=>{let{request:n}=r,o=n.headers.one("authorization");if(!o||!/basic/i.test(o.substring(0)))return;let i=o.length<=yr.length?"":o.substring(yr.length),a=Buffer.from(i,"base64").toString(e).split(":",2);if(a.length!==2)return;let c=a[0],d=a[1];return{type:"UsernamePassword",authenticated:!1,principal:c,credentials:d,name:c,eraseCredentials:()=>{d=null}}}};var wr=require("node:async_hooks"),q=class t{static hasSecurityContext(e){return e.getStore()?.securityContext!==void 0}static async getSecurityContext(e){return await e.getStore()?.securityContext}static clearSecurityContext(e){delete e.getStore()?.securityContext}static withSecurityContext(e){return(r=new wr.AsyncLocalStorage)=>(r.getStore().securityContext=e,r)}static withAuthentication(e){return t.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(t.hasSecurityContext(e))return t.getSecurityContext(e)}};async function Xn(t,e,r,n,o,i){let a=await(await n(t))?.(r);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await Jn(a,{exchange:t,next:e},o,i)}catch(c){throw c instanceof C,c}}async function Jn(t,e,r,n){q.withAuthentication(t)(n),await r(e,t)}function z(t){let e={matcher:he,successHandler:async({next:n})=>{await n()},converter:Be({}),failureHandler:oe({entryPoint:ie({})}),...t},r=e.managerResolver;if(r===void 0&&e.manager!==void 0){let n=e.manager;r=async o=>n}if(r===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return async(n,o)=>{let s=(await e.matcher(n)).match?await e.converter(n):void 0;if(s===void 0){await o();return}try{await Xn(n,o,s,r,e.successHandler,e.storage)}catch(a){if(a instanceof C){await e.failureHandler({exchange:n,next:o},a);return}throw a}}}var Sr=t=>async(e,r)=>{e.response.setStatusCode(t.httpStatus)};var se=w("auth.entry-point"),_e=t=>{let e=t.defaultEntryPoint??(async({response:r},n)=>{r.setStatusCode(S.UNAUTHORIZED),await r.end()});return async(r,n)=>{for(let[o,i]of t.entryPoints)if(se.enabledFor("debug")&&se.debug(`trying to match using: ${o}`),(await o(r)).match)return se.enabledFor("debug")&&se.debug(`match found. using default entry point ${i}`),i(r,n);return se.enabledFor("debug")&&se.debug(`no match found. using default entry point ${e}`),e(r,n)}};var br=t=>async({exchange:e,next:r},n)=>{for(let o of t)await o({exchange:e,next:r},n)};function vt(t){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?T():H,r=_e({entryPoints:[[e,Sr({httpStatus:S.UNAUTHORIZED})]],defaultEntryPoint:ie({})}),n=t.entryPoint??r,o=t.manager,i=mt({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),s=or(mt({mediaTypes:["text/html"]})),a=ee([s,i]),c=nr([e,a]);t.defaultEntryPoints.push([c,n]);let d=t.failureHandler??oe({entryPoint:n}),u=br(t.successHandlers??t.defaultSuccessHandlers),l=Be({});return z({storage:t.storage,manager:o,failureHandler:d,successHandler:u,converter:l})}var vr={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},xr="https://tools.ietf.org/html/rfc6750#section-3.1";function qe(t){return{errorCode:vr.invalid_token,httpStatus:S.UNAUTHORIZED,description:t,uri:xr}}function xt(t){return{errorCode:vr.invalid_request,httpStatus:S.BAD_REQUEST,description:t,uri:xr}}var Kn="access_token",Yn=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,D=class extends C{error;constructor(e,r,n){super(r??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},Er=t=>t.type==="BearerToken",Qn=t=>async e=>{let{request:r}=e;return Promise.all([eo(r.headers,t?.headerName).then(n=>n!==void 0?[n]:void 0),to(r,t?.uriQueryParameter),ro(e,t?.formEncodedBodyParameter)]).then(n=>n.filter(o=>o!==void 0).flat(1)).then(Zn).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function Zn(t){if(t.length===0)return;if(t.length>1){let r=xt("Found multiple access tokens in the request");throw new D(r)}let e=t[0];if(!e||e.length===0){let r=xt("The requested access token parameter is an empty string");throw new D(r)}return e}async function eo(t,e="authorization"){let r=t.one(e);if(!r||!/bearer/i.test(r.substring(0)))return;let n=Yn.exec(r);if(n===null){let o=qe("Bearer token is malformed");throw new D(o)}return n.groups?.token}async function Ar(t){let e=t.getAll(Kn);if(e.length!==0)return e}async function to(t,e=!1){if(!(!e||t.method!=="GET"))return Ar(t.URL.searchParams)}async function ro(t,e=!1){let{request:r}=t;if(!e||r.headers.one("content-type")!=="application/x-www-form-urlencoded"||r.method!=="POST")return;let n=await t.request.formData();if(n)return Ar(n)}var ze=Qn;function no(t){let e="Bearer";if(t.size!==0){e+=" ";let r=0;for(let[n,o]of t)e+=`${n}="${o}"`,r!==t.size-1&&(e+=", "),r++}return e}var Cr=t=>t.httpStatus!==void 0;function oo(t){if(t instanceof D){let{error:e}=t;if(Cr(e))return e.httpStatus}return S.UNAUTHORIZED}function io(t,e){let r=new Map;if(e&&r.set("realm",e),t instanceof D){let{error:n}=t;r.set("error",n.errorCode),n.description&&r.set("error_description",n.description),n.uri&&r.set("error_uri",n.uri),Cr(n)&&n.scope&&r.set("scope",n.scope)}return r}var so=t=>async(e,r)=>{let n=oo(r),o=io(r,t?.realmName),i=no(o),{response:s}=e;s.headers.set("WWW-Authenticate",i),s.setStatusCode(n),await s.end()},je=so;var ao=t=>{let e=t?.principalClaimName??"sub";return r=>({type:"JwtToken",authenticated:!0,name:r.getClaimAsString(e)})},co=t=>async e=>t(e),ae=class extends Error{},be=class extends ae{};function uo(t){if(t instanceof be)return new D(qe(t.message),t.message,{cause:t});throw new ne(t.message,{cause:t})}function Et(t){let e=t.decoder,r=t.authConverter??co(ao({}));return async n=>{if(Er(n)){let o=n.token;try{let i=await e(o);return await r(i)}catch(i){throw i instanceof ae?uo(i):i}}}}function At(t){let e=t.entryPoint??je({}),r=t?.converter??ze({}),n=t.failureHandler??oe({entryPoint:e});if(t.managerResolver!==void 0)return z({storage:t.storage,converter:r,failureHandler:n,managerResolver:t.managerResolver});if(t.jwt!==void 0){let o=t.jwt.manager??Et(t.jwt);return z({storage:t.storage,converter:r,failureHandler:n,managerResolver:async i=>o})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}var Ze=require("@interopio/gateway/jose/jwt");async function Pr(t,e,r){let n=new Ge("Full authentication is required to access this resource."),o=new C("Access Denied",{cause:n});e&&(o.authentication=e),await r(t,o)}function lo(t){return async(e,r)=>{e.response.setStatusCode(t),e.response.headers.set("Content-Type","text/plain; charset=utf-8");let n=Buffer.from("Access Denied","utf-8");e.response.headers.set("Content-Length",n.length),await e.response.body(n)}}var Hr=t=>{let e=lo(S.FORBIDDEN),r=t.authenticationEntryPoint??ie();return async(n,o)=>{try{await o()}catch(i){if(i instanceof X){let s=await n.principal();mr(s)?(s.authenticated||await e(n,i),await Pr(n,s,r)):await Pr(n,void 0,r);return}throw i}}};var po=w("security.auth");function Ct(t){let e=async(r,n)=>{let o;for(let[i,s]of t.mappings)if((await i(n))?.match){po.debug(`checking authorization on '${n.request.path}' using [${i}, ${s}]`);let a=await s.authorize(r,{exchange:n});if(a!==void 0){o=a;break}}return o??=new G(!1),o};return new _(e)}var Ve=w("security.auth");function Pt(t){let{manager:e,storage:r}=t;return async(n,o)=>{let i=q.getContext(r).then(s=>s?.authentication);try{await e.verify(i,n),Ve.enabledFor("debug")&&Ve.debug("authorization successful")}catch(s){throw s instanceof X&&Ve.enabledFor("debug")&&Ve.debug(`authorization failed: ${s.message}`),s}await o()}}var Ht=class extends Ie{#e;constructor(e,r){super(e),this.#e=r}async principal(){return(await this.#e())?.authentication}},kr=t=>{let e=t.storage;return async(r,n)=>{await n(new Ht(r,async()=>await q.getContext(e)))}};var Rr=t=>{let{principalExtractor:e}=t;return async r=>{let n=r.request.sslInfo;if(n===void 0||n.peerCertificate===void 0)return;let o=n.peerCertificate,i=e(o);return{type:"PreAuthenticated",authenticated:!1,principal:i,name:i??"",credentials:o}}};var Xe=t=>{let e=t?.principalAltName==="email",r=/CN=(.*?)(?:,|$)/mi;return n=>{if(e){let s=n.subjectAltName?.split(", ").find(a=>a.startsWith("email:"));if(s)return s.replace("email:","")}let o=r.exec(n.subject);if(o===null)throw new te(`Cannot extract principal from subject DN: ${n.subject}`);return o[1]}};var J=class{async encode(e){if(e!=null)return await this.encodeDefinedPassword(e.toString())}async matches(e,r){return!e||!r?!1:await this.matchesDefined(e.toString(),r)}upgradeEncoding(e){return e?this.upgradeEncodingDefined(e):!1}upgradeEncodingDefined(e){return!1}},ce=class t extends J{static DEFAULT_ID_PREFIX="{";static DEFAULT_ID_SUFFIX="}";#e;#r;#t;#n;#i;#s=new class extends J{#c;constructor(e){super(),this.#c=e}async encodeDefinedPassword(e){throw new Error("encode is not supported")}async matchesDefined(e,r){let n=this.#c.#o(r);if(!n)throw new Error(`No password encoder mapped for id ${n}`);if(r){let o=r.indexOf(this.#c.#e),i=r.indexOf(this.#c.#r,o+this.#c.#e.length);if(o===-1&&i===-1)throw new Error("No prefix found in encoded password")}throw new Error("malformed password encoder prefix")}}(this);constructor(e,r,n=t.DEFAULT_ID_PREFIX,o=t.DEFAULT_ID_SUFFIX){if(e==null)throw new Error("idForEncode cannot be null or undefined");if(n==null)throw new Error("idPrefix cannot be null or undefined");if(!o)throw new Error("idSuffix cannot be empty");if(n.indexOf(o)!==-1)throw new Error(`idPrefix "${n}" cannot contain idSuffix "${o}"`);if(!r.has(e))throw new Error(`No PasswordEncoder mapped for id "${e}"`);for(let i of r.keys())if(i!==null){if(n&&i.includes(n))throw new Error(`id "${i}" cannot include ${n}`);if(o&&i.includes(o))throw new Error(`id "${i}" cannot include ${o}`)}super(),this.#t=e,this.#n=r.get(e),this.#i=new Map(r),this.#e=n,this.#r=o}set defaultPasswordEncoderForMatches(e){if(e==null)throw new Error("defaultPasswordEncoderForMatches cannot be null or undefined");this.#s=e}async encodeDefinedPassword(e){let r=await this.#n.encode(e);return`${this.#e}${this.#t}${this.#r}${r}`}async matchesDefined(e,r){let n=this.#o(r),o=n?this.#i.get(n):void 0;if(o===void 0)return await this.#s.matches(e,r);{let i=this.#a(r);return await o.matches(e,i)}}#o(e){if(e===void 0)return;let r=e.indexOf(this.#e);if(r!==0)return;let n=e.indexOf(this.#r,r+this.#e.length);if(n!==-1)return e.substring(r+this.#e.length,n)}upgradeEncodingDefined(e){let r=this.#o(e);if(this.#t!==r)return!0;{let n=this.#a(e);return this.#n.upgradeEncoding?.(n)??!1}}#a(e){let r=e.indexOf(this.#r);return e.substring(r+this.#r.length)}},Je=class t extends J{static#e=new t;static get instance(){return t.#e}constructor(){super()}async encodeDefinedPassword(e){return e.toString()}async matchesDefined(e,r){return e.toString()===r}};var P=require("@interopio/gateway-server/tools");function ho(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Ke=class extends J{#e;#r;#t;#n;#i;constructor(e=P.argon2.DEFAULT_SALT_LENGTH,r=P.argon2.DEFAULT_HASH_LENGTH,n=P.argon2.DEFAULT_PARALLELISM,o=P.argon2.DEFAULT_MEMORY,i=P.argon2.DEFAULT_PASSES){super(),this.#e=e,this.#r=r,this.#t=n,this.#n=o,this.#i=i}async matchesDefined(e,r){try{let n=P.argon2.decode(r),o=await P.argon2.createHash(n.algorithm,e,n.hash.length,n.parameters);return ho(n.hash,o)}catch{return!1}}async encodeDefinedPassword(e){let r=P.keygen.createSalt(this.#e),n={memory:this.#n,passes:this.#i,parallelism:this.#t,nonce:r},o=await P.argon2.createHash("argon2id",e,this.#r,n);return P.argon2.encode({algorithm:"argon2id",version:P.argon2.ARGON2_VERSION,parameters:n,hash:o})}upgradeEncodingDefined(e){let r=P.argon2.decode(e);return r.version<P.argon2.ARGON2_VERSION||r.parameters.memory<this.#n||r.parameters.passes<this.#i}};var kt=4096;function Tr(){let t="argon2id",e=new Map([[t,new Ke],["noop",Je.instance]]);return new ce(t,e,ce.DEFAULT_ID_PREFIX,ce.DEFAULT_ID_SUFFIX)}var Or={async updatePassword(t,e){return t}},Ye=class extends C{username;constructor(e,r,n){super(e,n),this.username=r}},Qe=class t{#e;#r;#t=[];#n;#i;#s;#o;#a=e=>e;constructor(){}static ofUsername(e){return new t().username(e)}static ofUserDetails(e){let r=t.ofUsername(e.username).accountExpired(e.accountExpired??!1).accountLocked(e.accountLocked??!1).authorities(e.authorities).credentialsExpired(e.credentialsExpired??!1).disabled(e.disabled??!1);return e.password!==void 0&&r.password(e.password),r}username(e){if(!e)throw new TypeError("username cannot be empty");return this.#e=e,this}password(e){return this.#r=e,this}passwordEncoder(e){if(!e)throw new TypeError("password encoder cannot be null or undefined");return this.#a=e,this}roles(...e){return this.authorities(e.map(r=>{if(r.startsWith("role:"))throw new Error(`${r} must not start with 'role:' (it is automatically added)`);return{authority:`role:${r}`}}))}authorities(e){return this.#t=[...e],this}accountExpired(e){return this.#n=e,this}accountLocked(e){return this.#i=e,this}credentialsExpired(e){return this.#s=e,this}disabled(e){return this.#o=e,this}build(){if(!this.#e)throw new TypeError("username is required");let e=this.#r!==void 0?this.#a(this.#r):void 0;return{username:this.#e,password:e,authorities:this.#t,accountExpired:this.#n,accountLocked:this.#i,credentialsExpired:this.#s,disabled:this.#o,eraseCredentials(){e=null},toString(){return`User(username=${this.username}, password=[PROTECTED], authorities=${JSON.stringify(this.authorities)}, accountExpired=${this.accountExpired}, accountLocked=${this.accountLocked}, credentialsExpired=${this.credentialsExpired}, disabled=${this.disabled})`}}}};var j=w("security.users");function Mr(t,e){let r=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw j.debug("user account is locked"),new me("User account is locked");if(a.disabled)throw j.debug("user account is disabled"),new ye("User is disabled");if(a.accountExpired)throw j.debug("user account is expired"),new we("User account has expired")}),n=e?.postAuthenticationChecks??(a=>{if(a.credentialsExpired)throw j.debug("user credentials have expired"),new Se("User credentials have expired")}),o=e?.passwordEncoder??Tr(),i=e?.userDetailsPasswordService??Or,s=async(a,c)=>{let d=a.password;if(d!==void 0&&o.upgradeEncoding?.(d)){let l=await o.encode(c);return await i.updatePassword(a,l)}return a};return async a=>{let c=a.name,d=a.credentials!==void 0&&a.credentials!==null?a.credentials.toString():void 0,u=await t.findByUsername(c);if(!u)throw new Error(`User not found: ${c}`);if(r(u),!await o.matches(d,u.password))throw new te("Invalid Credentials");let l=await s(u,d);n(l);let m=l.password;return{type:"UsernamePassword",principal:l,credentials:m,authorities:l.authorities,authenticated:!0,name:l.username,eraseCredentials(){m=null}}}}function fo(){return t=>{if(t.accountLocked)throw j.debug("failed to authenticate since user account is locked"),new me("User account is locked");if(t.disabled)throw j.debug("failed to authenticate user account is disabled"),new ye("User is disabled");if(t.accountExpired)throw j.debug("failed to authenticate since user account is expired"),new we("User account has expired");if(t.credentialsExpired)throw j.debug("failed to authenticate since user credentials have expired"),new Se("User credentials have expired")}}function Ir(t){let e=t.userDetailsService,r=t.userDetailsChecker??fo(),n=o=>o.type==="PreAuthenticated"&&o.name!==void 0;return async o=>{let i=n(o)&&await e.findByUsername(o.name);if(!i)throw new Ye("user not found",o.name);r(i);let s=o.credentials;return{type:"PreAuthenticated",principal:i,credentials:s,authorities:i.authorities,authenticated:!0,details:i,name:i.username,eraseCredentials(){s=null}}}}function Rt(t){let e=t.manager??Ir({userDetailsService:t.getService("UserDetailsService")}),r=t.extractor??Xe(),n=t.converter??Rr({principalExtractor:r});return z({storage:t.storage,manager:e,converter:n})}var $={first:Number.MAX_SAFE_INTEGER,http_headers:100,https_redirect:200,cors:300,http_basic:600,authentication:800,security_context_server_web_exchange:1500,error_translation:1800,authorization:1900,last:Number.MAX_SAFE_INTEGER},W=Symbol.for("filterOrder"),Lr=(t,e)=>{let r=(a,c)=>{if(e===void 0)return c;if(a==="UserDetailsService"&&e.userDetailsService!==void 0)return e.userDetailsService;if(a==="AuthenticationManager"&&e.authenticationManager!==void 0)return e.authenticationManager;if(c!==void 0)return c;throw new Error(`No service registered with name: ${a}`)},n=()=>{if(e.authenticationManager!==void 0)return e.authenticationManager;if(e.userDetailsService!==void 0)return Mr(e.userDetailsService,{userDetailsPasswordService:e.userDetailsPasswordService})},o=[];class i{#e;#r=[];#t;set authenticationManager(c){this.#t=c}get authenticationEntryPoint(){return this.#e!==void 0||this.#r.length===0?this.#e:this.#r.length===1?this.#r[0][1]:_e({entryPoints:this.#r,defaultEntryPoint:this.#r[this.#r.length-1][1]})}build(){if(t.headers!==void 0&&t.headers.disabled!==!0){let d=bt(t.headers);d[W]=$.http_headers,o.push(d)}if(t.x509!==void 0&&t.x509.disabled!==!0){let d=Rt({storage:e.storage,getService:r,extractor:Xe({principalAltName:t.x509.principalAltName})});d[W]=$.authentication,o.push(d)}if(t.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=dr({corsConfigSource:e.corsConfigSource});d[W]=$.cors,o.push(d)}if(t.basic!==void 0&&t.basic?.disabled!==!0){let d=[async({exchange:l,next:m},x)=>m()],u=vt({storage:e.storage,manager:this.#t,defaultEntryPoints:this.#r,defaultSuccessHandlers:d});u[W]=$.http_basic,o.push(u)}if(t.jwt!==void 0&&t.jwt.disabled!==!0){let d=(0,Ze.jwtVerifier)({issuerBaseUri:t.jwt.issuerUri,issuer:t.jwt.issuer,audience:t.jwt.audience}),u=async f=>{try{let{payload:h}=await d(f);return{tokenValue:f,subject:h.sub,getClaimAsString(y){return h[y]}}}catch(h){throw h instanceof Ze.JwtVerifyError?new be(h.message,{cause:h}):new ae("error occurred while attempting to decoding jwt",{cause:h})}},l=ze({uriQueryParameter:!0}),m=async f=>{try{return await l(f)===void 0?H:T()}catch{return H}},x=je({});this.#r.push([m,x]);let p=At({storage:e.storage,entryPoint:x,converter:l,jwt:{decoder:u}});p[W]=$.authentication,o.push(p)}let c=kr({storage:e.storage});if(o.push(c),c[W]=$.security_context_server_web_exchange,t.authorize!==void 0){let d=Hr({authenticationEntryPoint:this.authenticationEntryPoint});d[W]=$.error_translation,o.push(d);let l=(x=>{let p=[],f=!1;for(let[h,y]of x??[]){let k;if(h==="any-exchange")f=!0,k=he;else{if(f)throw new Error("Cannot register other matchers after 'any-exchange' matcher");k=h}let R;if(y.access==="permitted")R=new _(async()=>new G(!0)),R.toString=()=>"AuthorizationManager[permitted]";else if(y.access==="denied")R=new _(async()=>new G(!1)),R.toString=()=>"AuthorizationManager[denied]";else if(y.access==="authenticated")R=new _(async K=>{let Lt=await K;return Lt!==void 0?new G(Lt.authenticated):new G(!1)}),R.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(y)}`);p.push([k,R])}return Ct({mappings:p})})(t.authorize),m=Pt({manager:l,storage:e.storage});m[W]=$.authorization,o.push(m)}o.sort((d,u)=>{let l=d[W]??$.last,m=u[W]??$.last;return l-m})}}let s=new i;return s.authenticationManager=n(),s.build(),o};var et=class{#e=new Map;constructor(...e){for(let r of e)this.#e.set(this.#r(r.username),r)}async findByUsername(e){let r=this.#r(e),n=this.#e.get(r);return n!==void 0?{...n}:void 0}async updatePassword(e,r){let n={...e,password:r};if(n){let o=this.#r(e.username);this.#e.set(o,n)}return n}#r(e){return e.toLowerCase()}};var Dr=require("node:crypto");var tt=w("auth");function go(t){let e=[],r=t.authConfig?.type,n={access:r!=="none"?"authenticated":"permitted"};tt.enabledFor("info")&&tt.info(`using auth type: ${r??"none"}, default access: ${n.access}`);for(let[o,i]of t.sockets){let s=i.authorize??n,a=O(o,{method:"GET"});a=ee([V,a]),e.push([a,s])}return e.push([O("/",{method:"GET"}),{access:"permitted"}]),e.push([O("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([O("/health",{method:"GET"}),{access:"permitted"}]),t.authorize.length>0&&e.push(...t.authorize),e.push(["any-exchange",n]),{authorize:e,cors:{disabled:t.corsConfig===!1},x509:{disabled:r!=="x509",...t.authConfig?.x509},basic:{disabled:r!=="basic",...t.authConfig?.basic},jwt:{disabled:r!=="oauth2",...t.authConfig?.oauth2?.jwt}}}function mo(t){function e(s,a){let c=s.password;if(c===void 0){let d=(0,Dr.randomUUID)().replaceAll("-","");tt.enabledFor("info")&&tt.info(`
1
+ "use strict";var Zs=Object.create;var it=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var ri=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var bn=(r,e)=>{for(var t in e)it(r,t,{get:e[t],enumerable:!0})},wn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ti(e))!ni.call(r,s)&&s!==t&&it(r,s,{get:()=>e[s],enumerable:!(n=ei(e,s))||n.enumerable});return r};var Oe=(r,e,t)=>(t=r!=null?Zs(ri(r)):{},wn(e||!r||!r.__esModule?it(t,"default",{value:r,enumerable:!0}):t,r)),si=r=>wn(it({},"__esModule",{value:!0}),r);var Xo={};bn(Xo,{GatewayServer:()=>yn,default:()=>jo});module.exports=si(Xo);var yn={};bn(yn,{Factory:()=>mn,VERSION:()=>Qs});var gn=Oe(require("node:http"),1),Ys=Oe(require("node:https"),1),Ks=require("node:async_hooks");var Sn=require("node:os"),ii=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function br(r){if(r>65535)throw new Error(`bad port ${r}`);return r}function*En(r){if(typeof r=="string")for(let e of r.split(",")){let t=e.trim(),n=ii.exec(t);if(n){let s=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let o=br(s);o<br(i)+1;o++)yield o}else throw new Error(`'${e}' is not a valid port or range.`)}else yield br(r)}var vn=(()=>{function r(t){return t.length>0?t[0]:void 0}let e=Object.values((0,Sn.networkInterfaces)()).flatMap(t=>(t??[]).filter(n=>n.family==="IPv4")).reduce((t,n)=>(t[n.internal?"internal":"external"].push(n),t),{internal:[],external:[]});return(r(e.internal)??r(e.external))?.address})();function ee(r){if(r)return r.family==="IPv6"?`[${r.address}]:${r.port}`:`${r.address}:${r.port}`}var Pn=Oe(require("@interopio/gateway/logging/core"),1);function w(r){return Pn.getLogger(`gateway.server.${r}`)}function Cn(r,e){return e instanceof RegExp?e.toString():e}var xn=require("@interopio/gateway"),An=require("node:async_hooks"),V=w("ws"),oi=xn.IOGateway.Encoding.json();function ai(r){let e;if(r.authenticated&&(e=r.name,e===void 0&&r.principal!==void 0)){let t=r.principal;typeof t=="object"&&t!==null&&("username"in t||"name"in t)&&(e=t.username??t.name),e===void 0&&(t==null?e="":e=String(t))}return e}function ci(r,e,t,n){let s=ee(n),i=n?.address??"<unknown>",o={key:s,host:i,codec:oi,onAuthenticate:async()=>{let a=await t();if(a?.authenticated)return{type:"success",user:ai(a)};throw new Error(`no valid client authentication ${s}`)},onPing:()=>{e.ping(a=>{a?V.warn(`failed to ping ${s}`,a):V.info(`ping sent to ${s}`)})},onDisconnect:a=>{switch(a){case"inactive":{V.warn(`no heartbeat (ping) received from ${s}, closing socket`),e.close(4001,"ping expected");break}case"shutdown":{e.close(1001,"shutdown");break}}}};try{return r.client(a=>e.send(a),o)}catch(a){V.warn(`${s} failed to create client`,a)}}async function di(r){return V.info(`starting gateway on ${r.endpoint}`),await this.start(r),async({socket:e,handshake:t})=>{let{logPrefix:n,remoteAddress:s,principal:i}=t,o=(await i())?.name;V.info(`${n}connected on gw as ${o??"<anonymous>"}`);let a=await this.getGateway(o),c=ci(a,e,i,s);if(!c){V.error(`${n}gw client init failed`),e.terminate();return}e.on("error",u=>{V.error(`${n}websocket error: ${u}`,u)});let d=r.storage!==void 0?An.AsyncLocalStorage.snapshot():void 0;e.on("message",(u,f)=>{Array.isArray(u)&&(u=Buffer.concat(u)),d!==void 0?d(()=>c.send(u)):c.send(u)}),e.on("close",u=>{V.info(`${n}disconnected from gw. code: ${u}`),c.close()})}}var Rn=di;var Er=require("@interopio/gateway");var pe=require("@interopio/gateway");function wr(r){if(r!==void 0)return r.map(e=>{let t={...e};for(let[n,s]of Object.entries(e))n!=="identity"&&n!=="restrictions"&&s!==void 0&&(t[n]=pe.IOGateway.Filtering.regexify(s));if(e.identity!==void 0){t.identity={};for(let[n,s]of Object.entries(e.identity))t.identity[n]=pe.IOGateway.Filtering.regexify(s)}return t})}function Tn(r){if(!r)return;let e={...r};return r.publishers&&(e.publishers=r.publishers.map(t=>{let{metrics:n,identity:s,...i}=t,o={...i};if(o.identity={},s)for(let[a,c]of Object.entries(s))o.identity[a]=pe.IOGateway.Filtering.regexify(c);if(o.metrics={},n){let a=(n.allow??n.whitelist??[]).map(d=>pe.IOGateway.Filtering.regexify(d)),c=(n.block??n.blacklist??[]).map(d=>pe.IOGateway.Filtering.regexify(d));a.length>0&&(o.metrics.allow=a),c.length>0&&(o.metrics.block=c)}return o})),e}function Sr(r){if(!r)return;let e={...r};return r.filters&&(e.filters=Tn(r.filters)),e}function ui(r){if(r?.enabled!==!1)return r}function li(r){if(r===void 0||r?.enabled===!1)return;let e={...r};return r.filters&&(e.filters=Tn(r.filters)),r.file&&(e.file=Sr(r.file)),r.rest&&(e.rest=Sr(r.rest)),r.publishers&&(e.publishers=r.publishers.map(t=>{if(typeof t=="string")return[t];let n=Sr(t);return n!==void 0?[n]:[]}).flat()),e}function Hn(r){let e={...r};return r.contexts&&(e.contexts={...r.contexts,visibility:wr(r.contexts.visibility)}),r.methods&&(e.methods={...r.methods,visibility:wr(r.methods.visibility)}),r.peers&&(e.peers={...r.peers,visibility:wr(r.peers.visibility)}),r.metrics&&(e.metrics=li(r.metrics)),r.mesh&&(e.mesh=ui(r.mesh)),e}var k=w("gateway-manager");function Mn(){return globalThis.crypto.randomUUID().replaceAll("-","")}var ot=class{#e;#t;#r=new Map;#n=new Map;#s;#i=!1;#o;constructor(e){this.#s={baseConfig:Hn(e.baseConfig),scope:e.scope??"principal"},this.#e=e.baseConfig.node??Mn(),k.enabledFor("debug")&&k.debug(`creating default gateway with gateway id: ${this.#e}`),this.#t=Er.IOGateway.Factory({...this.#s.baseConfig,node:this.#e})}async start(e){return this.#i?this:(this.#o=e,k.debug("starting default gateway"),await this.#t.start(e),this.#i=!0,this)}async getGateway(e){if(this.#s.scope==="singleton"||!e)return this.#t;let t=this.#n.get(e),n=t?this.#r.get(t):void 0;return n?k.enabledFor("debug")&&k.debug(`reusing existing gateway for principal '${e}'`):(k.enabledFor("debug")&&k.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.#c(e)),n}async#c(e){let t=Mn(),n={...this.#s.baseConfig,node:t};k.enabledFor("debug")&&k.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let s=Er.IOGateway.Factory(n);return this.#n.set(e,t),this.#r.set(t,s),await s.start(this.#o),s}getGateways(){let e=new Map(this.#r);return e.set(this.#e,this.#t),e}info(e){if(e&&this.#e!==e){let t=this.#r.get(e);if(t)return t.info();throw new Error(`no gateway found with ID: ${e}`)}return e===this.#e?this.#t.info():{...this.#t.info(),managedGateways:this.#r.size,scope:this.#s.scope}}async stop(e){if(e&&this.#e!==e){let t=this.#r.get(e);if(t){k.info(`stopping gateway with ID: ${e}`),await t.stop(),this.#r.delete(e);for(let[n,s]of this.#n.entries())if(s===e){this.#n.delete(n);break}return t}else throw new Error(`no gateway found with ID: ${e}`)}if(e===this.#e)return k.debug("stopping default gateway (managed gateways will continue running)"),await this.#t.stop(),this.#i=!1,this.#t;k.info(`stopping all gateways (1 default + ${this.#r.size} managed)`);for(let[t,n]of this.#r.entries())k.enabledFor("debug")&&k.debug(`stopping gateway with ID: ${t}`),await n.stop();return this.#r.clear(),this.#n.clear(),k.debug("stopping default gateway"),await this.#t.stop(),this.#i=!1,this.#t}getPrincipalGatewayId(e){return this.#n.get(e)}getPrincipalGatewayIds(){return new Map(this.#n)}getDefaultGateway(){return this.#t}client(e,t){return this.#t.client(e,t)}async connect(e){return this.#t.connect(e)}getPrincipalCount(){return this.#r.size}};function kn(...r){if(!Array.isArray(r))throw new Error("middleware must be array!");let e=r.flat();for(let t of e)if(typeof t!="function")throw new Error("middleware must be compose of functions!");return async function(t,n){let s=async(i,o)=>{let a=i===e.length?n:e[i];if(a===void 0)return;let c=!1,d=!1,f=await a(o,async m=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await s(i+1,m??o)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream.
2
+ You are probably missing an await or return statement in your middleware function.`);return f};return s(0,t)}}var Wn=require("node:net"),ut=require("tough-cookie");function hi(r,e){let t=r.get("x-forwarded-host");if(Array.isArray(t)&&(t=t[0]),t){let n=r.one("x-forwarded-port");n&&(t=`${t}:${n}`)}return t??=r.one("host"),Array.isArray(t)&&(t=t[0]),t?t.split(",",1)[0].trim():e}function pi(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function fi(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():pi(r)?"https":e}function gi(r,e,t){let n=t?t.port:r.protocol==="https:"?443:80,s=e.one("x-forwarded-for");if(Array.isArray(s)&&(s=s[0]),s!==void 0)return s=s.split(",",1)[0].trim(),{address:s,port:Number(n),family:(0,Wn.isIP)(s)===6?"IPv6":"IPv4"}}var at=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},ct=class r extends at{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++r.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return mi(this.headers)}parseHost(e){return hi(this.headers,e)}parseProtocol(e){return fi(this.headers,e)}parseRemoteAddress(e){return gi(this.URL,this.headers,e)}},dt=class extends at{get cookies(){return yi(this.headers)}setCookieValue(e){return new ut.Cookie({key:e.name,value:e.value,maxAge:e.maxAge,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httpOnly,sameSite:e.sameSite}).toString()}};function mi(r){return r.list("cookie").map(e=>e.split(";").map(t=>ut.Cookie.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function yi(r){return r.list("set-cookie").map(e=>{let t=ut.Cookie.parse(e);if(t){let n={name:t.key,value:t.value,maxAge:Number(t.maxAge??-1)};return t.httpOnly&&(n.httpOnly=!0),t.domain&&(n.domain=t.domain),t.path&&(n.path=t.path),t.secure&&(n.secure=!0),t.httpOnly&&(n.httpOnly=!0),t.sameSite&&(n.sameSite=t.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}var Ln=require("node:util");var lt=require("node:util"),ae="*",Fe=new lt.MIMEType(`${ae}/${ae}`),vr="application/octet-stream",aa=new lt.MIMEType(vr);function fe(r){return r.type===ae}function te(r){return r.subtype===ae||r.subtype.startsWith(`${ae}+`)}function Pr(r){return!fe(r)&&!te(r)}var Le=class extends Error{mimeType;constructor(e,t,n){super(t===void 0?`Invalid MIME type "${e}"`:`Invalid MIME type "${e}": ${t}`,n),this.mimeType=e}};function Cr(r,e,t){let n=`${r}/${e}`,s;try{s=new lt.MIMEType(n)}catch(i){throw new Le(n,void 0,{cause:i})}return t&&s.params.set("charset",t),s}function In(r){let e=r.subtype.lastIndexOf("+");return e!==-1&&e<r.subtype.length?r.subtype.substring(e+1):null}function re(r,e){if(!e)return!1;if(fe(r)||fe(e))return!0;if(r.type===e.type){if(r.subtype===e.subtype)return!0;if(te(r)||te(e)){let t=In(r),n=In(e);if(r.subtype===ae||e.subtype===ae)return!0;if(te(r)&&n!==null)return t===e.subtype||t===n;if(te(e)&&t!==null)return r.subtype===n||n===t}}return!1}var bi=`
3
+ application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy
4
+ application/json json
5
+ application/wasm wasm
6
+ application/x-pkcs12 p12 pfx
7
+ text/css css
8
+ text/csv csv
9
+ text/html html htm
10
+ text/javascript js mjs
11
+ text/plain txt text conf def list log in
12
+ `,R=class r extends Ln.MIMEType{static ALL=new r("*/*");static APPLICATION_OCTET_STREAM=new r(vr);static APPLICATION_JSON=new r("application/json");static APPLICATION_NDJSON=new r("application/x-ndjson");static MULTIPART_FORM_DATA=new r("multipart/form-data");static TEXT_PLAIN=new r("text/plain");static TEXT_HTML=new r("text/html");static#e="q";constructor(e){super(e),this.#t(this.type),this.#t(this.subtype);for(let[t,n]of this.params)this.checkParameters(t,n)}checkParameters(e,t){if(this.#t(e),Fn(t)||this.#t(t),e===r.#e){let n=On(t),s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new ht(`Invalid quality value: ${t}`)}}#t(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n>126||n===40||n===41||n===60||n===62||n===64||n===44||n===59||n===58||n===92||n===34||n===53||n===91||n===93||n===63||n===61||n===123||n===125||n===32||n===9)throw new ht(`Invalid token: ${e}`)}}get quality(){let e=this.params.get(r.#e);return e!==null?parseFloat(On(e)):1}static parseMediaType(e){return new r(e)}static parseMediaTypesList(e){return e?.trim()?e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>r.parseMediaType(t)):[]}static parseMediaTypes(...e){return e?e.length===1?r.parseMediaTypesList(e[0]):e.flatMap(t=>r.parseMediaTypesList(t)):[]}static asMediaType(e){return e instanceof r?e:new r(e.toString())}static asMediaTypes(...e){return e.map(t=>r.asMediaType(t))}},ht=class extends Error{constructor(e){super(e)}},ua=(function(){let e=new Map;for(let t of bi.trim().split(`
13
+ `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.split(/\s+/);if(s.length<2)continue;let[i,...o]=s,a=R.parseMediaType(i);for(let c of o){let d="."+c.toLowerCase(),u=e.get(d);u?u.push(a):e.set(d,[a])}}return e})();function Fn(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function On(r){return Fn(r)?r.substring(1,r.length-1):r}function wi(r,e){if(r instanceof R&&e instanceof R){let s=r.quality,i=e.quality;if(s>i)return!0;if(s<i)return!1}let t=fe(r),n=fe(e);if(t&&!n)return!1;if(!t&&n)return!0;{let s=te(r),i=te(e);if(s&&!i)return!1;if(!s&&i)return!0;if(r.type===e.type&&r.subtype===e.subtype){let o=Array.from(r.params.keys()).length,a=Array.from(e.params.keys()).length;return o>a}else return!1}}function Si(r,e){return wi(e,r)}function Ei(r,e){let t=r.length;for(let n=0;n<t;n++)for(let s=1;s<t-n;s++){let i=r[s-1],o=r[s];e(i,o)&&(r[s]=i,r[s-1]=o)}}function Dn(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Le("too many elements");Ei(r,Si)}function vi(r){let e=[];{let t=0,n=0;for(let s=0;s<r.length;s++)switch(r.charCodeAt(s)){case 32:t===n&&(t=n=s+1);break;case 44:e.push(r.slice(t,n)),t=n=s+1;break;default:n=n+1;break}e.push(r.slice(t,n))}return e}function $n(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...vi(t));return e}var De=class{constructor(){}toList(e){let t=this.get(e);return $n(t)}},A=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let t=super.get(e.toLowerCase());return $n(t)}set(e,t){return typeof t=="number"&&(t=String(t)),typeof t=="string"&&(t=[t]),t?super.set(e.toLowerCase(),t):(super.delete(e.toLowerCase()),this)}add(e,t){let n=super.get(e.toLowerCase());return typeof t=="string"&&(t=[t]),n&&(t=n.concat(t)),this.set(e,t),this}},Un=new A;function ge(r){let e=r.one("content-type");return e?R.parseMediaType(e):void 0}var xr=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},y=class r{static CONTINUE=new r(100,"Continue");static SWITCHING_PROTOCOLS=new r(101,"Switching Protocols");static OK=new r(200,"OK");static CREATED=new r(201,"Created");static ACCEPTED=new r(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new r(203,"Non-Authoritative Information");static NO_CONTENT=new r(204,"No Content");static RESET_CONTENT=new r(205,"Reset Content");static PARTIAL_CONTENT=new r(206,"Partial Content");static MULTI_STATUS=new r(207,"Multi-Status");static IM_USED=new r(226,"IM Used");static MULTIPLE_CHOICES=new r(300,"Multiple Choices");static MOVED_PERMANENTLY=new r(301,"Moved Permanently");static BAD_REQUEST=new r(400,"Bad Request");static UNAUTHORIZED=new r(401,"Unauthorized");static FORBIDDEN=new r(403,"Forbidden");static NOT_FOUND=new r(404,"Not Found");static METHOD_NOT_ALLOWED=new r(405,"Method Not Allowed");static NOT_ACCEPTABLE=new r(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new r(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new r(408,"Request Timeout");static CONFLICT=new r(409,"Conflict");static GONE=new r(410,"Gone");static LENGTH_REQUIRED=new r(411,"Length Required");static PRECONDITION_FAILED=new r(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new r(413,"Payload Too Large");static URI_TOO_LONG=new r(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new r(415,"Unsupported Media Type");static EXPECTATION_FAILED=new r(417,"Expectation Failed");static IM_A_TEAPOT=new r(418,"I'm a teapot");static TOO_EARLY=new r(425,"Too Early");static UPGRADE_REQUIRED=new r(426,"Upgrade Required");static PRECONDITION_REQUIRED=new r(428,"Precondition Required");static TOO_MANY_REQUESTS=new r(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new r(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new r(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new r(500,"Internal Server Error");static NOT_IMPLEMENTED=new r(501,"Not Implemented");static BAD_GATEWAY=new r(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new r(503,"Service Unavailable");static GATEWAY_TIMEOUT=new r(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new r(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new r(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new r(507,"Insufficient Storage");static LOOP_DETECTED=new r(508,"Loop Detected");static NOT_EXTENDED=new r(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new r(511,"Network Authentication Required");static#e=[];static{Object.keys(r).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let t=r[e];t instanceof r&&(Object.defineProperty(t,"name",{enumerable:!0,value:e,writable:!1}),r.#e.push(t))})}static resolve(e){for(let t of r.#e)if(t.value===e)return t}#t;#r;constructor(e,t){this.#t=e,this.#r=t}get value(){return this.#t}get phrase(){return this.#r}toString(){return`${this.#t} ${this.name}`}};function pt(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=y.resolve(r);return e!==void 0?e:new xr(r)}return r}var St=Oe(require("node:http"),1);function Ne(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return Ue.EMPTY_PATH;if(!(e>=0&&e<n.length))throw new Error("start index out of bounds: "+e);if(!(e>=0&&t<=n.length))throw new Error("end index out of bounds: "+t);if(!(e<t))throw new Error("start index must be less than end index: "+e+" >= "+t);let s=n.slice(e,t),i=s.map(o=>o.value).join("");return new Ue(i,s)}function z(r){return r.value.length===1&&r.valueToMatch===void 0&&r.parameters===void 0}function F(r){return!z(r)}var Ar={separator:47,decodeAndParseParameters:!0};function j(r,e){return Ue.createFromUrlPath(r,e??Ar)}var Ue=class r{static EMPTY_PATH=new r("",[]);static#e=new Map([[47,{value:"/",encoded:"%2F"}],[46,{value:".",encoded:"%2E"}]]);#t;#r;constructor(e,t){this.#t=e,this.#r=Object.freeze(t)}get value(){return this.#t}get elements(){return this.#r}static createFromUrlPath(e,t){if(e==="")return r.EMPTY_PATH;let n=t.separator,s=r.#e.get(n);if(s===void 0)throw new Error("Unsupported separator: "+n);let i=[],o;for(e.charCodeAt(0)===n?(o=1,i.push(s)):o=0;o<e.length;){let a=-1;for(let d=o;d<e.length;d++)if(e.charCodeAt(d)===n){a=d;break}let c=a!==-1?e.substring(o,a):e.substring(o);if(c.length>0&&i.push(t.decodeAndParseParameters?r.#n(c):$e.from(c,s)),a===-1)break;i.push(s),o=a+1}return new r(e,i)}static#n(e){let t=e.indexOf(";");if(t===-1){let n=decodeURIComponent(e);return $e.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),i=r.#s(s);return $e.from(e,n,i)}}static#s(e){let t=new Map,n=1;for(;n<e.length;){let s=-1;for(let o=n;o<e.length;o++)if(e.charAt(o)===";"){s=o;break}let i=s!==-1?e.substring(n,s):e.substring(n);if(r.#i(i,t),s===-1)break;n=s+1}if(t.size>0)for(let s of t.values())Object.freeze(s);return t}static#i(e,t){if(e){let n=e.indexOf("=");if(n!==-1){let s=decodeURIComponent(e.substring(0,n));if(s.trim()){let i=e.substring(n+1);for(let o of i.split(",")){let a=t.get(s);a!==void 0?a.push(decodeURIComponent(o)):t.set(s,[decodeURIComponent(o)])}}}else{let s=decodeURIComponent(e);if(s.trim()){let i=t.get(s);i!==void 0?i.push(""):t.set(s,[""])}}}}},$e=class r{static#e=new Map;static from(e,t,n){if(typeof t=="string"){let s=t;return new r(e,s,n)}else{let s=t,i=e.includes(s.encoded)?e.replaceAll(s.encoded,s.value):e;return r.from(e,i,n)}}#t;#r;#n;constructor(e,t,n=r.#e){this.#t=e,this.#r=t,this.#n=n}get value(){return this.#t}get valueToMatch(){return this.#r}get parameters(){return this.#n}};function Nn(r,e){return typeof r=="string"?Rr.parse(r,e):Nn(r.href,e)}var Rr=class r{static#e(e,t){if(!(t&&t.trim())||t.charAt(0)!=="/")return j("");r.#t(e.value,t);let n=t.length,s=0;for(let i=0;i<e.elements.length;i++){let o=e.elements[i];if(s+=o.value.length,n===s)return Ne(e,0,i+1)}throw new Error(`Failed to initialize context path: '${t}' for request path: '${e.value}'`)}static#t(e,t){let n=t.length;if(t.charAt(0)!=="/"||t.charAt(n-1)==="/")throw new Error(`Invalid context path: '${t}'. Context path must start with '/' and must not end with '/'`);if(!e.startsWith(t))throw new Error(`Invalid context path: '${t}'. Context path must be a prefix of request path: '${e}'`);if(e.length>n&&e.charAt(n)!=="/")throw new Error(`Invalid context path: '${t}'. Context path must match to full path segments for request path: '${e}'`)}static#r(e,t){let n=t.elements.length;return Ne(e,n)}static parse(e,t){let n=j(e),s=r.#e(n,t),i=r.#r(n,s);return new r(j(e),s,i)}#n;#s;#i;constructor(e,t,n){this.#n=e,this.#s=t,this.#i=n}get value(){return this.#n.value}get elements(){return this.#n.elements}get contextPath(){return this.#s}get pathWithinApplication(){return this.#i}modifyContextPath(e){let t=r.#e(this,e),n=r.#r(this,t);return new r(this,t,n)}toString(){return this.#n.toString()}},qe=class extends ct{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=Nn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var ft=class extends St.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},me=class extends St.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},gt=class extends dt{#e=[];#t;#r="new";#n=[];setStatusCode(e){return this.#r==="committed"?!1:(this.#t=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:pt(e))}get statusCode(){return this.#t}addCookie(e){if(this.#r==="committed")throw new Error(`Cannot add cookie ${JSON.stringify(e)} because HTTP response has already been committed`);return this.#e.push(e),this}beforeCommit(e){this.#n.push(e)}get commited(){let e=this.#r;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let t=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(t))).catch(n=>{throw n})}catch(n){throw n}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let t=this.#r,n=Promise.resolve();if(t==="new")this.#r="committing",this.#n.length>0&&(n=this.#n.reduce((s,i)=>s.then(()=>i()),Promise.resolve()).catch(s=>{this.#r==="committing"&&(this.#r="commit-action-failed")}));else if(t==="commit-action-failed")this.#r="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#r="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},ye=class extends qe{#e;#t;#r;constructor(e){super(new Hr(e)),this.#r=e}getNativeRequest(){return this.#r}get upgrade(){return this.#r.upgrade}get http2(){return this.#r.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#r.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#r.method}get host(){let e;return this.#r.httpVersionMajor>=2&&(e=this.#r.headers[":authority"]),e??=this.#r.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#r.httpVersionMajor>2&&(e=this.#r.headers[":scheme"]),e??=this.#r.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#r.socket}get remoteAddress(){let e=this.#r.socket.remoteFamily,t=this.#r.socket.remoteAddress,n=this.#r.socket.remotePort,s=!e||!t||!n?void 0:{family:e,address:t,port:n};return super.parseRemoteAddress(s)??s}initSslInfo(){if(this.#r.socketEncrypted)return new Tr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return St.default.IncomingMessage.toWeb(this.#r)}async blob(){let e=[];if(this.body!==void 0)for await(let t of this.body)e.push(t);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let t=await(await this.blob()).text();return new URLSearchParams(t)}async json(){let e=await this.blob();if(e.size===0)return;let t=await e.text();return JSON.parse(t)}initId(){let e=this.#r.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#r.socket.remotePort}`}},Tr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Hr=class extends De{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.headers[e]!==void 0}get(e){return this.#e.headers[e]}list(e){return super.toList(e)}one(e){let t=this.#e.headers[e];return Array.isArray(t)?t[0]:t}keys(){return Object.keys(this.#e.headers).values()}},Mr=class extends De{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.hasHeader(e)}keys(){return this.#e.getHeaderNames().values()}get(e){return this.#e.getHeader(e)}one(e){let t=this.#e.getHeader(e);return Array.isArray(t)?t[0]:t}set(e,t){return this.#e.headersSent||(Array.isArray(t)?t=t.map(n=>typeof n=="number"?String(n):n):typeof t=="number"&&(t=String(t)),t?this.#e.setHeader(e,t):this.#e.removeHeader(e)),this}add(e,t){return this.#e.headersSent||this.#e.appendHeader(e,t),this}list(e){return super.toList(e)}},mt=class extends gt{#e;constructor(e){super(new Mr(e)),this.#e=e}getNativeResponse(){return this.#e}get statusCode(){return super.statusCode??{value:this.#e.statusCode}}applyStatusCode(){let e=super.statusCode;e!==void 0&&(this.#e.statusCode=e.value)}addCookie(e){return this.headers.add("Set-Cookie",super.setCookieValue(e)),this}async bodyInternal(e){if(this.#e.headersSent)return!1;if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported in response");{let t=await e;return await new Promise((n,s)=>{try{t===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof t=="string"?this.headers.set("Content-Length",Buffer.byteLength(t)):t instanceof Blob?this.headers.set("Content-Length",t.size):this.headers.set("Content-Length",t.byteLength)),this.#e.end(t,()=>{n(!0)}))}catch(i){s(i instanceof Error?i:new Error(`end failed: ${i}`))}})}}},yt=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get id(){return this.#e.id}get method(){return this.#e.method}get path(){return this.#e.path}get requestPath(){return this.#e.requestPath}get protocol(){return this.#e.protocol}get host(){return this.#e.host}get URL(){return this.#e.URL}get headers(){return this.#e.headers}get cookies(){return this.#e.cookies}get remoteAddress(){return this.#e.remoteAddress}get upgrade(){return this.#e.upgrade}get sslInfo(){return this.#e.sslInfo}get body(){return this.#e.body}async blob(){return await this.#e.blob()}async text(){return await this.#e.text()}async formData(){return await this.#e.formData()}async json(){return await this.#e.json()}toString(){return`${r.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof qe)return e.getNativeRequest();if(e instanceof r)return r.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},be=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}setStatusCode(e){return this.delegate.setStatusCode(e)}setRawStatusCode(e){return this.delegate.setRawStatusCode(e)}get statusCode(){return this.delegate.statusCode}get cookies(){return this.delegate.cookies}addCookie(e){return this.delegate.addCookie(e),this}async end(){return await this.delegate.end()}async body(e){return await this.#e.body(e)}get headers(){return this.#e.headers}toString(){return`${r.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof gt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},bt=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get request(){return this.#e.request}get response(){return this.#e.response}attribute(e){return this.#e.attribute(e)}get attributes(){return this.#e.attributes}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${r.name} [delegate: ${this.delegate}]`}},wt=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[qn]=e.id,this.request=e,this.response=t}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes.get(e)}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(qn);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},qn="io.interop.web.server.exchange.log_id";var Et=require("node:v8"),X=require("node:fs/promises"),C=w("monitoring"),Pi={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function Ci(){return(0,Et.getHeapStatistics)()}async function _n(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;C.enabledFor("debug")&&C.debug(`starting heap dump in ${t}`),await kr(r.dumpLocation).catch(async s=>{C.enabledFor("debug")&&C.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await(0,X.mkdir)(r.dumpLocation,{recursive:!0}),C.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{C.error(`failed to create dump location ${r.dumpLocation}`)}});let n=(0,Et.writeHeapSnapshot)(t);C.info("heap dumped");try{C.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await kr(s).then(async()=>{C.enabledFor("debug")&&C.debug(`deleting ${s}`);try{await(0,X.unlink)(s)}catch(o){C.warn(`failed to delete ${s}`,o)}}).catch(()=>{});for(let o=r.maxBackups-1;o>0;o--){let a=`${r.dumpLocation}/${e}.${o}.heapsnapshot`,c=`${r.dumpLocation}/${e}.${o+1}.heapsnapshot`;await kr(a).then(async()=>{try{await(0,X.rename)(a,c)}catch(d){C.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${r.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,X.rename)(n,i)}catch(o){C.warn(`failed to rename ${n} to ${i}`,o)}C.debug("snapshots rolled")}catch(s){throw C.error("error rolling backups",s),s}}async function kr(r){C.enabledFor("trace")&&C.debug(`checking file ${r}`),await(0,X.access)(r)}async function xi(r,e,t){C.enabledFor("debug")&&C.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;C.info(`heap stats ${JSON.stringify(r)}`),s>=n?(C.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await _n(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Bn(r){let e={...Pi,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=Ci();await xi(a,n,e)},i=setInterval(s,e.reportInterval);return{...e,channel:async a=>{if(!t)switch(a??="run",a){case"run":{await s();break}case"dump":{await _n(e);break}case"stop":{t=!0,clearInterval(i),C.info("exit memory diagnostic");break}}return t}}}async function Ai({channel:r},e){await r(e)||C.warn(`cannot execute command "${e}" already closed`)}async function Gn(r){return await Ai(r,"stop")}var Ti=(r,e)=>(e??=r,async({response:t},n)=>{e!==!1&&!t.headers.has("server")&&t.headers.set("Server",e),await n()}),Vn=(r,e)=>Ti(r,e);var _e=require("@interopio/gateway");var Wr=w("gateway.ws.client-verify");function Hi(r){switch(r.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Mi(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&_e.IOGateway.Filtering.valuesMatch(t,e))return Wr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&_e.IOGateway.Filtering.valuesMatch(n,e))return Wr.enabledFor("debug")&&Wr.debug(`origin ${e} matches allow filter`),!0}function ki(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function zn(r,e){if(!e)return!0;if(r){let t=Mi(e,r);return t||ki(e)}else return Hi(e)}function jn(r){if(r){let e=(r.block??r.blacklist??[]).map(_e.IOGateway.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(_e.IOGateway.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Xn=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return O},we=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return O;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},Jn=r=>async e=>(await r(e)).match?O:D(),Se=async r=>D();Se.toString=()=>"any-exchange";var Yn=Object.freeze({}),O=Object.freeze({match:!1,variables:Yn}),D=(r=Yn)=>({match:!0,variables:r}),$=(r,e)=>{let t=e?.method,n=async s=>{let i=s.request,o=i.path;if(t!==void 0&&i.method!==t)return O;if(typeof r=="string")return o===r?D():O;{let a=r.exec(o);return a===null?O:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},Be=r=>{let e=t=>{if(r.ignoredMediaTypes!==void 0){for(let n of r.ignoredMediaTypes)if(t===n||n==="*/*")return!0}return!1};return async t=>{let n=t.request,s;try{s=n.headers.list("accept")}catch{return O}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return O}},ce=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():O;ce.toString=()=>"websocket upgrade";var Ir=require("@interopio/gateway");async function Or(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Ir.IOGateway.Filtering.regexify),allowMethods:i.method===void 0?["*"]:[i.method],allowCredentials:o.authorize?.access!=="permitted"?!0:void 0}:o.cors,c=i.path;t.cors.push([c,a])}},s=new class{handle(...i){i.forEach(({request:o,options:a,handler:c})=>{let d=$(Ir.IOGateway.Filtering.regexify(o.path),{method:o.method});a?.authorize&&t.authorize.push([d,a.authorize]),n(o,a);let u=async(f,m)=>{let{match:P,variables:l}=await d(f);P?await c(f,l):await m()};t.middleware.push(u)})}socket(...i){for(let{path:o,factory:a,options:c}of i){let d=o??"/";t.sockets.set(d,{default:o===void 0||o==="/",ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:jn(c?.origins)})}}};await r(s,e)}var Ct=require("@interopio/gateway");function Ii(r){let e=r.headers.one("origin");if(e===void 0)return!0;let t=r.URL,n=t.protocol,s=t.host,i=URL.parse(e),o=i?.host,a=i?.protocol;return n===a&&s===o}function Kn(r){return r.headers.has("origin")&&!Ii(r)}function J(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var Qn=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],Oi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",Qn.join(", "));else{let o=s.list("Vary");for(let a of Qn)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!Kn(t))return!0}catch{return U.enabledFor("debug")&&U.debug("reject: origin is malformed"),Ge(n),!1}if(s.has("access-control-allow-origin"))return U.enabledFor("trace")&&U.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=J(t);return e?Fi(r,e,i):i?(Ge(n),!1):!0},Pt=["*"],Lr=["GET","HEAD","POST"],Zn={allowOrigins:Pt,allowMethods:Lr,allowHeaders:Pt,maxAge:1800};function xt(r){if(r){let e=r.allowHeaders;e&&e!==x&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(ts(r),rs(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==x&&(n=Ct.IOGateway.Filtering.regexify(n),typeof n=="string")?ns(n).toLowerCase():n)}),r}}function vt(r,e){if(e===void 0)return r!==void 0?r===x?[x]:r:[];if(r===void 0)return e===x?[x]:e;if(r==Pt||r===Lr)return e===x?[x]:e;if(e==Pt||e===Lr)return r===x?[x]:r;if(r===x||r.includes(x)||e===x||e.includes(x))return[x];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var Ve=(r,e)=>e===void 0?r:{allowOrigins:vt(r.allowOrigins,e?.allowOrigins),allowMethods:vt(r.allowMethods,e?.allowMethods),allowHeaders:vt(r.allowHeaders,e?.allowHeaders),exposeHeaders:vt(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},Li=r=>{let e=r.corsConfigSource,t=r.corsProcessor??Oi;if(e===void 0)throw new Error("corsConfigSource is required");if(t===void 0)throw new Error("corsProcessor is required");return{filter:async(n,s)=>{let i=await e(n);!t(n,i)||J(n.request)||await s.filter(n)}}},es=Li,U=w("cors");function Ge(r){r.setStatusCode(y.FORBIDDEN)}function Fi(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=$i(e,o);if(a===void 0)return U.enabledFor("debug")&&U.debug(`reject: '${o}' origin is not allowed`),Ge(s),!1;let c=qi(n,t),d=Ui(e,c);if(d===void 0)return U.enabledFor("debug")&&U.debug(`reject: HTTP '${c}' is not allowed`),Ge(s),!1;let u=_i(n,t),f=Ni(e,u);if(t&&f===void 0)return U.enabledFor("debug")&&U.debug(`reject: headers '${u}' are not allowed`),Ge(s),!1;i.set("Access-Control-Allow-Origin",a),t&&i.set("Access-Control-Allow-Methods",d.join(",")),t&&f!==void 0&&f.length>0&&i.set("Access-Control-Allow-Headers",f.join(", "));let m=e.exposeHeaders;return m&&m.length>0&&i.set("Access-Control-Expose-Headers",m.join(", ")),e.allowCredentials&&i.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&i.set("Access-Control-Allow-Private-Network","true"),t&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var x="*",Di=["GET","HEAD"];function ts(r){if(r.allowCredentials===!0&&r.allowOrigins===x)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function rs(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===x)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function $i(r,e){if(e){let t=r.allowOrigins;if(t){if(t===x)return ts(r),rs(r),x;let n=ns(e.toLowerCase());for(let s of t)if(s===x||Ct.IOGateway.Filtering.valueMatches(s,n))return e}}}function Ui(r,e){if(e){let t=r.allowMethods??Di;if(t===x)return[e];if(Ct.IOGateway.Filtering.valuesMatch(t,e))return t}}function Ni(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===x||t.includes(x),s=[];for(let i of e){let o=i?.trim();if(o){if(n)s.push(o);else for(let a of t)if(o.toLowerCase()===a){s.push(o);break}}}if(s.length>0)return s}function ns(r){return r.endsWith("/")?r.slice(0,-1):r}function qi(r,e){return e?r.headers.one("access-control-request-method"):r.method}function _i(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var ss=r=>async e=>{for(let[t,n]of r.mappings)if((await t(e)).match)return U.debug(`resolved cors config on '${e.request.path}' using ${t}: ${JSON.stringify(n)}`),n};var is=require("@interopio/gateway");function os(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:Ve(Zn,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,f]of t)is.IOGateway.Filtering.valueMatches(u,o)&&(f===void 0?c=void 0:c=c===void 0?f:Ve(c,f));let d=r.corsConfig===!1?void 0:{allowOrigins:a.originFilters?.allow,allowMethods:["GET","CONNECT","OPTIONS"],allowHeaders:["Upgrade","Connection","Origin","Sec-Websocket-Key","Sec-Websocket-Version","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],exposeHeaders:["Sec-Websocket-Accept","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0};c=c===void 0?d:Ve(c,d),s.push([we([ce,$(o)]),xt(c)])}let i=[];for(let[o,a]of t){let[,c]=i.find(([u])=>String(u)===String(o))??[o,n];c=c===void 0?a:Ve(c,a);let d=!1;for(let u of i)if(String(u[0])===String(o)){u[1]=c,d=!0;break}d||i.push([o,c])}for(let[o,a]of i)s.push([$(o),xt(a)]);return s.push([$(/\/api\/.*/),xt(n)]),ss({mappings:s})}function as(r){return r!==void 0&&typeof r.type=="string"&&typeof r.authenticated=="boolean"}var W=class extends Error{_authentication;get authentication(){return this._authentication}set authentication(e){if(e===void 0)throw new TypeError("Authentication cannot be undefined");this._authentication=e}},At=class extends W{},Ee=class extends W{},ve=class extends W{constructor(e){super(e)}},ze=class extends ve{constructor(e){super(e)}},je=class extends ve{constructor(e){super(e)}},Xe=class extends ve{constructor(e){super(e)}},Je=class extends ve{constructor(e){super(e)}};var de=class extends Error{},Y=class{constructor(e){this.granted=e}granted},ne=class{#e;constructor(e){this.#e=e}async verify(e,t){if(!(await this.#e(e,t))?.granted)throw new de("Access denied")}async authorize(e,t){return await this.#e(e,t)}},Pe=class extends W{};var N=r=>async e=>{let t=!0,{response:n}=e;for(let s of r.keys())n.headers.has(s)&&(t=!1);if(t)for(let[s,i]of r)n.headers.set(s,i)},Bi=()=>N(new A().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Gi=()=>N(new A().add("x-content-type-options","nosniff")),Vi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=N(new A().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},zi=r=>N(new A().add("x-frame-options",r)),ji=r=>N(new A().add("x-xss-protection",r)),Xi=r=>{let e=r===void 0?void 0:N(new A().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},Ji=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:N(new A().add(t,r));return async s=>{n!==void 0&&await n(s)}},Yi=(r="no-referrer")=>N(new A().add("referer-policy",r)),Ki=r=>{let e=r===void 0?void 0:N(new A().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},Qi=r=>{let e=r===void 0?void 0:N(new A().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},Zi=r=>{let e=r===void 0?void 0:N(new A().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},eo=(...r)=>async e=>{for(let t of r)await t(e)};function Fr(r){let e=[];r?.cache?.disabled||e.push(Bi()),r?.contentType?.disabled||e.push(Gi()),r?.hsts?.disabled||e.push(Vi(r?.hsts?.maxAge??365*24*60*60,r?.hsts?.includeSubDomains??!0,r?.hsts?.preload??!1)),r?.frameOptions?.disabled||e.push(zi(r?.frameOptions?.mode??"DENY")),r?.xss?.disabled||e.push(ji(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(Xi(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push(Ji(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(Yi(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(Ki(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(Qi(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(Zi(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=eo(...e);return{filter:async(n,s)=>(await t(n),s.filter(n))}}var Ce=r=>{let e=r.entryPoint,t=r?.rethrowAuthenticationServiceError??!0;return async({exchange:n},s)=>{if(!t||!(s instanceof Pe))return e(n,s);throw s}};var to="Realm",ro=r=>`Basic realm="${r}"`,xe=r=>{let e=ro(r?.realm??to);return async(t,n)=>{let{response:s}=t;s.setStatusCode(y.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var cs="Basic ",Rt=r=>{let e=r?.credentialsEncoding??"utf-8";return async t=>{let{request:n}=t,s=n.headers.one("authorization");if(!s||!/basic/i.test(s.substring(0)))return;let i=s.length<=cs.length?"":s.substring(cs.length),a=Buffer.from(i,"base64").toString(e).split(":",2);if(a.length!==2)return;let c=a[0],d=a[1];return{type:"UsernamePassword",authenticated:!1,principal:c,credentials:d,name:c,eraseCredentials:()=>{d=null}}}};var ds=require("node:async_hooks"),se=class r{static hasSecurityContext(e){return e.getStore()?.securityContext!==void 0}static async getSecurityContext(e){return await e.getStore()?.securityContext}static clearSecurityContext(e){delete e.getStore()?.securityContext}static withSecurityContext(e){return(t=new ds.AsyncLocalStorage)=>(t.getStore().securityContext=e,t)}static withAuthentication(e){return r.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(r.hasSecurityContext(e))return r.getSecurityContext(e)}};async function no(r,e,t,n,s,i){let a=await(await n(r))?.(t);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await so(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof W,c}}async function so(r,e,t,n){se.withAuthentication(r)(n),await t(e,r)}function ie(r){let e={matcher:Se,successHandler:async({exchange:n,chain:s})=>{await s.filter(n)},converter:Rt({}),failureHandler:Ce({entryPoint:xe({})}),...r},t=e.managerResolver;if(t===void 0&&e.manager!==void 0){let n=e.manager;t=async s=>n}if(t===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return{filter:async(n,s)=>{let o=(await e.matcher(n)).match?await e.converter(n):void 0;if(o===void 0){await s.filter(n);return}try{await no(n,s,o,t,e.successHandler,e.storage)}catch(a){if(a instanceof W){await e.failureHandler({exchange:n,chain:s},a);return}throw a}}}}var us=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var Ae=w("auth.entry-point"),Tt=r=>{let e=r.defaultEntryPoint??(async({response:t},n)=>{t.setStatusCode(y.UNAUTHORIZED),await t.end()});return async(t,n)=>{for(let[s,i]of r.entryPoints)if(Ae.enabledFor("debug")&&Ae.debug(`trying to match using: ${s}`),(await s(t)).match)return Ae.enabledFor("debug")&&Ae.debug(`match found. using default entry point ${i}`),i(t,n);return Ae.enabledFor("debug")&&Ae.debug(`no match found. using default entry point ${e}`),e(t,n)}};var ls=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Dr(r){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():O,t=Tt({entryPoints:[[e,us({httpStatus:y.UNAUTHORIZED})]],defaultEntryPoint:xe({})}),n=r.entryPoint??t,s=r.manager,i=Be({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=Jn(Be({mediaTypes:["text/html"]})),a=we([o,i]),c=Xn([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Ce({entryPoint:n}),u=ls(r.successHandlers??r.defaultSuccessHandlers),f=Rt({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:f})}var hs={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},ps="https://tools.ietf.org/html/rfc6750#section-3.1";function Ht(r){return{errorCode:hs.invalid_token,httpStatus:y.UNAUTHORIZED,description:r,uri:ps}}function $r(r){return{errorCode:hs.invalid_request,httpStatus:y.BAD_REQUEST,description:r,uri:ps}}var io="access_token",oo=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,_=class extends W{error;constructor(e,t,n){super(t??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},fs=r=>r.type==="BearerToken",ao=r=>async e=>{let{request:t}=e;return Promise.all([uo(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),lo(t,r?.uriQueryParameter),ho(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(co).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function co(r){if(r.length===0)return;if(r.length>1){let t=$r("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=$r("The requested access token parameter is an empty string");throw new _(t)}return e}async function uo(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=oo.exec(t);if(n===null){let s=Ht("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function gs(r){let e=r.getAll(io);if(e.length!==0)return e}async function lo(r,e=!1){if(!(!e||r.method!=="GET"))return gs(r.URL.searchParams)}async function ho(r,e=!1){let{request:t}=r;if(!e||t.headers.one("content-type")!=="application/x-www-form-urlencoded"||t.method!=="POST")return;let n=await r.request.formData();if(n)return gs(n)}var Mt=ao;function po(r){let e="Bearer";if(r.size!==0){e+=" ";let t=0;for(let[n,s]of r)e+=`${n}="${s}"`,t!==r.size-1&&(e+=", "),t++}return e}var ms=r=>r.httpStatus!==void 0;function fo(r){if(r instanceof _){let{error:e}=r;if(ms(e))return e.httpStatus}return y.UNAUTHORIZED}function go(r,e){let t=new Map;if(e&&t.set("realm",e),r instanceof _){let{error:n}=r;t.set("error",n.errorCode),n.description&&t.set("error_description",n.description),n.uri&&t.set("error_uri",n.uri),ms(n)&&n.scope&&t.set("scope",n.scope)}return t}var mo=r=>async(e,t)=>{let n=fo(t),s=go(t,r?.realmName),i=po(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},kt=mo;var yo=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},bo=r=>async e=>r(e),Re=class extends Error{},Ye=class extends Re{};function wo(r){if(r instanceof Ye)return new _(Ht(r.message),r.message,{cause:r});throw new Pe(r.message,{cause:r})}function Ur(r){let e=r.decoder,t=r.authConverter??bo(yo({}));return async n=>{if(fs(n)){let s=n.token;try{let i=await e(s);return await t(i)}catch(i){throw i instanceof Re?wo(i):i}}}}function Nr(r){let e=r.entryPoint??kt({}),t=r?.converter??Mt({}),n=r.failureHandler??Ce({entryPoint:e});if(r.managerResolver!==void 0)return ie({storage:r.storage,converter:t,failureHandler:n,managerResolver:r.managerResolver});if(r.jwt!==void 0){let s=r.jwt.manager??Ur(r.jwt);return ie({storage:r.storage,converter:t,failureHandler:n,managerResolver:async i=>s})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}var Bt=require("@interopio/gateway/jose/jwt");async function ys(r,e,t){let n=new At("Full authentication is required to access this resource."),s=new W("Access Denied",{cause:n});e&&(s.authentication=e),await t(r,s)}function So(r){return async(e,t)=>{e.response.setStatusCode(r),e.response.headers.set("Content-Type","text/plain; charset=utf-8");let n=Buffer.from("Access Denied","utf-8");e.response.headers.set("Content-Length",n.length),await e.response.body(n)}}var bs=r=>{let e=So(y.FORBIDDEN),t=r.authenticationEntryPoint??xe();return{filter:async(n,s)=>{try{await s.filter(n)}catch(i){if(i instanceof de){let o=await n.principal();as(o)?(o.authenticated||await e(n,i),await ys(n,o,t)):await ys(n,void 0,t);return}throw i}}}};var Eo=w("security.auth");function qr(r){let e=async(t,n)=>{let s;for(let[i,o]of r.mappings)if((await i(n))?.match){Eo.debug(`checking authorization on '${n.request.path}' using [${i}, ${o}]`);let a=await o.authorize(t,{exchange:n});if(a!==void 0){s=a;break}}return s??=new Y(!1),s};return new ne(e)}var Wt=w("security.auth");function _r(r){let{manager:e,storage:t}=r;return{filter:async(n,s)=>{let i=se.getContext(t).then(o=>o?.authentication);try{await e.verify(i,n),Wt.enabledFor("debug")&&Wt.debug("authorization successful")}catch(o){throw o instanceof de&&Wt.enabledFor("debug")&&Wt.debug(`authorization failed: ${o.message}`),o}await s.filter(n)}}}var Br=class extends bt{#e;constructor(e,t){super(e),this.#e=t}async principal(){return(await this.#e())?.authentication}},ws=r=>{let e=r.storage;return{filter:async(t,n)=>{await n.filter(new Br(t,async()=>await se.getContext(e)))}}};var Ss=r=>{let{principalExtractor:e}=r;return async t=>{let n=t.request.sslInfo;if(n===void 0||n.peerCertificate===void 0)return;let s=n.peerCertificate,i=e(s);return{type:"PreAuthenticated",authenticated:!1,principal:i,name:i??"",credentials:s}}};var It=r=>{let e=r?.principalAltName==="email",t=/CN=(.*?)(?:,|$)/mi;return n=>{if(e){let o=n.subjectAltName?.split(", ").find(a=>a.startsWith("email:"));if(o)return o.replace("email:","")}let s=t.exec(n.subject);if(s===null)throw new Ee(`Cannot extract principal from subject DN: ${n.subject}`);return s[1]}};var ue=class{async encode(e){if(e!=null)return await this.encodeDefinedPassword(e.toString())}async matches(e,t){return!e||!t?!1:await this.matchesDefined(e.toString(),t)}upgradeEncoding(e){return e?this.upgradeEncodingDefined(e):!1}upgradeEncodingDefined(e){return!1}},Te=class r extends ue{static DEFAULT_ID_PREFIX="{";static DEFAULT_ID_SUFFIX="}";#e;#t;#r;#n;#s;#i=new class extends ue{#d;constructor(e){super(),this.#d=e}async encodeDefinedPassword(e){throw new Error("encode is not supported")}async matchesDefined(e,t){let n=this.#d.#o(t);if(!n)throw new Error(`No password encoder mapped for id ${n}`);if(t){let s=t.indexOf(this.#d.#e),i=t.indexOf(this.#d.#t,s+this.#d.#e.length);if(s===-1&&i===-1)throw new Error("No prefix found in encoded password")}throw new Error("malformed password encoder prefix")}}(this);constructor(e,t,n=r.DEFAULT_ID_PREFIX,s=r.DEFAULT_ID_SUFFIX){if(e==null)throw new Error("idForEncode cannot be null or undefined");if(n==null)throw new Error("idPrefix cannot be null or undefined");if(!s)throw new Error("idSuffix cannot be empty");if(n.indexOf(s)!==-1)throw new Error(`idPrefix "${n}" cannot contain idSuffix "${s}"`);if(!t.has(e))throw new Error(`No PasswordEncoder mapped for id "${e}"`);for(let i of t.keys())if(i!==null){if(n&&i.includes(n))throw new Error(`id "${i}" cannot include ${n}`);if(s&&i.includes(s))throw new Error(`id "${i}" cannot include ${s}`)}super(),this.#r=e,this.#n=t.get(e),this.#s=new Map(t),this.#e=n,this.#t=s}set defaultPasswordEncoderForMatches(e){if(e==null)throw new Error("defaultPasswordEncoderForMatches cannot be null or undefined");this.#i=e}async encodeDefinedPassword(e){let t=await this.#n.encode(e);return`${this.#e}${this.#r}${this.#t}${t}`}async matchesDefined(e,t){let n=this.#o(t),s=n?this.#s.get(n):void 0;if(s===void 0)return await this.#i.matches(e,t);{let i=this.#c(t);return await s.matches(e,i)}}#o(e){if(e===void 0)return;let t=e.indexOf(this.#e);if(t!==0)return;let n=e.indexOf(this.#t,t+this.#e.length);if(n!==-1)return e.substring(t+this.#e.length,n)}upgradeEncodingDefined(e){let t=this.#o(e);if(this.#r!==t)return!0;{let n=this.#c(e);return this.#n.upgradeEncoding?.(n)??!1}}#c(e){let t=e.indexOf(this.#t);return e.substring(t+this.#t.length)}},Ot=class r extends ue{static#e=new r;static get instance(){return r.#e}constructor(){super()}async encodeDefinedPassword(e){return e.toString()}async matchesDefined(e,t){return e.toString()===t}};var I=require("@interopio/gateway-server/tools");function vo(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Lt=class extends ue{#e;#t;#r;#n;#s;constructor(e=I.argon2.DEFAULT_SALT_LENGTH,t=I.argon2.DEFAULT_HASH_LENGTH,n=I.argon2.DEFAULT_PARALLELISM,s=I.argon2.DEFAULT_MEMORY,i=I.argon2.DEFAULT_PASSES){super(),this.#e=e,this.#t=t,this.#r=n,this.#n=s,this.#s=i}async matchesDefined(e,t){try{let n=I.argon2.decode(t),s=await I.argon2.createHash(n.algorithm,e,n.hash.length,n.parameters);return vo(n.hash,s)}catch{return!1}}async encodeDefinedPassword(e){let t=I.keygen.createSalt(this.#e),n={memory:this.#n,passes:this.#s,parallelism:this.#r,nonce:t},s=await I.argon2.createHash("argon2id",e,this.#t,n);return I.argon2.encode({algorithm:"argon2id",version:I.argon2.ARGON2_VERSION,parameters:n,hash:s})}upgradeEncodingDefined(e){let t=I.argon2.decode(e);return t.version<I.argon2.ARGON2_VERSION||t.parameters.memory<this.#n||t.parameters.passes<this.#s}};var Gr=4096;function Es(){let r="argon2id",e=new Map([[r,new Lt],["noop",Ot.instance]]);return new Te(r,e,Te.DEFAULT_ID_PREFIX,Te.DEFAULT_ID_SUFFIX)}var vs={async updatePassword(r,e){return r}},Ft=class extends W{username;constructor(e,t,n){super(e,n),this.username=t}},Dt=class r{#e;#t;#r=[];#n;#s;#i;#o;#c=e=>e;constructor(){}static ofUsername(e){return new r().username(e)}static ofUserDetails(e){let t=r.ofUsername(e.username).accountExpired(e.accountExpired??!1).accountLocked(e.accountLocked??!1).authorities(e.authorities).credentialsExpired(e.credentialsExpired??!1).disabled(e.disabled??!1);return e.password!==void 0&&t.password(e.password),t}username(e){if(!e)throw new TypeError("username cannot be empty");return this.#e=e,this}password(e){return this.#t=e,this}passwordEncoder(e){if(!e)throw new TypeError("password encoder cannot be null or undefined");return this.#c=e,this}roles(...e){return this.authorities(e.map(t=>{if(t.startsWith("role:"))throw new Error(`${t} must not start with 'role:' (it is automatically added)`);return{authority:`role:${t}`}}))}authorities(e){return this.#r=[...e],this}accountExpired(e){return this.#n=e,this}accountLocked(e){return this.#s=e,this}credentialsExpired(e){return this.#i=e,this}disabled(e){return this.#o=e,this}build(){if(!this.#e)throw new TypeError("username is required");let e=this.#t!==void 0?this.#c(this.#t):void 0;return{username:this.#e,password:e,authorities:this.#r,accountExpired:this.#n,accountLocked:this.#s,credentialsExpired:this.#i,disabled:this.#o,eraseCredentials(){e=null},toString(){return`User(username=${this.username}, password=[PROTECTED], authorities=${JSON.stringify(this.authorities)}, accountExpired=${this.accountExpired}, accountLocked=${this.accountLocked}, credentialsExpired=${this.credentialsExpired}, disabled=${this.disabled})`}}}};var oe=w("security.users");function Ps(r,e){let t=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw oe.debug("user account is locked"),new ze("User account is locked");if(a.disabled)throw oe.debug("user account is disabled"),new je("User is disabled");if(a.accountExpired)throw oe.debug("user account is expired"),new Xe("User account has expired")}),n=e?.postAuthenticationChecks??(a=>{if(a.credentialsExpired)throw oe.debug("user credentials have expired"),new Je("User credentials have expired")}),s=e?.passwordEncoder??Es(),i=e?.userDetailsPasswordService??vs,o=async(a,c)=>{let d=a.password;if(d!==void 0&&s.upgradeEncoding?.(d)){let f=await s.encode(c);return await i.updatePassword(a,f)}return a};return async a=>{let c=a.name,d=a.credentials!==void 0&&a.credentials!==null?a.credentials.toString():void 0,u=await r.findByUsername(c);if(!u)throw new Error(`User not found: ${c}`);if(t(u),!await s.matches(d,u.password))throw new Ee("Invalid Credentials");let f=await o(u,d);n(f);let m=f.password;return{type:"UsernamePassword",principal:f,credentials:m,authorities:f.authorities,authenticated:!0,name:f.username,eraseCredentials(){m=null}}}}function Po(){return r=>{if(r.accountLocked)throw oe.debug("failed to authenticate since user account is locked"),new ze("User account is locked");if(r.disabled)throw oe.debug("failed to authenticate user account is disabled"),new je("User is disabled");if(r.accountExpired)throw oe.debug("failed to authenticate since user account is expired"),new Xe("User account has expired");if(r.credentialsExpired)throw oe.debug("failed to authenticate since user credentials have expired"),new Je("User credentials have expired")}}function Cs(r){let e=r.userDetailsService,t=r.userDetailsChecker??Po(),n=s=>s.type==="PreAuthenticated"&&s.name!==void 0;return async s=>{let i=n(s)&&await e.findByUsername(s.name);if(!i)throw new Ft("user not found",s.name);t(i);let o=s.credentials;return{type:"PreAuthenticated",principal:i,credentials:o,authorities:i.authorities,authenticated:!0,details:i,name:i.username,eraseCredentials(){o=null}}}}function Vr(r){let e=r.manager??Cs({userDetailsService:r.getService("UserDetailsService")}),t=r.extractor??It(),n=r.converter??Ss({principalExtractor:t});return ie({storage:r.storage,manager:e,converter:n})}var $t=class{#e;constructor(e){if(e==null)throw new Error("delegate must not be null or undefined");this.#e=e}get delegate(){return this.#e}async handle(e){return await this.#e.handle(e)}toString(){return`WebHandlerDecorator[delegate=${this.#e}]`}},Ut=class extends $t{#e;constructor(e,...t){super(e),this.#e=[...t],Object.freeze(this.#e)}get errorHandlers(){return this.#e}handle(e){let t;try{t=super.handle(e)}catch(n){t=Promise.reject(n)}for(let n of this.#e)t=t.catch(async s=>{let i=s instanceof Error?s:new Error(String(s));await n.handle(e,i)});return t}},Ke=class r{#e;#t;#r;#n;static of(e,...t){let n=[...t],s=new r(t,e),i=r.initChain(t,e);return s.#r=i.#r,s.#n=i.#n,s}static initChain(e,t){let n=new r(e,t,void 0,void 0);for(let s of[...e].reverse())n=new r(e,t,s,n);return n}constructor(e,t,n,s){this.#e=e,this.#t=t,this.#r=n,this.#n=s}get filters(){return this.#e}get handler(){return this.#t}async filter(e){this.#r!==void 0&&this.#n!==void 0?await this.#s(this.#r,this.#n,e):await this.#t.handle(e)}#s(e,t,n){return e.filter(n,t)}},Nt=class extends $t{#e;constructor(e,...t){super(e),this.#e=Ke.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var qt=class{#e;#t=new jr;#r=new zr;#n=new Jr;constructor(...e){this.#e=[...e]}async filter(e,t){let n=await this.#t.firewalledExchange(e);try{await this.#s(n,t)}catch(s){if(s instanceof Xr)await this.#n.handle(e,s);else throw s}}async#s(e,t){for(let n of this.#e)if(await n.matches(e)){let s=await n.webFilters();await this.#r.decorate(t,s).filter(e);return}await this.#r.decorate(t).filter(e)}set firewall(e){if(!e)throw new Error("firewall must be provided");this.#t=e}set decorator(e){if(!e)throw new Error("decorator must be provided");this.#r=e}set exchangeRejectedHandler(e){if(!e)throw new Error("handler must be provided");this.#n=e}},zr=class{decorate(e,t){return t=t||[],Ke.of({handle:n=>e.filter(n)},...t)}},_t=class{#e;#t;constructor(e,...t){this.#e=e,this.#t=t}async matches(e){return(await this.#e(e))?.match===!0}async webFilters(){return this.#t}},jr=class{async firewalledExchange(e){return e}},Xr=class extends Error{constructor(e){super(e),this.name="ServerExchangeRejectedError"}},Jr=class{#e;constructor(e=y.BAD_REQUEST){this.#e=e}async handle(e,t){e.response.setStatusCode(this.#e)}};var B={first:Number.MAX_SAFE_INTEGER,http_headers:100,https_redirect:200,cors:300,http_basic:600,authentication:800,security_context_server_web_exchange:1500,error_translation:1800,authorization:1900,last:Number.MAX_SAFE_INTEGER},G=Symbol.for("filterOrder"),xs=(r,e)=>{let t=(a,c)=>{if(e===void 0)return c;if(a==="UserDetailsService"&&e.userDetailsService!==void 0)return e.userDetailsService;if(a==="AuthenticationManager"&&e.authenticationManager!==void 0)return e.authenticationManager;if(c!==void 0)return c;throw new Error(`No service registered with name: ${a}`)},n=()=>{if(e.authenticationManager!==void 0)return e.authenticationManager;if(e.userDetailsService!==void 0)return Ps(e.userDetailsService,{userDetailsPasswordService:e.userDetailsPasswordService})},s=[];class i{#e;#t=[];#r;set authenticationManager(c){this.#r=c}get authenticationEntryPoint(){return this.#e!==void 0||this.#t.length===0?this.#e:this.#t.length===1?this.#t[0][1]:Tt({entryPoints:this.#t,defaultEntryPoint:this.#t[this.#t.length-1][1]})}build(){if(r.headers!==void 0&&r.headers.disabled!==!0){let d=Fr(r.headers);d[G]=B.http_headers,s.push(d)}if(r.x509!==void 0&&r.x509.disabled!==!0){let d=Vr({storage:e.storage,getService:t,extractor:It({principalAltName:r.x509.principalAltName})});d[G]=B.authentication,s.push(d)}if(r.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=es({corsConfigSource:e.corsConfigSource});d[G]=B.cors,s.push(d)}if(r.basic!==void 0&&r.basic?.disabled!==!0){let d=[async({exchange:f,chain:m},P)=>await m.filter(f)],u=Dr({storage:e.storage,manager:this.#r,defaultEntryPoints:this.#t,defaultSuccessHandlers:d});u[G]=B.http_basic,s.push(u)}if(r.jwt!==void 0&&r.jwt.disabled!==!0){let d=(0,Bt.jwtVerifier)({issuerBaseUri:r.jwt.issuerUri,issuer:r.jwt.issuer,audience:r.jwt.audience}),u=async h=>{try{let{payload:p}=await d(h);return{tokenValue:h,subject:p.sub,getClaimAsString(g){return p[g]}}}catch(p){throw p instanceof Bt.JwtVerifyError?new Ye(p.message,{cause:p}):new Re("error occurred while attempting to decoding jwt",{cause:p})}},f=Mt({uriQueryParameter:!0}),m=async h=>{try{return await f(h)===void 0?O:D()}catch{return O}},P=kt({});this.#t.push([m,P]);let l=Nr({storage:e.storage,entryPoint:P,converter:f,jwt:{decoder:u}});l[G]=B.authentication,s.push(l)}let c=ws({storage:e.storage});if(s.push(c),c[G]=B.security_context_server_web_exchange,r.authorize!==void 0){let d=bs({authenticationEntryPoint:this.authenticationEntryPoint});d[G]=B.error_translation,s.push(d);let f=(P=>{let l=[],h=!1;for(let[p,g]of P??[]){let b;if(p==="any-exchange")h=!0,b=Se;else{if(h)throw new Error("Cannot register other matchers after 'any-exchange' matcher");b=p}let E;if(g.access==="permitted")E=new ne(async()=>new Y(!0)),E.toString=()=>"AuthorizationManager[permitted]";else if(g.access==="denied")E=new ne(async()=>new Y(!1)),E.toString=()=>"AuthorizationManager[denied]";else if(g.access==="authenticated")E=new ne(async H=>{let L=await H;return L!==void 0?new Y(L.authenticated):new Y(!1)}),E.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(g)}`);l.push([b,E])}return qr({mappings:l})})(r.authorize),m=_r({manager:f,storage:e.storage});m[G]=B.authorization,s.push(m)}s.sort((d,u)=>{let f=d[G]??B.last,m=u[G]??B.last;return f-m})}}let o=new i;return o.authenticationManager=n(),o.build(),new _t(Se,...s)};var Gt=class{#e=new Map;constructor(...e){for(let t of e)this.#e.set(this.#t(t.username),t)}async findByUsername(e){let t=this.#t(e),n=this.#e.get(t);return n!==void 0?{...n}:void 0}async updatePassword(e,t){let n={...e,password:t};if(n){let s=this.#t(e.username);this.#e.set(s,n)}return n}#t(e){return e.toLowerCase()}};var As=require("node:crypto");var Vt=w("auth");function Co(r){let e=[],t=r.authConfig?.type,n={access:t!=="none"?"authenticated":"permitted"};Vt.enabledFor("info")&&Vt.info(`using auth type: ${t??"none"}, default access: ${n.access}`);for(let[s,i]of r.sockets){let o=i.authorize??n,a=$(s,{method:"GET"});a=we([ce,a]),e.push([a,o])}return e.push([$("/",{method:"GET"}),{access:"permitted"}]),e.push([$("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([$("/health",{method:"GET"}),{access:"permitted"}]),r.authorize.length>0&&e.push(...r.authorize),e.push(["any-exchange",n]),{authorize:e,cors:{disabled:r.corsConfig===!1},x509:{disabled:t!=="x509",...r.authConfig?.x509},basic:{disabled:t!=="basic",...r.authConfig?.basic},jwt:{disabled:t!=="oauth2",...r.authConfig?.oauth2?.jwt}}}function xo(r){if(r.authConfig?.type==="none")return;function e(o,a){if(r.authConfig?.type==="x509")return null;let c=o.password;if(c===void 0){let d=(0,As.randomUUID)().replaceAll("-","");Vt.enabledFor("info")&&Vt.info(`
3
14
 
4
15
  using generated password: ${d}
5
16
 
6
17
  This generated password is for development only. Your authentication configuration should be updated before running in production.
7
- `),c=d}if(c.length>kt)throw new Error(`Password length exceeds maximum length of ${kt} characters`);return a!=null||/^\{.+}.*$/.test(c)?c:`{noop}${c}`}let r={name:"dev-user",roles:[],...t.authConfig?.user},n=e(r),o=r.roles,i=Qe.ofUsername(r.name).password(n).roles(...o).build();return new et(i)}async function $r(t){let e=gr(t),r=mo(t),n=go(t),{storage:o}=t;return Lr(n,{storage:o,corsConfigSource:e,userDetailsService:r,userDetailsPasswordService:r})}var Wr=require("node:async_hooks");var rt=class extends Z{},Tt=class{#e;#r=!1;#t;#n;constructor(e,r){this.#e=e,this.#t=r}createExchange(e,r){return new Le(e,r)}set storage(e){this.#n=e}set enableLoggingRequestDetails(e){this.#r=e}formatHeaders(e){let r="{";for(let n of e.keys())if(this.#r){let o=e.get(n);r+=`"${n}": "${o}", `}else{r+="masked, ";break}return r.endsWith(", ")&&(r=r.slice(0,-2)),r+="}",r}formatRequest(e){let r=e.URL.search;return`HTTP ${e.method} "${e.path}${r}`}logRequest(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${r?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${r?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,r){let{request:n,response:o,logPrefix:i}=e;if(o.setStatusCode(S.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,r);return}throw this.#e.error(`${i}Error [${r.message} for ${this.formatRequest(n)}, but already ended (${o.statusCode})`,r),r}async web(e){return await this.#t(e)}async http(e,r){let n=this.createExchange(e,r),o=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(i=>{this.handleUnresolvedError(n,i)}).then(async()=>{await n.response.end()}));await new Promise((i,s)=>{this.#n!==void 0?this.#n.run({exchange:n},()=>{o().then(()=>i()).catch(a=>s(a))}):o().then(()=>i()).catch(a=>s(a))})}},nt=class{#e;#r=new Wr.AsyncLocalStorage;#t;storage(e){return this.#r=e,this}httpHandlerDecorator(e){if(this.#t===void 0)this.#t=e;else{let r=this.#t;this.#t=n=>(n=r(n),e(n))}return this}constructor(e){this.#e=e}build(){let e=w("http"),r=new Tt(e,this.#e);this.#r!==void 0&&(r.storage=this.#r),r.enableLoggingRequestDetails=!1;let n=async(o,i)=>r.http(o,i);return this.#t?this.#t(n):n}};var Gr=require("ws");function Ur(t,e){let r=t?.exchange,n=r?.request??new Q(t),o=r?.principal,i=o?o.bind(r):async function(){},s=n.URL,a=new E;for(let m of n.headers.keys())a.set(m,n.headers.list(m));let c=n.cookies,d=r?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:s,headers:a,cookies:c,principal:i,protocol:e,remoteAddress:u,logPrefix:d}}function Nr(t){return[async(r,n)=>{let i=r.request.path??"/",s=t.sockets,a=s.get(i)??Array.from(s.values()).find(c=>{if(i==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=r,u=await V(r);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(r);return}else throw new Error(`No upgrade strategy defined for route on ${i}`);else{if(a.default){await n();return}d.setStatusCode(S.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let l=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(l)}}else await n()}]}var Fr=require("ws"),ot=class extends Fr.WebSocket{constructor(e,r,n){super(null,void 0,n)}connected},it=class t{static#e=Buffer.alloc(0);static#r=[0,Buffer.alloc(8)];#t;#n;#i;#s=!1;#o;constructor(e,r,n){this.#o=e,this.#n=typeof n=="number"?n:n?.interval,this.#t=typeof n=="number"||n?.data==="timestamp"?()=>t.#d(Date.now()):()=>t.#e,this.#n&&(this.#i=setInterval(()=>{let[o,i]=r();for(let s of i)this.#a(s,o)||this.#c(s,o)},this.#n))}#a(e,r){return e.connected===!1?(this.#o.enabledFor("debug")&&this.#o.debug(`terminating unresponsive ws client on [${r}]`),e.terminate(),!0):!1}#c(e,r){e.connected=!1;let n=this.#t();this.#o.enabledFor("trace")&&this.#o.debug(`pinging ws client on [${r}]`),e.ping(n,this.#s,o=>{o&&this.#o.enabledFor("warn")&&this.#o.warn(`failed to ping ws client on [${r}]`,o)})}static#d(e=Date.now()){if(e-t.#r[0]>0){let r=Buffer.allocUnsafe(8);r.writeBigInt64BE(BigInt(e),0),t.#r=[e,r]}return t.#r[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#i)}handlePing(e,r,n){r.connected=!0,r.pong(n,!1,o=>{o&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}failed to pong ws client ${B(e.remoteAddress)}`,o)})}handlePong(e,r,n){if(r.connected=!0,this.#o.enabledFor("warn")){let o=t.#u(n);if(o>0){let i=Date.now()-o;this.#o.enabledFor("debug")&&this.#o.debug(`${e.logPrefix}ws client ${B(e.remoteAddress)} ping-pong latency: ${i}ms`),this.#n&&i>this.#n/2&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}ws client ${B(e.remoteAddress)} high ping-pong latency: ${i}ms`)}}}};var L=w("ws");function yo(t,e,r,n){return o=>{let{logPrefix:i,request:s}=o,a=Me.getNativeRequest(s);a.exchange=o;let{socket:c,upgradeHead:d}=a,u=s.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&r.clients?.size>=e.maxConnections){L.warn(`${i}dropping ws connection request on ${u}${t}. max connections exceeded.`),c.destroy();return}let l=s.headers.one("origin");if(!tr(l,e.originFilters)){L.enabledFor("info")&&L.info(`${i}dropping ws connection request on ${u}${t}. origin ${l??"<missing>"}`),c.destroy();return}L.enabledFor("debug")&&L.debug(`${i}accepted new ws connection request on ${u}${t}`),r.handleUpgrade(a,c,d,(m,x)=>{r.emit("connection",m,x)})}}function wo(t,e){let r=new Set;t.forEach((o,i)=>{if(i===0&&o.startsWith("HTTP/1.1 101 ")){e.setStatusCode(S.SWITCHING_PROTOCOLS);return}let[s,a]=o.split(": ");e.headers.has(s)?t[i]=`${s}: ${e.headers.one(s)}`:e.headers.set(s,a),r.add(s.toLowerCase())});let n=Z.getNativeResponse(e);for(let o of n.getRawHeaderNames()){let i=o.toLowerCase();if(!r.has(i)){let s=e.headers.get(i);s!==void 0&&t.push(`${o}: ${s}`)}}n.markHeadersSent()}async function Br(t,e,r,n,o){try{L.info(`creating ws server for [${t}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,Gt):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new Gr.WebSocketServer({noServer:!0,WebSocket:ot,autoPong:!1}),s=new it(L.child("pings"),()=>[t,i.clients],e.ping),a=await e.factory({endpoint:r,storage:n});i.on("error",c=>{L.error(`error starting the ws server for [${t}]`,c)}).on("listening",()=>{L.info(`ws server for [${t}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;wo(c,u)}}).on("connection",(c,d)=>{let u=Ur(d,c.protocol);c.on("pong",l=>{s.handlePong(u,c,l)}),c.on("ping",l=>{s.handlePing(u,c,l)}),a({socket:c,handshake:u})}),i.on("close",()=>{s.close()}),e.upgradeStrategy=yo(t,e,i,o),e.close=async()=>{await a.close?.call(a),L.info(`stopping ws server for [${t}]. clients: ${i.clients?.size??0}`),i.clients?.forEach(c=>{c.terminate()}),i.close()}}catch(i){L.warn(`failed to init route ${t}`,i)}}var g=require("node:fs"),ve=require("node:path"),at=require("jsrsasign"),st=require("@interopio/gateway-server/tools");var de=w("ssl");function _r(t,e){let r={};if(t.requestCert!==void 0&&(r.requestCert=t.requestCert),t.rejectUnauthorized!==void 0&&(r.rejectUnauthorized=t.rejectUnauthorized),t.key&&t.cert&&(0,g.existsSync)(t.key)&&(0,g.existsSync)(t.cert)){de.info(`using SSL/TLS certificate ${t.cert} with private key in ${t.key}${t.passphrase?" (password-protected)":""}`);let p={key:(0,g.readFileSync)(t.key),cert:(0,g.readFileSync)(t.cert),...r};return t.passphrase&&(p.passphrase=t.passphrase),t.requestCert&&t.ca&&(0,g.existsSync)(t.ca)&&(p.ca=(0,g.readFileSync)(t.ca)),p}if(!t.key&&!t.cert){let p="./gateway-server.key",f="./gateway-server.crt";if((0,g.existsSync)(p)&&(0,g.existsSync)(f)){de.info(`using SSL/TLS certificate ${f} with private key in ${p}${t.passphrase?" (password-protected)":""}`);let h={key:(0,g.readFileSync)(p),cert:(0,g.readFileSync)(f),...r};return t.passphrase&&(h.passphrase=t.passphrase),t.requestCert&&t.ca&&(0,g.existsSync)(t.ca)&&(h.ca=(0,g.readFileSync)(t.ca)),h}}if(!e)throw new Error("SSL/TLS enabled but no server certificate provided. Either provide ssl.key and ssl.cert, or configure auth.x509.key for auto-generation.");let n=e.key??"gateway-ca.key",o=t.ca??`${n.replace(/\.key$/,".crt")}`,i=e.passphrase??t.passphrase;if(!(0,g.existsSync)(n)){if((0,g.existsSync)(o))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${o})`);let p=st.mkcert.generateRootCA({name:st.mkcert.DEFAULT_CA_NAME,passphrase:i}),f=(0,ve.dirname)(n);f&&f!=="."&&!(0,g.existsSync)(f)&&(0,g.mkdirSync)(f,{recursive:!0});let h=(0,ve.dirname)(o);h&&h!=="."&&h!==f&&!(0,g.existsSync)(h)&&(0,g.mkdirSync)(h,{recursive:!0}),(0,g.writeFileSync)(n,p.key,{mode:256}),(0,g.writeFileSync)(o,p.cert,{mode:420}),de.info(`created new local Root CA in ${o}, ${n}${i?" (password-protected)":""}`)}let s=(0,g.readFileSync)(n,"utf8"),a=at.KEYUTIL.getKey(s,i),c=(0,g.readFileSync)(o,"utf8"),d=new at.X509;d.readCertPEM(c);let u=d.getSubjectString(),l=e.host;de.debug(`generating server certificate signed by: ${u} for host: ${l}`);let m=st.mkcert.generateCert(a,u,[l],!1);if(t.key||t.cert){let p=t.key||"./gateway-server.key",f=t.cert||"./gateway-server.crt",h=(0,ve.dirname)(p);h&&h!=="."&&!(0,g.existsSync)(h)&&(0,g.mkdirSync)(h,{recursive:!0});let y=(0,ve.dirname)(f);y&&y!=="."&&y!==h&&!(0,g.existsSync)(y)&&(0,g.mkdirSync)(y,{recursive:!0}),(0,g.writeFileSync)(p,m.key,{mode:384}),(0,g.writeFileSync)(f,m.cert,{mode:420}),de.info(`generated server certificate saved to ${f} with private key in ${p}${i?" (password-protected)":""}`)}else de.info(`using in-memory server certificate for host: ${l}`);let x={key:m.key,cert:m.cert,...r};return t.requestCert&&t.ca&&(0,g.existsSync)(o)&&(x.ca=(0,g.readFileSync)(o)),x}var Ot=ue(require("@interopio/gateway-server/package.json"),1),U=w("app");async function So(t,e){let r=t.build();return async(n,o)=>{n.socket.addListener("error",e);let i;o instanceof Y?i=o:(n.upgradeHead=o,i=new Y(n),i.assignSocket(n.socket));let s=new Q(n),a=new Oe(i),c=s.method==="HEAD"?new rt(a):a;await r(s,c)}}function bo(t){return new Promise((e,r)=>{let n=t(o=>{o?r(o):e(n)})})}function vo(t){if(t)return Qt({memoryLimit:t.memory_limit,dumpLocation:t.dump_location,dumpPrefix:t.dump_prefix,reportInterval:t.report_interval,maxBackups:t.max_backups})}var Vr=`${Ot.default.name} - v${Ot.default.version}`;async function xo(t){let e=t.storage,r=await $r(t),n=Nr(t),o=jt(er(Vr,t.serverHeader),...r,...n,...t.middleware,async({request:i,response:s},a)=>{if(i.method==="GET"&&i.path==="/health"){s.setStatusCode(S.OK);let c=Buffer.from("UP","utf-8");s.headers.set("Content-Type","text/plain; charset=utf-8"),await s.body(c)}else await a()},async({request:i,response:s},a)=>{if(i.method==="GET"&&i.path==="/"){s.setStatusCode(S.OK);let c=Buffer.from("io.Gateway Server","utf-8");s.headers.set("Content-Type","text/plain; charset=utf-8"),await s.body(c)}else await a()},async({response:i},s)=>{i.setStatusCode(S.NOT_FOUND),await i.end()});return new nt(o).storage(e)}var Mt=async t=>{let e=t.ssl,r=t.host,n=t.auth?.x509?.key?{host:r??"localhost",key:t.auth.x509.key,passphrase:t.auth.x509.passphrase}:void 0,o=e?(p,f)=>zr.default.createServer({...p,..._r(e,n)},f):(p,f)=>qr.default.createServer(p,f),i=vo(t.memory),s={middleware:[],corsConfig:t.cors,cors:[],authConfig:t.auth,authorize:[],storage:new jr.AsyncLocalStorage,sockets:new Map},a=new Ee({baseConfig:{...t.gateway},scope:t.gateway?.scope??"principal"});if(t.gateway){let p=t.gateway;await wt(async f=>{f.socket({path:p.route,factory:qt.bind(a),options:p})},t,s)}t.app&&await wt(t.app,t,s);let c=Ut(t.port??0),d=p=>U.error(`socket error: ${p}`,p),u=await xo(s),l=await So(u,d),x=await new Promise((p,f)=>{let h=o({IncomingMessage:ke,ServerResponse:Y,...t.http},l);h.on("error",y=>{if(y.code==="EADDRINUSE"){U.debug(`port ${y.port} already in use on address ${y.address}`);let{value:k}=c.next();k?(U.info(`retry starting server on port ${k} and host ${r??"<unspecified>"}`),h.close(),h.listen(k,r)):(U.warn(`all configured port(s) ${t.port} are in use. closing...`),h.close(),f(y))}else U.error(`server error: ${y.message}`,y),f(y)}),h.on("listening",async()=>{let y=h.address();for(let[k,R]of s.sockets){let K=`${e?"wss":"ws"}://${Nt}:${y.port}${k}`;await Br(k,R,K,s.storage,d)}U.info(`http server listening on ${e?"https":"http"}://${B(y)}`),p(h)}),h.on("upgrade",(y,k,R)=>{try{l(y,R)}catch(K){U.error(`upgrade error: ${K}`,K)}}).on("close",async()=>{U.info("http server closed.")});try{let{value:y}=c.next();h.listen(y,r)}catch(y){U.error("error starting web socket server",y),f(y instanceof Error?y:new Error(`listen failed: ${y}`))}});return new class{gateway=a;get address(){let p=x.address();return typeof p=="object"?p:null}async close(){for(let[p,f]of s.sockets)try{f.close!==void 0&&await f.close()}catch(h){U.warn(`error closing route ${p}`,h)}await bo(p=>{x.closeAllConnections(),x.close(p)}),i&&await Zt(i),await a.stop()}}};var Eo=Mt;0&&(module.exports={GatewayServer});
18
+ `),c=d}if(c.length>Gr)throw new Error(`Password length exceeds maximum length of ${Gr} characters`);return a!=null||/^\{.+}.*$/.test(c)?c:`{noop}${c}`}let t={name:"dev-user",roles:[],...r.authConfig?.user},n=e(t),s=t.roles,i=Dt.ofUsername(t.name).password(n).roles(...s).build();return new Gt(i)}async function Rs(r){let e=os(r),t=Co(r),n=xo(r),{storage:s}=r;return xs(t,{storage:s,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var zt=class extends be{};var ks=require("ws");function Ts(r,e){let t=r?.exchange,n=t?.request??new ye(r),s=t?.principal,i=s?s.bind(t):async function(){},o=n.URL,a=new A;for(let m of n.headers.keys())a.set(m,n.headers.list(m));let c=n.cookies,d=t?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:o,headers:a,cookies:c,principal:i,protocol:e,remoteAddress:u,logPrefix:d}}function Hs(r){return[async(t,n)=>{let i=t.request.path??"/",o=r.sockets,a=o.get(i)??Array.from(o.values()).find(c=>{if(i==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=t,u=await ce(t);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(t);return}else throw new Error(`No upgrade strategy defined for route on ${i}`);else{if(a.default){await n();return}d.setStatusCode(y.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let f=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(f)}}else await n()}]}var Ms=require("ws"),jt=class extends Ms.WebSocket{constructor(e,t,n){super(null,void 0,n)}connected},Xt=class r{static#e=Buffer.alloc(0);static#t=[0,Buffer.alloc(8)];#r;#n;#s;#i=!1;#o;constructor(e,t,n){this.#o=e,this.#n=typeof n=="number"?n:n?.interval,this.#r=typeof n=="number"||n?.data==="timestamp"?()=>r.#a(Date.now()):()=>r.#e,this.#n&&(this.#s=setInterval(()=>{let[s,i]=t();for(let o of i)this.#c(o,s)||this.#d(o,s)},this.#n))}#c(e,t){return e.connected===!1?(this.#o.enabledFor("debug")&&this.#o.debug(`terminating unresponsive ws client on [${t}]`),e.terminate(),!0):!1}#d(e,t){e.connected=!1;let n=this.#r();this.#o.enabledFor("trace")&&this.#o.debug(`pinging ws client on [${t}]`),e.ping(n,this.#i,s=>{s&&this.#o.enabledFor("warn")&&this.#o.warn(`failed to ping ws client on [${t}]`,s)})}static#a(e=Date.now()){if(e-r.#t[0]>0){let t=Buffer.allocUnsafe(8);t.writeBigInt64BE(BigInt(e),0),r.#t=[e,t]}return r.#t[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#s)}handlePing(e,t,n){t.connected=!0,t.pong(n,!1,s=>{s&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}failed to pong ws client ${ee(e.remoteAddress)}`,s)})}handlePong(e,t,n){if(t.connected=!0,this.#o.enabledFor("warn")){let s=r.#u(n);if(s>0){let i=Date.now()-s;this.#o.enabledFor("debug")&&this.#o.debug(`${e.logPrefix}ws client ${ee(e.remoteAddress)} ping-pong latency: ${i}ms`),this.#n&&i>this.#n/2&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}ws client ${ee(e.remoteAddress)} high ping-pong latency: ${i}ms`)}}}};var q=w("ws");function Ao(r,e,t,n){return s=>{let{logPrefix:i,request:o}=s,a=yt.getNativeRequest(o);a.exchange=s;let{socket:c,upgradeHead:d}=a,u=o.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&t.clients?.size>=e.maxConnections){q.warn(`${i}dropping ws connection request on ${u}${r}. max connections exceeded.`),c.destroy();return}let f=o.headers.one("origin");if(!zn(f,e.originFilters)){q.enabledFor("info")&&q.info(`${i}dropping ws connection request on ${u}${r}. origin ${f??"<missing>"}`),c.destroy();return}q.enabledFor("debug")&&q.debug(`${i}accepted new ws connection request on ${u}${r}`),t.handleUpgrade(a,c,d,(m,P)=>{t.emit("connection",m,P)})}}function Ro(r,e){let t=new Set;r.forEach((s,i)=>{if(i===0&&s.startsWith("HTTP/1.1 101 ")){e.setStatusCode(y.SWITCHING_PROTOCOLS);return}let[o,a]=s.split(": ");e.headers.has(o)?r[i]=`${o}: ${e.headers.one(o)}`:e.headers.set(o,a),t.add(o.toLowerCase())});let n=be.getNativeResponse(e);for(let s of n.getRawHeaderNames()){let i=s.toLowerCase();if(!t.has(i)){let o=e.headers.get(i);o!==void 0&&r.push(`${s}: ${o}`)}}n.markHeadersSent()}async function Ws(r,e,t,n,s){try{q.info(`creating ws server for [${r}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,Cn):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new ks.WebSocketServer({noServer:!0,WebSocket:jt,autoPong:!1}),o=new Xt(q.child("pings"),()=>[r,i.clients],e.ping),a=await e.factory({endpoint:t,storage:n});i.on("error",c=>{q.error(`error starting the ws server for [${r}]`,c)}).on("listening",()=>{q.info(`ws server for [${r}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;Ro(c,u)}}).on("connection",(c,d)=>{let u=Ts(d,c.protocol);c.on("pong",f=>{o.handlePong(u,c,f)}),c.on("ping",f=>{o.handlePing(u,c,f)}),a({socket:c,handshake:u})}),i.on("close",()=>{o.close()}),e.upgradeStrategy=Ao(r,e,i,s),e.close=async()=>{await a.close?.call(a),q.info(`stopping ws server for [${r}]. clients: ${i.clients?.size??0}`),i.clients?.forEach(c=>{c.terminate()}),i.close()}}catch(i){q.warn(`failed to init route ${r}`,i)}}var S=require("node:fs"),Qe=require("node:path"),Yt=require("jsrsasign"),Jt=require("@interopio/gateway-server/tools");var He=w("ssl");function Is(r,e){let t={};if(r.requestCert!==void 0&&(t.requestCert=r.requestCert),r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.key&&r.cert&&(0,S.existsSync)(r.key)&&(0,S.existsSync)(r.cert)){He.info(`using SSL/TLS certificate ${r.cert} with private key in ${r.key}${r.passphrase?" (password-protected)":""}`);let l={key:(0,S.readFileSync)(r.key),cert:(0,S.readFileSync)(r.cert),...t};return r.passphrase&&(l.passphrase=r.passphrase),r.requestCert&&r.ca&&(0,S.existsSync)(r.ca)&&(l.ca=(0,S.readFileSync)(r.ca)),l}if(!r.key&&!r.cert){let l="./gateway-server.key",h="./gateway-server.crt";if((0,S.existsSync)(l)&&(0,S.existsSync)(h)){He.info(`using SSL/TLS certificate ${h} with private key in ${l}${r.passphrase?" (password-protected)":""}`);let p={key:(0,S.readFileSync)(l),cert:(0,S.readFileSync)(h),...t};return r.passphrase&&(p.passphrase=r.passphrase),r.requestCert&&r.ca&&(0,S.existsSync)(r.ca)&&(p.ca=(0,S.readFileSync)(r.ca)),p}}if(!e)throw new Error("SSL/TLS enabled but no server certificate provided. Either provide ssl.key and ssl.cert, or configure auth.x509.key for auto-generation.");let n=e.key??"gateway-ca.key",s=r.ca??`${n.replace(/\.key$/,".crt")}`,i=e.passphrase??r.passphrase;if(!(0,S.existsSync)(n)){if((0,S.existsSync)(s))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${s})`);let l=Jt.mkcert.generateRootCA({name:Jt.mkcert.DEFAULT_CA_NAME,passphrase:i}),h=(0,Qe.dirname)(n);h&&h!=="."&&!(0,S.existsSync)(h)&&(0,S.mkdirSync)(h,{recursive:!0});let p=(0,Qe.dirname)(s);p&&p!=="."&&p!==h&&!(0,S.existsSync)(p)&&(0,S.mkdirSync)(p,{recursive:!0}),(0,S.writeFileSync)(n,l.key,{mode:256}),(0,S.writeFileSync)(s,l.cert,{mode:420}),He.info(`created new local Root CA in ${s}, ${n}${i?" (password-protected)":""}`)}let o=(0,S.readFileSync)(n,"utf8"),a=Yt.KEYUTIL.getKey(o,i),c=(0,S.readFileSync)(s,"utf8"),d=new Yt.X509;d.readCertPEM(c);let u=d.getSubjectString(),f=e.host;He.debug(`generating server certificate signed by: ${u} for host: ${f}`);let m=Jt.mkcert.generateCert(a,u,[f],!1);if(r.key||r.cert){let l=r.key||"./gateway-server.key",h=r.cert||"./gateway-server.crt",p=(0,Qe.dirname)(l);p&&p!=="."&&!(0,S.existsSync)(p)&&(0,S.mkdirSync)(p,{recursive:!0});let g=(0,Qe.dirname)(h);g&&g!=="."&&g!==p&&!(0,S.existsSync)(g)&&(0,S.mkdirSync)(g,{recursive:!0}),(0,S.writeFileSync)(l,m.key,{mode:384}),(0,S.writeFileSync)(h,m.cert,{mode:420}),He.info(`generated server certificate saved to ${h} with private key in ${l}${i?" (password-protected)":""}`)}else He.info(`using in-memory server certificate for host: ${f}`);let P={key:m.key,cert:m.cert,...t};return r.requestCert&&r.ca&&(0,S.existsSync)(s)&&(P.ca=(0,S.readFileSync)(s)),P}function Yr(r){return r?.get("io.gateway.logging.suppress")===!0}var Kt="io.gateway.logging.prefix";function Kr(r){return r?.has(Kt)?r.get(Kt)??"":""}var Me=class{#e;logger=w("codec.encoder");constructor(...e){this.#e=[...e]}setLogger(e){this.logger=e}encodableMimeTypes(){return this.#e}canEncode(e,t){if(t===void 0)return!0;for(let n of this.#e)if(re(t,n))return!0;return!1}},Qt=class extends Me{constructor(){super(Fe)}canEncode(e,t){return super.canEncode(e,t)}async encode(e,t,n){let s=await e;return this.logger.enabledFor("debug")&&!Yr(n)&&this.#e(s),s}#e(e,t){let n=Kr(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},Zt=class r extends Me{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!Yr(n)&&this.logger.enabledFor("debug")){let s=Kr(n),i=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${i?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(Cr("text","plain","utf-8"))}static allMimeTypes(){return new r(Cr("text","plain","utf-8"),Fe)}};var le=class{log=w("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var Ze=class r extends le{static MEDIA_TYPES=Object.freeze([R.MULTIPART_FORM_DATA]);#e;constructor(e){super(),this.#e=e}get partReader(){return this.#e}getReadableMediaTypes(){return r.MEDIA_TYPES}canRead(e,t){return this.#t(t)&&e.name===FormData.name}#t(e){if(e===void 0)return!0;for(let t of r.MEDIA_TYPES)if(re(t,e))return!0;return!1}async readPromise(e,t,n){let s=this.#e.read(e,t,n),i=new FormData;for await(let[o,a]of s)i.append(o,a);return i}read(e,t,n){throw new Error("not implemented yet")}},et=class extends le{getReadableMediaTypes(){return[R.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||re(R.MULTIPART_FORM_DATA,t))}readPromise(e,t,n){throw new Error("not implemented yet")}read(e,t,n){throw new Error("not implemented yet")}};var tt=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=R.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>Pr(t))}get encoder(){return this.#e}getWriteableMediaTypes(){return this.#t}canWrite(e,t){return this.#e.canEncode(e,t)}async write(e,t,n,s,i){let o=this.#n(n,s),a=this.#e.encode(e,o,i);await n.body(a)}static initLogger(e){e instanceof Me}#n(e,t){let n=ge(e.headers);if(n)return n;let s=this.#r;n=Ho(t,s)?s:t,n&&(n=To(n,s),e.headers.set("Content-Type",n.toString()))}};function To(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=R.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function Ho(r,e){return(r===void 0||!Pr(r)||r.essence===R.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var Qr=class{#e;#t;#r;#n=!0;#s=Array();#i=Array();constructor(){this.initReaders(),this.initWriters()}multipartReader(e){this.#e=e,this.initReaders()}registerDefaults(e){this.#n!==e&&(this.#n=e,this.initReaders(),this.initWriters())}initReaders(){if(this.#i.length=0,!!this.#n)if(this.#e!==void 0)this.addCodec(this.#i,this.#e);else{let e=new et;this.addCodec(this.#i,e),this.addCodec(this.#i,new Ze(e))}}initWriters(){this.#s.length=0,this.#n&&(this.#s.push(...this.#o()),this.extendWriters(this.#s))}extendWriters(e){}#o(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new tt(new Qt)),e}maxInMemorySize(e){this.#t!==e&&(this.#t=e,this.initReaders())}enableLoggingRequestDetails(e){this.#r!==e&&(this.#r=e,this.initReaders(),this.initWriters())}get catchAllReaders(){return this.#n?Array():[]}get typedWriters(){return this.#s}get typedReaders(){return this.#i}get catchAllWriters(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new tt(Zt.allMimeTypes())),e}addCodec(e,t){this.#c(t),e.push(t)}#c(e){if(e instanceof tt&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof Ze&&(e.enableLoggingRequestDetails=n),e instanceof et&&(e.enableLoggingRequestDetails=n))}},Zr=class{baseDefaultCodecs;constructor(e){this.baseDefaultCodecs=e}get defaultCodecs(){return this.baseDefaultCodecs}registerDefaults(e){this.baseDefaultCodecs.registerDefaults(e)}get readers(){let e=new Array;return e.push(...this.baseDefaultCodecs.typedReaders),e.push(...this.baseDefaultCodecs.catchAllReaders),e}get writers(){let e=new Array;return e.push(...this.baseDefaultCodecs.typedWriters),e.push(...this.baseDefaultCodecs.catchAllWriters),e}},en=class extends Qr{},tn=class extends Zr{constructor(){super(new en)}};function Mo(){return new tn}var ke={serverConfigurer:{create:Mo}};var Os=require("node:net");function ko({logger:r,options:e,handler:t,onClose:n}){let s=e.path;r.enabledFor("info")&&r.info(`[${s}] opening command server pipe, waiting for the data...`);try{let i=(0,Os.createServer)(o=>{r.enabledFor("debug")&&r.debug(`[${s}] command pipe server got client, waiting for the data...`),o.on("close",()=>{r.enabledFor("debug")&&r.debug(`[${s}] client closed`)}),o.on("error",a=>{r.error(`[${s}] error on pipe stream`,a)}),o.on("data",async(...a)=>{try{let c=a.toString(),d=JSON.parse(c);r.enabledFor("info")&&r.info(`[${s}] received command ${d.command}`),t(d).then(u=>{let f=JSON.stringify({result:u});r.enabledFor("info")&&r.info(`[${s}] command ${d.command} processed successfully. sending : ${f}`),o.write(f,m=>{m&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending response for command ${d.command}`,m)})}).catch(u=>{let f=JSON.stringify({error:u.message});r.error(`[${s}] processing command ${d.command} failed, sending ${f}`,u),o.write(f,m=>{m&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending error response for command ${d.command}`,m)})}).finally(()=>{d.command==="shutdown"&&(r.enabledFor("info")&&r.info(`[${s}] stopping management pipe server`),i.close(n))})}catch(c){r.error(`[${s}] unable to parse the data`,c)}})});i.on("listening",()=>{r.enabledFor("info")&&r.info(`[${s}] connected to the pipe, waiting for the data...`)}),i.on("error",o=>{throw r.error(`[${s}] error while opening the pipe - ${s}`,o),o}),i.listen(e)}catch(i){let o=`error while opening the pipe - ${s}`;r.error(o,i);let a=new Error(o);throw a.cause=i,a}}function Ls({options:r,logger:e,shutdown:t,info:n}){ko({options:r,logger:e,onClose:()=>{e.enabledFor("info")&&e.info(`[${r.path}] command server closed, exiting gateway-server process`),process.exit(0)},handler:async s=>{if(s.command==="shutdown")return t?(await t?.(),"gateway-server stopped"):"gateway-server stopping is disabled";if(s.command==="get-info"||s.command==="info")return await n()}})}var fn=Oe(require("@interopio/gateway-server/package.json"),1);var Fs=require("node:path"),er=require("node:fs/promises"),Ds=require("node:fs");async function Wo(r){if(r)for(let e of r){let t=(0,Fs.resolve)(e,"index.html");try{return await(0,er.access)(t,Ds.constants.R_OK),t}catch{}}}async function rn(r){let e=await Wo(r),t=Be({mediaTypes:["text/html"]});return async(n,s)=>{let{request:i,response:o}=n;if(i.method==="GET"&&i.path==="/")if(o.setStatusCode(y.OK),e!==void 0&&(await t(n)).match)o.headers.set("Content-Type","text/html; charset=utf-8"),await o.body((0,er.readFile)(e));else{o.headers.set("Content-Type","text/plain; charset=utf-8");let a=Buffer.from("io.Gateway Server","utf-8");await o.body(a)}else await s()}}var Us=require("node:async_hooks");function nn(r){if(r==null)return!1;let{code:e,message:t}=r;return e==="ECONNRESET"||e==="EPIPE"||e==="ERR_STREAM_PREMATURE_CLOSE"||t?.toLowerCase().includes("client aborted")||t?.toLowerCase().includes("socket hang up")||t?.toLowerCase().includes("aborted")}function $s(r,e){return nn(r)?(e.enabledFor("trace")?e.debug("looks like the client has gone away:",r):e.enabledFor("debug")&&e.debug(`looks like the client has gone away: ${r.message} (For full stack trace enable trace logging level.)`),!0):!1}var sn=class{#e;#t=void 0;#r=!1;#n;#s;constructor(e,t){this.#e=e,this.#n=t}get codecConfigurer(){return this.#t===void 0&&(this.codecConfigurer=ke.serverConfigurer.create()),this.#t}set codecConfigurer(e){if(e==null)throw new Error("codecConfigurer must not be null or undefined");this.#t=e,this.#r=!1;for(let t of this.#t.readers)if(t instanceof le&&t.enableLoggingRequestDetails){this.#r=!0;break}}createExchange(e,t){return new wt(e,t,this.codecConfigurer)}set storage(e){this.#s=e}formatHeaders(e){let t="{";for(let n of e.keys())if(this.#r){let s=e.get(n);t+=`"${n}": "${s}", `}else{t+="masked, ";break}return t.endsWith(", ")&&(t=t.slice(0,-2)),t+="}",t}formatRequest(e){let t=e.URL.search;return`HTTP ${e.method} "${e.path}${t}`}logRequest(e){if(this.#e.enabledFor("debug")){let t=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${t?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let t=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${t?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,t){let{request:n,response:s,logPrefix:i}=e;if(s.setStatusCode(y.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,t);return}else{if($s(t,this.#e))return;throw this.#e.error(`${i}Error [${t.message} for ${this.formatRequest(n)}, but already ended (${s.statusCode})`,t),t}}async web(e){return await this.#n.handle(e)}async http(e,t){let n=this.createExchange(e,t),s=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(i=>{this.handleUnresolvedError(n,i)}).then(async()=>{await n.response.end()}));await new Promise((i,o)=>{this.#s!==void 0?this.#s.run({exchange:n},()=>{s().then(()=>i()).catch(a=>o(a))}):s().then(()=>i()).catch(a=>o(a))})}},tr=class r{#e;#t=[];#r=[];#n=[];#s;#i=new Us.AsyncLocalStorage;#o;constructor(e){this.#e=e}static webHandler(e){return new r(e)}filter(...e){return e&&this.#t.push(...e),this}middleware(e){return e(this.#n),this}exceptionHandler(...e){return e&&this.#r.push(...e),this}exceptionHandlers(e){return e(this.#r),this}storage(e){return this.#i=e,this}codecConfigurer(e){return this.#o=e,this}hasCodecConfigurer(){return this.#o!==void 0}httpHandlerDecorator(e){if(this.#s===void 0)this.#s=e;else{let t=this.#s;this.#s=n=>(n=e(n),n=t(n),n)}return this}hasHttpHandlerDecorator(){return this.#s!==void 0}build(){let e=w("http"),t=new Nt(this.#e,...this.#t);t=new Ut(t,...this.#r);let n=new sn(e,t);this.#i!==void 0&&(n.storage=this.#i),this.#o!==void 0&&(n.codecConfigurer=this.#o);let s=async(i,o)=>n.http(i,o);return this.#s?this.#s(s):s}};var rr={create:(r,e)=>new an(r,e)},on=class{#e;constructor(e){this.#e=e}accept(){return R.parseMediaTypes(...this.#e.list("accept"))}contentLength(){let e=this.#e.one("content-length");return e!==void 0?Number.parseInt(e):void 0}contentType(){return ge(this.#e)}header(e){return this.#e.list(e)}firstHeader(e){let t=this.#e.list(e);return t.length>0?t[0]:void 0}asHttpHeaders(){return this.#e}},an=class{exchange;messageReaders;#e;constructor(e,t){this.exchange=e,this.messageReaders=[...t],this.#e=new on(e.request.headers)}get attributes(){return this.exchange.attributes}get headers(){return this.#e}get method(){return this.request.method}get URL(){return this.request.URL}get requestPath(){return this.request.requestPath}queryParam(e){return this.request.URL.searchParams.get(e)}get principal(){return this.exchange.principal()}get request(){return this.exchange.request}};var v=class{static WILDCARD_WEIGHT=100;static CAPTURE_VARIABLE_WEIGHT=1;static NO_PARAMETERS=new Map;pos;separator;next;prev;constructor(e,t){this.pos=e,this.separator=t}get captureCount(){return 0}get wildcardCount(){return 0}get score(){return 0}get literal(){return!1}noMorePattern(){return this.next===void 0}};var he=class extends v{constructor(e,t){super(e,t)}matches(e,t){return e<t.pathLength&&t.isSeparator(e)?this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e+1,!0):e+1===t.pathLength:(e++,this.next!==void 0&&this.next.matches(e,t)):!1}get normalizedLength(){return 1}get chars(){return new Uint16Array([this.separator])}get literal(){return!0}toString(){return`Separator(${String.fromCharCode(this.separator)})`}};var We=class extends v{constructor(e,t){super(e,t)}matches(e,t){let n;if(e<t.pathLength){let s=t.pathElements[e];if(!F(s))return!1;n=s.valueToMatch,e++}return this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:n===void 0||n.length===0?!1:this.next!==void 0&&this.next.matches(e,t)}get normalizedLength(){return 1}get chars(){return new Uint16Array([42])}get wildcardCount(){return 1}get score(){return v.WILDCARD_WEIGHT}toString(){return"Wildcard(*)"}};var K=class extends v{#e;constructor(e,t,n){super(e,n),this.#e=String.fromCharCode(...t.slice(2,t.length-1))}matches(e,t){if(e===0&&this.next!==void 0){let n=e;for(;n<t.pathLength;){if(this.next.matches(n,t))return this.#t(t,e,n),!0;n++}return!1}else if(e<t.pathLength&&!t.isSeparator(e))return!1;return t.determinedRemainingPath&&(t.remainingPathIndex=t.pathLength),this.#t(t,e,t.pathLength),!0}#t(e,t,n){if(e.extractingVariables){let s=v.NO_PARAMETERS;for(let i=t;i<n;i++){let o=e.pathElements[i];if(F(o)){let{parameters:a}=o;if(a.size>0){s===v.NO_PARAMETERS&&(s=new Map);for(let[c,d]of a)if(s.has(c)){let u=s.get(c);s.set(c,u.concat(d))}else s.set(c,d)}}}e.set(this.#e,this.#r(t,n,e.pathElements),s)}}#r(e,t,n){let s=[];for(let i=e;i<t;i++){let o=n[i];F(o)?s.push(o.valueToMatch):s.push(o.value)}return s.join("")}get normalizedLength(){return 1}get chars(){let e=`${String.fromCharCode(this.separator)}{*${this.#e}}`,t=new Uint16Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}get wildcardCount(){return 0}get captureCount(){return 1}toString(){return`CaptureSegments(${String.fromCharCode(this.separator)}{*${this.#e}})`}};var Q=class extends v{constructor(e,t){super(e,t)}matches(e,t){if(e===0&&this.next!==void 0){let n=e;for(;n<t.pathLength;){if(this.next.matches(n,t))return!0;n++}return!1}else if(e<t.pathLength&&!t.isSeparator(e))return!1;return t.determinedRemainingPath&&(t.remainingPathIndex=t.pathLength),!0}get normalizedLength(){return 1}get chars(){let e=`${String.fromCharCode(this.separator)}**`,t=new Uint16Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}get wildcardCount(){return 1}toString(){return`WildcardSegments(${String.fromCharCode(this.separator)}**)`}};var nr=class{#e;pathElements;pathLength;#t;#r;extractingVariables=!1;#n=!1;remainingPathIndex=0;constructor(e,t){this.#e=e,this.pathElements=e.elements,this.pathLength=this.pathElements.length,this.extractingVariables=t}get determinedRemainingPath(){return this.#n}setMatchAllowExtraPath(){this.#n=!0}set(e,t,n){this.#t===void 0&&(this.#t=new Map),this.#t.set(e,t),n.size>0&&(this.#r===void 0&&(this.#r=new Map),this.#r.set(e,n))}get pathMatchResult(){return this.#t===void 0?rt.EMPTY:new rt(this.#t,this.#r)}isSeparator(e){return z(this.pathElements[e])}pathElementValue(e){let t=e<this.pathLength?this.pathElements[e]:null;return t!==null&&F(t)?t.valueToMatch:""}},rt=class r{static EMPTY=new r(new Map,new Map);uriVariables;matrixVariables;constructor(e,t){this.uriVariables=e,this.matrixVariables=t??new Map}toString(){return`PathMatchInfo(uriVariables=${this.uriVariables}, matrixVariables=${this.matrixVariables})`}},sr=class r{static#e=j("");static SPECIFICITY_COMPARATOR=(e,t)=>e==null?t==null?0:1:t==null?-1:e.catchAll&&!t.catchAll?1:!e.catchAll&&t.catchAll?-1:0;#t;#r;#n;#s;#i;#o=0;#c=0;#d=!1;#a=0;#u=!1;constructor(e,t,n){this.#t=e,this.#r=t,this.#n=t.pathOptions,this.#s=t.caseSensitive,this.#i=n;let s=n;for(;s!==void 0;)this.#o+=s.captureCount,this.#c+=s.normalizedLength,this.#a+=s.score,(s instanceof K||s instanceof Q)&&(this.#u=!0),s instanceof he&&s.next instanceof We&&s.next.next===void 0&&(this.#d=!0),s=s.next}get patternString(){return this.#t}get hasPatternSyntax(){return this.#a>0||this.#u||this.#t.indexOf("?")!==-1}#h(e){return e!==void 0&&e.elements.length>0}#p(e){return e.value.length===1&&e.value.charCodeAt(0)===this.separator}matches(e){if(this.#i===void 0)return!this.#h(e);if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return!1;let t=new nr(e,!1);return this.#i.matches(0,t)}matchAndExtract(e){if(this.#i===void 0)return this.#h(e)&&!this.#p(e)?void 0:rt.EMPTY;if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return;let t=new nr(e,!0);return this.#i.matches(0,t)?t.pathMatchResult:void 0}extractPathWithinPattern(e){let t=e.elements,n=t.length,s=0,i=this.#i;for(;i!==void 0&&i.literal;)i=i.next,s++;if(i===void 0)return j("");for(;s<n&&z(t[s]);)s++;let o=n;for(;o>0&&z(t[o-1]);)o--;let a=!1;for(let d=s;d<o-1;d++)if(z(t[d])&&z(t[d+1])){a=!0;break}let c;if(a){let d=[],u=s;for(;u<o;){let f=t[u++];if(d.push(f.value),z(f))for(;u<o&&z(t[u]);)u++}c=j(d.join(""),this.#n)}else s>=o?c=j("",this.#n):c=Ne(e,s,o);return c}get score(){return this.#a}get catchAll(){return this.#u}get normalizedLength(){return this.#c}get separator(){return this.#n.separator}get capturedVariableCount(){return this.#o}toChainString(){let e=[],t=this.#i;for(;t!==void 0;)e.push(t.toString()),t=t.next;return e.join(" ")}computePatternString(){let e=[],t=this.#i;for(;t!==void 0;)e.push(String.fromCharCode(...t.chars)),t=t.next;return e.join("")}get head(){return this.#i}};var Ns=require("node:util"),Io={MISSING_CLOSE_CAPTURE:"Expected close capture character after variable name '}'",MISSING_OPEN_CAPTURE:"Missing preceding open capture character before variable name'{'",ILLEGAL_NESTED_CAPTURE:"Not allowed to nest variable captures",CANNOT_HAVE_ADJACENT_CAPTURES:"Adjacent captures are not allowed",ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR:"Char '%s' not allowed at start of captured variable name",ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR:"Char '%s' is not allowed in a captured variable name",CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS:"Multiple '{*...}' or '**' pattern elements are not allowed",INVALID_LOCATION_FOR_MULTISEGMENT_PATH_ELEMENT:"'{*...}' or '**' pattern elements should be placed at the start or end of the pattern",MISSING_REGEX_CONSTRAINT:"Missing regex constraint on capture",ILLEGAL_DOUBLE_CAPTURE:"Not allowed to capture ''{0}'' twice in the same pattern",REGEX_PATTERN_SYNTAX_EXCEPTION:"Exception occurred in regex pattern compilation",CAPTURE_ALL_IS_STANDALONE_CONSTRUCT:"'{*...}' cannot be mixed with other path elements in the same path segment"},M=class r extends Error{position;messageType;inserts;#e;static formatMessage(e,t){return(0,Ns.format)(Io[e],...t)}static createWithCause(e,t,n,s,...i){let o=r.formatMessage(s,i);return new r(t,n,s,i,o,{cause:e})}static create(e,t,n,...s){let i=r.formatMessage(n,s);return new r(e,t,n,s,i)}constructor(e,t,n,s,i,o){super(i,o),this.position=e,this.#e=t,this.messageType=n,this.inserts=s}toDetailedString(){let e=[];e.push(String.fromCharCode(...this.#e)),e.push(`
19
+ `);for(let t=0;t<Math.max(0,this.position);t++)e.push(" ");return e.push(`^
20
+ `),e.push(this.message),e.join("")}};var ir=class extends v{variableName;#e;constructor(e,t,n,s){super(e,s);let i=-1;for(let o=0;o<t.length;o++)if(t[o]===58){i=o;break}if(i===-1)this.variableName=String.fromCharCode(...t.slice(1,t.length-1)),this.#e=void 0;else{this.variableName=String.fromCharCode(...t.slice(1,i));let o=String.fromCharCode(...t.slice(i+1,t.length-1)),a=n?"s":"si";this.#e=new RegExp(o,a)}}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElementValue(e);if(n.length===0)return!1;if(this.#e!==void 0){let i=this.#e.exec(n);if(i===null||i.index!==0||i[0].length!==n.length)return!1;if(i.length>1)throw new TypeError(`No capture groups allowed in the constraint regex: ${this.#e}`)}let s=!1;return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,s=!0):s=e===t.pathLength:this.next!==void 0&&(s=this.next.matches(e,t)),s&&t.extractingVariables&&t.set(this.variableName,n,t.pathElements[e-1].parameters),s}get normalizedLength(){return 1}get chars(){let e=[];e.push("{"),e.push(this.variableName),this.#e!==void 0&&(e.push(":"),e.push(this.#e.source)),e.push("}");let t=e.join(""),n=new Uint16Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}get wildcardCount(){return 0}get captureCount(){return 1}get score(){return v.CAPTURE_VARIABLE_WEIGHT}toString(){return`CaptureVariable({${this.variableName}${this.#e?":"+this.#e.source:""}})`}};var or=class extends v{#e;#t;#r;#n;constructor(e,t,n,s,i){if(super(e,i),this.#t=t.length,this.#r=n,this.#n=s,s)this.#e=t;else{this.#e=new Uint16Array(t.length);for(let o=0;o<t.length;o++)this.#e[o]=String.fromCharCode(t[o]).toLowerCase().charCodeAt(0)}}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElements[e];if(!F(n))return!1;let s=n.valueToMatch;if(s.length!==this.#t)return!1;if(this.#n)for(let i=0;i<this.#t;i++){let o=this.#e[i];if(o!==63&&o!==s.charCodeAt(i))return!1}else for(let i=0;i<this.#t;i++){let o=this.#e[i];if(o!==63&&o!==String.fromCharCode(s.charCodeAt(i)).toLowerCase().charCodeAt(0))return!1}return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:this.next!==void 0&&this.next.matches(e,t)}get wildcardCount(){return this.#r}get normalizedLength(){return this.#t}get chars(){return this.#e}toString(){return`SingleCharWildcarded(${String.fromCharCode(...this.#e)})`}};var nt=class extends v{#e;#t;#r;#n;#s;constructor(e,t,n,s,i){super(e,i),this.#e=t,this.#t=n,[this.#r,this.#n,this.#s]=this.#i(t,s)}#i(e,t){let n=String.fromCharCode(...e),s=[],i=0,o=[],a=0;for(;a<n.length;){let u=n.charAt(a);if(u==="{"){let f=n.indexOf("}",a);if(f===-1)throw new SyntaxError(`Missing closing brace in pattern: ${n}`);let m=n.substring(a+1,f),P=m.indexOf(":"),l,h;P!==-1?(l=m.substring(0,P),h=m.substring(P+1)):(l=m,h="[^/]*"),l.startsWith("*")&&(l=l.substring(1),h=".*"),s.push(l),o.push("(",h,")"),a=f+1}else u==="*"?(i++,o.push("[^/]*"),a++):u==="?"?(o.push("."),a++):".+()[]^$|\\".includes(u)?(o.push("\\",u),a++):(o.push(u),a++)}let c=o.join(""),d=this.#t?"s":"si";return[new RegExp(`^${c}$`,d),i,s]}matches(e,t){let n=t.pathElementValue(e),s=this.#r.exec(n),i=s!==null&&s.index===0&&s[0].length===n.length;if(i&&(this.noMorePattern()?t.determinedRemainingPath&&(this.#s.length===0||n.length!==0)?(t.remainingPathIndex=e+1,i=!0):i=e+1>=t.pathLength&&(this.#s.length===0||n.length!==0):i=this.next!==void 0&&this.next.matches(e+1,t)),i&&t.extractingVariables){if(this.#s.length+1!==s?.length)throw new Error(`The number of capturing groups in the pattern segment
21
+ ${this.#r} does not match the number of variables it defines, which can occur if capturing groups are used in the regex itself. Use non-capturing groups (?:...) instead.`);for(let o=1;o<s.length;o++){let a=this.#s[o-1],c=s[o];t.set(a,c,o==this.#s.length?t.pathElements[e].parameters:v.NO_PARAMETERS)}}return i}get variableNames(){return this.#s}get normalizedLength(){let e=0;for(let t of this.#s)e+=t.length;return this.#e.length-e-this.#s.length}get chars(){return this.#e}get captureCount(){return this.#s.length}get wildcardCount(){return this.#n}get score(){return this.captureCount*v.CAPTURE_VARIABLE_WEIGHT+this.wildcardCount*v.WILDCARD_WEIGHT}toString(){return`Regex(${String.fromCharCode(...this.#e)})`}};var ar=class extends v{#e;#t;#r;constructor(e,t,n,s){super(e,s),this.#t=t.length,this.#r=n,this.#e=String.fromCharCode(...t)}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElements[e];if(!F(n))return!1;let s=n.valueToMatch;if(s.length!==this.#t)return!1;if(this.#r){if(this.#e!==s)return!1}else if(this.#e.toLowerCase()!==s.toLowerCase())return!1;return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:this.next.matches(e,t)}get normalizedLength(){return this.#t}get chars(){let e=new Uint16Array(this.#t);for(let t=0;t<this.#t;t++)e[t]=this.#e.charCodeAt(t);return e}get literal(){return!0}toString(){return`Literal(${this.#e})`}};function Oo(r){return r===36||r===95||r>=65&&r<=90||r>=97&&r<=122}function Lo(r){return r===36||r===95||r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57}var cr=class{#e;#t=new Uint16Array(0);#r=0;#n=0;#s=0;#i=!1;#o=!1;#c=!1;#d=0;#a=0;#u=0;#h=!1;#p;#f;#l;constructor(e){this.#e=e}parse(e){if(e==null)throw new TypeError("pathPattern must be defined");this.#t=new Uint16Array(e.length);for(let t=0;t<e.length;t++)this.#t[t]=e.charCodeAt(t);for(this.#r=this.#t.length,this.#f=void 0,this.#l=void 0,this.#p=void 0,this.#a=-1,this.#n=0,this.#w();this.#n<this.#r;){let t=this.#t[this.#n],n=this.#e.pathOptions.separator;if(t===n)this.#a!==-1&&this.#m(this.#y()),this.#m(new he(this.#n,n));else{if(this.#a===-1&&(this.#a=this.#n),t===63)this.#s++;else if(t===123){if(this.#c)throw M.create(this.#n,this.#t,"ILLEGAL_NESTED_CAPTURE");this.#c=!0,this.#u=this.#n}else if(t===125){if(!this.#c)throw M.create(this.#n,this.#t,"MISSING_OPEN_CAPTURE");this.#c=!1,this.#d++}else t===58?this.#c&&!this.#o&&(this.#E(),this.#c=!1,this.#d++):this.#v(n)?(this.#b(this.#n,this.#n+1),this.#m(new Q(this.#n,n)),this.#h=!0,this.#n++):t===42&&(this.#c&&this.#u==this.#n-1&&(this.#o=!0),this.#i=!0);if(this.#c){if(this.#u+1+(this.#o?1:0)===this.#n&&!Oo(t))throw M.create(this.#n,this.#t,"ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR",String.fromCharCode(t));if(this.#n>this.#u+1+(this.#o?1:0)&&!Lo(t)&&t!==45)throw M.create(this.#n,this.#t,"ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR",String.fromCharCode(t))}}this.#n++}return this.#a!==-1&&this.#m(this.#y()),new sr(e,this.#e,this.#f)}#g(){let e=new Uint16Array(this.#n-this.#a),t=0;for(let n=this.#a;n<this.#n;n++)e[t++]=this.#t[n];return e}#y(){if(this.#c)throw M.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");let e,t=this.#e.pathOptions.separator;if(this.#d>0)if(this.#d===1&&this.#a===this.#u&&this.#t[this.#n-1]===125)if(this.#o)this.#b(this.#a,this.#n-1),this.#h=!0,e=new K(this.#a,this.#g(),t);else{try{e=new ir(this.#a,this.#g(),this.#e.caseSensitive,t)}catch(n){throw n instanceof SyntaxError?M.createWithCause(n,this.#P(this.#t,this.#a)+(n.index??0),this.#t,"REGEX_PATTERN_SYNTAX_EXCEPTION"):n}this.#S(this.#a,e.variableName)}else{if(this.#o)throw M.create(this.#a,this.#t,"CAPTURE_ALL_IS_STANDALONE_CONSTRUCT");let n=new nt(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t);for(let s of n.variableNames)this.#S(this.#a,s);e=n}else this.#i?this.#n-1===this.#a?e=new We(this.#a,t):e=new nt(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t):this.#s!==0?e=new or(this.#a,this.#g(),this.#s,this.#e.caseSensitive,t):e=new ar(this.#a,this.#g(),this.#e.caseSensitive,t);return e}#E(){this.#n++;let e=this.#n,t=0,n=!1;for(;this.#n<this.#r;){let s=this.#t[this.#n];if(s===92&&!n){this.#n++,n=!0;continue}if(s===123&&!n)t++;else if(s===125&&!n){if(t===0){if(e==this.#n)throw M.create(this.#n,this.#t,"MISSING_REGEX_CONSTRAINT");return}t--}if(s==this.#e.pathOptions.separator&&!n)throw M.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");this.#n++,n=!1}throw M.create(this.#n-1,this.#t,"MISSING_CLOSE_CAPTURE")}#v(e){return!(this.#n+1>=this.#r||this.#t[this.#n]!==42||this.#t[this.#n+1]!==42||this.#n-1>=0&&this.#t[this.#n-1]!==e||this.#n+2<this.#r&&this.#t[this.#n+2]!==e)}#b(e,t){if(this.#h)throw M.create(this.#n,this.#t,"CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS");if(e>1&&t!==this.#r-1)throw M.create(this.#n,this.#t,"INVALID_LOCATION_FOR_MULTISEGMENT_PATH_ELEMENT")}#m(e){if(e instanceof K||e instanceof Q)if(this.#l===void 0)this.#f=e,this.#l=e;else if(this.#l instanceof he){let t=this.#l.prev;t===void 0?(this.#f=e,e.prev=void 0):(t.next=e,e.prev=t),this.#l=e}else throw new Error(`expected SeparatorPathElement before ${e} but was ${this.#l}`);else this.#f===void 0?(this.#f=e,this.#l=e):this.#l!==void 0&&(this.#l.next=e,e.prev=this.#l,this.#l=e);this.#w()}#P(e,t){let n=t;for(;n<e.length;){if(e[n]===58)return n+1;n++}return-1}#w(){this.#a=-1,this.#s=0,this.#c=!1,this.#d=0,this.#i=!1,this.#o=!1,this.#u=-1}#S(e,t){if(this.#p===void 0&&(this.#p=[]),this.#p?.find(n=>n===t)!==void 0)throw M.create(e,this.#t,"ILLEGAL_DOUBLE_CAPTURE",t);this.#p.push(t)}};var dr=class r{#e=!0;#t=Ar;get caseSensitive(){return this.#e}set caseSensitive(e){this.#e=e}get pathOptions(){return this.#t}set pathOptions(e){this.#t=e}initFullPathPattern(e){return e&&!e.startsWith("/")?"/"+e:e}parse(e){return new cr(this).parse(e)}static DEFAULT=new class extends r{get caseSensitive(){return super.caseSensitive}set caseSensitive(e){this.#r()}get pathOptions(){return super.pathOptions}set pathOptions(e){this.#r()}#r(){throw new Error("PathPatternParser.DEFAULT is immutable")}}};var qs=w("web.async.fn.router"),cn="io.interop.web.async.fn.router.request",dn="io.interop.web.async.fn.router.variables",_s="io.interop.web.async.fn.router.pattern";function Bs(r){let e={route:r,and:t=>Fo(e,t)};return e}function Fo(r,e){return Bs(async t=>{let n=r.route(t);return n!==void 0?n:e.route(t)})}function Gs(r,e){return Bs(async t=>{if(r.test(t)){if(qs.enabledFor("trace")){let n=t.exchange.logPrefix;qs.debug(`${n}Matched ${r}`)}return e}else return})}var Vs=(function(){let r=w("request.predicates");function e(l){if(J(l.exchange.request)){let h=l.headers.firstHeader("Access-Control-Request-Method");if(h!==void 0)return h.toUpperCase()}return l.method}function t(l){let h={test:l,and:p=>n(h,p),negate:()=>i(h),or:p=>s(h,p),toString:()=>l.toString()};return h}function n(l,h){return t(p=>l.test(p)&&h.test(p))}function s(l,h){let p=t(g=>l.test(g)||h.test(g));return p.toString=()=>`(${l} || ${h})`,p}function i(l){let h=t(p=>!l.test(p));return h.toString=()=>`!${l}`,h}function o(l){let h=p=>{let g=e(p),b=l===g;return u("Method",l,g,b),b};return h.toString=()=>`${l}`,t(h)}function a(...l){if(!l)throw new Error("At least one HTTP method must be provided");if(l.length===1)return o(l[0]);let h=new Set(...l),p=g=>{let b=e(g),E=h.has(b);return u("Method",`[${[...h].join(", ")}]`,b,E),E};return p.toString=()=>`[${l.join(", ")}]`,t(p)}function c(l){let h=dr.DEFAULT;return l=h.initFullPathPattern(l),d(h)(l)}function d(l){return h=>{let p=l.parse(h),g=b=>{let E=b.requestPath.pathWithinApplication,H=p.matchAndExtract(E);return u("Pattern",p.patternString,E.value,H!==void 0),H!==void 0};return g.toString=()=>p.patternString,t(g)}}function u(l,h,p,g){r.enabledFor("trace")&&r.debug(`${l} "${h}" ${g?"matches":"does not match"} against value "${p}"`)}function f(l){let h=p=>J(p.exchange.request)?!0:l(p.headers);return h.toString=()=>l.toString(),t(h)}function m(...l){if(!l)throw new Error("mediaTypes must not be empty");function h(p){let g=p.accept();return g.length===0?g=[R.ALL]:Dn(g),g}if(l.length===1){let p=l[0],g=b=>{let E=h(b),H=!1;for(let L of E)if(re(L,p)){H=!0;break}return u("Accept",p,E,H),H};return g.toString=()=>`Accept: ${p}`,f(g)}else{let p=g=>{let b=h(g),E=!1;e:for(let H of b)for(let L of l)if(re(H,L)){E=!0;break e}return u("Accept",l,b,E),E};return p.toString=()=>`Accept: ${l.join(", ")}`,f(p)}}function P(l,h){let p=typeof h=="string"?h:void 0,g=typeof h=="string"?E=>E===p:h,b=E=>{let H=E.queryParam(l);return H!=null&&g(H)};return b.toString=()=>`?${l} ${h}`,t(b)}return{all:()=>t(l=>!0),method:o,methods:a,path:c,pathPredicates:d,headers:f,accept:m,GET:l=>o("GET").and(c(l)),HEAD:l=>o("HEAD").and(c(l)),POST:l=>o("POST").and(c(l)),PUT:l=>o("PUT").and(c(l)),PATCH:l=>o("PATCH").and(c(l)),DELETE:l=>o("DELETE").and(c(l)),OPTIONS:l=>o("OPTIONS").and(c(l)),queryParam:P}})();async function Do(r){return ur(r.statusCode).headers(e=>{for(let t of r.headers.keys())e.add(t,r.headers.list(t))}).bodyValue(r.body)}function ur(r){return r=typeof r=="number"?pt(r):r,new un(r)}function $o(){return ur(y.OK)}function Uo(r){return ur(y.CREATED).location(r)}var zs={from:Do,status:ur,ok:$o,created:Uo};function No(r,e,t,n){let s=ge(r.headers);for(let i of e.messageWriters)if(i.canWrite(n,s))return i.write(t,n,r,s);return Promise.reject(new Error(`No HttpMessageWriter found for body type ${n} and media type ${s}`))}function qo(r){return async(e,t)=>No(e,t,Promise.resolve(r),typeof r)}var un=class{#e;#t=new A;#r=new Map;#n=new Map;constructor(e){this.#e=e}header(e,...t){for(let n of t)this.#t.add(e,n);return this}cookie(e){let t=this.#r.get(e.name)??[];return t.push(e),this.#r.set(e.name,t),this}headers(e){return e(this.#t),this}contentType(e){return this.#t.set("Content-Type",e.toString()),this}contentLength(e){return this.#t.set("Content-Length",e.toString()),this}location(e){return this.#t.set("Location",e?.href),this}bodyValue(e){return this.#s(e,qo(e))}#s(e,t){return Promise.resolve(new hn(this.#e,this.#t,new Map(this.#r),e,t,new Map(this.#n)))}build(e){return e?Promise.resolve(new ln(this.#e,this.#t,this.#r,e)):this.build(async(t,n)=>{await t.response.end()})}},Ie=class{#e;#t;#r;hints;constructor(e,t,n,s){this.#e=e,this.#t=t,this.#r=n,this.hints=s}get statusCode(){return this.#e}get headers(){return this.#t}get cookies(){let e=[];for(let t of this.#r.values())e.push(...t);return e}async writeTo(e,t){return this.#n(e.response),this.writeInternal(e,t)}#n(e){e.setStatusCode(this.#e);for(let t of this.#t.keys())e.headers.add(t,this.#t.list(t));for(let t of this.#r.values())for(let n of t)e.addCookie(n)}};var ln=class extends Ie{#e;constructor(e,t,n,s){super(e,t,n),this.#e=s}async writeInternal(e,t){await this.#e(e,t)}},hn=class extends Ie{#e;#t;constructor(e,t,n,s,i,o){super(e,t,n,o),this.#e=s,this.#t=i}get entity(){return this.#e}get inserter(){return this.#t}async writeInternal(e,{messageWriters:t}){this.hints?.set(Kt,e.logPrefix),await this.inserter(e.response,{messageWriters:t,serverRequest:e.request,hints:this.hints})}};var js=require("node:util");var lr=class r extends Error{#e;#t=new A;body;constructor(e,t){super(),this.#e=e,this.body=t??r.problemDetailFor(e)}get statusCode(){return this.#e}set detail(e){this.body.detail=e}get headers(){return this.#t}static problemDetailFor(e,t){let n={status:e.value};return t!==void 0&&(n.detail=t),n}};var Z=class r extends lr{#e;constructor(e,t){super(e,r.problemDetailFor(e,t)),this.#e=t}get reason(){return this.#e}get headers(){return Un}};var st=class r{static ERROR_ATTRIBUTE="io.interop.web.server.exchange.error";getErrorAttributes(e,t){return this.#e(e,t.includes.includes("trace"))}getError(e){let t=e.attributes.get(r.ERROR_ATTRIBUTE);if(t===void 0)throw new Error("No error found in request attributes");return t}storeErrorInformation(e,t){t.attributes.set(r.ERROR_ATTRIBUTE,e)}#e(e,t){let n={};n.timestamp=new Date;let s=this.getError(e),i=this.#t(s);return n.status=i.value,n.reason=i.phrase,n.requestId=e.exchange.request.id,this.#r(n,s,t),n}#t(e){if(e instanceof Z){let t=y.resolve(e.statusCode.value);if(t)return t}return y.INTERNAL_SERVER_ERROR}#r(e,t,n){t instanceof Z&&(e.message=t.reason)}},pn=class{#e;#t;#r;constructor(e,t,n){if(!t)throw new Error("messageWriters must not be null.");this.#e=n,this.#t=e,this.#r=t}getErrorAttributes(e,t){return this.#e.getErrorAttributes(e,t)}async handle(e,t){if(e.response.commited||this.#n(t))return Promise.reject(t);this.#e.storeErrorInformation(t,e);let n=rr.create(e,this.#t),s=await this.getRoutingFunction(this.#e)?.route(n);if(s){let i=await s(n);this.logError(n,i,t),await this.#s(e,i)}else throw t}logError(e,t,n){}#n(e){return nn(e)}async#s(e,t){e.response.headers.set("Content-Type",t.headers.get("Content-Type"));let n={messageWriters:this.#r};return t.writeTo(e,n)}},hr=class r extends pn{static#e=new st;static#t={includes:["status"]};constructor(e,t,n,s={}){super(e,t,n)}getRoutingFunction(e){return Gs(Vs.all(),t=>this.#n(t))}#r(e,t){return super.getErrorAttributes(e,this.getErrorAttributeOptions(e,t))}getErrorAttributeOptions(e,t){return{includes:["error","message","status","path"]}}async#n(e){let t=this.#r(e,Fe),n=this.#s(e,t);return zs.status(n).contentType(new js.MIMEType("application/json")).bodyValue(JSON.stringify(t))}#s(e,t){return this.getHttpStatus(t.status!==void 0?t:r.#e.getErrorAttributes(e,r.#t))}getHttpStatus(e){let t=e.status;if(typeof t=="number")return t;throw new Error(`Invalid status code: ${t}`)}};var Xs="io.interop.web.async.handler.handler",Js="io.interop.web.async.handler.pattern";var pr=class{#e;#t;#r;constructor(e,t,n){this.#e=e,this.#t=t,this.#r=n}async handle(e){if(!this.#e)return this.#o();if(J(e.request))return this.handlePreFlight(e);let t;try{for(let n of this.#e)if(t=await n.getHandler(e),t!==void 0)break;t===void 0&&await this.#o()}catch(n){return this.#n(e,Promise.reject(n))}return this.#i(e,t)}async#n(e,t){this.#t;let n=await t;try{await this.#s(e,n,`Handler ${n.handler}`)}catch(s){let i=n.exceptionHandler;if(i){let o=s instanceof Error?s:new Error(String(s)),a=await i(e,o);await this.#s(e,a,`Exception handler ${a.handler}, error="${o.message}"`)}}}#s(e,t,n){if(this.#r){for(let s of this.#r)if(s.supports(t))return n+=" [DispatcherHandler]",s.handle(e,t)}return Promise.reject(new Error(`No HandlerResultHandler for ${t.returnValue}`))}#i(e,t){if(e.response.statusCode?.value===y.FORBIDDEN.value)return Promise.resolve();if(this.#t){for(let n of this.#t)if(n.supports(t)){let s=n.handle(e,t);return this.#n(e,s)}}return Promise.reject(new Error(`No HandlerAdapter for handler ${t}`))}#o(){return Promise.reject(new Z(y.NOT_FOUND))}async handlePreFlight(e){let t;for(let n of this.#e??[])if(t=await n.getHandler(e),t!==void 0)break;if(t===void 0){e.response.setStatusCode(y.FORBIDDEN);return}}},fr=class{logger=w("web.async.handler");#e;set corsConfigSource(e){if(e===void 0)throw new Error("CorsConfigSource must not be undefined");this.#e=e}async getHandler(e){let t=await this.getHandlerInternal(e);if(t!==void 0){this.logger.enabledFor("debug")&&this.logger.debug(`${e.logPrefix}Mapped to ${t}`);let n=e.request;if(this.hasCorsConfigSource(t)||J(n)){let s=this.#e!==void 0?await this.#e(e):void 0,i=this.getCorsConfig(t,e)}return t}}hasCorsConfigSource(e){return this.#e!==void 0}getCorsConfig(e,t){}};var gr=class{supports(e){return typeof e=="function"}async handle(e,t){let n=t,s=e.attribute(cn);if(!s)throw new Error("ServerRequest is not found in exchange attributes.");return n(s).then(i=>({handler:t,returnValue:i}))}},mr=class{#e=Array();constructor(e){if(!e||e.length===0)throw new Error("messageWriters must not be empty.");this.#e=e}supports(e){return e.returnValue instanceof Ie}get messageWriters(){return this.#e}async handle(e,t){let n=t.returnValue;if(n===void 0)throw new Error("No ServerResponse");return n.writeTo(e,{messageWriters:this.messageWriters})}},yr=class extends fr{#e;#t=void 0;constructor(e){super(),this.#e=e}set messageReaders(e){this.#t=e}init(...e){if((this.#t===void 0||this.#t.length===0)&&(this.#t=ke.serverConfigurer.create().readers),this.#e)throw new Error("RouterFunctionMapping is already initialized with a RouterFunction");this.#e=e.reduce((t,n)=>t.and(n))}async getHandlerInternal(e){if(this.#e===void 0)return;let t=rr.create(e,this.#t),n=await this.#e.route(t);return n!==void 0&&this.#r(e.attributes,t,n),n}#r(e,t,n){e.set(cn,t),e.set(Xs,n);let s=e.get(_s);s&&e.set(Js,s);let i=e.get(dn);i!==void 0&&e.set(dn,i)}};var T=w("app");async function Bo(r,e){let t=r.build();return async(n,s)=>{n.socket.addListener("error",e);let i;s instanceof me?i=s:(n.upgradeHead=s,i=new me(n),i.assignSocket(n.socket));try{let o=new ye(n),a=new mt(i),c=o.method==="HEAD"?new zt(a):a,d=t(o,c);try{await d,T.enabledFor("trace")&&T.debug(`${o.id} handling completed.`)}catch(u){if(u instanceof Error&&u.code==="ERR_INVALID_URL")throw u;T.enabledFor("trace")&&T.debug(`${o.id} failed to complete: ${u instanceof Error?u.message:u}`)}}catch(o){if(o instanceof Error&&o.code==="ERR_INVALID_URL")return T.enabledFor("debug")&&T.debug(`failed to get request URI: ${o.message}`),i.statusCode=400,i.end(gn.default.STATUS_CODES[400]),Promise.resolve();throw o}}}function Go(r){return new Promise((e,t)=>{let n=r(s=>{s?t(s):e(n)})})}function Vo(r){if(r)return Bn({memoryLimit:r.memory_limit,dumpLocation:r.dump_location,dumpPrefix:r.dump_prefix,reportInterval:r.report_interval,maxBackups:r.max_backups})}var Qs=`${fn.default.name} - v${fn.default.version}`;async function zo(r){let e=r.storage,t=await Rs(r),n=Hs(r),s=ke.serverConfigurer.create();s.defaultCodecs.enableLoggingRequestDetails(!0);let i=new yr,o=new pr([i],[new gr],[new mr(s.writers)]),a={handle:kn(Vn(Qs,r.serverHeader),...n,...r.middleware,async({request:c,response:d},u)=>{if(c.method==="GET"&&c.path==="/health"){d.setStatusCode(y.OK);let f=Buffer.from("UP","utf-8");d.headers.set("Content-Type","text/plain; charset=utf-8"),await d.body(f)}else await u()},await rn(r.resourcesConfig?.locations),async({response:c},d)=>{throw new Z(y.NOT_FOUND)})};return new tr(a).filter(new qt(t)).codecConfigurer(s).exceptionHandler(new hr(s.readers,s.writers,new st)).storage(e)}var mn=async r=>{let e=r.ssl,t=r.host,n=r.auth?.x509?.key?{host:t??"localhost",key:r.auth.x509.key,passphrase:r.auth.x509.passphrase}:void 0,s=e?(h,p)=>Ys.default.createServer({...h,...Is(e,n)},p):(h,p)=>gn.default.createServer(h,p),i=Vo(r.memory),o={middleware:[],corsConfig:r.cors,cors:[],authConfig:r.auth,authorize:[],storage:new Ks.AsyncLocalStorage,sockets:new Map,resourcesConfig:r.resources},a=new ot({baseConfig:{...r.gateway},scope:r.gateway?.scope??"principal"});if(r.gateway){let h=r.gateway.route?r.gateway.route==="/"?void 0:r.gateway.route:void 0;await Or(async p=>{p.socket({path:h,factory:Rn.bind(a),options:r.gateway})},r,o)}r.app&&await Or(r.app,r,o);let c=En(r.port??0),d=h=>T.error(`socket error: ${h}`,h),u=await zo(o),f=await Bo(u,d),P=await new Promise((h,p)=>{let g=s({IncomingMessage:ft,ServerResponse:me,...r.http},f);g.on("error",b=>{if(b.code==="EADDRINUSE"){T.debug(`port ${b.port} already in use on address ${b.address}`);let{value:E}=c.next();E?(T.info(`retry starting server on port ${E} and host ${t??"<unspecified>"}`),g.close(),g.listen(E,t)):(T.warn(`all configured port(s) ${r.port} are in use. closing...`),g.close(),p(b))}else T.error(`server error: ${b.message}`,b),p(b)}),g.on("listening",async()=>{let b=g.address();for(let[E,H]of o.sockets){let L=`${e?"wss":"ws"}://${vn}:${b.port}${E}`;await Ws(E,H,L,o.storage,d)}T.info(`http server listening on ${e?"https":"http"}://${ee(b)}`),h(g)}),g.on("upgrade",(b,E,H)=>{try{f(b,H)}catch(L){T.error(`upgrade error: ${L}`,L)}}).on("close",async()=>{T.info("http server closed.")});try{let{value:b}=c.next();g.listen(b,t)}catch(b){T.error("error starting web socket server",b),p(b instanceof Error?b:new Error(`listen failed: ${b}`))}}),l=new class{gateway=a;get address(){let h=P.address();return typeof h=="object"?h:null}async close(){for(let[h,p]of o.sockets)try{p.close!==void 0&&await p.close()}catch(g){T.warn(`error closing route ${h}`,g)}await Go(h=>{P.closeAllConnections(),P.close(h)}),i&&await Gn(i),await a.stop()}};return r.management?.server.path&&Ls({options:r.management.server,info:async()=>({pid:process.pid,type:"gateway-server",...l.gateway.info()}),logger:T.child("management"),shutdown:r.management.commands?.shutdown.enabled?async()=>{T.enabledFor("info")&&T.info("stopping gateway-server..."),await l.close()}:void 0}),l};var jo=mn;0&&(module.exports={GatewayServer});
8
22
  //# sourceMappingURL=index.cjs.map