@interopio/gateway-server
Version:
[](https://www.npmjs.com/package/@interopio/gateway-server)
13 lines • 121 kB
JavaScript
"use strict";var oi=Object.create;var at=Object.defineProperty;var ai=Object.getOwnPropertyDescriptor;var ci=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,ui=Object.prototype.hasOwnProperty;var En=(r,e)=>{for(var t in e)at(r,t,{get:e[t],enumerable:!0})},vn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ci(e))!ui.call(r,s)&&s!==t&&at(r,s,{get:()=>e[s],enumerable:!(n=ai(e,s))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?oi(di(r)):{},vn(e||!r||!r.__esModule?at(t,"default",{value:r,enumerable:!0}):t,r)),li=r=>vn(at({},"__esModule",{value:!0}),r);var ra={};En(ra,{GatewayServer:()=>Sn,default:()=>ta});module.exports=li(ra);var Sn={};En(Sn,{Factory:()=>wn,VERSION:()=>ii});var bn=fe(require("node:http"),1),ni=fe(require("node:https"),1),si=require("node:async_hooks");var Pn=require("node:os"),hi=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function Er(r){if(r>65535)throw new Error(`bad port ${r}`);return r}function*Cn(r){if(typeof r=="string")for(let e of r.split(",")){let t=e.trim(),n=hi.exec(t);if(n){let s=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let o=Er(s);o<Er(i)+1;o++)yield o}else throw new Error(`'${e}' is not a valid port or range.`)}else yield Er(r)}var xn=(()=>{function r(t){return t.length>0?t[0]:void 0}let e=Object.values((0,Pn.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 An=fe(require("@interopio/gateway/logging/core"),1);function S(r){return An.getLogger(`gateway.server.${r}`)}function Rn(r,e){return e instanceof RegExp?e.toString():e}var Tn=require("@interopio/gateway"),Mn=require("node:async_hooks"),V=S("ws"),pi=Tn.IOGateway.Encoding.json();function fi(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 gi(r,e,t,n){let s=ee(n),i=n?.address??"<unknown>",o={key:s,host:i,codec:pi,onAuthenticate:async()=>{let a=await t();if(a?.authenticated)return{type:"success",user:fi(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 mi(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=gi(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?Mn.AsyncLocalStorage.snapshot():void 0;e.on("message",(u,h)=>{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 Hn=mi;var Cr=require("@interopio/gateway");var ge=require("@interopio/gateway");function vr(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]=ge.IOGateway.Filtering.regexify(s));if(e.identity!==void 0){t.identity={};for(let[n,s]of Object.entries(e.identity))t.identity[n]=ge.IOGateway.Filtering.regexify(s)}return t})}function kn(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]=ge.IOGateway.Filtering.regexify(c);if(o.metrics={},n){let a=(n.allow??n.whitelist??[]).map(d=>ge.IOGateway.Filtering.regexify(d)),c=(n.block??n.blacklist??[]).map(d=>ge.IOGateway.Filtering.regexify(d));a.length>0&&(o.metrics.allow=a),c.length>0&&(o.metrics.block=c)}return o})),e}function Pr(r){if(!r)return;let e={...r};return r.filters&&(e.filters=kn(r.filters)),e}function yi(r){if(r?.enabled!==!1)return r}function bi(r){if(r===void 0||r?.enabled===!1)return;let e={...r};return r.filters&&(e.filters=kn(r.filters)),r.file&&(e.file=Pr(r.file)),r.rest&&(e.rest=Pr(r.rest)),r.publishers&&(e.publishers=r.publishers.map(t=>{if(typeof t=="string")return[t];let n=Pr(t);return n!==void 0?[n]:[]}).flat()),e}function In(r){let e={...r};return r.contexts&&(e.contexts={...r.contexts,visibility:vr(r.contexts.visibility)}),r.methods&&(e.methods={...r.methods,visibility:vr(r.methods.visibility)}),r.peers&&(e.peers={...r.peers,visibility:vr(r.peers.visibility)}),r.metrics&&(e.metrics=bi(r.metrics)),r.mesh&&(e.mesh=yi(r.mesh)),e}var I=S("gateway-manager");function Wn(){return globalThis.crypto.randomUUID().replaceAll("-","")}var ct=class{#e;#t;#r=new Map;#n=new Map;#s;#i=!1;#o;constructor(e){this.#s={baseConfig:In(e.baseConfig),scope:e.scope??"principal"},this.#e=e.baseConfig.node??Wn(),I.enabledFor("debug")&&I.debug(`creating default gateway with gateway id: ${this.#e}`),this.#t=Cr.IOGateway.Factory({...this.#s.baseConfig,node:this.#e})}async start(e){return this.#i?this:(this.#o=e,I.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?I.enabledFor("debug")&&I.debug(`reusing existing gateway for principal '${e}'`):(I.enabledFor("debug")&&I.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.#c(e)),n}async#c(e){let t=Wn(),n={...this.#s.baseConfig,node:t};I.enabledFor("debug")&&I.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let s=Cr.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){I.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 I.debug("stopping default gateway (managed gateways will continue running)"),await this.#t.stop(),this.#i=!1,this.#t;I.info(`stopping all gateways (1 default + ${this.#r.size} managed)`);for(let[t,n]of this.#r.entries())I.enabledFor("debug")&&I.debug(`stopping gateway with ID: ${t}`),await n.stop();return this.#r.clear(),this.#n.clear(),I.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 On(...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,h=await a(o,async g=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await s(i+1,g??o)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream.
You are probably missing an await or return statement in your middleware function.`);return h};return s(0,t)}}var Ln=require("node:net"),ht=require("tough-cookie");function wi(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 Si(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function Ei(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():Si(r)?"https":e}function vi(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,Ln.isIP)(s)===6?"IPv6":"IPv4"}}var dt=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},ut=class r extends dt{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 Pi(this.headers)}parseHost(e){return wi(this.headers,e)}parseProtocol(e){return Ei(this.headers,e)}parseRemoteAddress(e){return vi(this.URL,this.headers,e)}},lt=class extends dt{get cookies(){return Ci(this.headers)}setCookieValue(e){return new ht.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 Pi(r){return r.list("cookie").map(e=>e.split(";").map(t=>ht.Cookie.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function Ci(r){return r.list("set-cookie").map(e=>{let t=ht.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 $n=require("node:util");var pt=require("node:util"),ce="*",De=new pt.MIMEType(`${ce}/${ce}`),xr="application/octet-stream",ga=new pt.MIMEType(xr);function me(r){return r.type===ce}function te(r){return r.subtype===ce||r.subtype.startsWith(`${ce}+`)}function Ar(r){return!me(r)&&!te(r)}var Fe=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 Rr(r,e,t){let n=`${r}/${e}`,s;try{s=new pt.MIMEType(n)}catch(i){throw new Fe(n,void 0,{cause:i})}return t&&s.params.set("charset",t),s}function Fn(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(me(r)||me(e))return!0;if(r.type===e.type){if(r.subtype===e.subtype)return!0;if(te(r)||te(e)){let t=Fn(r),n=Fn(e);if(r.subtype===ce||e.subtype===ce)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 xi=`
application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy
application/json json
application/wasm wasm
application/x-pkcs12 p12 pfx
text/css css
text/csv csv
text/html html htm
text/javascript js mjs
text/plain txt text conf def list log in
`,H=class r extends $n.MIMEType{static ALL=new r("*/*");static APPLICATION_OCTET_STREAM=new r(xr);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),Nn(t)||this.#t(t),e===r.#e){let n=Dn(t),s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new ft(`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 ft(`Invalid token: ${e}`)}}get quality(){let e=this.params.get(r.#e);return e!==null?parseFloat(Dn(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))}},ft=class extends Error{constructor(e){super(e)}},ba=(function(){let e=new Map;for(let t of xi.trim().split(`
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.split(/\s+/);if(s.length<2)continue;let[i,...o]=s,a=H.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 Nn(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function Dn(r){return Nn(r)?r.substring(1,r.length-1):r}function Ai(r,e){if(r instanceof H&&e instanceof H){let s=r.quality,i=e.quality;if(s>i)return!0;if(s<i)return!1}let t=me(r),n=me(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 Ri(r,e){return Ai(e,r)}function Ti(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 Un(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Fe("too many elements");Ti(r,Ri)}function Mi(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 qn(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...Mi(t));return e}var $e=class{constructor(){}toList(e){let t=this.get(e);return qn(t)}},T=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 qn(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}},_n=new T;function ye(r){let e=r.one("content-type");return e?H.parseMediaType(e):void 0}var Tr=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},b=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 gt(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=b.resolve(r);return e!==void 0?e:new Tr(r)}return r}var vt=fe(require("node:http"),1);function qe(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 Mr={separator:47,decodeAndParseParameters:!0};function j(r,e){return Ue.createFromUrlPath(r,e??Mr)}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):Ne.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 Ne.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),i=r.#s(s);return Ne.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,[""])}}}}},Ne=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 Bn(r,e){return typeof r=="string"?Hr.parse(r,e):Bn(r.href,e)}var Hr=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 qe(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 qe(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()}},_e=class extends ut{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=Bn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var mt=class extends vt.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},be=class extends vt.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},yt=class extends lt{#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:gt(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(){}},we=class extends _e{#e;#t;#r;constructor(e){super(new Ir(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 kr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return vt.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}`}},kr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Ir=class extends $e{#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()}},Wr=class extends $e{#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)}},bt=class extends yt{#e;constructor(e){super(new Wr(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}`))}})}}},wt=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 _e)return e.getNativeRequest();if(e instanceof r)return r.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},Se=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 yt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},St=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}]`}},Et=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[Gn]=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(Gn);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},Gn="io.interop.web.server.exchange.log_id";var Pt=require("node:v8"),X=require("node:fs/promises"),A=S("monitoring"),Hi={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function ki(){return(0,Pt.getHeapStatistics)()}async function Vn(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;A.enabledFor("debug")&&A.debug(`starting heap dump in ${t}`),await Or(r.dumpLocation).catch(async s=>{A.enabledFor("debug")&&A.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await(0,X.mkdir)(r.dumpLocation,{recursive:!0}),A.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{A.error(`failed to create dump location ${r.dumpLocation}`)}});let n=(0,Pt.writeHeapSnapshot)(t);A.info("heap dumped");try{A.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await Or(s).then(async()=>{A.enabledFor("debug")&&A.debug(`deleting ${s}`);try{await(0,X.unlink)(s)}catch(o){A.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 Or(a).then(async()=>{try{await(0,X.rename)(a,c)}catch(d){A.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){A.warn(`failed to rename ${n} to ${i}`,o)}A.debug("snapshots rolled")}catch(s){throw A.error("error rolling backups",s),s}}async function Or(r){A.enabledFor("trace")&&A.debug(`checking file ${r}`),await(0,X.access)(r)}async function Ii(r,e,t){A.enabledFor("debug")&&A.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;A.info(`heap stats ${JSON.stringify(r)}`),s>=n?(A.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await Vn(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function zn(r){let e={...Hi,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=ki();await Ii(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 Vn(e);break}case"stop":{t=!0,clearInterval(i),A.info("exit memory diagnostic");break}}return t}}}async function Wi({channel:r},e){await r(e)||A.warn(`cannot execute command "${e}" already closed`)}async function jn(r){return await Wi(r,"stop")}var Li=(r,e)=>(e??=r,async({response:t},n)=>{e!==!1&&!t.headers.has("server")&&t.headers.set("Server",e),await n()}),Xn=(r,e)=>Li(r,e);var Be=require("@interopio/gateway");var Lr=S("gateway.ws.client-verify");function Fi(r){switch(r.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Di(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&Be.IOGateway.Filtering.valuesMatch(t,e))return Lr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&Be.IOGateway.Filtering.valuesMatch(n,e))return Lr.enabledFor("debug")&&Lr.debug(`origin ${e} matches allow filter`),!0}function $i(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Jn(r,e){if(!e)return!0;if(r){let t=Di(e,r);return t||$i(e)}else return Fi(e)}function Yn(r){if(r){let e=(r.block??r.blacklist??[]).map(Be.IOGateway.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(Be.IOGateway.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Kn=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return L},Ee=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return L;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},Qn=r=>async e=>(await r(e)).match?L:D(),ve=async r=>D();ve.toString=()=>"any-exchange";var Zn=Object.freeze({}),L=Object.freeze({match:!1,variables:Zn}),D=(r=Zn)=>({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 L;if(typeof r=="string")return o===r?D():L;{let a=r.exec(o);return a===null?L:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},Ge=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 L}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return L}},de=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():L;de.toString=()=>"websocket upgrade";var Fr=require("@interopio/gateway");async function Dr(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Fr.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=$(Fr.IOGateway.Filtering.regexify(o.path),{method:o.method});a?.authorize&&t.authorize.push([d,a.authorize]),n(o,a);let u=async(h,g)=>{let{match:v,variables:l}=await d(h);v?await c(h,l):await g()};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:Yn(c?.origins)})}}};await r(s,e)}var At=require("@interopio/gateway");function Ui(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 es(r){return r.headers.has("origin")&&!Ui(r)}function J(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var ts=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],qi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",ts.join(", "));else{let o=s.list("Vary");for(let a of ts)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!es(t))return!0}catch{return N.enabledFor("debug")&&N.debug("reject: origin is malformed"),Ve(n),!1}if(s.has("access-control-allow-origin"))return N.enabledFor("trace")&&N.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=J(t);return e?Bi(r,e,i):i?(Ve(n),!1):!0},xt=["*"],$r=["GET","HEAD","POST"],rs={allowOrigins:xt,allowMethods:$r,allowHeaders:xt,maxAge:1800};function Rt(r){if(r){let e=r.allowHeaders;e&&e!==R&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(ss(r),is(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==R&&(n=At.IOGateway.Filtering.regexify(n),typeof n=="string")?os(n).toLowerCase():n)}),r}}function Ct(r,e){if(e===void 0)return r!==void 0?r===R?[R]:r:[];if(r===void 0)return e===R?[R]:e;if(r==xt||r===$r)return e===R?[R]:e;if(e==xt||e===$r)return r===R?[R]:r;if(r===R||r.includes(R)||e===R||e.includes(R))return[R];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var ze=(r,e)=>e===void 0?r:{allowOrigins:Ct(r.allowOrigins,e?.allowOrigins),allowMethods:Ct(r.allowMethods,e?.allowMethods),allowHeaders:Ct(r.allowHeaders,e?.allowHeaders),exposeHeaders:Ct(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},_i=r=>{let e=r.corsConfigSource,t=r.corsProcessor??qi;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)}}},ns=_i,N=S("cors");function Ve(r){r.setStatusCode(b.FORBIDDEN)}function Bi(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=Vi(e,o);if(a===void 0)return N.enabledFor("debug")&&N.debug(`reject: '${o}' origin is not allowed`),Ve(s),!1;let c=Xi(n,t),d=zi(e,c);if(d===void 0)return N.enabledFor("debug")&&N.debug(`reject: HTTP '${c}' is not allowed`),Ve(s),!1;let u=Ji(n,t),h=ji(e,u);if(t&&h===void 0)return N.enabledFor("debug")&&N.debug(`reject: headers '${u}' are not allowed`),Ve(s),!1;i.set("Access-Control-Allow-Origin",a),t&&i.set("Access-Control-Allow-Methods",d.join(",")),t&&h!==void 0&&h.length>0&&i.set("Access-Control-Allow-Headers",h.join(", "));let g=e.exposeHeaders;return g&&g.length>0&&i.set("Access-Control-Expose-Headers",g.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 R="*",Gi=["GET","HEAD"];function ss(r){if(r.allowCredentials===!0&&r.allowOrigins===R)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function is(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===R)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Vi(r,e){if(e){let t=r.allowOrigins;if(t){if(t===R)return ss(r),is(r),R;let n=os(e.toLowerCase());for(let s of t)if(s===R||At.IOGateway.Filtering.valueMatches(s,n))return e}}}function zi(r,e){if(e){let t=r.allowMethods??Gi;if(t===R)return[e];if(At.IOGateway.Filtering.valuesMatch(t,e))return t}}function ji(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===R||t.includes(R),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 os(r){return r.endsWith("/")?r.slice(0,-1):r}function Xi(r,e){return e?r.headers.one("access-control-request-method"):r.method}function Ji(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var as=r=>async e=>{for(let[t,n]of r.mappings)if((await t(e)).match)return N.debug(`resolved cors config on '${e.request.path}' using ${t}: ${JSON.stringify(n)}`),n};var cs=require("@interopio/gateway");function ds(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:ze(rs,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,h]of t)cs.IOGateway.Filtering.valueMatches(u,o)&&(h===void 0?c=void 0:c=c===void 0?h:ze(c,h));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:ze(c,d),s.push([Ee([de,$(o)]),Rt(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:ze(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),Rt(a)]);return s.push([$(/\/api\/.*/),Rt(n)]),as({mappings:s})}function us(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}},Tt=class extends W{},Pe=class extends W{},Ce=class extends W{constructor(e){super(e)}},je=class extends Ce{constructor(e){super(e)}},Xe=class extends Ce{constructor(e){super(e)}},Je=class extends Ce{constructor(e){super(e)}},Ye=class extends Ce{constructor(e){super(e)}};var ue=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 ue("Access denied")}async authorize(e,t){return await this.#e(e,t)}},xe=class extends W{};var U=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)},Yi=()=>U(new T().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Ki=()=>U(new T().add("x-content-type-options","nosniff")),Qi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=U(new T().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},Zi=r=>U(new T().add("x-frame-options",r)),eo=r=>U(new T().add("x-xss-protection",r)),to=r=>{let e=r===void 0?void 0:U(new T().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},ro=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:U(new T().add(t,r));return async s=>{n!==void 0&&await n(s)}},no=(r="no-referrer")=>U(new T().add("referer-policy",r)),so=r=>{let e=r===void 0?void 0:U(new T().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},io=r=>{let e=r===void 0?void 0:U(new T().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},oo=r=>{let e=r===void 0?void 0:U(new T().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},ao=(...r)=>async e=>{for(let t of r)await t(e)};function Nr(r){let e=[];r?.cache?.disabled||e.push(Yi()),r?.contentType?.disabled||e.push(Ki()),r?.hsts?.disabled||e.push(Qi(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(eo(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(to(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push(ro(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(no(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(so(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(io(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(oo(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=ao(...e);return{filter:async(n,s)=>(await t(n),s.filter(n))}}var Ae=r=>{let e=r.entryPoint,t=r?.rethrowAuthenticationServiceError??!0;return async({exchange:n},s)=>{if(!t||!(s instanceof xe))return e(n,s);throw s}};var co="Realm",uo=r=>`Basic realm="${r}"`,Re=r=>{let e=uo(r?.realm??co);return async(t,n)=>{let{response:s}=t;s.setStatusCode(b.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var ls="Basic ",Mt=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<=ls.length?"":s.substring(ls.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 hs=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 hs.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 lo(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 ho(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof W,c}}async function ho(r,e,t,n){se.withAuthentication(r)(n),await t(e,r)}function ie(r){let e={matcher:ve,successHandler:async({exchange:n,chain:s})=>{await s.filter(n)},converter:Mt({}),failureHandler:Ae({entryPoint:Re({})}),...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 lo(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 ps=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var Te=S("auth.entry-point"),Ht=r=>{let e=r.defaultEntryPoint??(async({response:t},n)=>{t.setStatusCode(b.UNAUTHORIZED),await t.end()});return async(t,n)=>{for(let[s,i]of r.entryPoints)if(Te.enabledFor("debug")&&Te.debug(`trying to match using: ${s}`),(await s(t)).match)return Te.enabledFor("debug")&&Te.debug(`match found. using default entry point ${i}`),i(t,n);return Te.enabledFor("debug")&&Te.debug(`no match found. using default entry point ${e}`),e(t,n)}};var fs=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Ur(r){let e=async g=>g.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():L,t=Ht({entryPoints:[[e,ps({httpStatus:b.UNAUTHORIZED})]],defaultEntryPoint:Re({})}),n=r.entryPoint??t,s=r.manager,i=Ge({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=Qn(Ge({mediaTypes:["text/html"]})),a=Ee([o,i]),c=Kn([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Ae({entryPoint:n}),u=fs(r.successHandlers??r.defaultSuccessHandlers),h=Mt({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:h})}var gs={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},ms="https://tools.ietf.org/html/rfc6750#section-3.1";function kt(r){return{errorCode:gs.invalid_token,httpStatus:b.UNAUTHORIZED,description:r,uri:ms}}function qr(r){return{errorCode:gs.invalid_request,httpStatus:b.BAD_REQUEST,description:r,uri:ms}}var po="access_token",fo=/^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}},ys=r=>r.type==="BearerToken",go=r=>async e=>{let{request:t}=e;return Promise.all([yo(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),bo(t,r?.uriQueryParameter),wo(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(mo).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function mo(r){if(r.length===0)return;if(r.length>1){let t=qr("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=qr("The requested access token parameter is an empty string");throw new _(t)}return e}async function yo(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=fo.exec(t);if(n===null){let s=kt("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function bs(r){let e=r.getAll(po);if(e.length!==0)return e}async function bo(r,e=!1){if(!(!e||r.method!=="GET"))return bs(r.URL.searchParams)}async function wo(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 bs(n)}var It=go;function So(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 ws=r=>r.httpStatus!==void 0;function Eo(r){if(r instanceof _){let{error:e}=r;if(ws(e))return e.httpStatus}return b.UNAUTHORIZED}function vo(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),ws(n)&&n.scope&&t.set("scope",n.scope)}return t}var Po=r=>async(e,t)=>{let n=Eo(t),s=vo(t,r?.realmName),i=So(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},Wt=Po;var Co=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},xo=r